🪢 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(annotation): support annotation on sessions (#8130)
marliessophie825f030e813b
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsxindex 8e09ec0fe5..6c11e6d95a 100644--- a/web/src/components/session/index.tsx+++ b/web/src/components/session/index.tsx@@ -25,7 +25,8 @@ import {} from "@/src/components/ui/popover";import { ScrollArea } from "@/src/components/ui/scroll-area";import { Label } from "@/src/components/ui/label";-import { type APIScoreV2 } from "@langfuse/shared";+import { AnnotationQueueObjectType, type APIScoreV2 } from "@langfuse/shared";+import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";// some projects have thousands of traces in a sessions, paginate to avoid rendering all at onceconst PAGE_SIZE = 50;@@ -247,17 +248,26 @@ export const SessionPage: React.FC<{objectType="SESSION"count={sessionCommentCounts.data?.get(sessionId)}/>- <AnnotateDrawer- projectId={projectId}- scoreTarget={{- type: "session",- sessionId,- }}- scores={session.data?.scores ?? []}- emptySelectedConfigIds={emptySelectedConfigIds}- setEmptySelectedConfigIds={setEmptySelectedConfigIds}- buttonVariant="outline"- />+ <div className="flex items-start">+ <AnnotateDrawer+ projectId={projectId}+ scoreTarget={{+ type: "session",+ sessionId,+ }}+ scores={session.data?.scores ?? []}+ emptySelectedConfigIds={emptySelectedConfigIds}+ setEmptySelectedConfigIds={setEmptySelectedConfigIds}+ buttonVariant="outline"+ hasGroupedButton={true}+ />+ <CreateNewAnnotationQueueItem+ projectId={projectId}+ objectId={sessionId}+ objectType={AnnotationQueueObjectType.SESSION}+ variant="outline"+ />+ </div></>),}}@@ -341,7 +351,7 @@ export const SessionPage: React.FC<{);};-const SessionIO = ({+export const SessionIO = ({traceId,projectId,timestamp,diff --git a/web/src/features/annotation-queues/components/AnnotationQueueItemPage.tsx b/web/src/features/annotation-queues/components/AnnotationQueueItemPage.tsxindex 9c897842f4..6b7801b86c 100644--- a/web/src/features/annotation-queues/components/AnnotationQueueItemPage.tsx+++ b/web/src/features/annotation-queues/components/AnnotationQueueItemPage.tsx@@ -1,236 +1,21 @@-import { Trace } from "@/src/components/trace";-import { ObservationPreview } from "@/src/components/trace/ObservationPreview";-import { TracePreview } from "@/src/components/trace/TracePreview";-import {- Accordion,- AccordionContent,- AccordionItem,- AccordionTrigger,-} from "@/src/components/ui/accordion";-import { Button } from "@/src/components/ui/button";import { Card } from "@/src/components/ui/card";-import {- ResizableHandle,- ResizablePanel,- ResizablePanelGroup,-} from "@/src/components/ui/resizable";import { Skeleton } from "@/src/components/ui/skeleton";-import useSessionStorage from "@/src/components/useSessionStorage";-import { CommentList } from "@/src/features/comments/CommentList";import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";-import { AnnotateDrawerContent } from "@/src/features/scores/components/AnnotateDrawerContent";import { api } from "@/src/utils/api";import { type RouterOutput } from "@/src/utils/types";import {- type AnnotationQueueItem,- AnnotationQueueObjectType,AnnotationQueueStatus,- isPresent,- type ValidatedScoreConfig,+ AnnotationQueueObjectType,} from "@langfuse/shared";-import {- ArrowLeft,- ArrowRight,- SearchXIcon,- TriangleAlertIcon,-} from "lucide-react";-import { useSession } from "next-auth/react";+import { ArrowLeft, ArrowRight, SearchXIcon } from "lucide-react";import { useRouter } from "next/router";import { useEffect, useMemo, useState } from "react";-import { StringParam, useQueryParam } from "use-query-params";--const AnnotateIOView = ({- item,- configs,- view,-}: {- item: AnnotationQueueItem & {- parentTraceId?: string | null;- lockedByUser: { name: string | null | undefined } | null;- };- configs: ValidatedScoreConfig[];- view: "showTree" | "hideTree";-}) => {- const router = useRouter();- const session = useSession();- const traceId = item.parentTraceId ?? item.objectId;- const projectId = router.query.projectId as string;- const [showSaving, setShowSaving] = useState(false);- const [showComments, setShowComments] = useSessionStorage(- `annotationQueueShowComments-${projectId}`,- false,- );- const [panelSize, setPanelSize] = useSessionStorage(- `annotationQueuePanelSize-${projectId}`,- 65,- );-- const [currentObservationId, setCurrentObservationId] = useQueryParam(- "observation",- StringParam,- );- useEffect(() => {- if (- view === "showTree" &&- item.objectType === AnnotationQueueObjectType.OBSERVATION- ) {- setCurrentObservationId(item.objectId);- } else setCurrentObservationId(undefined);- }, [view, item, setCurrentObservationId]);-- const isLockedByOtherUser = item.lockedByUserId !== session.data?.user?.id;-- const trace = api.traces.byIdWithObservationsAndScores.useQuery(- { traceId, projectId },- {- retry(failureCount, error) {- if (error.data?.code === "UNAUTHORIZED") return false;- return failureCount < 3;- },- },- );-- const emptySelectedConfigIds = useMemo(() => {- return configs.map((c) => c.id);- }, [configs]);-- if (trace.isLoading || !trace.data)- return <div className="p-3">Loading...</div>;-- let isValidObservationId = false;-- if (- currentObservationId &&- trace.data.observations.some(({ id }) => id === currentObservationId)- ) {- isValidObservationId = true;- }-- return (- <ResizablePanelGroup- direction="horizontal"- className="h-full overflow-hidden"- onLayout={(sizes) => {- setPanelSize(sizes[0]);- }}- >- <ResizablePanel- className="col-span-1 h-full !overflow-y-auto rounded-md border"- minSize={30}- defaultSize={panelSize}- >- {view === "hideTree" ? (- <div className="max-h-full min-h-0 overflow-y-auto pl-4">- {item.objectType === AnnotationQueueObjectType.TRACE ? (- <TracePreview- key={trace.data.id}- trace={trace.data}- scores={trace.data.scores}- observations={trace.data.observations}- viewType="focused"- />- ) : (- <ObservationPreview- observations={trace.data.observations}- scores={trace.data.scores}- projectId={item.projectId}- currentObservationId={item.objectId}- traceId={traceId}- viewType="focused"- />- )}- </div>- ) : (- <div className="max-h-full min-h-0 overflow-y-auto">- <Trace- key={trace.data.id}- trace={trace.data}- scores={trace.data.scores}- projectId={trace.data.projectId}- observations={trace.data.observations}- viewType="focused"- isValidObservationId={isValidObservationId}- />- </div>- )}- </ResizablePanel>- <ResizableHandle withHandle className="ml-4 bg-transparent" />- <ResizablePanel- className="col-span-1 h-full md:flex md:flex-col md:overflow-hidden"- minSize={30}- >- <Card className="col-span-2 flex h-full flex-col overflow-hidden">- <div className="grid h-full w-full grid-cols-1 grid-rows-[minmax(auto,1fr),minmax(min-content,auto)] justify-between">- <div className="w-full overflow-auto">- <AnnotateDrawerContent- key={"annotation-drawer-content" + item.objectId}- scoreTarget={{- type: "trace",- traceId: traceId,- observationId: item.parentTraceId ? item.objectId : undefined,- }}- scores={trace.data?.scores ?? []}- configs={configs}- emptySelectedConfigIds={emptySelectedConfigIds}- setEmptySelectedConfigIds={() => {}}- projectId={item.projectId}- analyticsData={{- type: "trace",- source: "AnnotationQueue",- }}- isSelectHidden- queueId={item.queueId}- showSaving={showSaving}- setShowSaving={setShowSaving}- environment={trace.data?.environment}- actionButtons={- isLockedByOtherUser && isPresent(item.lockedByUser?.name) ? (- <div className="flex items-center justify-center rounded-sm border border-dark-red bg-light-red p-1">- <TriangleAlertIcon className="mr-1 h-4 w-4 text-dark-red" />- <span className="text-xs text-dark-red">- Currently edited by {item.lockedByUser.name}- </span>- </div>- ) : undefined- }- isDrawerOpen={true}- />- </div>- <div className="relative max-h-64 overflow-auto">- <Accordion- type="single"- collapsible- className="mx-4 mt-4"- value={showComments ? "item-1" : ""}- onValueChange={(value) => setShowComments(value === "item-1")}- >- <AccordionItem value="item-1" className="border-none">- <div className="sticky top-0 z-10 border-b bg-background">- <AccordionTrigger- onClick={() => setShowComments(!showComments)}- >- Comments- </AccordionTrigger>- </div>- <AccordionContent>- <CommentList- projectId={item.projectId}- objectId={item.objectId}- objectType={item.objectType}- className="rounded-t-none border-t-transparent"- cardView- />- </AccordionContent>- </AccordionItem>- </Accordion>- </div>- </div>- </Card>- </ResizablePanel>- </ResizablePanelGroup>- );-};+import { Button } from "@/src/components/ui/button";+import { useAnnotationQueueData } from "./shared/hooks/useAnnotationQueueData";+import { useAnnotationObjectData } from "./shared/hooks/useAnnotationObjectData";+import { TraceAnnotationProcessor } from "./processors/TraceAnnotationProcessor";+import { SessionAnnotationProcessor } from "./processors/SessionAnnotationProcessor";export const AnnotationQueueItemPage: React.FC<{annotationQueueId: string;@@ -250,6 +35,7 @@ export const AnnotationQueueItemPage: React.FC<{projectId,scope: "annotationQueues:CUD",});+const itemId = isSingleItem ? queryItemId : seenItemIds[progressIndex];const seenItemData = api.annotationQueueItems.byId.useQuery(@@ -260,6 +46,7 @@ export const AnnotationQueueItemPage: React.FC<{const fetchAndLockNextMutation =api.annotationQueues.fetchAndLockNext.useMutation();+ // EffectsuseEffect(() => {async function fetchNextItem() {if (!itemId && !isSingleItem) {@@ -274,18 +61,7 @@ export const AnnotationQueueItemPage: React.FC<{fetchNextItem();// eslint-disable-next-line react-hooks/exhaustive-deps}, []);-- const queueData = api.annotationQueues.byId.useQuery(- {- queueId: annotationQueueId,- projectId,- },- {- refetchOnMount: false,- refetchOnWindowFocus: false,- refetchOnReconnect: false,- },- );+ const { configs } = useAnnotationQueueData({ annotationQueueId, projectId });const unseenPendingItemCount =api.annotationQueueItems.unseenPendingItemCountByQueueId.useQuery(@@ -328,8 +104,6 @@ export const AnnotationQueueItemPage: React.FC<{return seenItemIds.length + (unseenPendingItemCount.data ?? 0);}, [unseenPendingItemCount.data, seenItemIds.length]);- const configs = queueData.data?.scoreConfigs ?? [];-const relevantItem = useMemo(() => {if (isSingleItem) return seenItemData.data;else@@ -344,6 +118,8 @@ export const AnnotationQueueItemPage: React.FC<{isSingleItem,]);+ const objectData = useAnnotationObjectData(relevantItem ?? null, projectId);+useEffect(() => {if (relevantItem && router.query.itemId !== relevantItem.id) {router.push(@@ -369,7 +145,8 @@ export const AnnotationQueueItemPage: React.FC<{if ((seenItemData.isLoading && itemId) ||(fetchAndLockNextMutation.isLoading && !itemId) ||- unseenPendingItemCount.isLoading+ unseenPendingItemCount.isLoading ||+ objectData.isLoading) {return <Skeleton className="h-full w-full" />;}@@ -380,11 +157,33 @@ export const AnnotationQueueItemPage: React.FC<{const isNextItemAvailable = totalItems > progressIndex + 1;- return (- <div className="grid h-full grid-rows-[1fr,auto] gap-4 overflow-hidden">- {relevantItem ? (- <AnnotateIOView item={relevantItem} configs={configs} view={view} />- ) : (+ const handleNavigateBack = () => {+ setProgressIndex(progressIndex - 1);+ };++ const handleNavigateNext = async () => {+ if (progressIndex >= seenItemIds.length - 1) {+ const nextItem = await fetchAndLockNextMutation.mutateAsync({+ queueId: annotationQueueId,+ projectId,+ seenItemIds,+ });+ setNextItemData(nextItem);+ }+ setProgressIndex(Math.max(progressIndex + 1, 0));+ };++ const handleComplete = async () => {+ if (!relevantItem) return;+ await completeMutation.mutateAsync({+ itemId: relevantItem.id,+ projectId,+ });+ };++ const renderContent = () => {+ if (!relevantItem) {+ return (<Card className="flex h-full w-full flex-col items-center justify-center overflow-hidden"><SearchXIcon className="mb-2 h-8 w-8 text-muted-foreground" /><span className="max-w-96 text-wrap text-sm text-muted-foreground">@@ -393,7 +192,38 @@ export const AnnotationQueueItemPage: React.FC<{unaffected by this action.</span></Card>- )}+ );+ }++ switch (relevantItem.objectType) {+ case AnnotationQueueObjectType.TRACE:+ case AnnotationQueueObjectType.OBSERVATION:+ return (+ <TraceAnnotationProcessor+ item={relevantItem}+ data={objectData.data}+ view={view}+ configs={configs}+ projectId={projectId}+ />+ );+ case AnnotationQueueObjectType.SESSION:+ return (+ <SessionAnnotationProcessor+ item={relevantItem}+ data={objectData.data}+ configs={configs}+ projectId={projectId}+ />+ );+ default:+ throw new Error(`Unsupported object type: ${relevantItem.objectType}`);+ }+ };++ return (+ <div className="grid h-full grid-rows-[1fr,auto] gap-4 overflow-hidden">+ {renderContent()}<div className="grid h-full w-full grid-cols-1 justify-end gap-2 sm:grid-cols-[auto,min-content]">{!isSingleItem && (<div className="flex max-h-10 flex-row gap-2">@@ -401,9 +231,7 @@ export const AnnotationQueueItemPage: React.FC<{{progressIndex + 1} / {totalItems}</span><Button- onClick={() => {- setProgressIndex(progressIndex - 1);- }}+ onClick={handleNavigateBack}variant="outline"disabled={progressIndex === 0 || !hasAccess}size="lg"@@ -417,18 +245,8 @@ export const AnnotationQueueItemPage: React.FC<{<div className="flex w-full min-w-[265px] justify-end gap-2">{!isSingleItem && (<Button- onClick={async () => {- if (progressIndex >= seenItemIds.length - 1) {- const nextItem = await fetchAndLockNextMutation.mutateAsync({- queueId: annotationQueueId,- projectId,- seenItemIds,- });- setNextItemData(nextItem);- }- setProgressIndex(Math.max(progressIndex + 1, 0));- }}- disabled={!isNextItemAvailable || !hasAccess} // Disable button during loading+ onClick={handleNavigateNext}+ disabled={!isNextItemAvailable || !hasAccess}size="lg"className={`px-4 ${!relevantItem ? "w-full" : ""}`}variant="outline"@@ -442,12 +260,7 @@ export const AnnotationQueueItemPage: React.FC<{{!!relevantItem &&(relevantItem.status === AnnotationQueueStatus.PENDING ? (<Button- onClick={async () => {- await completeMutation.mutateAsync({- itemId: relevantItem.id,- projectId,- });- }}+ onClick={handleComplete}size="lg"className="w-full"disabled={completeMutation.isLoading || !hasAccess}diff --git a/web/src/features/annotation-queues/components/AnnotationQueueItemsTable.tsx b/web/src/features/annotation-queues/components/AnnotationQueueItemsTable.tsxindex 9312f9f0d4..061335323a 100644--- a/web/src/features/annotation-queues/components/AnnotationQueueItemsTable.tsx+++ b/web/src/features/annotation-queues/components/AnnotationQueueItemsTable.tsx@@ -125,10 +125,6 @@ const QueueItemTableMultiSelectAction = ({export type QueueItemRowData = {id: string;- source: {- traceId: string;- observationId?: string;- };status: AnnotationQueueStatus;completedAt: string;annotatorUser: {@@ -136,7 +132,27 @@ export type QueueItemRowData = {userName?: string;image?: string;};-};+} & (+ | {+ objectType: "OBSERVATION";+ source: {+ traceId: string;+ observationId: string;+ };+ }+ | {+ objectType: "TRACE";+ source: {+ traceId: string;+ };+ }+ | {+ objectType: "SESSION";+ source: {+ sessionId: string;+ };+ }+);export function AnnotationQueueItemsTable({projectId,@@ -215,35 +231,57 @@ export function AnnotationQueueItemsTable({);},},+ {+ accessorKey: "objectType",+ header: "Type",+ id: "objectType",+ size: 50,+ cell: ({ row }) => {+ const objectType: QueueItemRowData["objectType"] =+ row.getValue("objectType");+ return <span className="capitalize">{objectType.toLowerCase()}</span>;+ },+ },{accessorKey: "source",header: "Source",headerTooltip: {description:- "Link to the source trace based on which this item was added",+ "Link to the source trace, observation or session based on which this item was added",},id: "source",size: 50,cell: ({ row }) => {- const source: QueueItemRowData["source"] = row.getValue("source");- if (!source) return null;+ const rowData = row.original;+ if (!rowData.source) return null;- if (!!source.observationId) {- return (- <TableLink- path={`/project/${projectId}/traces/${source.traceId}?observation=${source.observationId}`}- value={source.observationId}- icon={<ListTree className="h-4 w-4" />}- />- );- } else {- return (- <TableLink- path={`/project/${projectId}/traces/${source.traceId}`}- value={source.traceId}- icon={<ListTree className="h-4 w-4" />}- />- );+ switch (rowData.objectType) {+ case "OBSERVATION":+ return (+ <TableLink+ path={`/project/${projectId}/traces/${rowData.source.traceId}?observation=${rowData.source.observationId}`}+ value={`Observation: ${rowData.source.observationId}`}+ icon={<ListTree className="h-4 w-4" />}+ />+ );+ case "TRACE":+ return (+ <TableLink+ path={`/project/${projectId}/traces/${rowData.source.traceId}`}+ value={`Trace: ${rowData.source.traceId}`}+ icon={<ListTree className="h-4 w-4" />}+ />+ );+ case "SESSION":+ return (+ <TableLink+ path={`/project/${projectId}/sessions/${rowData.source.sessionId}`}+ value={`Session: ${rowData.source.sessionId}`}+ icon={<ListTree className="h-4 w-4" />}+ />+ );+ default:+ throw new Error(`Unknown object type`);}},},@@ -310,25 +348,46 @@ export function AnnotationQueueItemsTable({const convertToTableRow = (item: RouterOutput["annotationQueueItems"]["itemsByQueueId"]["queueItems"][number],): QueueItemRowData => {- return {+ const baseData = {id: item.id,completedAt: item.completedAt?.toLocaleString() ?? "",status: item.status,- source:- item.objectType === "OBSERVATION"- ? {- traceId: item.parentTraceId ?? "",- observationId: item.objectId,- }- : {- traceId: item.objectId,- },annotatorUser: {userId: item.annotatorUserId ?? undefined,userName: item.annotatorUserName ?? undefined,image: item.annotatorUserImage ?? undefined,},};++ switch (item.objectType) {+ case "OBSERVATION":+ return {+ ...baseData,+ objectType: "OBSERVATION" as const,+ source: {+ traceId: item.parentTraceId ?? "",+ observationId: item.objectId,+ },+ };+ case "TRACE":+ return {+ ...baseData,+ objectType: "TRACE" as const,+ source: {+ traceId: item.objectId,+ },+ };+ case "SESSION":+ return {+ ...baseData,+ objectType: "SESSION" as const,+ source: {+ sessionId: item.objectId,+ },+ };+ default:+ throw new Error(`Unknown object type: ${item.objectType}`);+ }};const [columnVisibility, setColumnVisibility] =diff --git a/web/src/features/annotation-queues/components/AnnotationQueuesItem.tsx b/web/src/features/annotation-queues/components/AnnotationQueuesItem.tsxindex 80147586db..bab5b74c78 100644--- a/web/src/features/annotation-queues/components/AnnotationQueuesItem.tsx+++ b/web/src/features/annotation-queues/components/AnnotationQueuesItem.tsx@@ -1,9 +1,16 @@import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";import useSessionStorage from "@/src/components/useSessionStorage";import { SupportOrUpgradePage } from "@/src/ee/features/billing/components/SupportOrUpgradePage";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { AnnotationQueueItemPage } from "@/src/features/annotation-queues/components/AnnotationQueueItemPage";import { api } from "@/src/utils/api";+import { AnnotationQueueObjectType } from "@langfuse/shared";import { Goal, Network } from "lucide-react";import Page from "@/src/components/layouts/page";@@ -36,18 +43,33 @@ export const AnnotationQueuesItem = ({},);+ const currentItemType = api.annotationQueueItems.typeById.useQuery(+ {+ projectId,+ itemId: itemId as string,+ queueId: annotationQueueId,+ },+ { enabled: !!itemId, refetchOnMount: false },+ );+const [view, setView] = useSessionStorage<"hideTree" | "showTree">(`annotationQueueView-${projectId}`,"hideTree",);+ const isSessionItem =+ currentItemType.data === AnnotationQueueObjectType.SESSION;+ const isDetailedViewDisabled = isSessionItem;+if (!hasAccess) return <SupportOrUpgradePage />;return (<PagewithPaddingheaderProps={{- title: `${queue.data?.name}: ${itemId}`,+ title: itemId+ ? `${queue.data?.name}: ${itemId}`+ : (queue.data?.name ?? annotationQueueId),itemType: "QUEUE_ITEM",breadcrumb: [{@@ -60,23 +82,49 @@ export const AnnotationQueuesItem = ({},],actionButtonsRight: (- <Tabs- value={view}- onValueChange={(view: string) => {- setView(view as "hideTree" | "showTree");- }}- >- <TabsList>- <TabsTrigger value="hideTree">- <Goal className="mr-1 h-4 w-4"></Goal>- Focused- </TabsTrigger>- <TabsTrigger value="showTree">- <Network className="mr-1 h-4 w-4"></Network>- Detailed- </TabsTrigger>- </TabsList>- </Tabs>+ <TooltipProvider>+ <Tabs+ value={isDetailedViewDisabled ? "hideTree" : view}+ onValueChange={(view: string) => {+ if (!isDetailedViewDisabled) {+ setView(view as "hideTree" | "showTree");+ }+ }}+ >+ <TabsList>+ <TabsTrigger value="hideTree">+ <Goal className="mr-1 h-4 w-4"></Goal>+ Focused+ </TabsTrigger>+ <Tooltip>+ <TooltipTrigger asChild>+ <span>+ <TabsTrigger+ value="showTree"+ disabled={isDetailedViewDisabled}+ className={+ isDetailedViewDisabled+ ? "cursor-not-allowed opacity-50"+ : ""+ }+ >+ <Network className="mr-1 h-4 w-4"></Network>+ Detailed+ </TabsTrigger>+ </span>+ </TooltipTrigger>+ {isDetailedViewDisabled && (+ <TooltipContent>+ <p>+ Detailed view is only available for traces and+ observations+ </p>+ </TooltipContent>+ )}+ </Tooltip>+ </TabsList>+ </Tabs>+ </TooltipProvider>),}}>diff --git a/web/src/features/annotation-queues/components/CreateNewAnnotationQueueItem.tsx b/web/src/features/annotation-queues/components/CreateNewAnnotationQueueItem.tsxindex 78d3626b0d..2c9f8a0d42 100644--- a/web/src/features/annotation-queues/components/CreateNewAnnotationQueueItem.tsx+++ b/web/src/features/annotation-queues/components/CreateNewAnnotationQueueItem.tsx@@ -1,4 +1,4 @@-import { Badge } from "@/src/components/ui/badge";+import { StatusBadge } from "@/src/components/layouts/status-badge";import { Button } from "@/src/components/ui/button";import {DropdownMenuItem,@@ -11,11 +11,7 @@ import {} from "@/src/components/ui/dropdown-menu";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { api } from "@/src/utils/api";-import { cn } from "@/src/utils/tailwind";-import {- AnnotationQueueStatus,- type AnnotationQueueObjectType,-} from "@langfuse/shared";+import { type AnnotationQueueObjectType } from "@langfuse/shared";import { ChevronDown, ExternalLink } from "lucide-react";import { useSession } from "next-auth/react";import Link from "next/link";@@ -25,10 +21,12 @@ export const CreateNewAnnotationQueueItem = ({projectId,objectId,objectType,+ variant = "secondary",}: {projectId: string;objectId: string;objectType: AnnotationQueueObjectType;+ variant?: "outline" | "secondary";}) => {const [isDropdownOpen, setIsDropdownOpen] = useState(false);const session = useSession();@@ -93,7 +91,7 @@ export const CreateNewAnnotationQueueItem = ({if (session.status !== "authenticated" || queues.isLoading) {return (<Button- variant="secondary"+ variant={variant}disabled={session.status !== "authenticated"}className="rounded-l-none rounded-r-md border-l-2">@@ -116,14 +114,14 @@ export const CreateNewAnnotationQueueItem = ({><DropdownMenuTrigger asChild><Button- variant="secondary"+ variant={variant}disabled={!hasAccess}className="rounded-l-none rounded-r-md border-l-2">{queues.data?.totalCount ? (<span className="relative mr-1 text-xs"><ChevronDown className="h-3 w-3 text-secondary-foreground" />- <span className="absolute -top-1.5 left-2.5 flex max-h-[0.8rem] min-w-[0.8rem] items-center justify-center rounded-full border border-muted-foreground bg-accent-light-blue px-[0.2rem] text-[8px]">+ <span className="absolute -top-1 left-2.5 flex h-3 min-w-3 items-center justify-center rounded-sm bg-slate-600 px-0.5 text-[8px] font-medium text-white shadow-sm">{queues.data?.totalCount > 99 ? "99+" : queues.data?.totalCount}</span></span>@@ -153,17 +151,11 @@ export const CreateNewAnnotationQueueItem = ({>{queue.name}{queue.status && (- <Badge- className={cn(- "ml-2 px-1 py-0.5 text-[10px] capitalize",- queue.status === AnnotationQueueStatus.COMPLETED- ? "bg-light-green text-dark-green"- : "bg-light-yellow text-dark-yellow",- )}- variant="outline"- >- {queue.status.toLowerCase()}- </Badge>+ <StatusBadge+ type={queue.status.toLowerCase()}+ isLive={false}+ className="ml-2"+ />)}</DropdownMenuCheckboxItem>))diff --git a/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsxnew file mode 100644index 0000000000..5dc6860ff0--- /dev/null+++ b/web/src/features/annotation-queues/components/processors/SessionAnnotationProcessor.tsx@@ -0,0 +1,167 @@+import {+ type AnnotationQueueItem,+ type ValidatedScoreConfig,+} from "@langfuse/shared";+import { AnnotationDrawerSection } from "../shared/AnnotationDrawerSection";+import { AnnotationProcessingLayout } from "../shared/AnnotationProcessingLayout";+import { SessionIO } from "@/src/components/session";+import { useState, useEffect } from "react";+import { Button } from "@/src/components/ui/button";+import { ItemBadge } from "@/src/components/ItemBadge";+import { CopyIdsPopover } from "@/src/components/trace/CopyIdsPopover";+import { Badge } from "@/src/components/ui/badge";+import { Separator } from "@/src/components/ui/separator";+import Link from "next/link";+import { Card } from "@/src/components/ui/card";++interface SessionAnnotationProcessorProps {+ item: AnnotationQueueItem & {+ parentTraceId?: string | null;+ lockedByUser: { name: string | null | undefined } | null;+ };+ data: any; // // Session data with scores+ configs: ValidatedScoreConfig[];+ projectId: string;+}++// some projects have thousands of traces in a session, paginate to avoid rendering all at once+const PAGE_SIZE = 10;++export const SessionAnnotationProcessor: React.FC<+ SessionAnnotationProcessorProps+> = ({ item, data, configs, projectId }) => {+ const [visibleTraces, setVisibleTraces] = useState(PAGE_SIZE);+ const [currentTraceIndex, setCurrentTraceIndex] = useState(1);++ // Intersection observer to which trace is currently in view+ useEffect(() => {+ if (!data?.traces) return;++ const observer = new IntersectionObserver(+ (entries) => {+ entries.forEach((entry) => {+ if (entry.isIntersecting && entry.intersectionRatio > 0.5) {+ const index = parseInt(+ entry.target.getAttribute("data-trace-index") || "0",+ );+ setCurrentTraceIndex(index + 1);+ }+ });+ },+ {+ threshold: 0.5, // Trigger when 50% of trace is visible+ rootMargin: "-25% 0px -25% 0px", // Focus on center area+ },+ );++ // Observe all trace cards+ const traceCards = document.querySelectorAll("[data-trace-index]");+ traceCards.forEach((card) => observer.observe(card));++ return () => observer.disconnect();+ }, [data?.traces, visibleTraces]);++ const leftPanel = (+ <div className="flex h-full flex-col overflow-hidden">+ {/* Sticky Header */}+ <div className="flex-shrink-0 bg-background">+ <div className="mt-3 grid w-full grid-cols-[auto,auto] items-start justify-between gap-2 px-4">+ <div className="flex w-full flex-row items-start gap-1">+ <div className="mt-1.5">+ <ItemBadge type="SESSION" isSmall />+ </div>+ <span className="mb-0 ml-1 line-clamp-2 min-w-0 break-all font-medium md:break-normal md:break-words">+ {item.objectId}+ </span>+ <CopyIdsPopover+ idItems={[{ id: item.objectId, name: "Session ID" }]}+ />+ </div>+ {data?.traces && (+ <div className="flex items-center">+ <Badge variant="outline" className="text-xs">+ Trace {currentTraceIndex} / {data.traces.length}+ </Badge>+ </div>+ )}+ </div>+ <div className="mb-4 mt-2 grid w-full min-w-0 items-center justify-between px-4">+ <div className="flex min-w-0 max-w-full flex-shrink flex-col">+ <div className="flex min-w-0 max-w-full flex-wrap items-center gap-1">+ {data.environment && (+ <Badge variant="tertiary">Env: {data.environment}</Badge>+ )}+ <Badge variant="outline">+ Total traces: {data?.traces.length}+ </Badge>+ </div>+ </div>+ </div>+ <Separator />+ </div>++ {/* Scrollable Content */}+ <div className="flex-1 overflow-y-auto">+ <div className="p-4">+ {data?.traces+ .slice(0, visibleTraces)+ .map((trace: any, index: number) => (+ <Card+ className="group mb-2 grid gap-2 border-border p-2 shadow-none hover:border-ring"+ key={trace.id}+ data-trace-index={index}+ >+ <div className="-mt-1 p-1 pt-0 opacity-50 transition-opacity group-hover:opacity-100">+ <Link+ href={`/project/${projectId}/traces/${trace.id}`}+ className="text-xs hover:underline"+ >+ Trace: {trace.name} ({trace.id}) ↗+ </Link>+ <div className="text-xs text-muted-foreground">+ {trace.timestamp.toLocaleString()}+ </div>+ </div>+ <SessionIO+ traceId={trace.id}+ projectId={projectId}+ timestamp={trace.timestamp}+ />+ </Card>+ ))}+ {data?.traces && data.traces.length > visibleTraces && (+ <div className="flex justify-center py-4">+ <Button+ onClick={() => setVisibleTraces((prev) => prev + PAGE_SIZE)}+ variant="ghost"+ >+ {`Load ${Math.min(data.traces.length - visibleTraces, PAGE_SIZE)} More`}+ </Button>+ </div>+ )}+ </div>+ </div>+ </div>+ );++ const rightPanel = (+ <AnnotationDrawerSection+ item={item}+ scoreTarget={{+ type: "session",+ sessionId: item.objectId,+ }}+ scores={data?.scores ?? []}+ configs={configs}+ environment={data?.environment}+ />+ );++ return (+ <AnnotationProcessingLayout+ leftPanel={leftPanel}+ rightPanel={rightPanel}+ projectId={projectId}+ />+ );+};diff --git a/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx b/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsxnew file mode 100644index 0000000000..9f69e02124--- /dev/null+++ b/web/src/features/annotation-queues/components/processors/TraceAnnotationProcessor.tsx@@ -0,0 +1,114 @@+import { Trace } from "@/src/components/trace";+import { ObservationPreview } from "@/src/components/trace/ObservationPreview";+import { TracePreview } from "@/src/components/trace/TracePreview";+import {+ type AnnotationQueueItem,+ AnnotationQueueObjectType,+ type ValidatedScoreConfig,+} from "@langfuse/shared";+import { useEffect } from "react";+import { StringParam, useQueryParam } from "use-query-params";+import { AnnotationDrawerSection } from "../shared/AnnotationDrawerSection";+import { AnnotationProcessingLayout } from "../shared/AnnotationProcessingLayout";++interface TraceAnnotationProcessorProps {+ item: AnnotationQueueItem & {+ parentTraceId?: string | null;+ lockedByUser: { name: string | null | undefined } | null;+ };+ data: any; // Trace data with observations and scores+ view: "showTree" | "hideTree";+ configs: ValidatedScoreConfig[];+ projectId: string;+}++export const TraceAnnotationProcessor: React.FC<+ TraceAnnotationProcessorProps+> = ({ item, data, view, configs, projectId }) => {+ const traceId = item.parentTraceId ?? item.objectId;++ const [currentObservationId, setCurrentObservationId] = useQueryParam(+ "observation",+ StringParam,+ );++ useEffect(() => {+ if (+ view === "showTree" &&+ item.objectType === AnnotationQueueObjectType.OBSERVATION+ ) {+ setCurrentObservationId(item.objectId);+ } else setCurrentObservationId(undefined);+ }, [view, item, setCurrentObservationId]);++ if (!data) return <div className="p-3">Loading...</div>;++ let isValidObservationId = false;++ if (+ currentObservationId &&+ data.observations.some(+ ({ id }: { id: string }) => id === currentObservationId,+ )+ ) {+ isValidObservationId = true;+ }++ const leftPanel =+ view === "hideTree" ? (+ <div className="flex h-full flex-col overflow-y-auto pl-4">+ {item.objectType === AnnotationQueueObjectType.TRACE ? (+ <TracePreview+ key={data.id}+ trace={data}+ scores={data.scores}+ observations={data.observations}+ viewType="focused"+ />+ ) : (+ <ObservationPreview+ observations={data.observations}+ scores={data.scores}+ projectId={item.projectId}+ currentObservationId={item.objectId}+ traceId={traceId}+ viewType="focused"+ />+ )}+ </div>+ ) : (+ <div className="flex h-full flex-col overflow-y-auto">+ <Trace+ key={data.id}+ trace={data}+ scores={data.scores}+ projectId={data.projectId}+ observations={data.observations}+ viewType="focused"+ isValidObservationId={isValidObservationId}+ />+ </div>+ );++ const rightPanel = (+ <AnnotationDrawerSection+ item={item}+ scoreTarget={{+ type: "trace",+ traceId: traceId,+ observationId: item.parentTraceId ? item.objectId : undefined,+ }}+ scores={data?.scores ?? []}+ configs={configs}+ environment={data?.environment}+ />+ );++ return (+ <AnnotationProcessingLayout+ leftPanel={leftPanel}+ rightPanel={rightPanel}+ projectId={projectId}+ />+ );+};diff --git a/web/src/features/annotation-queues/components/shared/AnnotationDrawerSection.tsx b/web/src/features/annotation-queues/components/shared/AnnotationDrawerSection.tsxnew file mode 100644index 0000000000..9f7fc15763--- /dev/null+++ b/web/src/features/annotation-queues/components/shared/AnnotationDrawerSection.tsx@@ -0,0 +1,96 @@+import { Card } from "@/src/components/ui/card";+import useSessionStorage from "@/src/components/useSessionStorage";+import { AnnotateDrawerContent } from "@/src/features/scores/components/AnnotateDrawerContent";+import { type ScoreTarget } from "@/src/features/scores/types";+import {+ type AnnotationQueueItem,+ type APIScoreV2,+ isPresent,+ type ValidatedScoreConfig,+} from "@langfuse/shared";+import { TriangleAlertIcon } from "lucide-react";+import { useSession } from "next-auth/react";+import { useRouter } from "next/router";+import { useMemo, useState } from "react";+import { CommentsSection } from "./CommentsSection";++interface AnnotationDrawerSectionProps {+ item: AnnotationQueueItem & {+ parentTraceId?: string | null;+ lockedByUser: { name: string | null | undefined } | null;+ };+ scoreTarget: ScoreTarget;+ scores: APIScoreV2[];+ configs: ValidatedScoreConfig[];+ environment?: string;+}++export const AnnotationDrawerSection: React.FC<+ AnnotationDrawerSectionProps+> = ({ item, scoreTarget, scores, configs, environment }) => {+ const router = useRouter();+ const session = useSession();+ const projectId = router.query.projectId as string;+ const [showSaving, setShowSaving] = useState(false);+ const [showComments, setShowComments] = useSessionStorage(+ `annotationQueueShowComments-${projectId}`,+ false,+ );++ const isLockedByOtherUser = item.lockedByUserId !== session.data?.user?.id;++ const emptySelectedConfigIds = useMemo(() => {+ return configs.map((c) => c.id);+ }, [configs]);++ const handleSavingChange = (saving: boolean) => {+ setShowSaving(saving);+ };++ return (+ <Card className="col-span-2 flex h-full flex-col overflow-hidden">+ <div className="grid h-full w-full grid-cols-1 grid-rows-[minmax(auto,1fr),minmax(min-content,auto)] justify-between">+ <div className="w-full overflow-auto">+ <AnnotateDrawerContent+ key={"annotation-drawer-content" + item.objectId}+ scoreTarget={scoreTarget}+ scores={scores}+ configs={configs}+ emptySelectedConfigIds={emptySelectedConfigIds}+ setEmptySelectedConfigIds={() => {}}+ projectId={item.projectId}+ analyticsData={{+ type: scoreTarget.type,+ source: "AnnotationQueue",+ }}+ isSelectHidden+ queueId={item.queueId}+ showSaving={showSaving}+ setShowSaving={handleSavingChange}+ environment={environment}+ actionButtons={+ isLockedByOtherUser && isPresent(item.lockedByUser?.name) ? (+ <div className="flex items-center justify-center rounded-sm border border-dark-red bg-light-red p-1">+ <TriangleAlertIcon className="mr-1 h-4 w-4 text-dark-red" />+ <span className="text-xs text-dark-red">+ Currently edited by {item.lockedByUser.name}+ </span>+ </div>+ ) : undefined+ }+ isDrawerOpen={true}+ />+ </div>+ <div className="relative max-h-64 overflow-auto">+ <CommentsSection+ projectId={item.projectId}+ objectId={item.objectId}+ objectType={item.objectType}+ showComments={showComments}+ onToggleComments={setShowComments}+ />+ </div>+ </div>+ </Card>+ );+};diff --git a/web/src/features/annotation-queues/components/shared/AnnotationProcessingLayout.tsx b/web/src/features/annotation-queues/components/shared/AnnotationProcessingLayout.tsxnew file mode 100644index 0000000000..543b1c83c3--- /dev/null+++ b/web/src/features/annotation-queues/components/shared/AnnotationProcessingLayout.tsx@@ -0,0 +1,46 @@+import {+ ResizableHandle,+ ResizablePanel,+ ResizablePanelGroup,+} from "@/src/components/ui/resizable";+import useSessionStorage from "@/src/components/useSessionStorage";++interface AnnotationProcessingLayoutProps {+ leftPanel: React.ReactNode;+ rightPanel: React.ReactNode;+ projectId: string;+}++export const AnnotationProcessingLayout: React.FC<+ AnnotationProcessingLayoutProps+> = ({ leftPanel, rightPanel, projectId }) => {+ const [panelSize, setPanelSize] = useSessionStorage(+ `annotationQueuePanelSize-${projectId}`,+ 65,+ );++ return (+ <ResizablePanelGroup+ direction="horizontal"+ className="h-full overflow-hidden"+ onLayout={(sizes) => {+ setPanelSize(sizes[0]);+ }}+ >+ <ResizablePanel+ className="col-span-1 h-full !overflow-y-auto rounded-md border"+ minSize={30}+ defaultSize={panelSize}+ >+ {leftPanel}+ </ResizablePanel>+ <ResizableHandle withHandle className="ml-4 bg-transparent" />+ <ResizablePanel+ className="col-span-1 h-full md:flex md:flex-col md:overflow-hidden"+ minSize={30}+ >+ {rightPanel}+ </ResizablePanel>+ </ResizablePanelGroup>+ );+};diff --git a/web/src/features/annotation-queues/components/shared/CommentsSection.tsx b/web/src/features/annotation-queues/components/shared/CommentsSection.tsxnew file mode 100644index 0000000000..0d0e87494a--- /dev/null+++ b/web/src/features/annotation-queues/components/shared/CommentsSection.tsx@@ -0,0 +1,51 @@+import {+ Accordion,+ AccordionContent,+ AccordionItem,+ AccordionTrigger,+} from "@/src/components/ui/accordion";+import { CommentList } from "@/src/features/comments/CommentList";+import { type AnnotationQueueObjectType } from "@langfuse/shared";++interface CommentsSectionProps {+ projectId: string;+ objectId: string;+ objectType: AnnotationQueueObjectType;+ showComments: boolean;+ onToggleComments: (show: boolean) => void;+}++export const CommentsSection: React.FC<CommentsSectionProps> = ({+ projectId,+ objectId,+ objectType,+ showComments,+ onToggleComments,+}) => {+ return (+ <Accordion+ type="single"+ collapsible+ className="mx-4 mt-4"+ value={showComments ? "item-1" : ""}+ onValueChange={(value) => onToggleComments(value === "item-1")}+ >+ <AccordionItem value="item-1" className="border-none">+ <div className="sticky top-0 z-10 border-b bg-background">+ <AccordionTrigger onClick={() => onToggleComments(!showComments)}>+ Comments+ </AccordionTrigger>+ </div>+ <AccordionContent>+ <CommentList+ projectId={projectId}+ objectId={objectId}+ objectType={objectType}+ className="rounded-t-none border-t-transparent"+ cardView+ />+ </AccordionContent>+ </AccordionItem>+ </Accordion>+ );+};diff --git a/web/src/features/annotation-queues/components/shared/hooks/useAnnotationObjectData.ts b/web/src/features/annotation-queues/components/shared/hooks/useAnnotationObjectData.tsnew file mode 100644index 0000000000..7ce4c2ed34--- /dev/null+++ b/web/src/features/annotation-queues/components/shared/hooks/useAnnotationObjectData.ts@@ -0,0 +1,73 @@+import { api } from "@/src/utils/api";+import {+ type AnnotationQueueItem,+ AnnotationQueueObjectType,+} from "@langfuse/shared";++export interface ObjectDataHook<TData> {+ data: TData | undefined;+ isLoading: boolean;+}++export const useAnnotationObjectData = (+ item: (AnnotationQueueItem & { parentTraceId?: string | null }) | null,+ projectId: string,+): ObjectDataHook<any> => {+ const traceId = item?.parentTraceId ?? item?.objectId;++ const traceQuery = api.traces.byIdWithObservationsAndScores.useQuery(+ { traceId: traceId as string, projectId },+ {+ enabled:+ !!item &&+ (item.objectType === AnnotationQueueObjectType.TRACE ||+ item.objectType === AnnotationQueueObjectType.OBSERVATION),+ retry(failureCount, error) {+ if (error.data?.code === "UNAUTHORIZED") return false;+ return failureCount < 3;+ },+ },+ );++ const sessionQuery = api.sessions.byIdWithScores.useQuery(+ {+ sessionId: item?.objectId as string,+ projectId,+ },+ {+ enabled: !!item && item.objectType === AnnotationQueueObjectType.SESSION,+ retry(failureCount, error) {+ if (+ error.data?.code === "UNAUTHORIZED" ||+ error.data?.code === "NOT_FOUND"+ )+ return false;+ return failureCount < 3;+ },+ },+ );++ if (!item) {+ return {+ data: undefined,+ isLoading: false,+ };+ }++ switch (item.objectType) {+ case AnnotationQueueObjectType.TRACE:+ case AnnotationQueueObjectType.OBSERVATION:+ return {+ data: traceQuery.data,+ isLoading: traceQuery.isLoading,+ };+ case AnnotationQueueObjectType.SESSION:+ return {+ data: sessionQuery.data,+ isLoading: sessionQuery.isLoading,+ };+ default:+ // This should never happen as it's a DB enum+ throw new Error(`Unsupported object type: ${item.objectType}`);+ }+};diff --git a/web/src/features/annotation-queues/components/shared/hooks/useAnnotationQueueData.ts b/web/src/features/annotation-queues/components/shared/hooks/useAnnotationQueueData.tsnew file mode 100644index 0000000000..8d034b743e--- /dev/null+++ b/web/src/features/annotation-queues/components/shared/hooks/useAnnotationQueueData.ts@@ -0,0 +1,25 @@+import { api } from "@/src/utils/api";++export interface AnnotationQueueDataConfig {+ annotationQueueId: string;+ projectId: string;+}++export const useAnnotationQueueData = (config: AnnotationQueueDataConfig) => {+ const queueData = api.annotationQueues.byId.useQuery(+ {+ queueId: config.annotationQueueId,+ projectId: config.projectId,+ },+ {+ refetchOnMount: false,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ },+ );++ return {+ queueData,+ configs: queueData.data?.scoreConfigs ?? [],+ };+};diff --git a/web/src/features/annotation-queues/server/annotationQueueItems.ts b/web/src/features/annotation-queues/server/annotationQueueItems.tsindex 9d29352eb5..70d077763b 100644--- a/web/src/features/annotation-queues/server/annotationQueueItems.ts+++ b/web/src/features/annotation-queues/server/annotationQueueItems.ts@@ -32,6 +32,27 @@ const isItemLocked = (item: AnnotationQueueItem) => {};export const queueItemRouter = createTRPCRouter({+ typeById: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ itemId: z.string(),+ queueId: z.string(),+ }),+ )+ .query(async ({ input, ctx }) => {+ const item = await ctx.prisma.annotationQueueItem.findUnique({+ where: {+ id: input.itemId,+ projectId: input.projectId,+ queueId: input.queueId,+ },+ select: {+ objectType: true,+ },+ });+ return item?.objectType;+ }),byId: protectedProjectProcedure.input(z.object({