Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(annotation): support assigning users to queues (#8325)

marliessophie026d8e2ba084
diff --git a/fern/apis/server/definition/annotation-queues.yml b/fern/apis/server/definition/annotation-queues.yml
index 1e37fab36e..31e06fcf98 100644
--- a/fern/apis/server/definition/annotation-queues.yml
+++ b/fern/apis/server/definition/annotation-queues.yml
@@ -105,6 +105,28 @@ service:
docs: The unique identifier of the annotation queue item
response: DeleteAnnotationQueueItemResponse
+ createQueueAssignment:
+ docs: Create an assignment for a user to an annotation queue
+ method: POST
+ path: /annotation-queues/{queueId}/assignments
+ path-parameters:
+ queueId:
+ type: string
+ docs: The unique identifier of the annotation queue
+ request: AnnotationQueueAssignmentRequest
+ response: CreateAnnotationQueueAssignmentResponse
+
+ deleteQueueAssignment:
+ docs: Delete an assignment for a user to an annotation queue
+ method: DELETE
+ path: /annotation-queues/{queueId}/assignments
+ path-parameters:
+ queueId:
+ type: string
+ docs: The unique identifier of the annotation queue
+ request: AnnotationQueueAssignmentRequest
+ response: DeleteAnnotationQueueAssignmentResponse
+
types:
AnnotationQueueStatus:
enum:
@@ -163,3 +185,17 @@ types:
properties:
success: boolean
message: string
+
+ AnnotationQueueAssignmentRequest:
+ properties:
+ userId: string
+
+ DeleteAnnotationQueueAssignmentResponse:
+ properties:
+ success: boolean
+
+ CreateAnnotationQueueAssignmentResponse:
+ properties:
+ userId: string
+ queueId: string
+ projectId: string
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 9fe6dce4d0..14940064bf 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -185,6 +185,14 @@ export type AnnotationQueue = {
created_at: Generated<Timestamp>;
updated_at: Generated<Timestamp>;
};
+export type AnnotationQueueAssignment = {
+ id: string;
+ project_id: string;
+ user_id: string;
+ queue_id: string;
+ created_at: Generated<Timestamp>;
+ updated_at: Generated<Timestamp>;
+};
export type AnnotationQueueItem = {
id: string;
queue_id: string;
@@ -804,6 +812,7 @@ export type VerificationToken = {
export type DB = {
Account: Account;
actions: Action;
+ annotation_queue_assignments: AnnotationQueueAssignment;
annotation_queue_items: AnnotationQueueItem;
annotation_queues: AnnotationQueue;
api_keys: ApiKey;
diff --git a/packages/shared/prisma/migrations/20250806100613_add_annotation_queue_assignment_table/migration.sql b/packages/shared/prisma/migrations/20250806100613_add_annotation_queue_assignment_table/migration.sql
new file mode 100644
index 0000000000..c7a0ee0437
--- /dev/null
+++ b/packages/shared/prisma/migrations/20250806100613_add_annotation_queue_assignment_table/migration.sql
@@ -0,0 +1,23 @@
+-- CreateTable
+CREATE TABLE "annotation_queue_assignments" (
+ "id" TEXT NOT NULL,
+ "project_id" TEXT NOT NULL,
+ "user_id" TEXT NOT NULL,
+ "queue_id" TEXT NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+
+ CONSTRAINT "annotation_queue_assignments_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "annotation_queue_assignments_project_id_queue_id_key" ON "annotation_queue_assignments"("project_id", "queue_id", "user_id");
+
+-- AddForeignKey
+ALTER TABLE "annotation_queue_assignments" ADD CONSTRAINT "annotation_queue_assignments_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "annotation_queue_assignments" ADD CONSTRAINT "annotation_queue_assignments_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "annotation_queue_assignments" ADD CONSTRAINT "annotation_queue_assignments_queue_id_fkey" FOREIGN KEY ("queue_id") REFERENCES "annotation_queues"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 6538d2af56..f9deb05b77 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -65,29 +65,30 @@ 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[]
- 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")
- annotatedLockedItem AnnotationQueueItem[] @relation("LockedByUser")
- annotatedCompletedItem AnnotationQueueItem[] @relation("AnnotatorUser")
- dashboardWidgetsCreated DashboardWidget[] @relation("CreatedByUser")
- dashboardWidgetsUpdated DashboardWidget[] @relation("UpdatedByUser")
- dashboardCreated Dashboard[] @relation("CreatedByUser")
- dashboardUpdated Dashboard[] @relation("UpdatedByUser")
- tableViewPresetCreated TableViewPreset[] @relation("CreatedByUser")
- tableViewPresetUpdated TableViewPreset[] @relation("UpdatedByUser")
+ 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")
+ annotatedLockedItem AnnotationQueueItem[] @relation("LockedByUser")
+ annotatedCompletedItem AnnotationQueueItem[] @relation("AnnotatorUser")
+ dashboardWidgetsCreated DashboardWidget[] @relation("CreatedByUser")
+ dashboardWidgetsUpdated DashboardWidget[] @relation("UpdatedByUser")
+ dashboardCreated Dashboard[] @relation("CreatedByUser")
+ dashboardUpdated Dashboard[] @relation("UpdatedByUser")
+ tableViewPresetCreated TableViewPreset[] @relation("CreatedByUser")
+ tableViewPresetUpdated TableViewPreset[] @relation("UpdatedByUser")
+ annotationQueueAssignment AnnotationQueueAssignment[]
@@map("users")
}
@@ -117,54 +118,55 @@ model Organization {
}
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")
- deletedAt DateTime? @map("deleted_at")
- name String
- retentionDays Int? @map("retention_days")
- metadata Json?
- projectMembers ProjectMembership[]
- organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)
- apiKeys ApiKey[]
- dataset Dataset[]
- invitations MembershipInvitation[]
- sessions TraceSession[]
- Prompt Prompt[]
- Model Model[]
- EvalTemplate EvalTemplate[]
- JobConfiguration JobConfiguration[]
- JobExecution JobExecution[]
- LlmApiKeys LlmApiKeys[]
- PosthogIntegration PosthogIntegration[]
- BlobStorageIntegration BlobStorageIntegration[]
- scoreConfig ScoreConfig[]
- BatchExport BatchExport[]
- comment Comment[]
- annotationQueue AnnotationQueue[]
- annotationQueueItem AnnotationQueueItem[]
- TraceMedia TraceMedia[]
- Media Media[]
- ObservationMedia ObservationMedia[]
- LegacyTrace LegacyPrismaTrace[]
- LegacyObservation LegacyPrismaObservation[]
- LegacyScore LegacyPrismaScore[]
- PromptDependency PromptDependency[]
- LlmSchema LlmSchema[]
- LlmTool LlmTool[]
- PromptProtectedLabels PromptProtectedLabels[]
- Dashboard Dashboard[]
- DashboardWidget DashboardWidget[]
- TableViewPreset TableViewPreset[]
- actions Action[]
- triggers Trigger[]
- automationExecutions AutomationExecution[]
- Automation Automation[]
- DefaultLlmModel DefaultLlmModel[]
- Price Price[]
- SlackIntegration SlackIntegration?
- PendingDeletion PendingDeletion[]
+ 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")
+ deletedAt DateTime? @map("deleted_at")
+ name String
+ retentionDays Int? @map("retention_days")
+ metadata Json?
+ projectMembers ProjectMembership[]
+ organization Organization @relation(fields: [orgId], references: [id], onUpdate: Cascade, onDelete: Cascade)
+ apiKeys ApiKey[]
+ dataset Dataset[]
+ invitations MembershipInvitation[]
+ sessions TraceSession[]
+ Prompt Prompt[]
+ Model Model[]
+ EvalTemplate EvalTemplate[]
+ JobConfiguration JobConfiguration[]
+ JobExecution JobExecution[]
+ LlmApiKeys LlmApiKeys[]
+ PosthogIntegration PosthogIntegration[]
+ BlobStorageIntegration BlobStorageIntegration[]
+ scoreConfig ScoreConfig[]
+ BatchExport BatchExport[]
+ comment Comment[]
+ annotationQueue AnnotationQueue[]
+ annotationQueueItem AnnotationQueueItem[]
+ TraceMedia TraceMedia[]
+ Media Media[]
+ ObservationMedia ObservationMedia[]
+ LegacyTrace LegacyPrismaTrace[]
+ LegacyObservation LegacyPrismaObservation[]
+ LegacyScore LegacyPrismaScore[]
+ PromptDependency PromptDependency[]
+ LlmSchema LlmSchema[]
+ LlmTool LlmTool[]
+ PromptProtectedLabels PromptProtectedLabels[]
+ Dashboard Dashboard[]
+ DashboardWidget DashboardWidget[]
+ TableViewPreset TableViewPreset[]
+ actions Action[]
+ triggers Trigger[]
+ automationExecutions AutomationExecution[]
+ Automation Automation[]
+ DefaultLlmModel DefaultLlmModel[]
+ Price Price[]
+ SlackIntegration SlackIntegration?
+ PendingDeletion PendingDeletion[]
+ AnnotationQueueAssignment AnnotationQueueAssignment[]
@@index([orgId])
@@map("projects")
@@ -491,15 +493,16 @@ enum ScoreDataType {
}
model AnnotationQueue {
- id String @id @default(cuid())
- name String
- description String?
- scoreConfigIds String[] @default([]) @map("score_config_ids")
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
- createdAt DateTime @default(now()) @map("created_at")
- updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
- annotationQueueItem AnnotationQueueItem[]
+ id String @id @default(cuid())
+ name String
+ description String?
+ scoreConfigIds String[] @default([]) @map("score_config_ids")
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+ annotationQueueItem AnnotationQueueItem[]
+ annotationQueueAssignment AnnotationQueueAssignment[]
@@unique([projectId, name])
@@index([id, projectId])
@@ -544,6 +547,21 @@ enum AnnotationQueueObjectType {
SESSION
}
+model AnnotationQueueAssignment {
+ id String @id @default(cuid())
+ 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)
+ queueId String @map("queue_id")
+ queue AnnotationQueue @relation(fields: [queueId], references: [id], onDelete: Cascade)
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ @@unique([projectId, queueId, userId])
+ @@map("annotation_queue_assignments")
+}
+
model CronJobs {
name String @id
lastRun DateTime? @map("last_run")
diff --git a/packages/shared/src/features/annotation/types.ts b/packages/shared/src/features/annotation/types.ts
index cc1df54823..d17d4d9bf7 100644
--- a/packages/shared/src/features/annotation/types.ts
+++ b/packages/shared/src/features/annotation/types.ts
@@ -91,4 +91,11 @@ export const CreateQueueData = z.object({
}),
});
+export const CreateQueueWithAssignmentsData = CreateQueueData.extend({
+ newAssignmentUserIds: z.array(z.string()),
+});
+
export type CreateQueue = z.infer<typeof CreateQueueData>;
+export type CreateQueueWithAssignments = z.infer<
+ typeof CreateQueueWithAssignmentsData
+>;
diff --git a/packages/shared/src/tableDefinitions/types.ts b/packages/shared/src/tableDefinitions/types.ts
index 29a58b1ecb..6e0cc426a3 100644
--- a/packages/shared/src/tableDefinitions/types.ts
+++ b/packages/shared/src/tableDefinitions/types.ts
@@ -77,6 +77,7 @@ export const tableNames = [
"job_configurations",
"job_executions",
"dataset_items",
+ "annotation_queue_assignments",
] as const;
export type TableNames = (typeof tableNames)[number];
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index fbab937cd4..000870ecc6 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -409,6 +409,111 @@ paths:
schema: {}
security:
- BasicAuth: []
+ /api/public/annotation-queues/{queueId}/assignments:
+ post:
+ description: Create an assignment for a user to an annotation queue
+ operationId: annotationQueues_createQueueAssignment
+ tags:
+ - AnnotationQueues
+ parameters:
+ - name: queueId
+ in: path
+ description: The unique identifier of the annotation queue
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CreateAnnotationQueueAssignmentResponse'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security:
+ - BasicAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AnnotationQueueAssignmentRequest'
+ delete:
+ description: Delete an assignment for a user to an annotation queue
+ operationId: annotationQueues_deleteQueueAssignment
+ tags:
+ - AnnotationQueues
+ parameters:
+ - name: queueId
+ in: path
+ description: The unique identifier of the annotation queue
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/DeleteAnnotationQueueAssignmentResponse'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security:
+ - BasicAuth: []
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AnnotationQueueAssignmentRequest'
/api/public/comments:
post:
description: >-
@@ -3149,7 +3254,7 @@ paths:
parameters:
- name: filter
in: query
- description: Filter expression (e.g. userName eq "value")
+ description: Filter expression (e.g. userName eq 'value')
required: false
schema:
type: string
@@ -4387,6 +4492,36 @@ components:
required:
- success
- message
+ AnnotationQueueAssignmentRequest:
+ title: AnnotationQueueAssignmentRequest
+ type: object
+ properties:
+ userId:
+ type: string
+ required:
+ - userId
+ DeleteAnnotationQueueAssignmentResponse:
+ title: DeleteAnnotationQueueAssignmentResponse
+ type: object
+ properties:
+ success:
+ type: boolean
+ required:
+ - success
+ CreateAnnotationQueueAssignmentResponse:
+ title: CreateAnnotationQueueAssignmentResponse
+ type: object
+ properties:
+ userId:
+ type: string
+ queueId:
+ type: string
+ projectId:
+ type: string
+ required:
+ - userId
+ - queueId
+ - projectId
CreateCommentRequest:
title: CreateCommentRequest
type: object
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index 88159c972f..2c944a6841 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -324,6 +324,88 @@
"body": null
},
"response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Create Queue Assignment",
+ "request": {
+ "description": "Create an assignment for a user to an annotation queue",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/annotation-queues/:queueId/assignments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "annotation-queues",
+ ":queueId",
+ "assignments"
+ ],
+ "query": [],
+ "variable": [
+ {
+ "key": "queueId",
+ "value": "",
+ "description": "The unique identifier of the annotation queue"
+ }
+ ]
+ },
+ "header": [],
+ "method": "POST",
+ "auth": null,
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"userId\": \"example\"\n}",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ }
+ },
+ "response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Delete Queue Assignment",
+ "request": {
+ "description": "Delete an assignment for a user to an annotation queue",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/annotation-queues/:queueId/assignments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "annotation-queues",
+ ":queueId",
+ "assignments"
+ ],
+ "query": [],
+ "variable": [
+ {
+ "key": "queueId",
+ "value": "",
+ "description": "The unique identifier of the annotation queue"
+ }
+ ]
+ },
+ "header": [],
+ "method": "DELETE",
+ "auth": null,
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"userId\": \"example\"\n}",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ }
+ },
+ "response": []
}
]
},
diff --git a/web/src/__tests__/async/annotation-queue-assignments-api.servertest.ts b/web/src/__tests__/async/annotation-queue-assignments-api.servertest.ts
new file mode 100644
index 0000000000..c805543c76
--- /dev/null
+++ b/web/src/__tests__/async/annotation-queue-assignments-api.servertest.ts
@@ -0,0 +1,342 @@
+/** @jest-environment node */
+
+import {
+ makeZodVerifiedAPICall,
+ makeAPICall,
+ pruneDatabase,
+} from "@/src/__tests__/test-utils";
+import { prisma } from "@langfuse/shared/src/db";
+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";
+import { v4 as uuidv4 } from "uuid";
+import {
+ CreateAnnotationQueueAssignmentResponse,
+ DeleteAnnotationQueueAssignmentResponse,
+} from "@/src/features/public-api/types/annotation-queues";
+
+describe("/api/public/annotation-queues/:queueId/assignments API", () => {
+ let auth: string;
+ let projectId: string;
+ let orgId: string;
+ let queueId: string;
+ let testUserId: string;
+ let secondTestUserId: string;
+
+ beforeAll(async () => {
+ const {
+ auth: newAuth,
+ projectId: newProjectId,
+ orgId: newOrgId,
+ } = await createOrgProjectAndApiKey();
+ auth = newAuth;
+ projectId = newProjectId;
+ orgId = newOrgId;
+
+ // Create a test annotation queue
+ const queue = await prisma.annotationQueue.create({
+ data: {
+ id: uuidv4(),
+ name: "Test Queue for Assignments",
+ description: "Test queue for assignment testing",
+ projectId,
+ scoreConfigIds: [],
+ },
+ });
+ queueId = queue.id;
+
+ // Create test users with project access
+ const testUser = await prisma.user.create({
+ data: {
+ id: uuidv4(),
+ email: `testuser1-${uuidv4()}@example.com`,
+ name: "Test User 1",
+ },
+ });
+ testUserId = testUser.id;
+
+ const secondTestUser = await prisma.user.create({
+ data: {
+ id: uuidv4(),
+ email: `testuser2-${uuidv4()}@example.com`,
+ name: "Test User 2",
+ },
+ });
+ secondTestUserId = secondTestUser.id;
+
+ // Give users project access - need to create org memberships first
+ await prisma.organizationMembership.createMany({
+ data: [
+ {
+ orgId,
+ userId: testUserId,
+ role: "MEMBER",
+ },
+ {
+ orgId,
+ userId: secondTestUserId,
+ role: "MEMBER",
+ },
+ ],
+ });
+
+ // Get the org membership IDs and create project memberships
+ const orgMembership1 = await prisma.organizationMembership.findFirst({
+ where: { orgId, userId: testUserId },
+ });
+ const orgMembership2 = await prisma.organizationMembership.findFirst({
+ where: { orgId, userId: secondTestUserId },
+ });
+
+ await prisma.projectMembership.createMany({
+ data: [
+ {
+ projectId,
+ userId: testUserId,
+ role: "MEMBER",
+ orgMembershipId: orgMembership1!.id,
+ },
+ {
+ projectId,
+ userId: secondTestUserId,
+ role: "MEMBER",
+ orgMembershipId: orgMembership2!.id,
+ },
+ ],
+ });
+ });
+
+ afterAll(async () => {
+ await pruneDatabase();
+ });
+
+ describe("POST /api/public/annotation-queues/:queueId/assignments", () => {
+ it("should create annotation queue assignment successfully", async () => {
+ const response = await makeZodVerifiedAPICall(
+ CreateAnnotationQueueAssignmentResponse,
+ "POST",
+ `/api/public/annotation-queues/${queueId}/assignments`,
+ {
+ userId: testUserId,
+ },
+ auth,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.userId).toBe(testUserId);
+ expect(response.body.projectId).toBe(projectId);
+ expect(response.body.queueId).toBe(queueId);
+
+ // Verify the membership was created in the database
+ const assignment = await prisma.annotationQueueAssignment.findUnique({
+ where: {
+ projectId_queueId_userId: {
+ projectId,
+ queueId,
+ userId: testUserId,
+ },
+ },
+ });
+
+ expect(assignment).toBeTruthy();
+ expect(assignment?.userId).toBe(testUserId);
+ expect(assignment?.projectId).toBe(projectId);
+ expect(assignment?.queueId).toBe(queueId);
+ });
+
+ it("should handle duplicate assignment creation gracefully", async () => {
+ // Create assignment first time
+ await makeZodVerifiedAPICall(
+ CreateAnnotationQueueAssignmentResponse,
+ "POST",
+ `/api/public/annotation-queues/${queueId}/assignments`,
+ {
+ userId: secondTestUserId,
+ },
+ auth,
+ );
+
+ // Create same assignment again - should succeed (upsert behavior)
+ const response = await makeZodVerifiedAPICall(
+ CreateAnnotationQueueAssignmentResponse,
+ "POST",
+ `/api/public/annotation-queues/${queueId}/assignments`,
+ {
+ userId: secondTestUserId,
+ },
+ auth,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.userId).toBe(secondTestUserId);
+
+ // Verify only one assignment exists
+ const assignments = await prisma.annotationQueueAssignment.findMany({
+ where: {
+ projectId,
+ queueId,
+ userId: secondTestUserId,
+ },
+ });
+
+ expect(assignments).toHaveLength(1);
+ });
+
+ it("should return 404 for non-existent annotation queue", async () => {
+ const nonExistentQueueId = uuidv4();
+
+ const response = await makeAPICall(
+ "POST",
+ `/api/public/annotation-queues/${nonExistentQueueId}/assignments`,
+ {
+ userId: testUserId,
+ },
+ auth,
+ );
+
+ expect(response.status).toBe(404);
+ });
+
+ it("should return 404 for non-existent user", async () => {
+ const nonExistentUserId = uuidv4();
+
+ const response = await makeAPICall(
+ "POST",
+ `/api/public/annotation-queues/${queueId}/assignments`,
+ {
+ userId: nonExistentUserId,
+ },
+ auth,
+ );
+
+ expect(response.status).toBe(404);
+ });
+
+ it("should return 404 for user without project access", async () => {
+ // Create a user without project access
+ const userWithoutAccess = await prisma.user.create({
+ data: {
+ id: uuidv4(),
+ email: `noaccess-${uuidv4()}@example.com`,
+ name: "No Access User",
+ },
+ });
+
+ const response = await makeAPICall(
+ "POST",
+ `/api/public/annotation-queues/${queueId}/assignments`,
+ {
+ userId: userWithoutAccess.id,
+ },
+ auth,
+ );
+
+ expect(response.status).toBe(404);
+ });
+
+ it("should validate request body", async () => {
+ // Missing userId
+ const response = await makeAPICall(
+ "POST",
+ `/api/public/annotation-queues/${queueId}/assignments`,
+ {},
+ auth,
+ );
+
+ expect(response.status).toBe(400);
+ });
+
+ it("should require valid queueId format", async () => {
+ const response = await makeAPICall(
+ "POST",
+ `/api/public/annotation-queues/invalid-queue-id/assignments`,
+ {
+ userId: testUserId,
+ },
+ auth,
+ );
+
+ expect(response.status).toBe(404);
+ });
+ });
+
+ describe("DELETE /api/public/annotation-queues/:queueId/assignments", () => {
+ beforeEach(async () => {
+ // Ensure assignment exists for delete tests
+ await prisma.annotationQueueAssignment.upsert({
+ where: {
+ projectId_queueId_userId: {
+ projectId,
+ queueId,
+ userId: testUserId,
+ },
+ },
+ create: {
+ projectId,
+ queueId,
+ userId: testUserId,
+ },
+ update: {},
+ });
+ });
+
+ it("should delete annotation queue membership successfully", async () => {
+ const response = await makeZodVerifiedAPICall(
+ DeleteAnnotationQueueAssignmentResponse,
+ "DELETE",
+ `/api/public/annotation-queues/${queueId}/assignments`,
+ {
+ userId: testUserId,
+ },
+ auth,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.success).toBe(true);
+
+ // Verify the membership was deleted from the database
+ const assignment = await prisma.annotationQueueAssignment.findUnique({
+ where: {
+ projectId_queueId_userId: {
+ projectId,
+ queueId,
+ userId: testUserId,
+ },
+ },
+ });
+
+ expect(assignment).toBeNull();
+ });
+
+ it("should handle deletion of non-existent assignment gracefully", async () => {
+ // Delete a assignment that doesn't exist
+ const nonExistentUserId = uuidv4();
+
+ const response = await makeZodVerifiedAPICall(
+ DeleteAnnotationQueueAssignmentResponse,
+ "DELETE",
+ `/api/public/annotation-queues/${queueId}/assignments`,
+ {
+ userId: nonExistentUserId,
+ },
+ auth,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.success).toBe(true);
+ });
+
+ it("should return 404 for non-existent annotation queue", async () => {
+ const nonExistentQueueId = uuidv4();
+
+ const response = await makeAPICall(
+ "DELETE",
+ `/api/public/annotation-queues/${nonExistentQueueId}/assignments`,
+ {
+ userId: testUserId,
+ },
+ auth,
+ );
+
+ expect(response.status).toBe(404);
+ });
+ });
+});
diff --git a/web/src/__tests__/async/generateUserProjectRolesQuery.servertest.ts b/web/src/__tests__/async/generateUserProjectRolesQuery.servertest.ts
new file mode 100644
index 0000000000..388ad043a2
--- /dev/null
+++ b/web/src/__tests__/async/generateUserProjectRolesQuery.servertest.ts
@@ -0,0 +1,443 @@
+/** @jest-environment node */
+
+import { prisma } from "@langfuse/shared/src/db";
+import { Prisma, type Role } from "@langfuse/shared";
+import { v4 } from "uuid";
+import { getUserProjectRoles } from "@/src/features/rbac/utils/userProjectRole";
+
+export const createOrgAndProject = async () => {
+ const org = await prisma.organization.create({
+ data: {
+ id: v4(),
+ name: v4(),
+ },
+ });
+
+ const project = await prisma.project.create({
+ data: {
+ id: v4(),
+ name: v4(),
+ orgId: org.id,
+ },
+ });
+
+ return { org, project };
+};
+
+describe("find user project roles", () => {
+ it("should find users with org role", async () => {
+ const { org, project } = await createOrgAndProject();
+
+ const user = await prisma.user.create({
+ data: {
+ id: v4(),
+ email: v4(),
+ name: v4(),
+ },
+ });
+
+ await prisma.organizationMembership.create({
+ data: {
+ userId: user.id,
+ orgId: org.id,
+ role: "MEMBER",
+ },
+ });
+
+ const users = await getUserProjectRoles({
+ projectId: project.id,
+ orgId: org.id,
+ filterCondition: [],
+ searchFilter: Prisma.empty,
+ orderBy: Prisma.empty,
+ });
+
+ expect(users).toEqual([
+ expect.objectContaining({
+ id: user.id,
+ name: user.name,
+ email: user.email,
+ }),
+ ]);
+ });
+
+ it("should exclude users with NONE role", async () => {
+ const { org, project } = await createOrgAndProject();
+
+ const user = await prisma.user.create({
+ data: {
+ id: v4(),
+ email: v4(),
+ name: v4(),
+ },
+ });
+
+ await prisma.organizationMembership.create({
+ data: {
+ userId: user.id,
+ orgId: org.id,
+ role: "NONE",
+ },
+ });
+
+ const users = await getUserProjectRoles({
+ projectId: project.id,
+ orgId: org.id,
+ filterCondition: [],
+ searchFilter: Prisma.empty,
+ orderBy: Prisma.empty,
+ });
+
+ expect(users).toEqual([]);
+ });
+
+ it("should find users with org and project role", async () => {
+ const { org, project } = await createOrgAndProject();
+
+ const user = await prisma.user.create({
+ data: {
+ id: v4(),
+ email: v4(),
+ name: v4(),
+ },
+ });
+
+ await prisma.organizationMembership.create({
+ data: {
+ userId: user.id,
+ orgId: org.id,
+ role: "MEMBER",
+ },
+ });
+ const user2 = await prisma.user.create({
+ data: {
+ id: v4(),
+ email: v4(),
+ name: v4(),
+ },
+ });
+
+ const orgMembershipOfUser2 = await prisma.organizationMembership.create({
+ data: {
+ userId: user2.id,
+ orgId: org.id,
+ role: "MEMBER",
+ },
+ });
+
+ // overwrite org role to ADMIN
+ await prisma.projectMembership.create({
+ data: {
+ userId: user2.id,
+ projectId: project.id,
+ role: "ADMIN",
+ orgMembershipId: orgMembershipOfUser2.id,
+ },
+ });
+
+ const user3 = await prisma.user.create({
+ data: {
+ id: v4(),
+ email: v4(),
+ name: v4(),
+ },
+ });
+
+ const orgMembershipOfUser3 = await prisma.organizationMembership.create({
+ data: {
+ userId: user3.id,
+ orgId: org.id,
+ role: "ADMIN",
+ },
+ });
+
+ // Downgrade org role to VIEWER
+ await prisma.projectMembership.create({
+ data: {
+ userId: user3.id,
+ projectId: project.id,
+ role: "VIEWER",
+ orgMembershipId: orgMembershipOfUser3.id,
+ },
+ });
+
+ const users = await getUserProjectRoles({
+ projectId: project.id,
+ orgId: org.id,
+ filterCondition: [],
+ searchFilter: Prisma.empty,
+ orderBy: Prisma.empty,
+ });
+
+ expect(users).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: user.id,
+ name: user.name,
+ email: user.email,
+ role: "MEMBER",
+ }),
+ expect.objectContaining({
+ id: user2.id,
+ name: user2.name,
+ email: user2.email,
+ role: "ADMIN",
+ }),
+ expect.objectContaining({
+ id: user3.id,
+ name: user3.name,
+ email: user3.email,
+ role: "VIEWER",
+ }),
+ ]),
+ );
+ });
+
+ it("should not select users from different projects", async () => {
+ const { org, project } = await createOrgAndProject();
+
+ // valid user
+ const user = await prisma.user.create({
+ data: {
+ id: v4(),
+ email: v4(),
+ name: v4(),
+ },
+ });
+
+ await prisma.organizationMembership.create({
+ data: {
+ userId: user.id,
+ orgId: org.id,
+ role: "MEMBER",
+ },
+ });
+
+ const { org: org2, project: project2 } = await createOrgAndProject();
+
+ const user2 = await prisma.user.create({
+ data: {
+ id: v4(),
+ email: v4(),
+ name: v4(),
+ },
+ });
+
+ await prisma.organizationMembership.create({
+ data: {
+ userId: user2.id,
+ orgId: org2.id,
+ role: "MEMBER",
+ },
+ });
+
+ const user3 = await prisma.user.create({
+ data: {
+ id: v4(),
+ email: v4(),
+ name: v4(),
+ },
+ });
+
+ const orgMembershipOfUser3 = await prisma.organizationMembership.create({
+ data: {
+ userId: user3.id,
+ orgId: org2.id,
+ role: "MEMBER",
+ },
+ });
+
+ await prisma.projectMembership.create({
+ data: {
+ userId: user3.id,
+ projectId: project2.id,
+ role: "MEMBER",
+ orgMembershipId: orgMembershipOfUser3.id,
+ },
+ });
+
+ const users = await getUserProjectRoles({
+ projectId: project.id,
+ orgId: org.id,
+ filterCondition: [],
+ searchFilter: Prisma.empty,
+ orderBy: Prisma.empty,
+ });
+
+ expect(users).toEqual([
+ expect.objectContaining({
+ id: user.id,
+ name: user.name,
+ email: user.email,
+ }),
+ ]);
+ });
+
+ it("should return empty array for empty organization", async () => {
+ const { org, project } = await createOrgAndProject();
+
+ const users = await getUserProjectRoles({
+ projectId: project.id,
+ orgId: org.id,
+ filterCondition: [],
+ searchFilter: Prisma.empty,
+ orderBy: Prisma.empty,
+ });
+
+ expect(users).toEqual([]);
+ });
+
+ it("should exclude users with project role NONE even if they have org membership", async () => {
+ const { org, project } = await createOrgAndProject();
+
+ const user = await prisma.user.create({
+ data: {
+ id: v4(),
+ email: v4(),
+ name: v4(),
+ },
+ });
+
+ const orgMembership = await prisma.organizationMembership.create({
+ data: {
+ userId: user.id,
+ orgId: org.id,
+ role: "ADMIN",
+ },
+ });
+
+ // Project role NONE should exclude user despite ADMIN org role
+ await prisma.projectMembership.create({
+ data: {
+ userId: user.id,
+ projectId: project.id,
+ role: "NONE",
+ orgMembershipId: orgMembership.id,
+ },
+ });
+
+ const users = await getUserProjectRoles({
+ projectId: project.id,
+ orgId: org.id,
+ filterCondition: [],
+ searchFilter: Prisma.empty,
+ orderBy: Prisma.empty,
+ });
+
+ expect(users).toEqual([]);
+ });
+
+ it("should test all role combinations inheritance vs override", async () => {
+ const { org, project } = await createOrgAndProject();
+
+ // Test inheritance: users with only org roles
+ const inheritanceTests = [
+ { orgRole: "OWNER", expectedRole: "OWNER" },
+ { orgRole: "ADMIN", expectedRole: "ADMIN" },
+ { orgRole: "MEMBER", expectedRole: "MEMBER" },
+ { orgRole: "VIEWER", expectedRole: "VIEWER" },
+ ];
+
+ const inheritanceUsers = [];
+ for (const test of inheritanceTests) {
+ const id = v4();
+ const user = await prisma.user.create({
+ data: {
+ id,
+ email: `${id}-${test.orgRole}@test.com`,
+ name: `${id}-${test.orgRole} User`,
+ },
+ });
+
+ await prisma.organizationMembership.create({
+ data: {
+ userId: user.id,
+ orgId: org.id,
+ role: test.orgRole as Role,
+ },
+ });
+
+ inheritanceUsers.push({
+ id,
+ role: test.expectedRole,
+ });
+ }
+
+ // Test overrides: users with project roles that override org roles
+ const overrideTests = [
+ { orgRole: "OWNER", projectRole: "VIEWER", expectedRole: "VIEWER" },
+ { orgRole: "MEMBER", projectRole: "ADMIN", expectedRole: "ADMIN" },
+ { orgRole: "VIEWER", projectRole: "MEMBER", expectedRole: "MEMBER" },
+ { orgRole: "ADMIN", projectRole: "VIEWER", expectedRole: "VIEWER" },
+ ];
+
+ const overrideUsers = [];
+ for (const test of overrideTests) {
+ const id = v4();
+ const user = await prisma.user.create({
+ data: {
+ id,
+ email: `${id}-${test.orgRole}-${test.projectRole}@test.com`,
+ name: `${id}-${test.orgRole}-${test.projectRole} User`,
+ },
+ });
+
+ const orgMembership = await prisma.organizationMembership.create({
+ data: {
+ userId: user.id,
+ orgId: org.id,
+ role: test.orgRole as Role,
+ },
+ });
+
+ await prisma.projectMembership.create({
+ data: {
+ userId: user.id,
+ projectId: project.id,
+ role: test.projectRole as Role,
+ orgMembershipId: orgMembership.id,
+ },
+ });
+
+ overrideUsers.push({
+ id: user.id,
+ role: test.expectedRole,
+ });
+ }
+
+ const users = await getUserProjectRoles({
+ projectId: project.id,
+ orgId: org.id,
+ filterCondition: [],
+ searchFilter: Prisma.empty,
+ orderBy: Prisma.empty,
+ });
+
+ // Verify all inheritance cases
+ for (const expectedUser of inheritanceUsers) {
+ expect(users).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: expectedUser.id,
+ role: expectedUser.role,
+ }),
+ ]),
+ );
+ }
+
+ // Verify all override cases
+ for (const expectedUser of overrideUsers) {
+ expect(users).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: expectedUser.id,
+ role: expectedUser.role,
+ }),
+ ]),
+ );
+ }
+
+ // Verify total count
+ expect(users).toHaveLength(inheritanceUsers.length + overrideUsers.length);
+ });
+});
diff --git a/web/src/components/table/data-table.tsx b/web/src/components/table/data-table.tsx
index 2a7045f20c..4dab80370f 100644
--- a/web/src/components/table/data-table.tsx
+++ b/web/src/components/table/data-table.tsx
@@ -67,6 +67,7 @@ interface DataTableProps<TData, TValue> {
pinFirstColumn?: boolean;
hidePagination?: boolean;
tableName: string;
+ getRowClassName?: (row: TData) => string;
}
export interface AsyncTableData<T> {
@@ -123,6 +124,7 @@ export function DataTable<TData extends object, TValue>({
pinFirstColumn = false,
hidePagination = false,
tableName,
+ getRowClassName,
}: DataTableProps<TData, TValue>) {
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
const rowheighttw = getRowHeightTailwindClass(rowHeight, customRowHeights);
@@ -381,6 +383,7 @@ export function DataTable<TData extends object, TValue>({
help={help}
onRowClick={hasRowClickAction ? handleOnRowClick : undefined}
pinFirstColumn={pinFirstColumn}
+ getRowClassName={getRowClassName}
/>
)}
</Table>
@@ -430,6 +433,7 @@ interface TableBodyComponentProps<TData> {
help?: { description: string; href: string };
onRowClick?: (row: TData) => void;
pinFirstColumn?: boolean;
+ getRowClassName?: (row: TData) => string;
tableSnapshot?: {
tableDataUpdatedAt?: number;
columnVisibility?: VisibilityState;
@@ -441,10 +445,12 @@ interface TableBodyComponentProps<TData> {
function TableRowComponent<TData>({
row,
onRowClick,
+ getRowClassName,
children,
}: {
row: Row<TData>;
onRowClick?: (row: TData) => void;
+ getRowClassName?: (row: TData) => string;
children: React.ReactNode;
}) {
const router = useRouter();
@@ -462,6 +468,7 @@ function TableRowComponent<TData>({
"hover:bg-accent",
!!onRowClick ? "cursor-pointer" : "cursor-default",
selectedRowId && selectedRowId === row.id ? "bg-accent" : undefined,
+ getRowClassName?.(row.original),
)}
>
{children}
@@ -477,6 +484,7 @@ function TableBodyComponent<TData>({
help,
onRowClick,
pinFirstColumn = false,
+ getRowClassName,
}: TableBodyComponentProps<TData>) {
return (
<TableBody>
@@ -491,7 +499,12 @@ function TableBodyComponent<TData>({
</TableRow>
) : table.getRowModel().rows.length ? (
table.getRowModel().rows.map((row) => (
- <TableRowComponent key={row.id} row={row} onRowClick={onRowClick}>
+ <TableRowComponent
+ key={row.id}
+ row={row}
+ onRowClick={onRowClick}
+ getRowClassName={getRowClassName}
+ >
{row.getVisibleCells().map((cell) => (
<TableCell
key={cell.id}
diff --git a/web/src/components/ui/multi-select-combobox.tsx b/web/src/components/ui/multi-select-combobox.tsx
new file mode 100644
index 0000000000..880cdd498f
--- /dev/null
+++ b/web/src/components/ui/multi-select-combobox.tsx
@@ -0,0 +1,214 @@
+import { useState, useEffect, useRef } from "react";
+import { Input } from "@/src/components/ui/input";
+import { Button } from "@/src/components/ui/button";
+import { Search, X, MoreHorizontal } from "lucide-react";
+
+interface MultiSelectComboboxProps<T> {
+ selectedItems: T[];
+ onItemsChange: (items: T[]) => void;
+ searchQuery: string;
+ onSearchChange: (query: string) => void;
+ searchResults: T[];
+ isLoading?: boolean;
+ placeholder?: string;
+ hasMoreResults?: boolean;
+ renderItem: (
+ item: T,
+ isSelected: boolean,
+ onToggle: () => void,
+ ) => React.ReactNode;
+ renderSelectedItem: (item: T, onRemove: () => void) => React.ReactNode;
+ getItemKey: (item: T) => string;
+ disabled?: boolean;
+}
+
+export function MultiSelectCombobox<T>({
+ selectedItems,
+ onItemsChange,
+ searchQuery,
+ onSearchChange,
+ searchResults,
+ isLoading = false,
+ placeholder = "Search...",
+ hasMoreResults = false,
+ renderItem,
+ renderSelectedItem,
+ getItemKey,
+ disabled = false,
+}: MultiSelectComboboxProps<T>) {
+ const [isInputFocused, setIsInputFocused] = useState(false);
+ const [showDropdown, setShowDropdown] = useState(false);
+ const [previousResults, setPreviousResults] = useState<T[]>([]);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const dropdownRef = useRef<HTMLDivElement>(null);
+
+ // Handle focus/blur for dropdown visibility
+ const handleInputFocus = () => {
+ setIsInputFocused(true);
+ setShowDropdown(true);
+ };
+
+ const handleInputBlur = () => {
+ setIsInputFocused(false);
+ // Delay hiding dropdown to allow clicking on dropdown items
+ setTimeout(() => {
+ if (!isInputFocused) {
+ setShowDropdown(false);
+ }
+ }, 200);
+ };
+
+ // Auto-scroll to input when items are added/removed
+ useEffect(() => {
+ if (inputRef.current && containerRef.current) {
+ containerRef.current.scrollTop = containerRef.current.scrollHeight;
+ }
+ }, [selectedItems.length]);
+
+ // Update previous results when new data arrives (not loading)
+ useEffect(() => {
+ if (!isLoading && searchResults.length > 0) {
+ setPreviousResults(searchResults);
+ }
+ }, [isLoading, searchResults]);
+
+ // Handle click outside to close dropdown
+ useEffect(() => {
+ const handleClickOutside = (event: MouseEvent) => {
+ if (
+ dropdownRef.current &&
+ containerRef.current &&
+ !dropdownRef.current.contains(event.target as Node) &&
+ !containerRef.current.contains(event.target as Node)
+ ) {
+ setShowDropdown(false);
+ setIsInputFocused(false);
+ }
+ };
+
+ if (showDropdown) {
+ document.addEventListener("mousedown", handleClickOutside);
+ return () => {
+ document.removeEventListener("mousedown", handleClickOutside);
+ };
+ }
+ }, [showDropdown]);
+
+ const handleItemToggle = (item: T) => {
+ const itemKey = getItemKey(item);
+ const isSelected = selectedItems.some(
+ (selected) => getItemKey(selected) === itemKey,
+ );
+
+ if (isSelected) {
+ onItemsChange(
+ selectedItems.filter((selected) => getItemKey(selected) !== itemKey),
+ );
+ } else {
+ onItemsChange([...selectedItems, item]);
+ }
+
+ // Keep dropdown open after item toggle
+ setShowDropdown(true);
+ setIsInputFocused(true);
+ };
+
+ const handleItemRemove = (item: T) => {
+ const itemKey = getItemKey(item);
+ onItemsChange(
+ selectedItems.filter((selected) => getItemKey(selected) !== itemKey),
+ );
+ };
+
+ return (
+ <div className="space-y-2">
+ {/* Custom Input with Embedded Pills */}
+ <div className="relative">
+ <div
+ ref={containerRef}
+ className="flex max-h-14 min-h-9 w-full overflow-y-auto rounded-md border border-input bg-background text-xs"
+ >
+ <Search className="absolute left-2 top-2.5 z-10 h-4 w-4 text-muted-foreground" />
+ <div className="flex max-h-full flex-1 flex-wrap items-center gap-1 pl-8">
+ {/* Selected Items Pills */}
+ {selectedItems.map((item) => (
+ <div key={getItemKey(item)}>
+ {renderSelectedItem(item, () => handleItemRemove(item))}
+ </div>
+ ))}
+ {/* Search Input */}
+ <Input
+ ref={inputRef}
+ type="text"
+ placeholder={selectedItems.length === 0 ? placeholder : ""}
+ value={searchQuery}
+ onChange={(e) => onSearchChange(e.target.value)}
+ onFocus={handleInputFocus}
+ onBlur={handleInputBlur}
+ disabled={disabled}
+ className="min-w-24 flex-1 border-none bg-transparent text-xs outline-none placeholder:text-muted-foreground"
+ />
+ </div>
+ {searchQuery && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="absolute right-2 top-1 h-7 w-7 p-0"
+ onClick={() => onSearchChange("")}
+ >
+ <X className="h-3 w-3" />
+ </Button>
+ )}
+ </div>
+ </div>
+
+ {/* Search Results Dropdown */}
+ {showDropdown && (
+ <div ref={dropdownRef} className="relative">
+ {searchResults.length > 0 ||
+ (isLoading && previousResults.length > 0) ? (
+ <div
+ className="absolute top-0 z-10 max-h-48 w-full overflow-y-auto rounded-md border bg-background shadow-md"
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ {(isLoading && previousResults.length > 0
+ ? previousResults
+ : searchResults
+ ).map((item, index, array) => (
+ <div key={getItemKey(item)}>
+ {renderItem(
+ item,
+ selectedItems.some(
+ (selected) => getItemKey(selected) === getItemKey(item),
+ ),
+ () => handleItemToggle(item),
+ )}
+ {(index < array.length - 1 || hasMoreResults) && (
+ <div className="border-b border-border/50" />
+ )}
+ </div>
+ ))}
+ {hasMoreResults && (
+ <div className="flex items-center gap-3 px-3 py-2 text-muted-foreground">
+ <MoreHorizontal className="h-4 w-4" />
+ <div className="min-w-0 flex-1">
+ <p className="text-xs italic">
+ More results available, refine your search
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+ ) : (
+ <div className="absolute top-0 z-10 w-full rounded-md border bg-background py-6 text-center text-xs text-muted-foreground shadow-md">
+ {searchQuery
+ ? `No results found for "${searchQuery}"`
+ : "No results available"}
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/features/annotation-queues/components/AnnotationQueuesTable.tsx b/web/src/features/annotation-queues/components/AnnotationQueuesTable.tsx
index 7ad1fb820c..738c471ec2 100644
--- a/web/src/features/annotation-queues/components/AnnotationQueuesTable.tsx
+++ b/web/src/features/annotation-queues/components/AnnotationQueuesTable.tsx
@@ -34,6 +34,7 @@ type RowData = {
countPendingItems: number;
scoreConfigs: { id: string; name: string; dataType: ScoreDataType }[];
createdAt: string;
+ isAssigned: boolean;
};
export function AnnotationQueuesTable({ projectId }: { projectId: string }) {
@@ -213,6 +214,7 @@ export function AnnotationQueuesTable({ projectId }: { projectId: string }) {
createdAt: item.createdAt.toLocaleString(),
countCompletedItems: item.countCompletedItems,
countPendingItems: item.countPendingItems,
+ isAssigned: item.isCurrentUserAssigned,
};
};
@@ -265,6 +267,9 @@ export function AnnotationQueuesTable({ projectId }: { projectId: string }) {
columnOrder={columnOrder}
onColumnOrderChange={setColumnOrder}
rowHeight={rowHeight}
+ getRowClassName={(row) =>
+ row.isAssigned ? "bg-primary/5 border-l-4 border-l-primary/40" : ""
+ }
/>
</>
);
diff --git a/web/src/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx b/web/src/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx
index 09b18f99dd..e8c2ac4d19 100644
--- a/web/src/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx
+++ b/web/src/features/annotation-queues/components/CreateOrEditAnnotationQueueButton.tsx
@@ -26,8 +26,8 @@ import { useForm } from "react-hook-form";
import { Form } from "@/src/components/ui/form";
import { Textarea } from "@/src/components/ui/textarea";
import {
- type CreateQueue,
- CreateQueueData,
+ type CreateQueueWithAssignments,
+ CreateQueueWithAssignmentsData,
type ValidatedScoreConfig,
} from "@langfuse/shared";
import { api } from "@/src/utils/api";
@@ -39,6 +39,14 @@ import { useEntitlementLimit } from "@/src/features/entitlements/hooks";
import { ActionButton } from "@/src/components/ActionButton";
import { DropdownMenuItem } from "@/src/components/ui/dropdown-menu";
import { useUniqueNameValidation } from "@/src/hooks/useUniqueNameValidation";
+import {
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
+} from "@/src/components/ui/collapsible";
+import { ChevronDown, ChevronRight } from "lucide-react";
+import { UserAssignmentSection } from "@/src/features/annotation-queues/components/UserAssignmentSection";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
export const CreateOrEditAnnotationQueueButton = ({
projectId,
@@ -52,21 +60,26 @@ export const CreateOrEditAnnotationQueueButton = ({
size?: ButtonProps["size"];
}) => {
const [isOpen, setIsOpen] = useState(false);
- const hasAccess = useHasProjectAccess({
+ const [isAdvancedOpen, setIsAdvancedOpen] = useState(false);
+ const hasQueueAccess = useHasProjectAccess({
projectId: projectId,
scope: "annotationQueues:CUD",
});
+ const hasQueueAssignmentsReadAccess = useHasProjectAccess({
+ projectId: projectId,
+ scope: "annotationQueueAssignments:read",
+ });
const queueLimit = useEntitlementLimit("annotation-queue-count");
const router = useRouter();
const capture = usePostHogClientCapture();
const queueQuery = api.annotationQueues.byId.useQuery(
{ projectId, queueId: queueId as string },
- { enabled: !!queueId && hasAccess },
+ { enabled: !!queueId && hasQueueAccess },
);
const form = useForm({
- resolver: zodResolver(CreateQueueData),
+ resolver: zodResolver(CreateQueueWithAssignmentsData),
});
useEffect(() => {
@@ -77,11 +90,13 @@ export const CreateOrEditAnnotationQueueButton = ({
scoreConfigIds: queueQuery.data.scoreConfigs.map(
(config: ValidatedScoreConfig) => config.id,
),
+ newAssignmentUserIds: [],
});
} else {
form.reset({
name: "",
scoreConfigIds: [],
+ newAssignmentUserIds: [],
});
}
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -89,24 +104,14 @@ export const CreateOrEditAnnotationQueueButton = ({
const utils = api.useUtils();
- const createQueueMutation = api.annotationQueues.create.useMutation({
- onSuccess: async () => {
- await Promise.all([utils.annotationQueues.invalidate()]);
- form.reset();
- setIsOpen(false);
- },
- });
- const editQueueMutation = api.annotationQueues.update.useMutation({
- onSuccess: async () => {
- await Promise.all([utils.annotationQueues.invalidate()]);
- form.reset();
- setIsOpen(false);
- },
- });
+ const createQueueMutation = api.annotationQueues.create.useMutation();
+ const editQueueMutation = api.annotationQueues.update.useMutation();
+ const createQueueAssignmentsMutation =
+ api.annotationQueueAssignments.createMany.useMutation();
const queueCountData = api.annotationQueues.count.useQuery(
{ projectId },
- { enabled: hasAccess },
+ { enabled: hasQueueAccess },
);
const configsData = api.scoreConfigs.all.useQuery(
@@ -114,13 +119,13 @@ export const CreateOrEditAnnotationQueueButton = ({
projectId,
},
{
- enabled: hasAccess && isOpen,
+ enabled: hasQueueAccess && isOpen,
},
);
const allQueueNamesAndIds = api.annotationQueues.allNamesAndIds.useQuery(
{ projectId },
- { enabled: hasAccess && !queueId },
+ { enabled: hasQueueAccess && !queueId },
);
const allQueueNames = useMemo(() => {
@@ -138,18 +143,54 @@ export const CreateOrEditAnnotationQueueButton = ({
const configs = configsData.data?.configs ?? [];
- const onSubmit = (data: CreateQueue) => {
- if (queueId) {
- editQueueMutation.mutateAsync({
- ...data,
- projectId,
- queueId,
- });
- } else {
- createQueueMutation.mutateAsync({
- ...data,
- projectId,
- });
+ const onSubmit = async (data: CreateQueueWithAssignments) => {
+ try {
+ // Step 1: Create or update the queue
+ let queueResponse;
+ if (queueId) {
+ // Update existing queue
+ queueResponse = await editQueueMutation.mutateAsync({
+ name: data.name,
+ description: data.description,
+ scoreConfigIds: data.scoreConfigIds,
+ projectId,
+ queueId,
+ });
+ } else {
+ // Create new queue
+ queueResponse = await createQueueMutation.mutateAsync({
+ name: data.name,
+ description: data.description,
+ scoreConfigIds: data.scoreConfigIds,
+ projectId,
+ });
+ }
+
+ // Step 2: Handle assignment if provided
+ if (data.newAssignmentUserIds && data.newAssignmentUserIds.length > 0) {
+ const targetQueueId = queueId || queueResponse.id;
+
+ await createQueueAssignmentsMutation.mutateAsync({
+ projectId,
+ queueId: targetQueueId,
+ userIds: data.newAssignmentUserIds,
+ });
+ }
+
+ // Step 3: Success handling
+ await Promise.all([
+ utils.annotationQueues.invalidate(),
+ utils.annotationQueueAssignments.invalidate(),
+ ]);
+ form.reset();
+ setIsOpen(false);
+
+ // capture posthog event
+ } catch (error) {
+ showErrorToast(
+ "Operation failed",
+ "Failed to create or update queue or assign users. Please try again.",
+ );
}
};
@@ -183,7 +224,7 @@ export const CreateOrEditAnnotationQueueButton = ({
<PlusIcon className="h-4 w-4" aria-hidden="true" />
)
}
- hasAccess={hasAccess}
+ hasAccess={hasQueueAccess}
limitValue={queueCountData.data}
limit={queueLimit}
size={size}
@@ -258,6 +299,7 @@ export const CreateOrEditAnnotationQueueButton = ({
<MultiSelectKeyValues
placeholder="Value"
align="end"
+ variant="outline"
className="grid grid-cols-[auto,1fr,auto,auto] gap-2"
onValueChange={handleOnValueChange}
options={configs
@@ -299,14 +341,80 @@ export const CreateOrEditAnnotationQueueButton = ({
</FormItem>
)}
/>
+
+ {/* Advanced Section */}
+ <FormField
+ control={form.control}
+ name="newAssignmentUserIds"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Advanced Settings</FormLabel>
+ <div className="mt-1 rounded-md border">
+ <Collapsible
+ open={isAdvancedOpen && hasQueueAssignmentsReadAccess}
+ onOpenChange={(open) => {
+ if (!hasQueueAssignmentsReadAccess) {
+ setIsAdvancedOpen(false);
+ } else {
+ setIsAdvancedOpen(open);
+ }
+ }}
+ >
+ <CollapsibleTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ className="group flex w-full items-center justify-between px-3 py-2.5 text-left hover:bg-transparent"
+ >
+ <div className="flex items-center gap-2">
+ {isAdvancedOpen ? (
+ <ChevronDown className="h-4 w-4 text-muted-foreground" />
+ ) : (
+ <ChevronRight className="h-4 w-4 text-muted-foreground" />
+ )}
+ <span className="text-sm font-medium">
+ User Assignment
+ </span>
+ </div>
+ </Button>
+ </CollapsibleTrigger>
+ <CollapsibleContent className="border-t border-border/20 px-3 pb-3 pt-1">
+ {hasQueueAssignmentsReadAccess && (
+ <>
+ <FormControl>
+ <UserAssignmentSection
+ projectId={projectId}
+ queueId={queueId}
+ selectedUserIds={field.value}
+ onChange={field.onChange}
+ />
+ </FormControl>
+ <FormMessage />
+ </>
+ )}
+ </CollapsibleContent>
+ </Collapsible>
+ </div>
+ </FormItem>
+ )}
+ />
</DialogBody>
<DialogFooter>
<Button
type="submit"
className="text-xs"
- disabled={!!form.formState.errors.name}
+ disabled={
+ !!form.formState.errors.name ||
+ createQueueMutation.isLoading ||
+ editQueueMutation.isLoading ||
+ createQueueAssignmentsMutation.isLoading
+ }
>
- {queueId ? "Save" : "Create"} queue
+ {createQueueMutation.isLoading ||
+ editQueueMutation.isLoading ||
+ createQueueAssignmentsMutation.isLoading
+ ? "Processing..."
+ : `${queueId ? "Save" : "Create"} queue`}
</Button>
</DialogFooter>
</form>
diff --git a/web/src/features/annotation-queues/components/UserAssignmentSection.tsx b/web/src/features/annotation-queues/components/UserAssignmentSection.tsx
new file mode 100644
index 0000000000..0d214ffce3
--- /dev/null
+++ b/web/src/features/annotation-queues/components/UserAssignmentSection.tsx
@@ -0,0 +1,165 @@
+import { api } from "@/src/utils/api";
+import { MoreHorizontal, X } from "lucide-react";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { Button } from "@/src/components/ui/button";
+import { MultiSelectCombobox } from "@/src/components/ui/multi-select-combobox";
+import { useUserSearch } from "@/src/features/annotation-queues/hooks/useUserSearch";
+import { useSelectedUsers } from "@/src/features/annotation-queues/hooks/useSelectedUsers";
+
+interface UserAssignmentSectionProps {
+ projectId: string;
+ selectedUserIds: string[];
+ onChange: (userIds: string[]) => void;
+ queueId?: string;
+}
+
+export const UserAssignmentSection = ({
+ projectId,
+ selectedUserIds,
+ onChange,
+ queueId,
+}: UserAssignmentSectionProps) => {
+ const hasQueueAssignmentsReadAccess = useHasProjectAccess({
+ projectId: projectId,
+ scope: "annotationQueueAssignments:read",
+ });
+ const hasQueueAssignmentWriteAccess = useHasProjectAccess({
+ projectId: projectId,
+ scope: "annotationQueueAssignments:CUD",
+ });
+
+ // Get current assigned users
+ const queueAssignmentsQuery =
+ api.annotationQueueAssignments.byQueueId.useQuery(
+ { projectId, queueId: queueId as string },
+ { enabled: !!queueId && hasQueueAssignmentsReadAccess },
+ );
+
+ // Combine selected users and assigned users for exclusion
+ const assignedUserIds =
+ queueAssignmentsQuery.data?.assignments.map((user: any) => user.id) || [];
+ const excludeUserIds = [...new Set([...selectedUserIds, ...assignedUserIds])];
+
+ const userSearch = useUserSearch({
+ projectId,
+ excludeUserIds,
+ });
+
+ const { selectedUsers } = useSelectedUsers({
+ projectId,
+ selectedUserIds,
+ });
+
+ // Handle user selection changes
+ const handleUsersChange = (users: typeof userSearch.searchResults) => {
+ const userIds = users.map((user) => user.id);
+ onChange(userIds);
+ };
+
+ // Check if there are more assigned users than shown
+ const hasMoreAssignedUsers =
+ queueAssignmentsQuery.data &&
+ queueAssignmentsQuery.data.totalCount >
+ queueAssignmentsQuery.data.assignments.length;
+
+ return (
+ <div className="space-y-4">
+ {/* User Selection Combobox */}
+ <MultiSelectCombobox
+ selectedItems={selectedUsers}
+ onItemsChange={handleUsersChange}
+ searchQuery={userSearch.searchQuery}
+ onSearchChange={userSearch.setSearchQuery}
+ searchResults={userSearch.searchResults}
+ isLoading={userSearch.isLoading}
+ disabled={!hasQueueAssignmentWriteAccess}
+ placeholder="Search users to add..."
+ hasMoreResults={userSearch.hasMoreResults}
+ getItemKey={(user) => user.id}
+ renderSelectedItem={(user, onRemove) => (
+ <div className="flex flex-shrink-0 items-center gap-1 rounded-md bg-muted px-2 py-1 text-xs">
+ <span className="max-w-32 truncate">{user.name || user.email}</span>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-4 w-4 p-0 hover:bg-muted-foreground/20"
+ onClick={onRemove}
+ >
+ <X className="h-3 w-3" />
+ </Button>
+ </div>
+ )}
+ renderItem={(user, isSelected, onToggle) => (
+ <div
+ className="flex cursor-pointer items-center gap-3 px-3 py-2 transition-colors hover:bg-muted/50"
+ onClick={onToggle}
+ >
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-3">
+ <p className="truncate text-xs font-medium">
+ {user.name || "Unnamed User"}
+ </p>
+ <p className="truncate text-xs text-muted-foreground">
+ {user.email}
+ </p>
+ </div>
+ </div>
+ {isSelected && (
+ <div className="text-xs text-muted-foreground">✓</div>
+ )}
+ </div>
+ )}
+ />
+
+ {/* Assigned Users Section */}
+ {queueAssignmentsQuery.data &&
+ queueAssignmentsQuery.data?.totalCount > 0 && (
+ <div className="space-y-2">
+ <h4 className="text-sm text-muted-foreground">
+ Assigned to ({queueAssignmentsQuery.data?.totalCount})
+ </h4>
+ <div className="max-h-32 overflow-y-auto rounded-md border bg-background">
+ {queueAssignmentsQuery.data?.assignments.map(
+ (user: any, index: number) => (
+ <div key={user.id}>
+ <div className="flex items-center justify-between gap-3 px-3 py-2">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-3">
+ <p className="truncate text-xs font-medium">
+ {user.name || "Unnamed User"}
+ </p>
+ <p className="truncate text-xs text-muted-foreground">
+ {user.email}
+ </p>
+ </div>
+ </div>
+ {/* <Button variant="ghost" size="icon-sm">
+ <X className="h-3 w-3" />
+ </Button> */}
+ </div>
+ {(index <
+ queueAssignmentsQuery.data?.assignments.length - 1 ||
+ hasMoreAssignedUsers) && (
+ <div className="border-b border-border/50" />
+ )}
+ </div>
+ ),
+ )}
+ {hasMoreAssignedUsers && (
+ <div className="flex items-center gap-3 px-3 py-2 text-muted-foreground">
+ <MoreHorizontal className="h-4 w-4" />
+ <div className="min-w-0 flex-1">
+ <p className="text-xs italic">
+ {queueAssignmentsQuery.data.totalCount -
+ queueAssignmentsQuery.data.assignments.length}{" "}
+ more assigned users
+ </p>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/web/src/features/annotation-queues/hooks/useSelectedUsers.ts b/web/src/features/annotation-queues/hooks/useSelectedUsers.ts
new file mode 100644
index 0000000000..613dffd9fb
--- /dev/null
+++ b/web/src/features/annotation-queues/hooks/useSelectedUsers.ts
@@ -0,0 +1,37 @@
+import { api } from "@/src/utils/api";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+
+interface UseSelectedUsersProps {
+ projectId: string;
+ selectedUserIds: string[];
+}
+
+export function useSelectedUsers({
+ projectId,
+ selectedUserIds,
+}: UseSelectedUsersProps) {
+ const hasProjectMembersReadAccess = useHasProjectAccess({
+ projectId: projectId,
+ scope: "projectMembers:read",
+ });
+
+ // Get all users without search filter to maintain selected users data
+ const allUsersForPills = api.members.byProjectId.useQuery(
+ {
+ projectId,
+ },
+ {
+ enabled: hasProjectMembersReadAccess && selectedUserIds.length > 0,
+ },
+ );
+
+ const selectedUsers =
+ allUsersForPills.data?.users.filter((user) =>
+ selectedUserIds.includes(user.id),
+ ) || [];
+
+ return {
+ selectedUsers,
+ isLoading: allUsersForPills.isLoading,
+ };
+}
diff --git a/web/src/features/annotation-queues/hooks/useUserSearch.ts b/web/src/features/annotation-queues/hooks/useUserSearch.ts
new file mode 100644
index 0000000000..014278bc7c
--- /dev/null
+++ b/web/src/features/annotation-queues/hooks/useUserSearch.ts
@@ -0,0 +1,59 @@
+import { useState, useEffect } from "react";
+import { api } from "@/src/utils/api";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+
+interface UseUserSearchProps {
+ projectId: string;
+ excludeUserIds?: string[];
+}
+
+export function useUserSearch({
+ projectId,
+ excludeUserIds,
+}: UseUserSearchProps) {
+ const [searchQuery, setSearchQuery] = useState("");
+ const [debouncedSearchQuery, setDebouncedSearchQuery] = useState("");
+
+ const hasProjectMembersReadAccess = useHasProjectAccess({
+ projectId: projectId,
+ scope: "projectMembers:read",
+ });
+
+ // Debounce search query
+ useEffect(() => {
+ const timer = setTimeout(() => {
+ setDebouncedSearchQuery(searchQuery);
+ }, 300);
+
+ return () => clearTimeout(timer);
+ }, [searchQuery]);
+
+ // Get search results
+ const searchResults = api.members.byProjectId.useQuery(
+ {
+ projectId,
+ searchQuery: debouncedSearchQuery || undefined,
+ page: 0,
+ limit: 50,
+ excludeUserIds:
+ excludeUserIds && excludeUserIds.length > 0
+ ? excludeUserIds
+ : undefined,
+ },
+ {
+ enabled: hasProjectMembersReadAccess,
+ },
+ );
+
+ const hasMoreResults =
+ searchResults.data &&
+ searchResults.data.totalCount > searchResults.data.users.length;
+
+ return {
+ searchQuery,
+ setSearchQuery,
+ searchResults: searchResults.data?.users || [],
+ isLoading: searchResults.isLoading,
+ hasMoreResults: hasMoreResults || false,
+ };
+}
diff --git a/web/src/features/annotation-queues/server/annotationQueueAssignments.ts b/web/src/features/annotation-queues/server/annotationQueueAssignments.ts
new file mode 100644
index 0000000000..9b9693b694
--- /dev/null
+++ b/web/src/features/annotation-queues/server/annotationQueueAssignments.ts
@@ -0,0 +1,205 @@
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import { getUserProjectRoles } from "@/src/features/rbac/utils/userProjectRole";
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import {
+ LangfuseNotFoundError,
+ optionalPaginationZod,
+ Prisma,
+} from "@langfuse/shared";
+import { partition } from "lodash";
+import z from "zod/v4";
+
+export const queueAssignmentRouter = createTRPCRouter({
+ createMany: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ queueId: z.string(),
+ userIds: z.array(z.string()),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueueAssignments:CUD",
+ });
+
+ // Verify the annotation queue exists and belongs to the project
+ const queue = await ctx.prisma.annotationQueue.findUnique({
+ where: {
+ id: input.queueId,
+ projectId: input.projectId,
+ },
+ });
+
+ if (!queue) {
+ throw new LangfuseNotFoundError("Annotation queue not found");
+ }
+
+ // Verify the users exist and have access to the project
+ const users = await getUserProjectRoles({
+ projectId: input.projectId,
+ orgId: ctx.session.orgId,
+ filterCondition: [
+ {
+ column: "userId",
+ operator: "any of",
+ value: input.userIds,
+ type: "stringOptions",
+ },
+ ],
+ searchFilter: Prisma.empty,
+ orderBy: Prisma.empty,
+ });
+
+ // Create a Set of valid user IDs for efficient lookup
+ const validUserIdSet = new Set(users.map((u) => u.id));
+
+ // Partition the input user IDs into valid and invalid using lodash
+ const [validUserIds, invalidUserIds] = partition(
+ input.userIds,
+ (userId) => validUserIdSet.has(userId),
+ );
+
+ // Create assignments (using createMany with skipDuplicates)
+ await ctx.prisma.annotationQueueAssignment.createMany({
+ data: validUserIds.map((userId) => ({
+ userId,
+ projectId: input.projectId,
+ queueId: input.queueId,
+ })),
+ skipDuplicates: true,
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "annotationQueueAssignment",
+ resourceId: input.queueId,
+ action: "create",
+ after: { addedMemberCount: validUserIds.length },
+ });
+
+ return {
+ success: true,
+ addedCount: validUserIds.length,
+ skippedCount: invalidUserIds.length,
+ };
+ }),
+
+ delete: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ queueId: z.string(),
+ userId: z.string(),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueueAssignments:CUD",
+ });
+
+ // Verify the annotation queue exists and belongs to the project
+ const queue = await ctx.prisma.annotationQueue.findUnique({
+ where: {
+ id: input.queueId,
+ projectId: input.projectId,
+ },
+ });
+
+ if (!queue) {
+ throw new LangfuseNotFoundError("Annotation queue not found");
+ }
+
+ // Remove memberships
+ await ctx.prisma.annotationQueueAssignment.deleteMany({
+ where: {
+ projectId: input.projectId,
+ queueId: input.queueId,
+ userId: input.userId,
+ },
+ });
+
+ await auditLog({
+ session: ctx.session,
+ resourceType: "annotationQueueAssignment",
+ resourceId: input.queueId,
+ before: { ...input },
+ action: "delete",
+ });
+
+ return {
+ success: true,
+ };
+ }),
+
+ byQueueId: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ queueId: z.string(),
+ ...optionalPaginationZod,
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "annotationQueueAssignments:read",
+ });
+
+ // Verify the annotation queue exists and belongs to the project
+ const queue = await ctx.prisma.annotationQueue.findUnique({
+ where: {
+ id: input.queueId,
+ projectId: input.projectId,
+ },
+ });
+
+ if (!queue) {
+ throw new LangfuseNotFoundError("Annotation queue not found");
+ }
+
+ const assignments = await ctx.prisma.annotationQueueAssignment.findMany({
+ where: {
+ projectId: input.projectId,
+ queueId: input.queueId,
+ },
+ include: {
+ user: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
+ },
+ },
+ },
+ orderBy: [{ createdAt: "desc" }],
+ take: input.limit ?? undefined,
+ skip: input.page ? input.page * (input.limit ?? 0) : undefined,
+ });
+
+ const totalCount = await ctx.prisma.annotationQueueAssignment.count({
+ where: {
+ projectId: input.projectId,
+ queueId: input.queueId,
+ },
+ });
+
+ return {
+ assignments: assignments.map((assignment) => ({
+ id: assignment.user.id,
+ name: assignment.user.name,
+ email: assignment.user.email,
+ })),
+ totalCount,
+ };
+ }),
+});
diff --git a/web/src/features/annotation-queues/server/annotationQueues.ts b/web/src/features/annotation-queues/server/annotationQueues.ts
index 85504cbbfb..4502828d60 100644
--- a/web/src/features/annotation-queues/server/annotationQueues.ts
+++ b/web/src/features/annotation-queues/server/annotationQueues.ts
@@ -106,6 +106,16 @@ export const queueRouter = createTRPCRouter({
}),
]);
+ const userQueueAssignments =
+ await ctx.prisma.annotationQueueAssignment.findMany({
+ where: {
+ userId: ctx.session.user.id,
+ },
+ select: {
+ queueId: true,
+ },
+ });
+
return {
totalCount,
queues: queues.map((queue) => ({
@@ -113,6 +123,9 @@ export const queueRouter = createTRPCRouter({
scoreConfigs: scoreConfigs.filter((config) =>
queue.scoreConfigIds.includes(config.id),
),
+ isCurrentUserAssigned: userQueueAssignments.some(
+ (assignment) => assignment.queueId === queue.id,
+ ),
})),
};
} catch (error) {
diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.ts
index 3af4e8e919..a1626d88c2 100644
--- a/web/src/features/audit-logs/auditLog.ts
+++ b/web/src/features/audit-logs/auditLog.ts
@@ -7,6 +7,7 @@ import {
export type AuditableResource =
| "annotationQueue"
| "annotationQueueItem"
+ | "annotationQueueAssignment"
| "organization"
| "orgMembership"
| "projectMembership"
diff --git a/web/src/features/public-api/types/annotation-queues.ts b/web/src/features/public-api/types/annotation-queues.ts
index 0f9e934d4e..3a5b7b5151 100644
--- a/web/src/features/public-api/types/annotation-queues.ts
+++ b/web/src/features/public-api/types/annotation-queues.ts
@@ -129,3 +129,41 @@ export const DeleteAnnotationQueueItemResponse = z
message: z.string(),
})
.strict();
+
+// Assignment endpoints
+export const AnnotationQueueAssignmentSchema = z
+ .object({
+ userId: z.string(),
+ projectId: z.string(),
+ queueId: z.string(),
+ })
+ .strict();
+
+export const AnnotationQueueAssignmentQuery = z
+ .object({
+ queueId: z.string(),
+ })
+ .strict();
+
+// POST /annotation-queues/:queueId/assignments
+export const CreateAnnotationQueueAssignmentBody = z
+ .object({
+ userId: z.string(),
+ })
+ .strict();
+
+export const CreateAnnotationQueueAssignmentResponse =
+ AnnotationQueueAssignmentSchema;
+
+// DELETE /annotation-queues/:queueId/assignments
+export const DeleteAnnotationQueueAssignmentBody = z
+ .object({
+ userId: z.string(),
+ })
+ .strict();
+
+export const DeleteAnnotationQueueAssignmentResponse = z
+ .object({
+ success: z.boolean(),
+ })
+ .strict();
diff --git a/web/src/features/rbac/constants/projectAccessRights.ts b/web/src/features/rbac/constants/projectAccessRights.ts
index bb3ec553b9..00e4b1ac2c 100644
--- a/web/src/features/rbac/constants/projectAccessRights.ts
+++ b/web/src/features/rbac/constants/projectAccessRights.ts
@@ -20,6 +20,8 @@ const projectScopes = [
"annotationQueues:read",
"annotationQueues:CUD",
+ "annotationQueueAssignments:read",
+ "annotationQueueAssignments:CUD",
"project:read",
"project:update",
@@ -121,6 +123,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"comments:read",
"annotationQueues:read",
"annotationQueues:CUD",
+ "annotationQueueAssignments:read",
+ "annotationQueueAssignments:CUD",
"promptExperiments:CUD",
"promptExperiments:read",
"auditLogs:read",
@@ -172,6 +176,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"comments:read",
"annotationQueues:read",
"annotationQueues:CUD",
+ "annotationQueueAssignments:read",
+ "annotationQueueAssignments:CUD",
"promptExperiments:CUD",
"promptExperiments:read",
"auditLogs:read",
@@ -211,6 +217,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {
"comments:read",
"annotationQueues:read",
"annotationQueues:CUD",
+ "annotationQueueAssignments:read",
"promptExperiments:CUD",
"promptExperiments:read",
"dashboards:read",
diff --git a/web/src/features/rbac/server/membersRouter.ts b/web/src/features/rbac/server/membersRouter.ts
index 8cb28ebe31..078de0b03b 100644
--- a/web/src/features/rbac/server/membersRouter.ts
+++ b/web/src/features/rbac/server/membersRouter.ts
@@ -2,6 +2,7 @@ import { auditLog } from "@/src/features/audit-logs/auditLog";
import {
createTRPCRouter,
protectedOrganizationProcedure,
+ protectedProjectProcedure,
} from "@/src/server/api/trpc";
import { TRPCError } from "@trpc/server";
import * as z from "zod/v4";
@@ -9,7 +10,13 @@ import {
hasOrganizationAccess,
throwIfNoOrganizationAccess,
} from "@/src/features/rbac/utils/checkOrganizationAccess";
-import { Prisma, type PrismaClient, Role } from "@langfuse/shared";
+import {
+ type FilterState,
+ optionalPaginationZod,
+ Prisma,
+ 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";
@@ -20,6 +27,26 @@ import {
import { allMembersRoutes } from "@/src/features/rbac/server/allMembersRoutes";
import { allInvitesRoutes } from "@/src/features/rbac/server/allInvitesRoutes";
import { orderedRoles } from "@/src/features/rbac/constants/orderedRoles";
+import {
+ getUserProjectRoles,
+ getUserProjectRolesCount,
+} from "@/src/features/rbac/utils/userProjectRole";
+
+function buildUserSearchFilter(searchQuery: string | undefined | null) {
+ if (searchQuery === undefined || searchQuery === null || searchQuery === "") {
+ return Prisma.empty;
+ }
+
+ const q = searchQuery;
+ const searchConditions: Prisma.Sql[] = [];
+
+ searchConditions.push(Prisma.sql`u.name ILIKE ${`%${q}%`}`);
+ searchConditions.push(Prisma.sql`u.email ILIKE ${`%${q}%`}`);
+
+ return searchConditions.length > 0
+ ? Prisma.sql` AND (${Prisma.join(searchConditions, " OR ")})`
+ : Prisma.empty;
+}
// Record as it allows to type check that all roles are included
function throwIfHigherRole({ ownRole, role }: { ownRole: Role; role: Role }) {
@@ -665,4 +692,55 @@ export const membersRouter = createTRPCRouter({
return updatedProjectMembership;
}),
+ byProjectId: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ searchQuery: z.string().optional(),
+ excludeUserIds: z.array(z.string()).optional(),
+ ...optionalPaginationZod,
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ const searchFilter = buildUserSearchFilter(input.searchQuery);
+
+ const filterCondition: FilterState =
+ input.excludeUserIds && input.excludeUserIds.length > 0
+ ? [
+ {
+ column: "userId",
+ operator: "none of",
+ value: input.excludeUserIds,
+ type: "stringOptions",
+ },
+ ]
+ : [];
+
+ const [users, totalCount] = await Promise.all([
+ getUserProjectRoles({
+ projectId: input.projectId,
+ orgId: ctx.session.orgId,
+ searchFilter: searchFilter,
+ filterCondition,
+ limit: input.limit,
+ page: input.page,
+ orderBy: Prisma.sql`ORDER BY all_eligible_users.name ASC NULLS LAST, all_eligible_users.email ASC NULLS LAST`,
+ }),
+ getUserProjectRolesCount({
+ projectId: input.projectId,
+ orgId: ctx.session.orgId,
+ searchFilter: searchFilter,
+ filterCondition,
+ }),
+ ]);
+
+ return {
+ users: users.map((user) => ({
+ id: user.id,
+ name: user.name,
+ email: user.email,
+ })),
+ totalCount,
+ };
+ }),
});
diff --git a/web/src/features/rbac/utils/userProjectRole.ts b/web/src/features/rbac/utils/userProjectRole.ts
new file mode 100644
index 0000000000..e4e7809b12
--- /dev/null
+++ b/web/src/features/rbac/utils/userProjectRole.ts
@@ -0,0 +1,155 @@
+import { usersTableCols } from "@/src/server/api/definitions/usersTable";
+import { type FilterState, Prisma, type Role } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { tableColumnsToSqlFilterAndPrefix } from "@langfuse/shared/src/server";
+
+export function resolveProjectRole({
+ projectId,
+ orgMembership,
+}: {
+ projectId: string;
+ orgMembership: any;
+}) {
+ return (
+ orgMembership.ProjectMemberships.find(
+ (membership: any) => membership.projectId === projectId,
+ )?.role ?? orgMembership.role
+ );
+}
+
+/**
+ * Generates a SQL query to fetch users with their project roles, respecting role hierarchy.
+ *
+ * ROLE HIERARCHY (from highest to lowest permissions):
+ * 1. OWNER - Full org and project access
+ * 2. ADMIN - Project admin access
+ * 3. MEMBER - Project member access
+ * 4. VIEWER - Read-only project access
+ * 5. NONE - No access (excluded from results)
+ *
+ * PRIORITY SYSTEM:
+ * - Priority 1: Organization members without specific project roles (inherit org role)
+ * - Priority 2: Users with explicit project roles (overrides org role)
+ *
+ * ROLE RESOLUTION:
+ * - If user has explicit project role: use project role
+ * - If user has no project role: inherit organization role
+ * - Users with NONE role at either level are excluded
+ *
+ * @param params Query parameters
+ * @returns Prisma SQL query for user project roles
+ */
+function generateUserProjectRolesQuery({
+ select,
+ projectId,
+ orgId,
+ searchFilter = Prisma.empty,
+ filterCondition,
+ limit,
+ page,
+ orderBy,
+}: {
+ select: Prisma.Sql;
+ projectId: string;
+ orgId: string;
+ filterCondition: FilterState;
+ searchFilter: Prisma.Sql;
+ limit?: number;
+ page?: number;
+ orderBy: Prisma.Sql;
+}) {
+ const sqlFilter = filterCondition
+ ? tableColumnsToSqlFilterAndPrefix(filterCondition, usersTableCols, "users")
+ : Prisma.empty;
+
+ return Prisma.sql`
+ WITH all_eligible_users AS (
+ SELECT u.id, u.name, u.email, om.role as role
+ FROM organization_memberships om
+ INNER JOIN users u ON om.user_id = u.id
+ WHERE om.org_id = ${orgId}
+ AND om.role != 'NONE'
+ AND NOT EXISTS (
+ SELECT 1 FROM project_memberships pm
+ WHERE pm.org_membership_id = om.id
+ )
+ ${sqlFilter}
+ ${searchFilter}
+ UNION
+ SELECT u.id, u.name, u.email, pm.role as role
+ FROM organization_memberships om
+ INNER JOIN project_memberships pm ON om.id = pm.org_membership_id
+ INNER JOIN users u ON om.user_id = u.id
+ WHERE om.org_id = ${orgId}
+ AND pm.project_id = ${projectId}
+ AND pm.role != 'NONE'
+ ${sqlFilter}
+ ${searchFilter}
+ )
+ SELECT ${select}
+ FROM all_eligible_users
+ ${orderBy}
+ ${limit ? Prisma.sql`LIMIT ${limit}` : Prisma.empty}
+ ${page && limit ? Prisma.sql`OFFSET ${page * limit}` : Prisma.empty}
+ `;
+}
+
+export const getUserProjectRoles = async ({
+ projectId,
+ orgId,
+ searchFilter = Prisma.empty,
+ filterCondition,
+ limit,
+ page,
+ orderBy,
+}: {
+ projectId: string;
+ orgId: string;
+ filterCondition: FilterState;
+ searchFilter: Prisma.Sql;
+ limit?: number;
+ page?: number;
+ orderBy: Prisma.Sql;
+}) => {
+ return await prisma.$queryRaw<
+ Array<{ id: string; name: string; email: string; role: Role }>
+ >(
+ generateUserProjectRolesQuery({
+ select: Prisma.sql`all_eligible_users.id, all_eligible_users.name, all_eligible_users.email, all_eligible_users.role`,
+ projectId,
+ orgId,
+ filterCondition,
+ searchFilter,
+ limit,
+ page,
+ orderBy,
+ }),
+ );
+};
+
+export const getUserProjectRolesCount = async ({
+ projectId,
+ orgId,
+ searchFilter = Prisma.empty,
+ filterCondition,
+}: {
+ projectId: string;
+ orgId: string;
+ filterCondition: FilterState;
+ searchFilter: Prisma.Sql;
+}) => {
+ const count = await prisma.$queryRaw<Array<{ count: bigint }>>(
+ generateUserProjectRolesQuery({
+ select: Prisma.sql`COUNT(*) AS count`,
+ projectId,
+ orgId,
+ filterCondition,
+ searchFilter,
+ limit: 1,
+ page: 0,
+ orderBy: Prisma.empty,
+ }),
+ );
+
+ return count.length > 0 ? Number(count[0]?.count) : 0;
+};
diff --git a/web/src/pages/api/public/annotation-queues/[queueId]/assignments.ts b/web/src/pages/api/public/annotation-queues/[queueId]/assignments.ts
new file mode 100644
index 0000000000..75684b7bd3
--- /dev/null
+++ b/web/src/pages/api/public/annotation-queues/[queueId]/assignments.ts
@@ -0,0 +1,133 @@
+import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";
+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
+import { prisma } from "@langfuse/shared/src/db";
+import { LangfuseNotFoundError, Prisma } from "@langfuse/shared";
+import {
+ AnnotationQueueAssignmentQuery,
+ CreateAnnotationQueueAssignmentBody,
+ CreateAnnotationQueueAssignmentResponse,
+ DeleteAnnotationQueueAssignmentBody,
+ DeleteAnnotationQueueAssignmentResponse,
+} from "@/src/features/public-api/types/annotation-queues";
+import { getUserProjectRoles } from "@/src/features/rbac/utils/userProjectRole";
+
+export default withMiddlewares({
+ POST: createAuthedProjectAPIRoute({
+ name: "Create Annotation Queue Assignment",
+ bodySchema: CreateAnnotationQueueAssignmentBody,
+ querySchema: AnnotationQueueAssignmentQuery,
+ responseSchema: CreateAnnotationQueueAssignmentResponse,
+ fn: async ({ query, body, auth }) => {
+ const { userId } = body;
+
+ // Verify the annotation queue exists and belongs to the project
+ const queue = await prisma.annotationQueue.findUnique({
+ where: {
+ id: query.queueId,
+ projectId: auth.scope.projectId,
+ },
+ });
+
+ if (!queue) {
+ throw new LangfuseNotFoundError("Annotation queue not found");
+ }
+
+ // Verify the user exists and has access to the project
+ const user = await getUserProjectRoles({
+ projectId: auth.scope.projectId,
+ orgId: auth.scope.orgId,
+ filterCondition: [
+ {
+ column: "userId",
+ operator: "any of",
+ value: [userId],
+ type: "stringOptions",
+ },
+ ],
+ searchFilter: Prisma.empty,
+ limit: 1,
+ page: 0,
+ orderBy: Prisma.empty,
+ });
+
+ if (!user || user.length === 0) {
+ throw new LangfuseNotFoundError(
+ "User not found or not authorized for this project",
+ );
+ }
+
+ // Create the assignment (upsert to handle duplicates gracefully)
+ await prisma.annotationQueueAssignment.upsert({
+ where: {
+ projectId_queueId_userId: {
+ projectId: auth.scope.projectId,
+ queueId: query.queueId,
+ userId,
+ },
+ },
+ create: {
+ userId,
+ projectId: auth.scope.projectId,
+ queueId: query.queueId,
+ },
+ update: {},
+ });
+
+ return {
+ userId: userId,
+ projectId: auth.scope.projectId,
+ queueId: query.queueId,
+ };
+ },
+ }),
+
+ DELETE: createAuthedProjectAPIRoute({
+ name: "Delete Annotation Queue Assignment",
+ querySchema: AnnotationQueueAssignmentQuery,
+ bodySchema: DeleteAnnotationQueueAssignmentBody,
+ responseSchema: DeleteAnnotationQueueAssignmentResponse,
+ fn: async ({ query, body, auth }) => {
+ const { userId } = body;
+
+ // Verify the annotation queue exists and belongs to the project
+ const queue = await prisma.annotationQueue.findUnique({
+ where: {
+ id: query.queueId,
+ projectId: auth.scope.projectId,
+ },
+ });
+
+ if (!queue) {
+ throw new LangfuseNotFoundError("Annotation queue not found");
+ }
+
+ // Delete the assignment if it exists
+ try {
+ await prisma.annotationQueueAssignment.delete({
+ where: {
+ projectId_queueId_userId: {
+ projectId: auth.scope.projectId,
+ queueId: query.queueId,
+ userId,
+ },
+ },
+ });
+ } catch (error) {
+ // If the record doesn't exist, that's fine - we still return success
+ // Only catch NotFound errors, re-throw other errors
+ if (
+ error &&
+ typeof error === "object" &&
+ "code" in error &&
+ error.code !== "P2025"
+ ) {
+ throw error;
+ }
+ }
+
+ return {
+ success: true,
+ };
+ },
+ }),
+});
diff --git a/web/src/server/api/definitions/usersTable.ts b/web/src/server/api/definitions/usersTable.ts
index 160a5f7f88..91105bf595 100644
--- a/web/src/server/api/definitions/usersTable.ts
+++ b/web/src/server/api/definitions/usersTable.ts
@@ -7,4 +7,11 @@ export const usersTableCols: ColumnDefinition[] = [
type: "datetime",
internal: 't."timestamp"',
},
+ {
+ name: "User ID",
+ id: "userId",
+ type: "stringOptions",
+ options: [],
+ internal: 'u."id"',
+ },
];
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index c2d61932ad..864e32ed0e 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -42,6 +42,7 @@ import { automationsRouter } from "@/src/features/automations/server/router";
import { defaultEvalModelRouter } from "@/src/features/evals/server/defaultEvalModelRouter";
import { plainRouter } from "@/src/features/support-chat/trpc/plain";
import { slackRouter } from "@/src/features/slack/server/router";
+import { queueAssignmentRouter } from "@/src/features/annotation-queues/server/annotationQueueAssignments";
/**
* This is the primary router for your server.
@@ -51,6 +52,7 @@ import { slackRouter } from "@/src/features/slack/server/router";
export const appRouter = createTRPCRouter({
annotationQueues: queueRouter,
annotationQueueItems: queueItemRouter,
+ annotationQueueAssignments: queueAssignmentRouter,
batchExport: batchExportRouter,
traces: traceRouter,
sessions: sessionRouter,
diff --git a/web/src/server/auth.ts b/web/src/server/auth.ts
index 8ed60a231b..d85f9d6e1a 100644
--- a/web/src/server/auth.ts
+++ b/web/src/server/auth.ts
@@ -55,6 +55,7 @@ import { projectRoleAccessRights } from "@/src/features/rbac/constants/projectAc
import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";
import { getSSOBlockedDomains } from "@/src/features/auth-credentials/server/signupApiHandler";
import { createSupportEmailHash } from "@/src/features/support-chat/createSupportEmailHash";
+import { resolveProjectRole } from "@/src/features/rbac/utils/userProjectRole";
function canCreateOrganizations(userEmail: string | null): boolean {
const instancePlan = getSelfHostedInstancePlanServerSide();
@@ -540,11 +541,10 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {
cloudConfig: parsedCloudConfig.data,
projects: orgMembership.organization.projects
.map((project) => {
- const projectRole: Role =
- orgMembership.ProjectMemberships.find(
- (membership) =>
- membership.projectId === project.id,
- )?.role ?? orgMembership.role;
+ const projectRole: Role = resolveProjectRole({
+ projectId: project.id,
+ orgMembership,
+ });
return {
id: project.id,
name: project.name,