🪢 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(review): embed comments and annotation beside traces and sessions (#17745)
Nikita Kabardin1af345f08005
diff --git a/web/src/components/layouts/app-layout/right-drawer/AppContentWithRightDrawer.tsx b/web/src/components/layouts/app-layout/right-drawer/AppContentWithRightDrawer.tsxindex 2c15bac2a4..5f00375b26 100644--- a/web/src/components/layouts/app-layout/right-drawer/AppContentWithRightDrawer.tsx+++ b/web/src/components/layouts/app-layout/right-drawer/AppContentWithRightDrawer.tsx@@ -50,18 +50,14 @@ function RightDrawerLoadingFallback() {/*** App-shell content wrapper that attaches the support right drawer.*- * Desktop keeps a stable split wrapper so routed page content does not remount- * when a right drawer opens or closes. Mobile uses a bottom drawer.+ * Routed page content keeps a stable split wrapper across viewport changes.+ * Desktop uses the secondary panel; mobile drawers render as sibling overlays.*/export function AppContentWithRightDrawer({ children }: PropsWithChildren) {const isDesktop = useMediaQuery({ query: "(min-width: 768px)" });const { open: supportOpen } = useSupportDrawer();const { open: migrationOpen } = useV4MigrationPanel();- if (!isDesktop) {- return <DynamicMobileRightDrawer>{children}</DynamicMobileRightDrawer>;- }-const rightDrawerContent = supportOpen ? (<DynamicSupportDrawer />) : migrationOpen ? (@@ -69,17 +65,20 @@ export function AppContentWithRightDrawer({ children }: PropsWithChildren) {) : null;return (- <ResizableSplitLayout- primaryContent={children}- secondaryContent={rightDrawerContent}- open={supportOpen || migrationOpen}- defaultPrimarySize={supportOpen ? 70 : 60}- // The migration panel carries denser content than the support drawer,- // so it opens wider by default.- defaultSecondarySize={supportOpen ? 30 : 40}- minPrimarySize={30}- maxSecondarySize={60}- keepSecondaryMounted={false}- />+ <>+ <ResizableSplitLayout+ primaryContent={children}+ secondaryContent={rightDrawerContent}+ open={isDesktop && (supportOpen || migrationOpen)}+ defaultPrimarySize={supportOpen ? 70 : 60}+ // The migration panel carries denser content than the support drawer,+ // so it opens wider by default.+ defaultSecondarySize={supportOpen ? 30 : 40}+ minPrimarySize={30}+ maxSecondarySize={60}+ keepSecondaryMounted={false}+ />+ {!isDesktop && <DynamicMobileRightDrawer />}+ </>);}diff --git a/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.clienttest.tsx b/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.clienttest.tsxindex bb384c2a0f..73e6a73eff 100644--- a/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.clienttest.tsx+++ b/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.clienttest.tsx@@ -1,10 +1,34 @@-import { render, screen } from "@testing-library/react";+import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { useState, type ReactNode } from "react";import { MobileRightDrawer } from "@/src/components/layouts/app-layout/right-drawer/MobileRightDrawer";+import { AppContentWithRightDrawer } from "@/src/components/layouts/app-layout/right-drawer/AppContentWithRightDrawer";import { LayerProvider } from "@/src/context/LayerContext/LayerContext";const mocks = vi.hoisted(() => ({supportOpen: true,migrationOpen: false,+ isDesktop: true,+}));++vi.mock("react-responsive", () => ({+ useMediaQuery: () => mocks.isDesktop,+}));++vi.mock("@/src/components/ui/resizable-split-layout", () => ({+ ResizableSplitLayout: ({+ primaryContent,+ secondaryContent,+ open,+ }: {+ primaryContent: ReactNode;+ secondaryContent: ReactNode;+ open: boolean;+ }) => (+ <div>+ <main>{primaryContent}</main>+ {open ? secondaryContent : null}+ </div>+ ),}));vi.mock("@/src/features/support-chat/SupportDrawerProvider", () => ({@@ -26,7 +50,7 @@ vi.mock("@/src/features/support-chat/SupportDrawer", () => ({}));vi.mock("@/src/features/v4-migration/V4MigrationPanel", () => ({- V4MigrationPanel: () => null,+ V4MigrationPanel: () => <div>Migration panel</div>,}));vi.mock("@/src/features/v4-migration/V4MigrationContent", () => ({@@ -37,15 +61,11 @@ describe("MobileRightDrawer", () => {beforeEach(() => {mocks.supportOpen = true;mocks.migrationOpen = false;+ mocks.isDesktop = true;});it("does not stretch the support sheet to the full viewport", () => {- render(- <MobileRightDrawer>- <div>page</div>- </MobileRightDrawer>,- { wrapper: LayerProvider },- );+ render(<MobileRightDrawer />, { wrapper: LayerProvider });const drawer = document.querySelector("#support-drawer");expect(drawer).not.toBeNull();@@ -56,15 +76,58 @@ describe("MobileRightDrawer", () => {mocks.supportOpen = false;mocks.migrationOpen = true;- render(- <MobileRightDrawer>- <div>page</div>- </MobileRightDrawer>,- { wrapper: LayerProvider },- );+ render(<MobileRightDrawer />, { wrapper: LayerProvider });expect(screen.getByText("Ensure compatibility after November 16"),).toBeInTheDocument();});++ it("preserves routed page state across breakpoints and shows each drawer once", async () => {+ mocks.supportOpen = false;+ function PageDraft() {+ const [value, setValue] = useState("");+ return (+ <input+ aria-label="Page draft"+ value={value}+ onChange={(event) => setValue(event.target.value)}+ />+ );+ }+ const page = () => (+ <AppContentWithRightDrawer>+ <PageDraft />+ </AppContentWithRightDrawer>+ );+ const { rerender } = render(page(), { wrapper: LayerProvider });+ const draft = screen.getByLabelText("Page draft");+ fireEvent.change(draft, { target: { value: "Unsent review" } });++ mocks.isDesktop = false;+ rerender(page());+ await waitFor(() =>+ expect(screen.getByLabelText("Page draft")).toBe(draft),+ );+ expect(draft).toHaveValue("Unsent review");++ mocks.supportOpen = true;+ rerender(page());+ expect(await screen.findByText("Email a Support Engineer")).toBeVisible();+ expect(screen.getAllByText("Email a Support Engineer")).toHaveLength(1);++ mocks.supportOpen = false;+ mocks.migrationOpen = true;+ rerender(page());+ expect(await screen.findByText("Migration panel")).toBeVisible();+ expect(screen.getAllByText("Migration panel")).toHaveLength(1);++ mocks.isDesktop = true;+ rerender(page());+ await waitFor(() =>+ expect(screen.getAllByText("Migration panel")).toHaveLength(1),+ );+ expect(screen.getByLabelText("Page draft")).toBe(draft);+ expect(draft).toHaveValue("Unsent review");+ });});diff --git a/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.tsx b/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.tsxindex 57ad0a9676..685ffe8960 100644--- a/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.tsx+++ b/web/src/components/layouts/app-layout/right-drawer/MobileRightDrawer.tsx@@ -1,4 +1,3 @@-import { type PropsWithChildren } from "react";import {Drawer,DrawerContent,@@ -12,7 +11,7 @@ import { useV4MigrationPanel } from "@/src/features/v4-migration/V4MigrationPaneimport { V4MigrationPanel } from "@/src/features/v4-migration/V4MigrationPanel";import { useV4MigrationTitle } from "@/src/features/v4-migration/V4MigrationContent";-export function MobileRightDrawer({ children }: PropsWithChildren) {+export function MobileRightDrawer() {const { open: supportOpen, setOpen: setSupportOpen } = useSupportDrawer();const { open: migrationOpen, setOpen: setMigrationOpen } =useV4MigrationPanel();@@ -20,10 +19,6 @@ export function MobileRightDrawer({ children }: PropsWithChildren) {return (<>- <main className="h-full flex-1" style={{ overscrollBehaviorY: "none" }}>- {children}- </main>-<Draweropen={supportOpen}onOpenChange={(open) => {diff --git a/web/src/components/layouts/app-shell-chrome.clienttest.tsx b/web/src/components/layouts/app-shell-chrome.clienttest.tsxindex 48d7b212cf..5f488c22ad 100644--- a/web/src/components/layouts/app-shell-chrome.clienttest.tsx+++ b/web/src/components/layouts/app-shell-chrome.clienttest.tsx@@ -1,7 +1,14 @@-import { render, screen } from "@testing-library/react";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+} from "@testing-library/react";import { Home, Settings } from "lucide-react";import { APP_SHELL_CHROME_ROW_TEST_ID } from "@/src/components/layouts/app-shell-chrome";+import { MobilePageTitle } from "@/src/components/layouts/mobile-page-title";import PageHeader from "@/src/components/layouts/page-header";import { AppSidebar } from "@/src/components/nav/AppSidebar/AppSidebar";import { SidebarPresenceProvider } from "@/src/components/nav/sidebar-presence";@@ -158,3 +165,58 @@ describe("app shell chrome row", () => {expect((inner as HTMLElement).className).toContain("lg:mx-auto");});});++describe("mobile page action focus handoff", () => {+ afterEach(() => {+ cleanup();+ vi.useRealTimers();+ });++ it("closes before panel focus and restores the trigger only on ordinary dismissals", async () => {+ vi.useFakeTimers();+ const openReview = vi.fn();+ render(+ <>+ <MobilePageTitle+ headerProps={{+ title: "Session",+ actionButtonsMenu: ({+ closeMenu,+ }: {+ closeMenu: (options?: { handoffFocus?: boolean }) => void;+ }) => (+ <>+ <button+ onClick={() => {+ closeMenu({ handoffFocus: true });+ openReview(document.activeElement);+ }}+ >+ Open review+ </button>+ <button onClick={() => closeMenu()}>Close menu</button>+ </>+ ),+ }}+ />+ <input aria-label="Review field" />+ </>,+ );+ const trigger = screen.getByRole("button", { name: "More actions" });+ trigger.focus();+ fireEvent.click(trigger);+ fireEvent.click(screen.getByRole("button", { name: "Open review" }));+ expect(openReview).toHaveBeenCalledWith(trigger);+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();++ const field = screen.getByRole("textbox", { name: "Review field" });+ field.focus();+ await act(async () => vi.runOnlyPendingTimersAsync());+ expect(field).toHaveFocus();++ fireEvent.click(trigger);+ fireEvent.click(screen.getByRole("button", { name: "Close menu" }));+ await act(async () => vi.runOnlyPendingTimersAsync());+ expect(trigger).toHaveFocus();+ });+});diff --git a/web/src/components/layouts/mobile-page-title.tsx b/web/src/components/layouts/mobile-page-title.tsxindex 86b885b9f1..e610a49317 100644--- a/web/src/components/layouts/mobile-page-title.tsx+++ b/web/src/components/layouts/mobile-page-title.tsx@@ -18,6 +18,7 @@ import {TooltipTrigger,} from "@/src/components/ui/tooltip";import { MoreHorizontal } from "lucide-react";+import { useRef, useState } from "react";/*** The page-specific block for the minimal-chrome mobile shell. Rendered between@@ -51,6 +52,17 @@ export const MobilePageTitle = ({tabsProps,} = headerProps;+ const [isMenuOpen, setMenuOpen] = useState(false);+ const restoreFocus = useRef(true);+ const menuTriggerRef = useRef<HTMLButtonElement>(null);+ const closeMenu = (options?: { handoffFocus?: boolean }) => {+ restoreFocus.current = !options?.handoffFocus;+ setMenuOpen(false);+ if (options?.handoffFocus) {+ menuTriggerRef.current?.focus({ preventScroll: true });+ }+ };+return (<div className="bg-background border-b px-3 pt-2 pb-3">{/* Context line: org / project switcher plus any page-supplied@@ -123,25 +135,41 @@ export const MobilePageTitle = ({nodes as-is. Either way the actions' own dialogs/drawers portalthrough the layer system, so they keep working from the popover. */}{(actionButtonsMenu || actionButtonsRight || actionButtonsLeft) && (- <Popover>+ <Popover+ open={isMenuOpen}+ onOpenChange={(open) => {+ if (open) restoreFocus.current = true;+ setMenuOpen(open);+ }}+ ><PopoverTrigger asChild><Buttonvariant="outline"size="icon"+ ref={menuTriggerRef}aria-label="More actions"className="ml-auto shrink-0"><MoreHorizontal className="h-4 w-4" /></Button></PopoverTrigger>- <PopoverContent align="end" className="w-auto min-w-44 p-1">+ <PopoverContent+ align="end"+ className="w-auto min-w-44 p-1"+ onCloseAutoFocus={(event) => {+ if (!restoreFocus.current) event.preventDefault();+ restoreFocus.current = true;+ }}+ ><div className="flex flex-col items-stretch gap-0.5">- {actionButtonsMenu ?? (- <>- {actionButtonsRight}- {actionButtonsLeft}- </>- )}+ {typeof actionButtonsMenu === "function"+ ? actionButtonsMenu({ closeMenu })+ : (actionButtonsMenu ?? (+ <>+ {actionButtonsRight}+ {actionButtonsLeft}+ </>+ ))}</div></PopoverContent></Popover>diff --git a/web/src/components/layouts/page-header.tsx b/web/src/components/layouts/page-header.tsxindex cf361c8deb..0d851d9e78 100644--- a/web/src/components/layouts/page-header.tsx+++ b/web/src/components/layouts/page-header.tsx@@ -49,8 +49,13 @@ export type PageHeaderProps = {* `layout="menu"` variant of their actions here (mirrors the table peek's* `actionsMenu`). When omitted, the mobile header falls back to folding the* inline `actionButtonsRight`/`actionButtonsLeft` nodes as-is. Desktop- * `PageHeader` ignores this. */- actionButtonsMenu?: React.ReactNode;+ * `PageHeader` ignores this. The render callback can hand off focus through the stable menu trigger+ * before opening another panel, without delayed trigger focus restoration. */+ actionButtonsMenu?:+ | ReactNode+ | ((control: {+ closeMenu: (options?: { handoffFocus?: boolean }) => void;+ }) => ReactNode);help?: { description: React.ReactNode; href?: string; className?: string };titleTooltip?: string;itemType?: LangfuseItemType;diff --git a/web/src/components/table/peek.tsx b/web/src/components/table/peek.tsxindex a33b9fea30..f49478e4d9 100644--- a/web/src/components/table/peek.tsx+++ b/web/src/components/table/peek.tsx@@ -313,20 +313,25 @@ function TablePeekViewComponent(props: TablePeekViewProps) {open={!!itemId}onOpenChange={handleOpenChange}forceDirection="bottom"+ modal={false}>- <DrawerContent- size="full"- className="min-h-screen-with-banner top-[calc(var(--banner-offset)+10px)] bottom-0 gap-0 p-0"- onPointerDownOutside={preventDismissOnKeptOpen}- onInteractOutside={preventDismissOnKeptOpen}- >- <DrawerTitle className="sr-only">{resolvedTitle}</DrawerTitle>- <div className="flex w-full shrink-0 items-center justify-center pt-2 pb-1">- <div className="bg-muted h-1.5 w-12 rounded-full" />- </div>- {header}- {content}- </DrawerContent>+ {/* Vaul does not forward modal to its Radix root. Keep its gestures,+ but give portaled child dialogs the same non-modal host as desktop. */}+ <Sheet open={!!itemId} onOpenChange={handleOpenChange} modal={false}>+ <DrawerContent+ size="full"+ className="min-h-screen-with-banner top-[calc(var(--banner-offset)+10px)] bottom-0 gap-0 p-0"+ onPointerDownOutside={preventDismissOnKeptOpen}+ onInteractOutside={preventDismissOnKeptOpen}+ >+ <DrawerTitle className="sr-only">{resolvedTitle}</DrawerTitle>+ <div className="flex w-full shrink-0 items-center justify-center pt-2 pb-1">+ <div className="bg-muted h-1.5 w-12 rounded-full" />+ </div>+ {header}+ {content}+ </DrawerContent>+ </Sheet></Drawer>) : (// Desktop: a docked-right, resizable panel that stays on top of the@@ -355,6 +360,7 @@ function TablePeekViewComponent(props: TablePeekViewProps) {// would flip to a white glow)."shadow-[-12px_0_32px_-16px_hsl(var(--foreground)/0.3)] dark:shadow-[-12px_0_32px_-16px_hsl(var(--background)/0.3)]","data-[state=open]:animate-in data-[state=open]:slide-in-from-right data-[state=closed]:animate-out data-[state=closed]:slide-out-to-right data-[state=closed]:duration-100 data-[state=open]:duration-100",+ "has-[[data-peek-layout=review-navigation]]:min-w-[min(1120px,var(--peek-max-width))] has-[[data-peek-layout=review]]:min-w-[min(800px,var(--peek-max-width))]",panel.isResizing && "select-none",)}>diff --git a/web/src/components/table/peek/README.md b/web/src/components/table/peek/README.mdindex 8c8e5746b1..221f5d8793 100644--- a/web/src/components/table/peek/README.md+++ b/web/src/components/table/peek/README.md@@ -18,7 +18,9 @@ Peek views allow users to quickly preview table items in a side panel. When navi- **Handheld** (`useIsHandheld` — narrower than `md`, _or_ a coarse pointer on ashort screen, i.e. a phone in landscape) — a `vaul` bottom drawer with nativeswipe-down dismissal (Expand is hidden). Not width-only: a landscape phone is- wider than `md` and would otherwise get the desktop sheet.+ wider than `md` and would otherwise get the desktop sheet. An inner non-modal+ Radix root keeps child menus and dialogs accessible: Vaul's `modal` option+ controls its gestures and backdrop but is not forwarded to its Radix root.Dismissal:@@ -389,3 +391,9 @@ const filters = useSidebarFilterState(config, options, queryFilterOptions);- Full text search hook: [`search-bar/hooks/useFullTextSearch.ts`](../../../features/search-bar/hooks/useFullTextSearch.ts)- Filter state hook: [`web/src/features/filters/hooks/useSidebarFilterState.tsx`](../../../features/filters/hooks/useSidebarFilterState.tsx)- Order by hook: [`web/src/features/orderBy/hooks/useOrderByState.ts`](../../../features/orderBy/hooks/useOrderByState.ts)++Content may request a temporary review width with `data-peek-layout="review"`+(two columns) or `"review-navigation"` (three columns). The shell's CSS minimum+width is capped at the sidebar edge; it does not write the stored widget width+or expanded URL state. Nested content owns its responsive fallback when the+available width is smaller than its preferred columns.diff --git a/web/src/components/table/peek/usePeekPanelState.ts b/web/src/components/table/peek/usePeekPanelState.tsindex 0889b48bf1..aa5be33008 100644--- a/web/src/components/table/peek/usePeekPanelState.ts+++ b/web/src/components/table/peek/usePeekPanelState.ts@@ -160,7 +160,8 @@ export function usePeekPanelState({// lands on the exact same width as expanded — no snap-back jump — and the// panel never paints over the sidebar even if a stored fraction is large.const maxWidth = `calc(100vw - ${sidebarOffset}px)`;- const panelStyle: CSSProperties = {+ const panelStyle: CSSProperties & { "--peek-max-width": string } = {+ "--peek-max-width": maxWidth,width: effectiveExpanded ? maxWidth : `min(${widgetWidth}, ${maxWidth})`,};diff --git a/web/src/features/comments/CommentDrawerController.clienttest.tsx b/web/src/features/comments/CommentDrawerController.clienttest.tsxindex 4febe2ed80..2716fbc503 100644--- a/web/src/features/comments/CommentDrawerController.clienttest.tsx+++ b/web/src/features/comments/CommentDrawerController.clienttest.tsx@@ -6,8 +6,13 @@ import {waitFor,} from "@testing-library/react";import { vi } from "vitest";+import { useStore } from "zustand";import { LayerProvider } from "@/src/context/LayerContext/LayerContext";+import {+ TraceReviewPanelProvider,+ useTraceReviewPanel,+} from "@/src/features/traces/contexts/TraceReviewPanelContext";import {CommentDrawerController,type CommentDrawerControllerProps,@@ -65,6 +70,18 @@ const target = {objectType: "TRACE" as const,};+function EmbeddedReviewState() {+ const store = useTraceReviewPanel();+ const active = useStore(store, (state) => state.active);+ const objectId = useStore(store, (state) => state.comments?.target.objectId);+ return (+ <>+ <output>{active === "comments" ? objectId : "closed"}</output>+ <button onClick={store.getState().actions.close}>Close review</button>+ </>+ );+}+describe("CommentDrawerController", () => {beforeEach(() => {vi.clearAllMocks();@@ -74,6 +91,33 @@ describe("CommentDrawerController", () => {invalidateComments.mockResolvedValue(undefined);});+ it("opens embedded comments immediately without a lookup or rerendering the trigger", () => {+ const renderView = vi.fn(+ ({+ openDrawer,+ }: Parameters<CommentDrawerControllerProps["children"]>[0]) => (+ <button onClick={() => openDrawer(target)}>Open comments</button>+ ),+ );+ render(+ <TraceReviewPanelProvider projectId="project-id">+ <CommentDrawerController projectId="project-id" count={0}>+ {renderView}+ </CommentDrawerController>+ <EmbeddedReviewState />+ </TraceReviewPanelProvider>,+ );+ const initialRenders = renderView.mock.calls.length;+ fireEvent.click(screen.getByRole("button", { name: "Open comments" }));+ expect(screen.getByRole("status")).toHaveTextContent(target.objectId);+ expect(fetchComments).not.toHaveBeenCalled();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(renderView).toHaveBeenCalledTimes(initialRenders);+ fireEvent.click(screen.getByRole("button", { name: "Close review" }));+ expect(screen.getByRole("status")).toHaveTextContent("closed");+ expect(renderView).toHaveBeenCalledTimes(initialRenders);+ });+it("uses the fetched thread when counts are missing or stale, then opens the discussion after posting", async () => {const onCommentChange = vi.fn();const controller = (count?: number) => (@@ -164,6 +208,26 @@ describe("CommentDrawerController", () => {expect(renderView).toHaveBeenCalledTimes(initialRenders);});+ it("returns focus to the opening action when the fallback discussion closes", async () => {+ fetchComments.mockResolvedValue([{ id: "existing" }]);+ render(+ <CommentDrawerController projectId="project-id">+ {({ openDrawer }) => (+ <button onClick={() => openDrawer(target)}>More actions</button>+ )}+ </CommentDrawerController>,+ { wrapper: LayerProvider },+ );+ const trigger = screen.getByRole("button", { name: "More actions" });+ trigger.focus();+ fireEvent.click(trigger);+ const dialog = await screen.findByRole("dialog", { name: "Comments" });+ dialog.style.animationName = "none";+ screen.getByRole("button", { name: "Close comments" }).focus();+ fireEvent.keyDown(document, { key: "Escape" });+ await waitFor(() => expect(trigger).toHaveFocus());+ });+it("ignores an obsolete lookup instead of opening a second overlay", async () => {let resolveFirst!: (comments: { id: string }[]) => void;fetchComments.mockImplementation(({ objectId }) =>diff --git a/web/src/features/comments/CommentDrawerController.tsx b/web/src/features/comments/CommentDrawerController.tsxindex 4108a733f1..f43f0a642f 100644--- a/web/src/features/comments/CommentDrawerController.tsx+++ b/web/src/features/comments/CommentDrawerController.tsx@@ -1,8 +1,9 @@import { useRouter } from "next/router";-import { useState, type ReactNode } from "react";+import { useRef, useState, type ReactNode } from "react";import { type CommentObjectType } from "@langfuse/shared";import { useHasProjectAccess } from "@/src/features/rbac";import { api } from "@/src/utils/api";+import { useTraceReviewPanelOptional } from "@/src/features/traces/contexts/TraceReviewPanelContext";import {createCommentOverlayStore,type CommentTarget,@@ -54,7 +55,9 @@ export function CommentDrawerController({onCommentChange,}: CommentDrawerControllerProps) {const router = useRouter();+ const reviewPanel = useTraceReviewPanelOptional();const [store] = useState(createCommentOverlayStore);+ const triggerRef = useRef<HTMLElement | null>(null);const utils = api.useUtils();const hasReadAccess = useHasProjectAccess({projectId,@@ -73,6 +76,21 @@ export function CommentDrawerController({disabled,openDrawer: (target) => {if (disabled) return;+ triggerRef.current =+ document.activeElement instanceof HTMLElement+ ? document.activeElement+ : null;+ if (reviewPanel) {+ const actions = reviewPanel.getState().actions;+ actions.rememberTrigger(triggerRef.current);+ actions.openComments({+ target,+ onCommentChange,+ confirmDiscard: () =>+ window.confirm("Discard your unsent comment?"),+ });+ return;+ }store.getState().actions.open({target,canWrite: hasWriteAccess,@@ -87,7 +105,7 @@ export function CommentDrawerController({});},})}- {router.isReady && hasReadAccess ? (+ {!reviewPanel && router.isReady && hasReadAccess ? (<CommentOverlayState store={store} initialState={initialState}>{(overlay) => (<CommentOverlayHost@@ -95,6 +113,14 @@ export function CommentDrawerController({overlay={overlay}projectId={projectId}onCommentChange={onCommentChange}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ if (+ !store.getState().overlay?.isOpen &&+ triggerRef.current?.isConnected+ )+ triggerRef.current.focus({ preventScroll: true });+ }}/>)}</CommentOverlayState>diff --git a/web/src/features/comments/CommentList.tsx b/web/src/features/comments/CommentList.tsxindex a8282df996..70375daa4c 100644--- a/web/src/features/comments/CommentList.tsx+++ b/web/src/features/comments/CommentList.tsx@@ -21,6 +21,7 @@ type CommentListProps = {onDraftChange?: (hasDraft: boolean) => void;onMentionDropdownChange?: (isOpen: boolean) => void;isDrawerOpen?: boolean;+ isActive?: boolean;pendingSelection?: SelectionData | null;onSelectionUsed?: () => void;onCommentChange?: () => void | Promise<void>;@@ -44,6 +45,7 @@ function CommentThread({onDraftChange,onMentionDropdownChange,isDrawerOpen = false,+ isActive = true,pendingSelection,onSelectionUsed,onCommentChange,@@ -91,7 +93,7 @@ function CommentThread({return (<divclassName={cn(- "flex h-full min-h-0 flex-col overflow-hidden",+ "flex h-full min-h-0 flex-col overflow-y-auto",cardView && "rounded-md",)}>@@ -114,6 +116,7 @@ function CommentThread({{hasWriteAccess && (<div className="shrink-0 border-t p-4 pb-[max(1rem,env(safe-area-inset-bottom))]"><CommentComposer+ isActive={isActive}projectId={projectId}objectId={objectId}objectType={objectType}diff --git a/web/src/features/comments/components/CommentComposer.clienttest.tsx b/web/src/features/comments/components/CommentComposer.clienttest.tsxnew file mode 100644index 0000000000..a6dc632cb9--- /dev/null+++ b/web/src/features/comments/components/CommentComposer.clienttest.tsx@@ -0,0 +1,87 @@+import {+ act,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { CommentComposer } from "./CommentComposer";++const mocks = vi.hoisted(() => ({+ focus: vi.fn(),+ mutate: vi.fn(),+}));++vi.mock("@/src/features/rbac", () => ({ useHasProjectAccess: () => false }));+vi.mock("@/src/utils/api", () => ({+ api: {+ comments: {+ create: {+ useMutation: ({ onSuccess }: { onSuccess: () => Promise<void> }) => ({+ mutate: () => {+ mocks.mutate();+ return onSuccess();+ },+ isPending: false,+ }),+ },+ },+ },+}));+vi.mock("../hooks/useMentionAutocomplete", () => ({+ useMentionAutocomplete: () => ({+ showDropdown: false,+ closeDropdown: vi.fn(),+ updateQuery: vi.fn(),+ users: [],+ selectedIndex: 0,+ mentionStartPos: null,+ }),+}));+vi.mock("./CommentEditor", async () => {+ const { forwardRef, useImperativeHandle } = await import("react");+ return {+ CommentEditor: forwardRef(function Editor(+ { value, onChange }: { value: string; onChange: (value: string) => void },+ ref,+ ) {+ useImperativeHandle(ref, () => ({ focus: mocks.focus }));+ return (+ <textarea+ aria-label="New comment"+ value={value}+ onChange={(event) => onChange(event.target.value)}+ />+ );+ }),+ };+});++it("does not restore focus after the composer becomes inactive during comment refresh", async () => {+ let resolveRefresh!: () => void;+ const onCommentCreated = vi.fn(+ () =>+ new Promise<void>((resolve) => {+ resolveRefresh = resolve;+ }),+ );+ const composer = (isActive: boolean) => (+ <CommentComposer+ projectId="project"+ objectId="trace"+ objectType="TRACE"+ isActive={isActive}+ onCommentCreated={onCommentCreated}+ />+ );+ const { rerender } = render(composer(true));+ fireEvent.change(screen.getByRole("textbox", { name: "New comment" }), {+ target: { value: "Review note" },+ });+ fireEvent.click(screen.getByRole("button", { name: "Comment" }));+ await waitFor(() => expect(onCommentCreated).toHaveBeenCalledOnce());+ rerender(composer(false));+ await act(async () => resolveRefresh());+ expect(mocks.mutate).toHaveBeenCalledOnce();+ expect(mocks.focus).not.toHaveBeenCalled();+});diff --git a/web/src/features/comments/components/CommentComposer.tsx b/web/src/features/comments/components/CommentComposer.tsxindex 3616dadec8..419843bb29 100644--- a/web/src/features/comments/components/CommentComposer.tsx+++ b/web/src/features/comments/components/CommentComposer.tsx@@ -35,6 +35,7 @@ export function CommentComposer({onDraftChange,onMentionDropdownChange,onCommentCreated,+ isActive = true,}: {projectId: string;objectId: string;@@ -45,8 +46,10 @@ export function CommentComposer({onDraftChange?: (hasDraft: boolean) => void;onMentionDropdownChange?: (isOpen: boolean) => void;onCommentCreated: () => void | Promise<void>;+ isActive?: boolean;}) {const editorRef = useRef<CommentEditorHandle>(null);+ const formElementRef = useRef<HTMLFormElement | null>(null);const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(null,);@@ -55,6 +58,7 @@ export function CommentComposer({editorRef.current?.getCursorRect() ?? new DOMRect(),}));const attachForm = useCallback((node: HTMLFormElement | null) => {+ formElementRef.current = node;if (node) setPortalContainer(node.closest<HTMLElement>('[role="dialog"]'));}, []);const hasMembersReadAccess = useHasProjectAccess({@@ -75,7 +79,7 @@ export function CommentComposer({// Window capture runs before the overlay's document-level Escape handler.useEffect(() => {- if (!showDropdown) return;+ if (!showDropdown || !isActive) return;function dismissMentions(event: KeyboardEvent) {if (event.key !== "Escape") return;event.preventDefault();@@ -84,7 +88,7 @@ export function CommentComposer({}window.addEventListener("keydown", dismissMentions, true);return () => window.removeEventListener("keydown", dismissMentions, true);- }, [showDropdown, closeDropdown]);+ }, [showDropdown, closeDropdown, isActive]);const createComment = api.comments.create.useMutation({onSuccess: async () => {@@ -93,7 +97,12 @@ export function CommentComposer({mentions.closeDropdown();onSelectionUsed?.();await onCommentCreated();- editorRef.current?.focus();+ const element = formElementRef.current;+ if (+ element?.isConnected &&+ !element.closest('[inert], [hidden], [data-state="closed"]')+ )+ editorRef.current?.focus();},});@@ -155,6 +164,7 @@ export function CommentComposer({<Form {...form}><formref={attachForm}+ inert={!isActive}className="flex min-w-0 flex-col gap-3"onSubmit={form.handleSubmit(submit)}>@@ -181,7 +191,7 @@ export function CommentComposer({}onKeyDown={handleKeyDown}disabled={createComment.isPending}- autoFocus+ autoFocus={isActive}/></FormControl><FormMessage />@@ -189,7 +199,7 @@ export function CommentComposer({)}/><Popover- open={mentions.showDropdown}+ open={isActive && mentions.showDropdown}onOpenChange={(open) => {if (!open) mentions.closeDropdown();}}diff --git a/web/src/features/comments/components/CommentConversation.tsx b/web/src/features/comments/components/CommentConversation.tsxindex 709a6e5042..56efacbcce 100644--- a/web/src/features/comments/components/CommentConversation.tsx+++ b/web/src/features/comments/components/CommentConversation.tsx@@ -154,7 +154,7 @@ export function CommentConversation({)}<divref={commentsContainerRef}- className="min-h-0 flex-1 overflow-y-auto px-4 py-4"+ className="min-h-24 flex-1 overflow-y-auto px-4 py-4"><div className="flex min-h-full flex-col justify-end gap-4">{filteredComments.length === 0 && (diff --git a/web/src/features/comments/components/CommentOverlayHost.tsx b/web/src/features/comments/components/CommentOverlayHost.tsxindex ef39c6ec25..fb912d8150 100644--- a/web/src/features/comments/components/CommentOverlayHost.tsx+++ b/web/src/features/comments/components/CommentOverlayHost.tsx@@ -1,4 +1,4 @@-import { useState, type ReactNode } from "react";+import { useState, type ComponentProps, type ReactNode } from "react";import { useStore } from "zustand";import { useRouter } from "next/router";import { X } from "lucide-react";@@ -54,11 +54,13 @@ export function CommentOverlayHost({projectId,overlay,onCommentChange,+ onCloseAutoFocus,}: {store: CommentOverlayStore;projectId: string;overlay: CommentOverlay;onCommentChange?: () => void | Promise<void>;+ onCloseAutoFocus: ComponentProps<typeof DrawerContent>["onCloseAutoFocus"];}) {const router = useRouter();const utils = api.useUtils();@@ -93,7 +95,11 @@ export function CommentOverlayHost({if (!open) close();}}>- <DialogContent className="overflow-visible" closeOnInteractionOutside>+ <DialogContent+ className="overflow-visible"+ closeOnInteractionOutside+ onCloseAutoFocus={onCloseAutoFocus}+ ><DialogHeader><DialogTitle>Add a comment</DialogTitle></DialogHeader>@@ -139,6 +145,7 @@ export function CommentOverlayHost({}onSelectionUsed={() => actions.consumeSelection(overlay)}onCommentChange={onCommentChange}+ onCloseAutoFocus={onCloseAutoFocus}{...guardProps}/></Drawer>@@ -155,6 +162,7 @@ type CommentDrawerContentProps = {onCommentChange?: () => void | Promise<void>;onMentionDropdownChange: (isOpen: boolean) => void;onDraftChange: (hasDraft: boolean) => void;+ onCloseAutoFocus: ComponentProps<typeof DrawerContent>["onCloseAutoFocus"];};function CommentDrawerContent({@@ -167,11 +175,13 @@ function CommentDrawerContent({onCommentChange,onMentionDropdownChange,onDraftChange,+ onCloseAutoFocus,}: CommentDrawerContentProps) {return (<DrawerContentoverlayClassName="bg-primary/10"className="h-screen-with-banner max-h-screen-with-banner overflow-hidden outline-hidden"+ onCloseAutoFocus={onCloseAutoFocus}><DrawerHeader className="flex shrink-0 flex-row items-center justify-between border-b text-left"><DrawerTitle>Comments</DrawerTitle>diff --git a/web/src/features/datasets/components/ExistingDatasetItemsDropdownMenuController.clienttest.tsx b/web/src/features/datasets/components/ExistingDatasetItemsDropdownMenuController.clienttest.tsxdeleted file mode 100644index d37f0af7c1..0000000000--- a/web/src/features/datasets/components/ExistingDatasetItemsDropdownMenuController.clienttest.tsx+++ /dev/null@@ -1,204 +0,0 @@-import { fireEvent, render, screen } from "@testing-library/react";-import {- cloneElement,- type KeyboardEventHandler,- type PointerEventHandler,- type ReactElement,- type ReactNode,-} from "react";-import { vi } from "vitest";--import { ExistingDatasetItemsDropdownMenuController } from "@/src/features/datasets/components/ExistingDatasetItemsDropdownMenuController";-import { type RouterOutputs } from "@/src/utils/api";--const { radixKeyDown, radixPointerDown } = vi.hoisted(() => ({- radixKeyDown: vi.fn(),- radixPointerDown: vi.fn(),-}));--vi.mock("@/src/components/ui/dropdown-menu", () => ({- DropdownMenu: ({- children,- open,- }: {- children: ReactNode;- open: boolean;- }) => (- <div data-testid="dropdown-root" data-open={String(open)}>- {children}- </div>- ),- DropdownMenuTrigger: ({- children,- }: {- children: ReactElement<{- "aria-haspopup"?: string;- onKeyDown?: KeyboardEventHandler;- onPointerDown?: PointerEventHandler;- }>;- }) =>- cloneElement(children, {- "aria-haspopup": "menu",- onKeyDown: radixKeyDown,- onPointerDown: radixPointerDown,- }),- DropdownMenuContent: ({ children }: { children: ReactNode }) => (- <div>{children}</div>- ),- DropdownMenuItem: ({- asChild,- children,- onSelect,- }: {- asChild?: boolean;- children: ReactNode;- onSelect?: () => void;- }) =>- asChild ? (- <>{children}</>- ) : (- <button type="button" onClick={onSelect}>- {children}- </button>- ),- DropdownMenuSeparator: () => <hr />,-}));--const datasetItems = [- {- id: "dataset-item-id",- datasetId: "dataset-id",- datasetName: "Dataset name",- },-] as RouterOutputs["datasets"]["datasetItemsBasedOnTraceOrObservation"];--function renderController(props: {- datasetItems: RouterOutputs["datasets"]["datasetItemsBasedOnTraceOrObservation"];- disabled: boolean;- onOpenDialog: () => void;- onButtonClick?: () => void;-}) {- return render(- <ExistingDatasetItemsDropdownMenuController- projectId="project-id"- datasetItems={props.datasetItems}- disabled={props.disabled}- onOpenDialog={props.onOpenDialog}- >- {({ Anchor, openDropdown }) => (- <Anchor>- <button- type="button"- disabled={props.disabled}- onClick={() => {- props.onButtonClick?.();-- if (props.datasetItems.length > 0) {- openDropdown();- return;- }-- props.onOpenDialog();- }}- >- Add to datasets- </button>- </Anchor>- )}- </ExistingDatasetItemsDropdownMenuController>,- );-}--describe("ExistingDatasetItemsDropdownMenuController", () => {- beforeEach(() => {- vi.clearAllMocks();- });-- it("leaves direct opening to the button when the dropdown is inactive", () => {- const onOpenDialog = vi.fn();- const onButtonClick = vi.fn();-- renderController({- datasetItems: [],- disabled: false,- onOpenDialog,- onButtonClick,- });- fireEvent.click(screen.getByRole("button", { name: "Add to datasets" }));-- expect(onButtonClick).toHaveBeenCalledOnce();- expect(onOpenDialog).toHaveBeenCalledOnce();- expect(screen.queryByText("Add to more datasets")).not.toBeInTheDocument();- });-- it("uses the trigger only as an anchor and opens programmatically", () => {- const onOpenDialog = vi.fn();-- renderController({- datasetItems,- disabled: false,- onOpenDialog,- });- const button = screen.getByRole("button", { name: "Add to datasets" });-- expect(button).toHaveAttribute("aria-haspopup", "menu");- fireEvent.pointerDown(button);- expect(radixPointerDown).not.toHaveBeenCalled();- expect(screen.getByTestId("dropdown-root")).toHaveAttribute(- "data-open",- "false",- );-- fireEvent.click(button);-- expect(onOpenDialog).not.toHaveBeenCalled();- expect(screen.getByTestId("dropdown-root")).toHaveAttribute(- "data-open",- "true",- );- expect(screen.getByRole("link", { name: "Dataset name" })).toHaveAttribute(- "href",- "/project/project-id/datasets/dataset-id/items/dataset-item-id",- );-- fireEvent.click(- screen.getByRole("button", { name: "Add to more datasets" }),- );- expect(onOpenDialog).toHaveBeenCalledOnce();- expect(screen.getByTestId("dropdown-root")).toHaveAttribute(- "data-open",- "false",- );- });-- it("opens from ArrowDown without running Radix trigger handlers", () => {- renderController({- datasetItems,- disabled: false,- onOpenDialog: vi.fn(),- });-- fireEvent.keyDown(screen.getByRole("button", { name: "Add to datasets" }), {- key: "ArrowDown",- });-- expect(radixKeyDown).not.toHaveBeenCalled();- expect(screen.getByTestId("dropdown-root")).toHaveAttribute(- "data-open",- "true",- );- });-- it("does not open either overlay when disabled", () => {- const onOpenDialog = vi.fn();-- renderController({- datasetItems: [],- disabled: true,- onOpenDialog,- });- fireEvent.click(screen.getByRole("button", { name: "Add to datasets" }));-- expect(onOpenDialog).not.toHaveBeenCalled();- });-});diff --git a/web/src/features/datasets/components/ExistingDatasetItemsDropdownMenuController.tsx b/web/src/features/datasets/components/ExistingDatasetItemsDropdownMenuController.tsxdeleted file mode 100644index 912739dfe7..0000000000--- a/web/src/features/datasets/components/ExistingDatasetItemsDropdownMenuController.tsx+++ /dev/null@@ -1,143 +0,0 @@-import { Slot } from "@radix-ui/react-slot";-import {- createContext,- forwardRef,- type ComponentPropsWithoutRef,- type ReactElement,- type ReactNode,- useContext,- useState,-} from "react";-import Link from "next/link";-import { PlusIcon } from "lucide-react";--import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/src/components/ui/dropdown-menu";-import { type RouterOutputs } from "@/src/utils/api";--const ExistingDatasetItemsDropdownMenuContext = createContext<{- isDropdownEnabled: boolean;- openDropdown: () => void;-} | null>(null);--const PositionOnlyAnchorProxy = forwardRef<- HTMLButtonElement,- ComponentPropsWithoutRef<"button"> & {- children: ReactElement;- openDropdown: () => void;- }->(function PositionOnlyAnchorProxy(props, ref) {- const { children, openDropdown, ...radixTriggerProps } = props;-- return (- <Slot- {...radixTriggerProps}- ref={ref}- // Radix DropdownMenu has no public positioning-only anchor. Its Trigger- // currently injects opening behavior through these two handlers, so strip- // them while retaining its positioning ref and accessibility attributes.- onPointerDown={undefined}- onKeyDown={(event) => {- if (event.key === "ArrowDown") {- openDropdown();- event.preventDefault();- }- }}- >- {children}- </Slot>- );-});--function ExistingDatasetItemsDropdownMenuAnchor(props: {- children: ReactElement;-}) {- const context = useContext(ExistingDatasetItemsDropdownMenuContext);-- if (!context) {- throw new Error(- "ExistingDatasetItemsDropdownMenuAnchor must be used within ExistingDatasetItemsDropdownMenuController",- );- }-- if (context.isDropdownEnabled) {- return (- <DropdownMenuTrigger asChild>- <PositionOnlyAnchorProxy openDropdown={context.openDropdown}>- {props.children}- </PositionOnlyAnchorProxy>- </DropdownMenuTrigger>- );- }-- return <Slot>{props.children}</Slot>;-}--export function ExistingDatasetItemsDropdownMenuController(props: {- projectId: string;- datasetItems: RouterOutputs["datasets"]["datasetItemsBasedOnTraceOrObservation"];- disabled: boolean;- onOpenDialog: () => void;- children: (control: {- Anchor: typeof ExistingDatasetItemsDropdownMenuAnchor;- openDropdown: () => void;- }) => ReactNode;-}) {- const [isOpen, setIsOpen] = useState(false);- const hasDatasetItems = props.datasetItems.length > 0;- const isDropdownEnabled = hasDatasetItems && !props.disabled;- const openDialog = () => {- setIsOpen(false);- props.onOpenDialog();- };- const openDropdown = () => {- if (isDropdownEnabled) {- setIsOpen(true);- }- };-- return (- <ExistingDatasetItemsDropdownMenuContext.Provider- value={{- isDropdownEnabled,- openDropdown,- }}- >- <DropdownMenu open={isDropdownEnabled && isOpen} onOpenChange={setIsOpen}>- {props.children({- Anchor: ExistingDatasetItemsDropdownMenuAnchor,- openDropdown,- })}- {isDropdownEnabled ? (- <DropdownMenuContent align="end">- {props.datasetItems.map(- ({ id: datasetItemId, datasetName, datasetId }) => (- <DropdownMenuItem- key={datasetItemId}- className="capitalize"- asChild- >- <Link- href={`/project/${props.projectId}/datasets/${datasetId}/items/${encodeURIComponent(datasetItemId)}`}- >- {datasetName}- </Link>- </DropdownMenuItem>- ),- )}- <DropdownMenuSeparator />- <DropdownMenuItem className="capitalize" onSelect={openDialog}>- <PlusIcon size={16} className="mr-2" aria-hidden="true" />- Add to more datasets- </DropdownMenuItem>- </DropdownMenuContent>- ) : null}- </DropdownMenu>- </ExistingDatasetItemsDropdownMenuContext.Provider>- );-}diff --git a/web/src/features/datasets/hooks/useDatasetItemFromTraceOrObservation.ts b/web/src/features/datasets/hooks/useDatasetItemFromTraceOrObservation.tsdeleted file mode 100644index d1ec4cf43e..0000000000--- a/web/src/features/datasets/hooks/useDatasetItemFromTraceOrObservation.ts+++ /dev/null@@ -1,40 +0,0 @@-import { useIsAuthenticatedAndProjectMember } from "@/src/features/auth";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics";-import { useHasProjectAccess } from "@/src/features/rbac";-import { api } from "@/src/utils/api";--export const useDatasetItemFromTraceOrObservation = (props: {- projectId: string;- traceId: string;- observationId?: string;- enabled?: boolean;-}) => {- const isAuthenticatedAndProjectMember = useIsAuthenticatedAndProjectMember(- props.projectId,- );- const existingDatasetItems =- api.datasets.datasetItemsBasedOnTraceOrObservation.useQuery(- {- projectId: props.projectId,- traceId: props.traceId,- observationId: props.observationId,- },- {- enabled: (props.enabled ?? true) && isAuthenticatedAndProjectMember,- },- ).data ?? [];- const hasAccess = useHasProjectAccess({- projectId: props.projectId,- scope: "datasets:CUD",- });- const capture = usePostHogClientCapture();-- return {- existingDatasetItems,- hasAccess,- captureNewDatasetItemFormOpen: () =>- capture("dataset_item:new_from_trace_form_open", {- object: props.observationId ? "observation" : "trace",- }),- };-};diff --git a/web/src/features/datasets/index.ts b/web/src/features/datasets/index.tsindex 2c86bdbac7..66b140134a 100644--- a/web/src/features/datasets/index.ts+++ b/web/src/features/datasets/index.ts@@ -1,13 +1,11 @@// The datasets feature's public client surface (RFC rule 8). Named re-exports// only — exactly what other features already imported. The public-API dataset// services live behind server/index.ts.-export { DatasetForm } from "@/src/features/datasets/components/DatasetForm";export type { DatasetFormRef } from "@/src/features/datasets/components/DatasetForm";+export { DatasetForm } from "@/src/features/datasets/components/DatasetForm";export { DatasetSchemaHoverCard } from "@/src/features/datasets/components/DatasetSchemaHoverCard";export { DiffLabel } from "@/src/features/datasets/components/DiffLabel";-export { ExistingDatasetItemsDropdownMenuController } from "@/src/features/datasets/components/ExistingDatasetItemsDropdownMenuController";export { NewDatasetItemFromExistingObjectDialogController } from "@/src/features/datasets/components/NewDatasetItemFromExistingObjectDialogController";-export { useDatasetItemFromTraceOrObservation } from "@/src/features/datasets/hooks/useDatasetItemFromTraceOrObservation";export { calculateNumericDiff } from "@/src/features/datasets/lib/calculateBaselineDiff";export type { BaselineDiff } from "@/src/features/datasets/lib/calculateBaselineDiff";export { computeScoreDiffs } from "@/src/features/datasets/lib/computeScoreDiffs";diff --git a/web/src/features/scores/README.md b/web/src/features/scores/README.mdindex 3a05cc875a..8cab33d5be 100644--- a/web/src/features/scores/README.md+++ b/web/src/features/scores/README.md@@ -49,6 +49,10 @@ discards that local draft. Clear cancels deferred autosave, while dismissing theclear menu commits the deferred edit. Numeric validation reads native `badInput`on every input event before interpreting an empty value as a deliberate clear.+Opening annotation focuses the first score row, or Add score when no rows exist.+The ready form owns that focus handoff; reopening an active panel requests it+explicitly. Autosave and query refreshes never request focus.+## Effect inventory| Location | External system / lifecycle | Status |@@ -56,6 +60,7 @@ on every input event before interpreting an empty value as a deliberate clear.| `AnnotationFormContent` | Analytics session opens on mount and closes on unmount, using current field counts. | Retained; stable action-owner dependency. || `useAnnotationKeyboard` keydown listener | Window keyboard events for row navigation and score selection. | Retained; symmetric registration/cleanup, current values read at event time. || `useAnnotationKeyboard` capture listener | Escape focus handling before the parent drawer's capture listener. | Retained; symmetric registration/cleanup. |+| `useAnnotationKeyboard` activation focus | DOM focus when the ready form becomes active, after the opening menu closes. | Retained; scheduled frame cancelled on inactivity or unmount. || Score-comment editor | No external system: draft was mirrored from `savedComment`. | Removed; popover mount seeds the editor. |No other direct effects exist in this feature. Query, cache, and local-storagediff --git a/web/src/features/scores/actions/annotationFormActions.ts b/web/src/features/scores/actions/annotationFormActions.tsindex 026c8b51a9..ed01a42341 100644--- a/web/src/features/scores/actions/annotationFormActions.ts+++ b/web/src/features/scores/actions/annotationFormActions.ts@@ -84,7 +84,15 @@ export function createAnnotationFormActions({const latestSaves = new Map<string, number>();const pendingFields = new Map<string, number>();const failedFields = new Set<string>();-+ const serverFields = new Map(+ fields().map((field) => [annotationFieldKey(field), { ...field }]),+ );+ const sameScore = (+ left: AnnotationScoreFormData,+ right: AnnotationScoreFormData | undefined,+ ) =>+ (left.id ?? null) === (right?.id ?? null) &&+ !hasChangedAnnotationValue(left, right);const finishPendingField = (key: string) => {const remaining = (pendingFields.get(key) ?? 1) - 1;if (remaining) pendingFields.set(key, remaining);@@ -324,6 +332,76 @@ export function createAnnotationFormActions({isSaving: (key: string) => pendingFields.has(key),clear,validateNumericInput,+ reconcileServerFields(incoming: AnnotationScoreFormData[]) {+ const confirmedFields = new Map(saveStore.getState().confirmedFields);+ let changed = false;+ for (const next of incoming) {+ const key = annotationFieldKey(next);+ if (pendingFields.has(key) || failedFields.has(key)) continue;+ const current = find(key);+ const confirmed = confirmedFields.get(key);+ // A repeated pre-save snapshot is not an external edit, including+ // after a cleared row is removed. Once the server acknowledges the+ // local value, later changes can replace it.+ const previousServer = serverFields.get(key);+ if (+ confirmed &&+ confirmed.sequence > 0 &&+ !sameScore(confirmed.field, previousServer) &&+ sameScore(next, previousServer) &&+ !sameScore(next, confirmed.field)+ )+ continue;+ if (current) {+ const index = indexOf(key);+ if (+ !sameScore(current, confirmed?.field) ||+ form.getFieldState(`scoreData.${index}.value`).invalid ||+ form.getFieldState(`scoreData.${index}.stringValue`).invalid ||+ form.getFieldState(`scoreData.${index}.comment`).invalid+ )+ continue;+ const properties = [+ "id",+ "name",+ "dataType",+ "value",+ "stringValue",+ "comment",+ "timestamp",+ ] as const;+ for (const property of properties) {+ const value = next[property];+ const previous = current[property];+ const equal =+ property === "timestamp"+ ? next.timestamp?.getTime() === current.timestamp?.getTime()+ : value === previous;+ if (equal) continue;+ form.setValue(`scoreData.${index}.${property}`, value);+ changed = true;+ }+ } else {+ // Empty selections belong to the local form. Only saved server+ // scores can introduce rows during a refresh.+ if (!next.id) continue;+ const currentFields = fields();+ const before = currentFields.findIndex(+ (field) => field.name.localeCompare(next.name) > 0,+ );+ insertField(before < 0 ? currentFields.length : before, next, {+ shouldFocus: false,+ });+ changed = true;+ }+ serverFields.set(key, { ...next });+ confirmedFields.set(key, {+ field: { ...next },+ sequence: confirmed?.sequence ?? 0,+ });+ }+ if (changed) saveStore.setState({ confirmedFields });+ },addDraftTarget(key: string, destination: PreparedAnnotationTarget) {const field = find(key);const config = destination.configControl.configs.find(diff --git a/web/src/features/scores/components/AddScoreCategoryDialog.tsx b/web/src/features/scores/components/AddScoreCategoryDialog.tsxindex 0ef80def52..f7d9444d3e 100644--- a/web/src/features/scores/components/AddScoreCategoryDialog.tsx+++ b/web/src/features/scores/components/AddScoreCategoryDialog.tsx@@ -25,6 +25,7 @@ export function AddScoreCategoryDialog({analyticsData,onClose,onCategoryAdded,+ isActive = true,}: {projectId: string;config: ScoreConfigDomain;@@ -32,6 +33,7 @@ export function AddScoreCategoryDialog({analyticsData: AnnotationAnalyticsContext;onClose: () => void;onCategoryAdded: (label: string, numericValue: number) => void;+ isActive?: boolean;}) {const capture = usePostHogClientCapture();const utils = api.useUtils();@@ -70,12 +72,17 @@ export function AddScoreCategoryDialog({return (<Dialog- open+ open={isActive}onOpenChange={(open) => {if (!open) onClose();}}>- <DialogContent closeOnInteractionOutside>+ <DialogContent+ closeOnInteractionOutside+ onCloseAutoFocus={(event) => {+ if (!isActive) event.preventDefault();+ }}+ ><DialogHeader variant="action"><DialogTitle>Add category</DialogTitle><DialogDescription>diff --git a/web/src/features/scores/components/AnnotateDrawerContent.tsx b/web/src/features/scores/components/AnnotateDrawerContent.tsxdeleted file mode 100644index bb72b99f12..0000000000--- a/web/src/features/scores/components/AnnotateDrawerContent.tsx+++ /dev/null@@ -1,46 +0,0 @@-import { DrawerContent } from "@/src/components/ui/drawer";-import { AnnotationForm } from "@/src/features/scores/components/AnnotationForm";-import {- type AnalyticsData,- type ScoreTarget,-} from "@/src/features/scores/types";-import { type ScoreDomain } from "@langfuse/shared";-import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";--type AnnotateDrawerContentProps<Target extends ScoreTarget> = {- analyticsData: AnalyticsData;- scoreMetadata: {- projectId: string;- queueId?: string;- environment?: string;- };- scoreTarget: Target;- scores: WithStringifiedMetadata<ScoreDomain>[];-};--export function AnnotateDrawerContent<Target extends ScoreTarget>({- analyticsData,- scoreMetadata,- scoreTarget,- scores,-}: AnnotateDrawerContentProps<Target>) {- const hasNonAnnotationScores = scores.some(- (score) => score.source !== "ANNOTATION",- );-- return (- <DrawerContent className="p-3 [--annotation-surface:var(--modal)]">- <AnnotationForm- serverScores={scores}- scoreTarget={scoreTarget}- analyticsData={analyticsData}- scoreMetadata={scoreMetadata}- />- {hasNonAnnotationScores ? (- <div className="text-muted-foreground mt-4 text-xs">- API and eval scores visible on left. Add manual annotations above.- </div>- ) : null}- </DrawerContent>- );-}diff --git a/web/src/features/scores/components/AnnotateDrawerController.tsx b/web/src/features/scores/components/AnnotateDrawerController.tsxindex 85e1a95fc3..0406cda4b9 100644--- a/web/src/features/scores/components/AnnotateDrawerController.tsx+++ b/web/src/features/scores/components/AnnotateDrawerController.tsx@@ -2,24 +2,15 @@ import { useHasProjectAccess } from "@/src/features/rbac";import { DrawerContent, DrawerController } from "@/src/components/ui/drawer";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";import {- type AnalyticsData,type ScoreTarget,+ type AnnotationPanelData,} from "@/src/features/scores/types";-import { type ReactNode, useMemo } from "react";+import { useRef, type ReactNode } from "react";import { getAnnotationTargetType } from "@/src/features/scores/lib/annotationAnalytics";-import { AnnotateDrawerContent } from "@/src/features/scores/components/AnnotateDrawerContent";-import {- filterAndValidateDbScoreList,- ScoreDataTypeArray,- ScoreDataTypeEnum,- type ScoreDomain,-} from "@langfuse/shared";-import {- toDomainArrayWithStringifiedMetadata,- type WithStringifiedMetadata,-} from "@/src/utils/clientSideDomainTypes";-import { api } from "@/src/utils/api";-import { Button } from "@/src/components/ui/button";+import { type ScoreDomain } from "@langfuse/shared";+import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";+import { AnnotationPanelContent } from "./AnnotationPanelContent";+import { useTraceReviewPanelOptional } from "@/src/features/traces/contexts/TraceReviewPanelContext";export type AnnotateDrawerControllerProps<Target extends ScoreTarget> = {children: (control: {@@ -29,16 +20,7 @@ export type AnnotateDrawerControllerProps<Target extends ScoreTarget> = {projectId: string;};-type AnnotateDrawerState = {- analyticsData: AnalyticsData;- scoreMetadata: {- projectId: string;- queueId?: string;- environment?: string;- };- scoreTarget: ScoreTarget;- scores?: WithStringifiedMetadata<ScoreDomain>[];-};+type AnnotateDrawerState = AnnotationPanelData;type AnnotateDrawerPayload<Target extends ScoreTarget> =Target extends Extract<ScoreTarget, { type: "trace" }>@@ -51,83 +33,13 @@ type AnnotateDrawerPayload<Target extends ScoreTarget> =scores: WithStringifiedMetadata<ScoreDomain>[];};-function ConnectedAnnotateDrawerContent({- state,-}: {- state: AnnotateDrawerState;-}) {- const shouldFetchScores =- state.scores === undefined && state.scoreTarget.type === "trace";- const scoresQuery = api.events.scoresForTrace.useQuery(- {- projectId: state.scoreMetadata.projectId,- traceId:- state.scoreTarget.type === "trace" ? state.scoreTarget.traceId : "",- },- {- enabled: shouldFetchScores,- staleTime: 60 * 1000,- },- );- const fetchedScores = useMemo(() => {- const scoreTarget = state.scoreTarget;- if (!scoresQuery.data || scoreTarget.type !== "trace") return;-- const scores = filterAndValidateDbScoreList({- scores: scoresQuery.data,- dataTypes: [...ScoreDataTypeArray],- onParseError: (error) => console.error(error),- }).filter((score) => {- if (score.dataType === ScoreDataTypeEnum.CORRECTION) return false;- if (scoreTarget.observationId) {- return score.observationId === scoreTarget.observationId;- }- return !score.observationId;- });-- return toDomainArrayWithStringifiedMetadata(scores);- }, [scoresQuery.data, state.scoreTarget]);- const scores = state.scores ?? fetchedScores;-- if (scoresQuery.isError && scores === undefined) {- return (- <DrawerContent className="flex flex-col gap-3 p-3">- <p className="text-sm">Could not load scores.</p>- <Button- className="self-start"- onClick={async () => {- await scoresQuery.refetch();- }}- >- Try again- </Button>- </DrawerContent>- );- }-- if (scores === undefined) {- return (- <DrawerContent className="p-3">- <p className="text-muted-foreground text-sm">Loading scores...</p>- </DrawerContent>- );- }-- return (- <AnnotateDrawerContent- analyticsData={state.analyticsData}- scoreMetadata={state.scoreMetadata}- scoreTarget={state.scoreTarget}- scores={scores}- />- );-}-export function AnnotateDrawerController<Target extends ScoreTarget>({children,projectId,}: AnnotateDrawerControllerProps<Target>) {const capture = usePostHogClientCapture();+ const reviewPanel = useTraceReviewPanelOptional();+ const triggerRef = useRef<HTMLElement | null>(null);const hasAccess = useHasProjectAccess({projectId,scope: "scores:CUD",@@ -137,7 +49,22 @@ export function AnnotateDrawerController<Target extends ScoreTarget>({return (<DrawerController<AnnotateDrawerState>renderContent={({ state }) => (- <ConnectedAnnotateDrawerContent state={state} />+ <DrawerContent+ className="[--annotation-surface:var(--modal)]"+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ if (triggerRef.current?.isConnected)+ triggerRef.current.focus({ preventScroll: true });+ }}+ >+ <div className="min-h-0 overflow-y-auto overscroll-contain p-3">+ <AnnotationPanelContent+ data={state}+ actionButtons={null}+ isActive+ />+ </div>+ </DrawerContent>)}>{({ openDrawer }) =>@@ -151,7 +78,16 @@ export function AnnotateDrawerController<Target extends ScoreTarget>({targetType: getAnnotationTargetType(payload.scoreTarget),entryPoint: "annotate_button",});- openDrawer(payload);+ triggerRef.current =+ document.activeElement instanceof HTMLElement+ ? document.activeElement+ : null;+ if (reviewPanel) {+ reviewPanel+ .getState()+ .actions.rememberTrigger(triggerRef.current);+ reviewPanel.getState().actions.openAnnotation(payload);+ } else openDrawer(payload);},})}diff --git a/web/src/features/scores/components/AnnotationForm.tsx b/web/src/features/scores/components/AnnotationForm.tsxindex 7f62157e60..078b5190e0 100644--- a/web/src/features/scores/components/AnnotationForm.tsx+++ b/web/src/features/scores/components/AnnotationForm.tsx@@ -1,4 +1,4 @@-import React, { useEffect, useRef, useState } from "react";+import React, { useEffect, useImperativeHandle, useRef, useState } from "react";import Link from "next/link";import { Plus, Settings2 } from "lucide-react";import { useFieldArray, useForm } from "react-hook-form";@@ -43,6 +43,7 @@ import type {PreparedAnnotationTarget,ScoreTarget,AnnotationForm as AnnotationFormType,+ AnnotationRefreshHandle,} from "@/src/features/scores/types";function AnnotateHeader({@@ -92,9 +93,13 @@ const getEmptySelectedConfigIdsStorageKey = (scoreTarget: ScoreTarget) => {export function AnnotationFormContent({targets,actionButtons,+ isActive = true,+ refreshRef,}: {targets: PreparedAnnotationTarget[];actionButtons?: React.ReactNode;+ isActive?: boolean;+ refreshRef?: React.Ref<AnnotationRefreshHandle>;}) {const capture = usePostHogClientCapture();const primaryTarget = targets[0]!;@@ -132,13 +137,44 @@ export function AnnotationFormContent({deleteScore: deleteMutation.mutateAsync,}),);+ const formRootRef = useRef<HTMLDivElement | null>(null);+ const focus = useAnnotationKeyboard({+ formRootRef,+ form,+ actions,+ targets,+ isActive,+ });+ useImperativeHandle(refreshRef, () => ({+ focus,+ refresh(data) {+ const refreshed = targets.flatMap((target) => {+ const primary =+ target.scoreTarget.type === data.scoreTarget.type &&+ (target.scoreTarget.type !== "trace" ||+ data.scoreTarget.type !== "trace" ||+ target.scoreTarget.observationId ===+ data.scoreTarget.observationId);+ const scores = primary ? data.scores : data.companionTrace?.scores;+ if (!scores) return [];+ const selected = form+ .getValues("scoreData")+ .filter((field) => field.targetKey === target.key)+ .map((field) => field.configId);+ return prepareAnnotationFormData(+ transformToAnnotationScores(scores, target.configControl.configs),+ target.configControl.configs,+ selected,+ ).map((field) => ({ ...field, targetKey: target.key }));+ });+ actions.reconcileServerFields(refreshed);+ },+ }));// The analytics session follows the mounted form, not query refetches.useEffect(() => {actions.open();return () => actions.close();}, [actions]);- const formRootRef = useRef<HTMLDivElement | null>(null);- useAnnotationKeyboard({ formRootRef, form, actions, targets });const targetFor = (field: AnnotationScoreSchemaType) =>targets.find((target) => target.key === field.targetKey)!;@@ -187,6 +223,7 @@ export function AnnotationFormContent({<divref={formRootRef}data-annotation-form+ tabIndex={-1}className="ph-no-capture mx-auto w-full space-y-4 overflow-y-auto p-1 md:max-h-full"><div className="sticky top-0 z-10 flex flex-col gap-4 rounded-sm bg-[hsl(var(--annotation-surface,var(--background)))] pb-2">@@ -244,6 +281,7 @@ export function AnnotationFormContent({return config ? (<AnnotationScoreRowkey={field.id}+ isActive={isActive}onRemove={() => {if (actions.isSaving(annotationFieldKey(field))) return;getScoreConfigSelection({@@ -288,7 +326,7 @@ export function AnnotationFormContent({) : null;})}</div>- {allowManualSelection ? (+ {allowManualSelection && isActive ? (<div><PopoverControlleralign="start"@@ -333,12 +371,12 @@ export function AnnotationFormContent({{({ Trigger, disabled }) => (<Trigger asChild><Button+ data-add-scoretype="button"variant="outline"size="sm"className="gap-1.5 text-xs"disabled={disabled}- data-add-score><Plus className="size-3.5" aria-hidden="true" />Add score@@ -460,6 +498,8 @@ export function AnnotationForm<Target extends ScoreTarget>(key={target.key}targets={[target]}actionButtons={props.actionButtons}+ isActive={props.isActive}+ refreshRef={props.refreshRef}/>);}diff --git a/web/src/features/scores/components/AnnotationPanelContent.tsx b/web/src/features/scores/components/AnnotationPanelContent.tsxnew file mode 100644index 0000000000..6a1fc858da--- /dev/null+++ b/web/src/features/scores/components/AnnotationPanelContent.tsx@@ -0,0 +1,108 @@+import { type ReactNode, type Ref } from "react";+import {+ filterAndValidateDbScoreList,+ ScoreDataTypeArray,+ ScoreDataTypeEnum,+} from "@langfuse/shared";+import { Button } from "@/src/components/ui/button";+import { Skeleton } from "@/src/components/ui/skeleton";+import Header from "@/src/components/layouts/header";+import { api } from "@/src/utils/api";+import { toDomainArrayWithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";+import { AnnotationForm } from "./AnnotationForm";+import { DualAnnotationContent } from "./DualAnnotationContent";+import {+ type AnnotationPanelData,+ type AnnotationRefreshHandle,+} from "../types";++export function AnnotationPanelContent({+ data,+ actionButtons,+ isActive,+ refreshRef,+}: {+ data: AnnotationPanelData;+ actionButtons: ReactNode;+ isActive: boolean;+ refreshRef?: Ref<AnnotationRefreshHandle>;+}) {+ const target = data.scoreTarget;+ const scoresQuery = api.events.scoresForTrace.useQuery(+ {+ projectId: data.scoreMetadata.projectId,+ traceId: target.type === "trace" ? target.traceId : "",+ },+ {+ enabled: data.scores === undefined && target.type === "trace",+ staleTime: 60 * 1000,+ },+ );+ const fetchedScores =+ scoresQuery.data && target.type === "trace"+ ? toDomainArrayWithStringifiedMetadata(+ filterAndValidateDbScoreList({+ scores: scoresQuery.data,+ dataTypes: [...ScoreDataTypeArray],+ onParseError: (error) => console.error(error),+ }).filter(+ (score) =>+ score.dataType !== ScoreDataTypeEnum.CORRECTION &&+ (target.observationId+ ? score.observationId === target.observationId+ : !score.observationId),+ ),+ )+ : undefined;+ const scores = data.scores ?? fetchedScores;++ if (scores === undefined) {+ return (+ <div className="flex flex-col gap-4">+ <Header title="Annotate" actionButtons={[actionButtons]} />+ {scoresQuery.isError ? (+ <div className="flex flex-col items-start gap-3">+ <p className="text-sm">Could not load scores.</p>+ <Button+ variant="outline"+ size="sm"+ onClick={() => scoresQuery.refetch()}+ >+ Try again+ </Button>+ </div>+ ) : (+ <Skeleton className="h-48 w-full" />+ )}+ </div>+ );+ }++ return data.companionTrace &&+ target.type === "trace" &&+ target.observationId ? (+ <DualAnnotationContent+ projectId={data.scoreMetadata.projectId}+ isV4={data.analyticsData.isV4}+ traceId={target.traceId}+ observationId={target.observationId}+ traceEnvironment={data.companionTrace.environment}+ observationEnvironment={data.scoreMetadata.environment ?? "default"}+ observationScores={scores}+ traceScores={data.companionTrace.scores}+ actionButtons={actionButtons}+ isActive={isActive}+ refreshRef={refreshRef}+ />+ ) : (+ <AnnotationForm+ serverScores={scores}+ scoreTarget={target}+ analyticsData={data.analyticsData}+ scoreMetadata={data.scoreMetadata}+ actionButtons={actionButtons}+ isActive={isActive}+ refreshRef={refreshRef}+ />+ );+}diff --git a/web/src/features/scores/components/AnnotationScoreRow.tsx b/web/src/features/scores/components/AnnotationScoreRow.tsxindex 94782399f9..96f0e2f553 100644--- a/web/src/features/scores/components/AnnotationScoreRow.tsx+++ b/web/src/features/scores/components/AnnotationScoreRow.tsx@@ -56,17 +56,19 @@ import { cn } from "@/src/utils/tailwind";function CommentField({savedComment,+ localValue,+ onValueChange,disabled,loading,onSave,}: {savedComment: string | null;+ localValue: string;+ onValueChange: (value: string | null) => void;disabled: boolean;loading: boolean;onSave: (comment: string | null) => void;}) {- const [localValue, setLocalValue] = useState(savedComment || "");-const hasChanges = localValue.trim() !== (savedComment || "");return (@@ -81,7 +83,10 @@ function CommentField({type="button"size="icon-xs"loading={loading}- onClick={() => onSave(null)}+ onClick={() => {+ onSave(null);+ onValueChange(null);+ }}><Trash className="h-3 w-3" /></Button>@@ -92,7 +97,7 @@ function CommentField({<TextareaclassName="text-xs"value={localValue}- onChange={(e) => setLocalValue(e.target.value)}+ onChange={(e) => onValueChange(e.target.value)}disabled={disabled}/>@@ -107,7 +112,7 @@ function CommentField({disabled={disabled}loading={loading}onClick={() => {- setLocalValue(savedComment || "");+ onValueChange(null);}}>Discard Changes@@ -122,6 +127,7 @@ function CommentField({loading={loading}onClick={() => {onSave(localValue);+ onValueChange(null);}}>Save Changes@@ -144,6 +150,7 @@ export function AnnotationScoreRow({formRootRef,commentSaving,targetOptions,+ isActive = true,onRemove,}: {form: UseFormReturn<AnnotateFormSchemaType>;@@ -156,8 +163,12 @@ export function AnnotationScoreRow({formRootRef: React.RefObject<HTMLDivElement | null>;commentSaving: boolean;targetOptions: { target: PreparedAnnotationTarget; hasField: boolean }[];+ isActive?: boolean;onRemove: () => void;}) {+ const [commentOpen, setCommentOpen] = useState(false);+ const [commentDraft, setCommentDraft] = useState<string | null>(null);+ const [detailsOpen, setDetailsOpen] = useState(false);const score = useWatch({ control: form.control, name: `scoreData.${index}` });const fieldState = useFormState({control: form.control,@@ -234,7 +245,10 @@ export function AnnotationScoreRow({{config.description ||isPresent(config.maxValue) ||isPresent(config.minValue) ? (- <HoverCard>+ <HoverCard+ open={isActive && detailsOpen}+ onOpenChange={setDetailsOpen}+ ><HoverCardTrigger asChild><spanclassName={cn(@@ -260,7 +274,10 @@ export function AnnotationScoreRow({{score.name}</span>)}- <Popover>+ <Popover+ open={isActive && commentOpen}+ onOpenChange={setCommentOpen}+ ><PopoverTrigger asChild><Buttonvariant="link"@@ -285,7 +302,11 @@ export function AnnotationScoreRow({)}</Button></PopoverTrigger>- <PopoverContent>+ <PopoverContent+ onCloseAutoFocus={(event) => {+ if (!isActive) event.preventDefault();+ }}+ ><FormFieldcontrol={form.control}name={`scoreData.${index}.comment`}@@ -294,6 +315,8 @@ export function AnnotationScoreRow({<FormControl><CommentFieldsavedComment={score.comment ?? null}+ localValue={commentDraft ?? score.comment ?? ""}+ onValueChange={setCommentDraft}disabled={config.isArchived}loading={commentSaving}onSave={(newComment) => {@@ -409,6 +432,7 @@ export function AnnotationScoreRow({<FormItem><FormControl><CategoricalScoreInput+ isActive={isActive}projectId={target.scoreMetadata.projectId}config={config}categories={categories}@@ -440,11 +464,13 @@ export function AnnotationScoreRow({{hasScoreValue || invalid || canRemove || targetOptions.length > 0 ? (<DropdownMenuControlleralign="end"+ isActive={isActive}onCloseAutoFocus={(event) => {event.preventDefault();const nextFocus = focusFieldKey.current;focusFieldKey.current = fieldKey;commitDeferredScore();+ if (!isActive) return;const nextRow = formRootRef.current?.querySelector<HTMLElement>(`[data-score-row="${actions.indexOf(nextFocus)}"]`,);diff --git a/web/src/features/scores/components/CategoricalScoreInput.tsx b/web/src/features/scores/components/CategoricalScoreInput.tsxindex b42674847e..e0295ce999 100644--- a/web/src/features/scores/components/CategoricalScoreInput.tsx+++ b/web/src/features/scores/components/CategoricalScoreInput.tsx@@ -40,6 +40,7 @@ export function CategoricalScoreInput({name,analyticsData,onValueChange,+ isActive = true,}: {projectId: string;config: ScoreConfigDomain;@@ -49,6 +50,7 @@ export function CategoricalScoreInput({name: string;analyticsData: AnnotationAnalyticsContext;onValueChange: (value: string, numericValue?: number) => void;+ isActive?: boolean;}) {const hasConfigCudAccess = useHasProjectAccess({projectId,@@ -84,7 +86,7 @@ export function CategoricalScoreInput({<Comboboxname={name}value={value}- disabled={disabled}+ disabled={disabled || !isActive}onValueChange={onValueChange}options={categories.map((category) => ({value: category.label,@@ -167,6 +169,7 @@ export function CategoricalScoreInput({)}{pendingLabel !== null ? (<AddScoreCategoryDialog+ isActive={isActive}projectId={projectId}config={config}initialLabel={pendingLabel}diff --git a/web/src/features/scores/components/DualAnnotationContent.clienttest.tsx b/web/src/features/scores/components/DualAnnotationContent.clienttest.tsxindex 8c53872f2e..bc3b7e77b7 100644--- a/web/src/features/scores/components/DualAnnotationContent.clienttest.tsx+++ b/web/src/features/scores/components/DualAnnotationContent.clienttest.tsx@@ -24,6 +24,8 @@ import {} from "@/src/features/scores/contexts/ScoreCacheContext";import { DualAnnotationContent } from "./DualAnnotationContent";import { AnnotationForm } from "./AnnotationForm";+import { cloneElement, createRef } from "react";+import type { AnnotationRefreshHandle } from "../types";const mocks = vi.hoisted(() => ({create: vi.fn(),@@ -31,6 +33,8 @@ const mocks = vi.hoisted(() => ({remove: vi.fn(),capture: vi.fn(),headerRender: vi.fn(),+ hasConfigAccess: false,+ configsLoading: false,}));const defaultConfig = {id: "quality",@@ -59,7 +63,9 @@ vi.mock("@/src/components/layouts/header", async (importOriginal) => {};});-vi.mock("@/src/features/rbac", () => ({ useHasProjectAccess: () => false }));+vi.mock("@/src/features/rbac", () => ({+ useHasProjectAccess: () => mocks.hasConfigAccess,+}));vi.mock("@/src/features/notifications", () => ({ showErrorToast: vi.fn() }));vi.mock("@/src/features/posthog-analytics", () => ({usePostHogClientCapture: () => mocks.capture,@@ -72,8 +78,20 @@ vi.mock("@/src/utils/api", async () => {return {api: {scoreConfigs: {- all: { useQuery: () => ({ isLoading: false, data: { configs } }) },+ all: {+ useQuery: () => ({+ isLoading: mocks.configsLoading,+ data: { configs },+ }),+ },+ appendCategory: {+ useMutation: () => ({ mutate: vi.fn(), isPending: false }),+ },},+ useUtils: () => ({+ scoreConfigs: { invalidate: vi.fn() },+ annotationQueues: { invalidate: vi.fn() },+ }),scores: {createAnnotationScore: {useMutation: (@@ -117,6 +135,33 @@ const content = (/>);+function serverQualityScore() {+ return {+ longStringValue: "",+ executionTraceId: null,+ datasetRunId: null,+ id: "saved-quality",+ configId: "quality",+ name: "Quality",+ source: "ANNOTATION",+ dataType: "BOOLEAN",+ value: 0,+ stringValue: "False",+ comment: "Saved comment",+ traceId: "trace",+ observationId: "observation",+ projectId: "project",+ timestamp: new Date(),+ createdAt: new Date(),+ updatedAt: new Date(),+ metadata: {},+ environment: "default",+ queueId: null,+ sessionId: null,+ authorUserId: null,+ } satisfies ScoreDomain;+}+function renderContent(children = content) {const queryClient = new QueryClient({defaultOptions: { mutations: { retry: false } },@@ -141,6 +186,8 @@ function renderContent(children = content) {describe("unified annotation targets", () => {beforeEach(() => {vi.clearAllMocks();+ mocks.hasConfigAccess = false;+ mocks.configsLoading = false;Element.prototype.scrollIntoView = vi.fn();localStorage.clear();localStorage.setItem(@@ -198,6 +245,382 @@ describe("unified annotation targets", () => {).not.toBeInTheDocument();});+ it("focuses the first score on activation without taking focus on rerenders", async () => {+ mocks.create.mockResolvedValue({});+ const refreshRef = createRef<AnnotationRefreshHandle>();+ const view = (isActive: boolean) => (+ <>+ <button>Outside annotation</button>+ {cloneElement(content, { isActive, refreshRef })}+ </>+ );+ const rendered = renderContent(view(false));+ const outside = screen.getByRole("button", { name: "Outside annotation" });+ outside.focus();+ rendered.rerenderContent(view(true));+ const row = screen.getByRole("group", { name: "Quality" });+ await waitFor(() => expect(row).toHaveFocus());+ fireEvent.keyDown(row, { key: "2" });+ await waitFor(() => expect(mocks.create).toHaveBeenCalledOnce());+ expect(row).toHaveFocus();++ outside.focus();+ rendered.rerenderContent(view(true));+ await new Promise((resolve) => requestAnimationFrame(resolve));+ expect(outside).toHaveFocus();+ act(() => refreshRef.current?.focus());+ await waitFor(() => expect(row).toHaveFocus());+ outside.focus();+ rendered.rerenderContent(view(false));+ rendered.rerenderContent(view(true));+ await waitFor(() => expect(row).toHaveFocus());+ });++ it("focuses a loaded empty form unless its drawer is closing", async () => {+ localStorage.clear();+ mocks.configsLoading = true;+ const view = (state: "open" | "closed") => (+ <>+ <button>Outside annotation</button>+ <div data-state={state}>{content}</div>+ </>+ );+ const rendered = renderContent(view("open"));+ expect(screen.queryByRole("button", { name: "Add score" })).toBeNull();+ mocks.configsLoading = false;+ rendered.rerenderContent(view("open"));+ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Add score" })).toHaveFocus(),+ );++ mocks.configsLoading = true;+ rendered.rerenderContent(view("closed"));+ const outside = screen.getByRole("button", { name: "Outside annotation" });+ outside.focus();+ mocks.configsLoading = false;+ rendered.rerenderContent(view("closed"));+ await new Promise((resolve) => requestAnimationFrame(resolve));+ expect(outside).toHaveFocus();+ });++ it("suspends score shortcuts while a shared action menu is open", async () => {+ mocks.create.mockResolvedValue({});+ const view = (menuOpen: boolean) => (+ <>+ {content}+ {menuOpen && <div role="menu" aria-label="More actions" />}+ </>+ );+ const rendered = renderContent(view(false));+ const row = screen.getByRole("group", { name: "Quality" });+ await waitFor(() => expect(row).toHaveFocus());+ rendered.rerenderContent(view(true));+ await act(async () => fireEvent.keyDown(row, { key: "2" }));+ expect(mocks.create).not.toHaveBeenCalled();+ rendered.rerenderContent(view(false));+ row.focus();+ fireEvent.keyDown(row, { key: "2" });+ await waitFor(() => expect(mocks.create).toHaveBeenCalledOnce());+ });++ it("preserves inactive drafts without handling keyboard navigation until reopened", () => {+ configs.push({+ ...defaultConfig,+ id: "feedback",+ name: "Feedback",+ dataType: "TEXT",+ categories: null,+ });+ localStorage.setItem(+ "emptySelectedConfigIds:observation",+ JSON.stringify(["quality", "feedback"]),+ );+ const rendered = renderContent();+ fireEvent.change(screen.getByRole("textbox"), {+ target: { value: "Keep this draft" },+ });+ rendered.rerenderContent(cloneElement(content, { isActive: false }));+ fireEvent.keyDown(document.body, { key: "ArrowDown" });+ expect(document.activeElement).toBe(document.body);+ expect(mocks.create).not.toHaveBeenCalled();+ rendered.rerenderContent(content);+ expect(screen.getByRole("textbox")).toHaveValue("Keep this draft");+ fireEvent.keyDown(document.body, { key: "ArrowDown" });+ expect(screen.getByRole("group", { name: "Feedback" })).toHaveFocus();+ });++ it.each(["picker", "row menu", "category"])(+ "hides an open %s portal while annotation is inactive",+ async (control) => {+ if (control === "picker")+ configs.push({ ...defaultConfig, id: "accuracy", name: "Accuracy" });+ if (control === "category") {+ configs.push({+ ...defaultConfig,+ id: "accuracy",+ name: "Accuracy",+ dataType: "CATEGORICAL",+ categories: [+ { label: "Fully correct", value: 1 },+ { label: "Partly correct", value: 0 },+ ],+ });+ localStorage.setItem(+ "emptySelectedConfigIds:observation",+ JSON.stringify(["accuracy"]),+ );+ }+ const rendered = renderContent();+ if (control === "row menu") {+ fireEvent.keyDown(+ screen.getByRole("button", { name: "Score actions for Quality" }),+ { key: "ArrowDown" },+ );+ expect(await screen.findByRole("menu")).toBeVisible();+ } else {+ const trigger =+ control === "picker"+ ? screen.getByRole("button", { name: "Add score" })+ : within(screen.getByRole("group", { name: "Accuracy" })).getByRole(+ "combobox",+ );+ fireEvent.click(trigger);+ expect(await screen.findByRole("listbox")).toBeVisible();+ }+ rendered.rerenderContent(cloneElement(content, { isActive: false }));+ await waitFor(() => {+ expect(screen.queryByRole("listbox")).not.toBeInTheDocument();+ expect(screen.queryByRole("menu")).not.toBeInTheDocument();+ });+ expect(mocks.create).not.toHaveBeenCalled();+ },+ );++ it("refreshes clean scores on reopening while retaining text and score-comment drafts", async () => {+ configs.push({+ ...defaultConfig,+ id: "feedback",+ name: "Feedback",+ dataType: "TEXT",+ categories: undefined,+ });+ localStorage.setItem(+ "emptySelectedConfigIds:observation",+ JSON.stringify(["quality", "feedback"]),+ );+ const score = serverQualityScore();+ const refreshRef = createRef<AnnotationRefreshHandle>();+ renderContent(+ cloneElement(content, {+ observationScores: [{ ...score, metadata: "{}" }],+ refreshRef,+ }),+ );+ const quality = screen.getByRole("group", { name: "Quality" });+ const feedback = within(+ screen.getByRole("group", { name: "Feedback" }),+ ).getByRole("textbox");+ fireEvent.change(feedback, { target: { value: "Unsent feedback" } });+ fireEvent.click(within(quality).getByTitle("Add or view score comment"));+ const comment = await within(screen.getByRole("dialog")).findByRole(+ "textbox",+ );+ fireEvent.change(comment, { target: { value: "Unsent score comment" } });+ act(() =>+ refreshRef.current?.refresh({+ scoreTarget: {+ type: "trace",+ traceId: "trace",+ observationId: "observation",+ },+ scoreMetadata: { projectId: "project" },+ analyticsData: { type: "trace", source: "TraceDetail", isV4: true },+ scores: [+ {+ ...score,+ metadata: "{}",+ value: 1,+ stringValue: "True",+ comment: "Updated remotely",+ },+ ],+ companionTrace: {+ environment: "default",+ scores: [+ {+ ...score,+ metadata: "{}",+ id: "trace-quality",+ observationId: null,+ value: 1,+ stringValue: "True",+ },+ ],+ },+ }),+ );+ expect(+ within(screen.getByRole("group", { name: "Quality (Trace)" })).getByRole(+ "radio",+ { name: /True/ },+ ),+ ).toHaveAttribute("aria-checked", "true");+ expect(+ within(quality).getByRole("radio", { name: /True/ }),+ ).toHaveAttribute("aria-checked", "true");+ expect(feedback).toHaveValue("Unsent feedback");+ expect(comment).toHaveValue("Unsent score comment");+ expect(mocks.create).not.toHaveBeenCalled();+ expect(mocks.update).not.toHaveBeenCalled();+ });++ it("retains pending and just-saved values across lagging refreshes, then accepts acknowledged external edits", async () => {+ const score = serverQualityScore();+ const pending = deferred();+ mocks.update.mockReturnValueOnce(pending.promise);+ const refreshRef = createRef<AnnotationRefreshHandle>();+ renderContent(+ cloneElement(content, {+ observationScores: [{ ...score, metadata: "{}" }],+ refreshRef,+ }),+ );+ const row = screen.getByRole("group", { name: "Quality" });+ const refresh = (value: number, scoresPresent = true) =>+ act(() =>+ refreshRef.current?.refresh({+ scoreTarget: {+ type: "trace",+ traceId: "trace",+ observationId: "observation",+ },+ scoreMetadata: { projectId: "project" },+ analyticsData: { type: "trace", source: "TraceDetail", isV4: true },+ scores: scoresPresent+ ? [+ {+ ...score,+ metadata: "{}",+ value,+ stringValue: value ? "True" : "False",+ },+ ]+ : [],+ companionTrace: { environment: "default", scores: [] },+ }),+ );+ fireEvent.click(within(row).getByRole("radio", { name: /True/ }));+ await waitFor(() => expect(mocks.update).toHaveBeenCalledOnce());+ refresh(0);+ expect(within(row).getByRole("radio", { name: /True/ })).toHaveAttribute(+ "aria-checked",+ "true",+ );+ await act(async () => pending.resolve({}));+ refresh(0);+ expect(within(row).getByRole("radio", { name: /True/ })).toHaveAttribute(+ "aria-checked",+ "true",+ );+ refresh(1);+ refresh(0);+ expect(within(row).getByRole("radio", { name: /False/ })).toHaveAttribute(+ "aria-checked",+ "true",+ );+ refresh(0, false);+ expect(within(row).getByRole("radio", { name: /False/ })).toHaveAttribute(+ "aria-checked",+ "false",+ );+ expect(mocks.update).toHaveBeenCalledOnce();++ refresh(0);+ const clearing = deferred();+ mocks.remove.mockReturnValueOnce(clearing.promise);+ fireEvent.keyDown(+ screen.getByRole("button", { name: "Score actions for Quality" }),+ { key: "ArrowDown" },+ );+ fireEvent.click(+ await screen.findByRole("menuitem", { name: "Clear score" }),+ );+ await waitFor(() => expect(mocks.remove).toHaveBeenCalledOnce());+ await act(async () => clearing.resolve({}));+ fireEvent.keyDown(+ screen.getByRole("button", { name: "Score actions for Quality" }),+ { key: "ArrowDown" },+ );+ fireEvent.click(+ await screen.findByRole("menuitem", { name: "Remove score" }),+ );+ refresh(0);+ expect(+ screen.queryByRole("group", { name: "Quality" }),+ ).not.toBeInTheDocument();++ refresh(1);+ expect(screen.getByRole("radio", { name: /True/ })).toHaveAttribute(+ "aria-checked",+ "true",+ );+ });++ it("hides the score comment portal without losing its unsaved draft", async () => {+ mocks.create.mockResolvedValue({});+ const rendered = renderContent();+ fireEvent.click(screen.getByRole("radio", { name: /True/ }));+ await waitFor(() =>+ expect(+ screen.getByRole("status", { name: "Score save status" }),+ ).toHaveTextContent("Saved"),+ );+ fireEvent.click(screen.getByTitle("Add or view score comment"));+ fireEvent.change(screen.getByRole("textbox"), {+ target: { value: "Unsent score comment" },+ });+ rendered.rerenderContent(cloneElement(content, { isActive: false }));+ await waitFor(() =>+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument(),+ );+ rendered.rerenderContent(content);+ expect(await screen.findByRole("textbox")).toHaveValue(+ "Unsent score comment",+ );+ expect(mocks.update).not.toHaveBeenCalled();+ });++ it("retains an unfinished new category while its annotation panel is inactive", async () => {+ mocks.hasConfigAccess = true;+ configs.push({+ ...defaultConfig,+ id: "accuracy",+ name: "Accuracy",+ dataType: "CATEGORICAL",+ categories: [{ label: "Good", value: 1 }],+ });+ localStorage.setItem(+ "emptySelectedConfigIds:observation",+ JSON.stringify(["accuracy"]),+ );+ const rendered = renderContent();+ fireEvent.click(screen.getByRole("button", { name: "Add new category" }));+ fireEvent.change(screen.getByRole("textbox", { name: "Category name" }), {+ target: { value: "Needs follow-up" },+ });+ rendered.rerenderContent(cloneElement(content, { isActive: false }));+ await waitFor(() =>+ expect(+ screen.queryByRole("dialog", { name: "Add category" }),+ ).not.toBeInTheDocument(),+ );+ rendered.rerenderContent(content);+ expect(+ await screen.findByRole("textbox", { name: "Category name" }),+ ).toHaveValue("Needs follow-up");+ expect(mocks.create).not.toHaveBeenCalled();+ });+it("chooses a target before the first save and cannot change it during or after saving", async () => {const pending = deferred();mocks.create.mockReturnValue(pending.promise);diff --git a/web/src/features/scores/components/DualAnnotationContent.tsx b/web/src/features/scores/components/DualAnnotationContent.tsxindex 5136cf3071..1e3b62edea 100644--- a/web/src/features/scores/components/DualAnnotationContent.tsx+++ b/web/src/features/scores/components/DualAnnotationContent.tsx@@ -6,6 +6,7 @@ import {} from "@/src/features/scores/components/AnnotationForm";import { Skeleton } from "@/src/components/ui/skeleton";import { prepareCombinedAnnotationTargets } from "@/src/features/scores/lib/prepareAnnotationFormData";+import { type AnnotationRefreshHandle } from "../types";interface DualAnnotationContentProps {projectId: string;@@ -16,6 +17,9 @@ interface DualAnnotationContentProps {observationEnvironment: string;observationScores: WithStringifiedMetadata<ScoreDomain>[];traceScores: WithStringifiedMetadata<ScoreDomain>[];+ actionButtons?: React.ReactNode;+ isActive?: boolean;+ refreshRef?: React.Ref<AnnotationRefreshHandle>;}export function DualAnnotationContent({@@ -27,6 +31,9 @@ export function DualAnnotationContent({observationEnvironment,observationScores,traceScores,+ actionButtons,+ isActive = true,+ refreshRef,}: DualAnnotationContentProps) {const observation = usePreparedAnnotationFormTarget({serverScores: observationScores,@@ -51,6 +58,9 @@ export function DualAnnotationContent({observation.target,trace.target,])}+ actionButtons={actionButtons}+ isActive={isActive}+ refreshRef={refreshRef}/>)}</div>diff --git a/web/src/features/scores/hooks/useAnnotationKeyboard.ts b/web/src/features/scores/hooks/useAnnotationKeyboard.tsindex 6f1d3fa11f..1f5be50df3 100644--- a/web/src/features/scores/hooks/useAnnotationKeyboard.ts+++ b/web/src/features/scores/hooks/useAnnotationKeyboard.ts@@ -1,4 +1,4 @@-import { useEffect, type RefObject } from "react";+import { useCallback, useEffect, useRef, type RefObject } from "react";import type { UseFormReturn } from "react-hook-form";import type {AnnotateFormSchemaType,@@ -21,12 +21,48 @@ export function useAnnotationKeyboard({form,actions,targets,+ isActive,}: {formRootRef: RefObject<HTMLDivElement | null>;form: UseFormReturn<AnnotateFormSchemaType>;actions: AnnotationFormActions;targets: PreparedAnnotationTarget[];+ isActive: boolean;}) {+ const focusFrame = useRef<number | null>(null);+ const focus = useCallback(() => {+ if (focusFrame.current !== null) cancelAnimationFrame(focusFrame.current);+ // Focus after panel layout, once the opening menu has released focus.+ focusFrame.current = requestAnimationFrame(() => {+ focusFrame.current = null;+ const root = formRootRef.current;+ if (+ !root?.isConnected ||+ root.closest('[hidden], [inert], [data-state="closed"]') ||+ hasBlockingOverlay(root)+ )+ return;+ const active = document.activeElement;+ if (+ active instanceof HTMLElement &&+ root.contains(active) &&+ active.closest("[data-score-row], [data-add-score]")+ )+ return;+ const entry = root.querySelector<HTMLElement>(+ "[data-score-row], [data-add-score]:not(:disabled)",+ );+ (entry ?? root).focus();+ });+ }, [formRootRef]);++ useEffect(() => {+ if (isActive) focus();+ return () => {+ if (focusFrame.current !== null) cancelAnimationFrame(focusFrame.current);+ };+ }, [isActive, focus]);+// Keyboard navigation uses real DOM focus with a// spreadsheet-style navigate-vs-edit split (single source of truth, one// outline, never trapped):@@ -38,6 +74,7 @@ export function useAnnotationKeyboard({// - `1`-`9` pick the Nth option of the focused row (option rows only).// A focused text field owns its keys; an open popover/drawer suspends these.useEffect(() => {+ if (!isActive) return;const targetFor = (field: AnnotationScoreSchemaType) =>targets.find((target) => target.key === field.targetKey)!;const configFor = (field: AnnotationScoreSchemaType | undefined) =>@@ -234,7 +271,7 @@ export function useAnnotationKeyboard({};window.addEventListener("keydown", handleKeyDown);return () => window.removeEventListener("keydown", handleKeyDown);- }, [actions, form, formRootRef, targets]);+ }, [actions, form, formRootRef, targets, isActive]);// `Esc` leaves a focused score field (back to its row) without// dismissing a wrapping drawer. Vaul/Radix DismissableLayer listens for Esc on@@ -243,6 +280,7 @@ export function useAnnotationKeyboard({// from closing. Scoped to fields inside this form (a portaled comment popover// is not inside the form root, so its own Esc-to-close still works).useEffect(() => {+ if (!isActive) return;const onEscapeCapture = (event: KeyboardEvent) => {if (event.key !== "Escape") return;const root = formRootRef.current;@@ -262,5 +300,7 @@ export function useAnnotationKeyboard({};window.addEventListener("keydown", onEscapeCapture, true);return () => window.removeEventListener("keydown", onEscapeCapture, true);- }, [formRootRef]);+ }, [formRootRef, isActive]);++ return focus;}diff --git a/web/src/features/scores/index.ts b/web/src/features/scores/index.tsindex 561b705dd6..69642b6f6a 100644--- a/web/src/features/scores/index.ts+++ b/web/src/features/scores/index.ts@@ -19,7 +19,6 @@ export {} from "@/src/features/scores/adapters";export { AnnotateDrawerController } from "@/src/features/scores/components/AnnotateDrawerController";export { AnnotationForm } from "@/src/features/scores/components/AnnotationForm";-export { DualAnnotationContent } from "@/src/features/scores/components/DualAnnotationContent";export { ScoreRow } from "@/src/features/scores/components/ScoreRow";export { MultiSelectKeyValues } from "@/src/features/scores/components/multi-select-key-values";export {diff --git a/web/src/features/scores/lib/keyboardShortcuts.ts b/web/src/features/scores/lib/keyboardShortcuts.tsindex 214c338045..5519fd215e 100644--- a/web/src/features/scores/lib/keyboardShortcuts.ts+++ b/web/src/features/scores/lib/keyboardShortcuts.ts@@ -95,7 +95,7 @@ export function isOpenDialogPresent(): boolean {export function hasBlockingOverlay(root: HTMLElement | null): boolean {if (typeof document === "undefined") return false;const overlays = document.querySelectorAll(- '[role="dialog"]:not([aria-hidden="true"]), [role="menu"][data-state="open"]',+ '[role="dialog"]:not([aria-hidden="true"]):not([data-state="closed"]), [role="menu"]:not([data-state="closed"])',);for (const overlay of overlays) {if (!root || !overlay.contains(root)) return true;diff --git a/web/src/features/scores/types.ts b/web/src/features/scores/types.tsindex 5508437ad5..02d5c52ee5 100644--- a/web/src/features/scores/types.ts+++ b/web/src/features/scores/types.ts@@ -74,6 +74,26 @@ export type AnalyticsData = {| "SessionTable";};+export type AnnotationPanelData = {+ analyticsData: AnalyticsData;+ scoreMetadata: {+ projectId: string;+ queueId?: string;+ environment?: string;+ };+ scoreTarget: ScoreTarget;+ scores?: WithStringifiedMetadata<ScoreDomain>[];+ companionTrace?: {+ environment: string;+ scores: WithStringifiedMetadata<ScoreDomain>[];+ };+};++export type AnnotationRefreshHandle = {+ focus: () => void;+ refresh: (data: AnnotationPanelData) => void;+};+export type AnnotateFormSchemaType = z.infer<typeof AnnotateFormSchema>;export type AnnotationScoreSchemaType = z.infer<typeof AnnotationScoreDataSchema@@ -102,6 +122,8 @@ export type ScoreConfigSelection =| { mode: "selectable" };export type AnnotationForm<Target extends ScoreTarget> = {+ refreshRef?: React.Ref<AnnotationRefreshHandle>;+ isActive?: boolean;scoreTarget: Target;serverScores: WithStringifiedMetadata<ScoreDomain>[] | ScoreAggregate;scoreMetadata: {diff --git a/web/src/features/sessions/ConnectedModernSessionBodyLegacy.tsx b/web/src/features/sessions/ConnectedModernSessionBodyLegacy.tsxindex bcb4b1ce93..1d5440f25d 100644--- a/web/src/features/sessions/ConnectedModernSessionBodyLegacy.tsx+++ b/web/src/features/sessions/ConnectedModernSessionBodyLegacy.tsx@@ -394,7 +394,7 @@ export function ConnectedModernSessionBodyLegacy({};return (- <div className="bg-background relative grid min-h-0 flex-1 grid-rows-[minmax(10rem,13rem)_minmax(0,1fr)] gap-x-4 overflow-hidden lg:grid-cols-[clamp(200px,24vw,296px)_minmax(0,1fr)] lg:grid-rows-1">+ <div className="bg-background relative grid min-h-0 flex-1 grid-rows-[minmax(10rem,13rem)_minmax(0,1fr)] gap-x-4 overflow-hidden @3xl/session-workspace:grid-cols-[clamp(200px,24cqw,296px)_minmax(0,1fr)] @3xl/session-workspace:grid-rows-1">{tracesState.type === "loading" ? (<ModernSessionSidebar state="loading" />) : (diff --git a/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsx b/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsxindex cb495c93a5..62f1ceb645 100644--- a/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsx+++ b/web/src/features/sessions/ConnectedModernSessionBodyTimeline.tsx@@ -405,7 +405,7 @@ export function ConnectedModernSessionBodyTimeline({};return (- <div className="bg-background relative grid min-h-0 flex-1 grid-rows-[minmax(10rem,13rem)_minmax(0,1fr)] gap-x-4 overflow-hidden lg:grid-cols-[clamp(200px,24vw,296px)_minmax(0,1fr)] lg:grid-rows-1">+ <div className="bg-background relative grid min-h-0 flex-1 grid-rows-[minmax(10rem,13rem)_minmax(0,1fr)] gap-x-4 overflow-hidden @3xl/session-workspace:grid-cols-[clamp(200px,24cqw,296px)_minmax(0,1fr)] @3xl/session-workspace:grid-rows-1">{tracesState.type === "loading" ? (<ModernSessionSidebar state="loading" />) : (diff --git a/web/src/features/sessions/README.md b/web/src/features/sessions/README.mdnew file mode 100644index 0000000000..8e573317a3--- /dev/null+++ b/web/src/features/sessions/README.md@@ -0,0 +1,16 @@+# Session review++`SessionPages` owns one keyed `TraceReviewPanelProvider` per project/session.+Header, trace-row, and timeline actions open the same persistent Comments or+Annotate editor. Query data stays in tRPC; draft state belongs to the mounted+editor and the shared review store.++`SessionReviewWorkspace` subscribes only to the active review mode. It measures+available space and lays out session content beside or above the review panel.+Its layout effects control the resizable-panel API and reveal review inside+the narrow workspace scrollport; changing layout+keeps the session and both editors mounted. Modern session minimap/feed grids+use the session column's container width.++Trace peek is a sibling outside the session review provider. Its review context+and mobile overlays remain independent of the underlying session.diff --git a/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.stories.tsx b/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.stories.tsxindex c6760ad7c8..64639b7c06 100644--- a/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.stories.tsx+++ b/web/src/features/sessions/SessionConversationTimeline/SessionConversationTimeline.stories.tsx@@ -2255,7 +2255,7 @@ export const UseObservationFilters = meta.story({page.getByRole("menuitem", { name: "Annotate" }),).toBeInTheDocument();await expect(- page.getByRole("menuitem", { name: "Add comment" }),+ page.getByRole("menuitem", { name: "Comments" }),).toBeInTheDocument();await expect(page.getByRole("menuitem", { name: "Add to dataset" }),diff --git a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx b/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsxindex 1a5149b31e..236d7e0091 100644--- a/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx+++ b/web/src/features/sessions/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace.tsx@@ -161,7 +161,7 @@ function SessionObservationActionsMenuContent({disabled={actions.comment.disabled}onSelect={() => actions.comment.onSelect(observation)}>- Add comment+ Comments</DropdownMenuItem><DropdownMenuItemdisabled={actions.addToDataset.disabled}diff --git a/web/src/features/sessions/SessionPages.tsx b/web/src/features/sessions/SessionPages.tsxindex b6828fa35e..7d3bbe058e 100644--- a/web/src/features/sessions/SessionPages.tsx+++ b/web/src/features/sessions/SessionPages.tsx@@ -36,7 +36,7 @@ import {LockIcon,MessageSquare,MessageSquareOff,- ListPlus,+ Plus,MoreVertical,SquarePen,} from "lucide-react";@@ -112,6 +112,8 @@ import { ModernSessionHeaderActionsController } from "@/src/features/sessions/Moimport { useIsFeatureEnabled } from "@/src/features/feature-flags";import { useIsMobile } from "@/src/hooks/use-mobile";import { useStore } from "zustand";+import { TraceReviewPanelProvider } from "@/src/features/traces/contexts/TraceReviewPanelContext";+import { SessionReviewWorkspace } from "@/src/features/sessions/SessionReviewWorkspace";import { useHistoryEntryRevisit } from "@/src/features/sessions/useHistoryEntryRevisit";import {areDetailPageListsEqual,@@ -528,127 +530,255 @@ export const SessionPage: React.FC<{return (<SessionDetailStoreProvider store={sessionDetailStore}>- <Page- headerProps={{- title: sessionId,- itemType: "SESSION",- breadcrumb: [- {- name: "Sessions",- href: `/project/${projectId}/sessions`,- },- ],- actionButtonsLeft: (- <div className="flex items-center gap-0">- <PublishSessionSwitch- projectId={projectId}- sessionId={sessionId}- isPublic={session.data?.public ?? false}- key="publish"- size="icon-xs"- />- <CopySessionIdButton key="copy-id" sessionId={sessionId} />- </div>- ),- actionButtonsRight: (- <>- {webCalloutAction && (- <WebCalloutButton action={webCalloutAction} />- )}- <Button- variant="outline"- size="icon"- onClick={onDownloadSessionAsJson}- title="Download session as JSON"- >- <Download className="h-4 w-4" />- </Button>- {!router.query.peek && (- <DetailPageNav- key="nav"- currentId={encodeURIComponent(sessionId)}- path={(entry) =>- `/project/${projectId}/sessions/${encodeURIComponent(entry.id)}`- }- listKey="sessions"+ <TraceReviewPanelProvider+ key={`${projectId}:${sessionId}`}+ projectId={projectId}+ initialComments={+ router.query.peek+ ? undefined+ : getCommentDrawerInitialStateFromUrl(router.query)+ }+ >+ <Page+ headerProps={{+ title: sessionId,+ itemType: "SESSION",+ breadcrumb: [+ {+ name: "Sessions",+ href: `/project/${projectId}/sessions`,+ },+ ],+ actionButtonsLeft: (+ <div className="flex items-center gap-0">+ <PublishSessionSwitch+ projectId={projectId}+ sessionId={sessionId}+ isPublic={session.data?.public ?? false}+ key="publish"+ size="icon-xs"/>- )}- <CommentDrawerController- key="comment"- projectId={projectId}- initialState={() =>- getCommentDrawerInitialStateFromUrl(router.query)- }- count={getNumberFromMap(sessionCommentCounts.data, sessionId)}- >- {({ disabled, openDrawer }) => (- <Button- type="button"- variant="outline"- disabled={disabled}- onClick={() =>- openDrawer({- type: "comments",- objectId: sessionId,- objectType: "SESSION",- })+ <CopySessionIdButton key="copy-id" sessionId={sessionId} />+ </div>+ ),+ actionButtonsRight: (+ <>+ {webCalloutAction && (+ <WebCalloutButton action={webCalloutAction} />+ )}+ <Button+ variant="outline"+ size="icon"+ onClick={onDownloadSessionAsJson}+ title="Download session as JSON"+ >+ <Download className="h-4 w-4" />+ </Button>+ {!router.query.peek && (+ <DetailPageNav+ key="nav"+ currentId={encodeURIComponent(sessionId)}+ path={(entry) =>+ `/project/${projectId}/sessions/${encodeURIComponent(entry.id)}`}- className="gap-1"- >- {disabled ? (- <MessageSquareOff className="text-muted-foreground h-4 w-4" />- ) : (- <>- <MessageSquare className="h-4 w-4" />- <span>Add comment</span>- {getNumberFromMap(- sessionCommentCounts.data,- sessionId,- ) ? (- <ActionButtonCountBadge- count={- getNumberFromMap(- sessionCommentCounts.data,- sessionId,- ) ?? 0- }- />- ) : null}- </>- )}- </Button>+ listKey="sessions"+ />)}- </CommentDrawerController>- <div className="flex items-start">- <AnnotateDrawerController projectId={projectId}>+ <CommentDrawerController+ key="comment"+ projectId={projectId}+ count={getNumberFromMap(sessionCommentCounts.data, sessionId)}+ >{({ disabled, openDrawer }) => (<Button+ type="button"variant="outline"- size="default"disabled={disabled}- className="rounded-r-none"onClick={() =>+ openDrawer({+ type: "comments",+ objectId: sessionId,+ objectType: "SESSION",+ })+ }+ className="gap-1"+ >+ {disabled ? (+ <MessageSquareOff className="text-muted-foreground h-4 w-4" />+ ) : (+ <>+ <MessageSquare className="h-4 w-4" />+ <span>Comments</span>+ {getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ ) ? (+ <ActionButtonCountBadge+ count={+ getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ ) ?? 0+ }+ />+ ) : null}+ </>+ )}+ </Button>+ )}+ </CommentDrawerController>+ <div className="flex items-start gap-2">+ <AnnotateDrawerController projectId={projectId}>+ {({ disabled, openDrawer }) => (+ <Button+ variant="outline"+ size="default"+ disabled={disabled}+ onClick={() =>+ openDrawer({+ scoreTarget: { type: "session", sessionId },+ scores: session.data?.scores ?? [],+ analyticsData: {+ type: "session",+ source: "SessionDetail",+ isV4: false,+ },+ scoreMetadata: {+ projectId,+ environment: session.data?.environment,+ },+ })+ }+ >+ {disabled ? (+ <LockIcon className="mr-1.5 h-3 w-3" />+ ) : (+ <SquarePen className="mr-1.5 h-4 w-4" />+ )}+ <span>Annotate</span>+ </Button>+ )}+ </AnnotateDrawerController>+ <AnnotationQueueItemDropdownMenuController+ projectId={projectId}+ objectId={sessionId}+ objectType="SESSION"+ analyticsData={{ source: "SessionDetail", isV4: false }}+ >+ {({ disabled, totalCount, Trigger }) => (+ <Trigger asChild>+ <Button+ variant="outline"+ disabled={disabled !== undefined}+ className="gap-1.5"+ >+ <Plus className="h-4 w-4" />+ <span>Add to</span>+ {totalCount > 0 && (+ <ActionButtonCountBadge count={totalCount} />+ )}+ <ChevronDown className="h-3 w-3" />+ </Button>+ </Trigger>+ )}+ </AnnotationQueueItemDropdownMenuController>+ </div>+ <div className="flex items-center">+ <div className="mx-1">+ <Switch+ checked={showCorrections}+ onCheckedChange={setShowCorrectionsForSession}+ size="sm"+ />+ </div>+ <span className="text-muted-foreground text-xs">+ Show corrections+ </span>+ </div>+ </>+ ),+ // Mobile compact header: the same session actions as full-width+ // labeled menu rows for the `⋯` overflow popover, instead of the+ // inline icon toolbar. Session-to-session nav stays desktop-only.+ actionButtonsMenu: ({ closeMenu }) => (+ <>+ <PublishSessionSwitch+ projectId={projectId}+ sessionId={sessionId}+ isPublic={session.data?.public ?? false}+ label="Share"+ />+ <CopySessionIdButton sessionId={sessionId} layout="menu" />+ <CommentDrawerController+ projectId={projectId}+ count={getNumberFromMap(sessionCommentCounts.data, sessionId)}+ >+ {({ disabled, openDrawer }) => (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ disabled={disabled}+ onClick={() => {+ closeMenu({ handoffFocus: true });+ openDrawer({+ type: "comments",+ objectId: sessionId,+ objectType: "SESSION",+ });+ }}+ className="w-full justify-start gap-2 font-normal"+ >+ {disabled ? (+ <MessageSquareOff className="text-muted-foreground h-4 w-4" />+ ) : (+ <MessageSquare className="h-4 w-4" />+ )}+ <span className="text-sm">Comments</span>+ {!disabled &&+ getNumberFromMap(sessionCommentCounts.data, sessionId) ? (+ <ActionButtonCountBadge+ count={+ getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ ) ?? 0+ }+ />+ ) : null}+ </Button>+ )}+ </CommentDrawerController>+ <AnnotateDrawerController projectId={projectId}>+ {({ disabled, openDrawer }) => (+ <Button+ variant="ghost"+ size="sm"+ disabled={disabled}+ className="w-full justify-start gap-2 font-normal"+ onClick={() => {+ closeMenu({ handoffFocus: true });openDrawer({scoreTarget: { type: "session", sessionId },scores: session.data?.scores ?? [],analyticsData: {- type: "trace",- source: "TraceDetail",+ type: "session",+ source: "SessionDetail",isV4: false,},scoreMetadata: {projectId,environment: session.data?.environment,},- })- }+ });+ }}>{disabled ? (- <LockIcon className="mr-1.5 h-3 w-3" />+ <LockIcon className="h-3 w-3" />) : (- <SquarePen className="mr-1.5 h-4 w-4" />+ <SquarePen className="h-4 w-4" />)}- <span>Annotate</span>+ <span className="text-sm">Annotate</span></Button>)}</AnnotateDrawerController>@@ -661,253 +791,133 @@ export const SessionPage: React.FC<{{({ disabled, totalCount, Trigger }) => (<Trigger asChild><Button- variant="outline"+ variant="ghost"+ size="sm"disabled={disabled !== undefined}- className="rounded-l-none rounded-r-md border-l-2"+ className="w-full justify-start gap-2 font-normal">- <span className="relative mr-1 text-xs">- <ChevronDown className="h-3 w-3" />- {totalCount > 0 && (- <AnnotationQueueItemCountBadge- totalCount={totalCount}- layout="toolbar"- />- )}- </span>+ <Plus className="h-4 w-4" />+ <span className="text-sm">Add to</span>+ {totalCount > 0 && (+ <AnnotationQueueItemCountBadge+ totalCount={totalCount}+ layout="menu"+ />+ )}</Button></Trigger>)}</AnnotationQueueItemDropdownMenuController>- </div>- <div className="flex items-center">- <div className="mx-1">+ {webCalloutAction && (+ <WebCalloutButton action={webCalloutAction} layout="menu" />+ )}+ <Button+ variant="ghost"+ size="sm"+ onClick={onDownloadSessionAsJson}+ className="w-full justify-start gap-2 font-normal"+ >+ <Download className="h-4 w-4" />+ <span className="text-sm">Download JSON</span>+ </Button>+ <label className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5">+ <span className="text-sm">Show corrections</span><Switchchecked={showCorrections}onCheckedChange={setShowCorrectionsForSession}size="sm"/>- </div>- <span className="text-muted-foreground text-xs">- Show corrections- </span>- </div>- </>- ),- // Mobile compact header: the same session actions as full-width- // labeled menu rows for the `⋯` overflow popover, instead of the- // inline icon toolbar. Session-to-session nav stays desktop-only.- actionButtonsMenu: (- <>- <PublishSessionSwitch- projectId={projectId}- sessionId={sessionId}- isPublic={session.data?.public ?? false}- label="Share"- />- <CopySessionIdButton sessionId={sessionId} layout="menu" />- <CommentDrawerController- projectId={projectId}- count={getNumberFromMap(sessionCommentCounts.data, sessionId)}- >- {({ disabled, openDrawer }) => (- <Button- type="button"- variant="ghost"- size="sm"- disabled={disabled}- onClick={() =>- openDrawer({- type: "comments",- objectId: sessionId,- objectType: "SESSION",- })- }- className="w-full justify-start gap-2 font-normal"- >- {disabled ? (- <MessageSquareOff className="text-muted-foreground h-4 w-4" />- ) : (- <MessageSquare className="h-4 w-4" />- )}- <span className="text-sm">Add comment</span>- {!disabled &&- getNumberFromMap(sessionCommentCounts.data, sessionId) ? (- <ActionButtonCountBadge- count={- getNumberFromMap(- sessionCommentCounts.data,- sessionId,- ) ?? 0- }- />- ) : null}- </Button>- )}- </CommentDrawerController>- <AnnotateDrawerController projectId={projectId}>- {({ disabled, openDrawer }) => (- <Button- variant="ghost"- size="sm"- disabled={disabled}- className="w-full justify-start gap-2 font-normal"- onClick={() =>- openDrawer({- scoreTarget: { type: "session", sessionId },- scores: session.data?.scores ?? [],- analyticsData: {- type: "trace",- source: "TraceDetail",- isV4: false,- },- scoreMetadata: {- projectId,- environment: session.data?.environment,- },- })- }- >- {disabled ? (- <LockIcon className="h-3 w-3" />- ) : (- <SquarePen className="h-4 w-4" />- )}- <span className="text-sm">Annotate</span>- </Button>- )}- </AnnotateDrawerController>- <AnnotationQueueItemDropdownMenuController- projectId={projectId}- objectId={sessionId}- objectType="SESSION"- analyticsData={{ source: "SessionDetail", isV4: false }}- >- {({ disabled, totalCount, Trigger }) => (- <Trigger asChild>- <Button- variant="ghost"- size="sm"- disabled={disabled !== undefined}- className="w-full justify-start gap-2 font-normal"+ </label>+ </>+ ),+ }}+ >+ <SessionReviewWorkspace projectId={projectId}>+ <div className="flex h-full flex-col overflow-auto">+ <SessionControlsBar+ isMobile={isMobile}+ desktopClassName="bg-background sticky top-0 z-40 flex flex-wrap gap-2 border-b p-4"+ summary={+ <>+ <span className="text-sm font-bold">Session controls</span>+ <span+ className="text-muted-foreground min-w-0 truncate text-xs"+ title={`${session.data?.traces.length ?? 0} traces · ${usdFormatter(+ session.data?.totalCost ?? 0,+ 2,+ )}`}>- <ListPlus className="h-4 w-4" />- <span className="text-sm">- Add to human annotation queue- </span>- {totalCount > 0 && (- <AnnotationQueueItemCountBadge- totalCount={totalCount}- layout="menu"- />- )}- </Button>- </Trigger>- )}- </AnnotationQueueItemDropdownMenuController>- {webCalloutAction && (- <WebCalloutButton action={webCalloutAction} layout="menu" />- )}- <Button- variant="ghost"- size="sm"- onClick={onDownloadSessionAsJson}- className="w-full justify-start gap-2 font-normal"+ {session.data?.traces.length ?? 0} traces ·{" "}+ {usdFormatter(session.data?.totalCost ?? 0, 2)}+ </span>+ </>+ }>- <Download className="h-4 w-4" />- <span className="text-sm">Download JSON</span>- </Button>- <label className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5">- <span className="text-sm">Show corrections</span>- <Switch- checked={showCorrections}- onCheckedChange={setShowCorrectionsForSession}- size="sm"- />- </label>- </>- ),- }}- >- <div className="flex h-full flex-col overflow-auto">- <SessionControlsBar- isMobile={isMobile}- desktopClassName="bg-background sticky top-0 z-40 flex flex-wrap gap-2 border-b p-4"- summary={- <>- <span className="text-sm font-bold">Session controls</span>- <span- className="text-muted-foreground min-w-0 truncate text-xs"- title={`${session.data?.traces.length ?? 0} traces · ${usdFormatter(- session.data?.totalCost ?? 0,- 2,- )}`}+ {session.data?.users?.length ? (+ <SessionUsers+ projectId={projectId}+ users={session.data.users}+ />+ ) : null}+ <Badge variant="outline">+ Total traces: {session.data?.traces.length}+ </Badge>+ {session.data && (+ <Badge variant="outline">+ Total cost: {usdFormatter(session.data.totalCost, 2)}+ </Badge>+ )}+ <SessionScores scores={session.data?.scores ?? []} />+ </SessionControlsBar>+ <div ref={parentRef} className="flex-1 overflow-auto p-4">+ <div+ style={{+ height: `${virtualizer.getTotalSize()}px`,+ width: "100%",+ position: "relative",+ }}>- {session.data?.traces.length ?? 0} traces ·{" "}- {usdFormatter(session.data?.totalCost ?? 0, 2)}- </span>- </>- }- >- {session.data?.users?.length ? (- <SessionUsers projectId={projectId} users={session.data.users} />- ) : null}- <Badge variant="outline">- Total traces: {session.data?.traces.length}- </Badge>- {session.data && (- <Badge variant="outline">- Total cost: {usdFormatter(session.data.totalCost, 2)}- </Badge>- )}- <SessionScores scores={session.data?.scores ?? []} />- </SessionControlsBar>- <div ref={parentRef} className="flex-1 overflow-auto p-4">- <div- style={{- height: `${virtualizer.getTotalSize()}px`,- width: "100%",- position: "relative",- }}- >- {virtualItems.map((virtualItem) => {- const trace = session.data?.traces[virtualItem.index];- if (!trace) return null;-- return (- <SessionVirtualizedRow- key={virtualItem.key}- itemKey={String(virtualItem.key)}- measurementKey={`${String(virtualItem.key)}:${showCorrections}`}- source="legacy"- virtualItem={virtualItem}- virtualizer={virtualizer}- >- <LazyTraceRow- trace={trace}- projectId={projectId}- openPeek={openPeek}- traceCommentCounts={asCommentCounts(- traceCommentCounts.data,- )}- index={virtualItem.index}- />- </SessionVirtualizedRow>- );- })}+ {virtualItems.map((virtualItem) => {+ const trace = session.data?.traces[virtualItem.index];+ if (!trace) return null;++ return (+ <SessionVirtualizedRow+ key={virtualItem.key}+ itemKey={String(virtualItem.key)}+ measurementKey={`${String(virtualItem.key)}:${showCorrections}`}+ source="legacy"+ virtualItem={virtualItem}+ virtualizer={virtualizer}+ >+ <LazyTraceRow+ trace={trace}+ projectId={projectId}+ openPeek={openPeek}+ traceCommentCounts={asCommentCounts(+ traceCommentCounts.data,+ )}+ index={virtualItem.index}+ />+ </SessionVirtualizedRow>+ );+ })}+ </div>+ </div></div>- </div>- </div>- <TablePeekViewTraceDetail- itemType="TRACE"- detailNavigationKey="traces"- closePeek={closePeek}- expandPeek={expandPeek}- resolveDetailNavigationPath={resolveDetailNavigationPath}- tableName="sessions"- isV4={false}- projectId={projectId}- />- </Page>+ </SessionReviewWorkspace>+ </Page>+ </TraceReviewPanelProvider>+ <TablePeekViewTraceDetail+ itemType="TRACE"+ detailNavigationKey="traces"+ closePeek={closePeek}+ expandPeek={expandPeek}+ resolveDetailNavigationPath={resolveDetailNavigationPath}+ tableName="sessions"+ isV4={false}+ projectId={projectId}+ /></SessionDetailStoreProvider>);};@@ -1587,119 +1597,280 @@ const LoadedSessionEventsPage: React.FC<{const virtualItems = virtualizer.getVirtualItems();return (<SessionDetailStoreProvider store={sessionDetailStore}>- <Page- headerProps={{- title: sessionId,- itemType: "SESSION",- breadcrumb: [- {- name: "Sessions",- href: `/project/${projectId}/sessions`,- },- ],- actionButtonsLeft: !isModernSessionEnabled ? (- <div className="flex items-center gap-0">- <PublishSessionSwitch- projectId={projectId}- sessionId={sessionId}- isPublic={session.public}- key="publish"- size="icon-xs"- />- <CopySessionIdButton key="copy-id" sessionId={sessionId} />- </div>- ) : undefined,- actionButtonsRight: (- <>- {webCalloutAction && (- <WebCalloutButton action={webCalloutAction} />- )}- {!router.query.peek && (- <DetailPageNav- key="nav"- currentId={encodeURIComponent(sessionId)}- path={(entry) =>- `/project/${projectId}/sessions/${encodeURIComponent(entry.id)}`- }- listKey="sessions"+ <TraceReviewPanelProvider+ key={`${projectId}:${sessionId}`}+ projectId={projectId}+ initialComments={+ router.query.peek+ ? undefined+ : getCommentDrawerInitialStateFromUrl(router.query)+ }+ >+ <Page+ headerProps={{+ title: sessionId,+ itemType: "SESSION",+ breadcrumb: [+ {+ name: "Sessions",+ href: `/project/${projectId}/sessions`,+ },+ ],+ actionButtonsLeft: !isModernSessionEnabled ? (+ <div className="flex items-center gap-0">+ <PublishSessionSwitch+ projectId={projectId}+ sessionId={sessionId}+ isPublic={session.public}+ key="publish"+ size="icon-xs"/>- )}- <CommentDrawerController- key="comment"- projectId={projectId}- initialState={() =>- getCommentDrawerInitialStateFromUrl(router.query)- }- count={getNumberFromMap(sessionCommentCounts.data, sessionId)}- >- {({ disabled, openDrawer }) => (- <Button- type="button"- variant="outline"- disabled={disabled}- onClick={() =>- openDrawer({- type: "comments",- objectId: sessionId,- objectType: "SESSION",- })+ <CopySessionIdButton key="copy-id" sessionId={sessionId} />+ </div>+ ) : undefined,+ actionButtonsRight: (+ <>+ {webCalloutAction && (+ <WebCalloutButton action={webCalloutAction} />+ )}+ {!router.query.peek && (+ <DetailPageNav+ key="nav"+ currentId={encodeURIComponent(sessionId)}+ path={(entry) =>+ `/project/${projectId}/sessions/${encodeURIComponent(entry.id)}`}- className="gap-1"- >- {disabled ? (- <MessageSquareOff className="text-muted-foreground h-4 w-4" />- ) : (- <>- <MessageSquare className="h-4 w-4" />- <span>Add comment</span>- {getNumberFromMap(- sessionCommentCounts.data,- sessionId,- ) ? (- <ActionButtonCountBadge- count={- getNumberFromMap(- sessionCommentCounts.data,- sessionId,- ) ?? 0- }- />+ listKey="sessions"+ />+ )}+ <CommentDrawerController+ key="comment"+ projectId={projectId}+ count={getNumberFromMap(sessionCommentCounts.data, sessionId)}+ >+ {({ disabled, openDrawer }) => (+ <Button+ type="button"+ variant="outline"+ disabled={disabled}+ onClick={() =>+ openDrawer({+ type: "comments",+ objectId: sessionId,+ objectType: "SESSION",+ })+ }+ className="gap-1"+ >+ {disabled ? (+ <MessageSquareOff className="text-muted-foreground h-4 w-4" />+ ) : (+ <>+ <MessageSquare className="h-4 w-4" />+ <span>Comments</span>+ {getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ ) ? (+ <ActionButtonCountBadge+ count={+ getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ ) ?? 0+ }+ />+ ) : null}+ </>+ )}+ </Button>+ )}+ </CommentDrawerController>+ <div className="flex items-start gap-2">+ <AnnotateDrawerController projectId={projectId}>+ {({ disabled, openDrawer }) => (+ <Button+ variant="outline"+ size="default"+ disabled={disabled}+ onClick={() =>+ openDrawer({+ scoreTarget: { type: "session", sessionId },+ scores: session.scores,+ analyticsData: {+ type: "session",+ source: "SessionDetail",+ isV4: true,+ },+ scoreMetadata: {+ projectId,+ environment: session.environment,+ },+ })+ }+ >+ {disabled ? (+ <LockIcon className="mr-1.5 h-3 w-3" />+ ) : (+ <SquarePen className="mr-1.5 h-4 w-4" />+ )}+ <span>Annotate</span>+ {isModernSessionEnabled && annotationCount > 0 ? (+ <span className="ml-1">+ <ActionButtonCountBadge count={annotationCount} />+ </span>) : null}- </>+ </Button>)}- </Button>+ </AnnotateDrawerController>+ <AnnotationQueueItemDropdownMenuController+ projectId={projectId}+ objectId={sessionId}+ objectType="SESSION"+ analyticsData={{ source: "SessionDetail", isV4: true }}+ >+ {({ disabled, totalCount, Trigger }) => (+ <Trigger asChild>+ <Button+ variant="outline"+ disabled={disabled !== undefined}+ className="gap-1.5"+ >+ <Plus className="h-4 w-4" />+ <span>Add to</span>+ {totalCount > 0 && (+ <ActionButtonCountBadge count={totalCount} />+ )}+ <ChevronDown className="h-3 w-3" />+ </Button>+ </Trigger>+ )}+ </AnnotationQueueItemDropdownMenuController>+ </div>+ {!isModernSessionEnabled ? (+ <label className="flex items-center gap-1.5">+ <Switch+ checked={showCorrections}+ onCheckedChange={setShowCorrectionsForSession}+ size="sm"+ />+ <span className="text-muted-foreground text-xs">+ Show corrections+ </span>+ </label>+ ) : (+ <ModernSessionHeaderActionsController+ projectId={projectId}+ sessionId={sessionId}+ isPublic={session.public}+ {...(!isSessionTimelineEnabled+ ? {+ showCorrections,+ showInlineToolCalls,+ showSystemPrompt,+ onShowCorrectionsChange: setShowCorrectionsForSession,+ onShowInlineToolCallsChange:+ setInlineToolCallsForSession,+ onShowSystemPromptChange:+ setShowSystemPromptForSession,+ }+ : {})}+ >+ <DropdownMenuTrigger asChild>+ <Button+ variant="outline"+ size="icon"+ aria-label="Session actions"+ >+ <MoreVertical className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ </ModernSessionHeaderActionsController>)}- </CommentDrawerController>- <div className="flex items-start">+ </>+ ),+ // Mobile compact header: the same session actions as full-width+ // labeled menu rows for the `⋯` overflow popover, instead of the+ // inline icon toolbar. Session-to-session nav stays desktop-only.+ actionButtonsMenu: ({ closeMenu }) => (+ <>+ <PublishSessionSwitch+ projectId={projectId}+ sessionId={sessionId}+ isPublic={session.public}+ label="Share"+ />+ <CopySessionIdButton sessionId={sessionId} layout="menu" />+ <CommentDrawerController+ projectId={projectId}+ count={getNumberFromMap(sessionCommentCounts.data, sessionId)}+ >+ {({ disabled, openDrawer }) => (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ disabled={disabled}+ onClick={() => {+ closeMenu({ handoffFocus: true });+ openDrawer({+ type: "comments",+ objectId: sessionId,+ objectType: "SESSION",+ });+ }}+ className="w-full justify-start gap-2 font-normal"+ >+ {disabled ? (+ <MessageSquareOff className="text-muted-foreground h-4 w-4" />+ ) : (+ <MessageSquare className="h-4 w-4" />+ )}+ <span className="text-sm">Comments</span>+ {!disabled &&+ getNumberFromMap(sessionCommentCounts.data, sessionId) ? (+ <ActionButtonCountBadge+ count={+ getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ ) ?? 0+ }+ />+ ) : null}+ </Button>+ )}+ </CommentDrawerController><AnnotateDrawerController projectId={projectId}>{({ disabled, openDrawer }) => (<Button- variant="outline"- size="default"+ variant="ghost"+ size="sm"disabled={disabled}- className="rounded-r-none"- onClick={() =>+ className="w-full justify-start gap-2 font-normal"+ onClick={() => {+ closeMenu({ handoffFocus: true });openDrawer({scoreTarget: { type: "session", sessionId },scores: session.scores,analyticsData: {- type: "trace",- source: "TraceDetail",+ type: "session",+ source: "SessionDetail",isV4: true,},scoreMetadata: {projectId,environment: session.environment,},- })- }+ });+ }}>{disabled ? (- <LockIcon className="mr-1.5 h-3 w-3" />+ <LockIcon className="h-3 w-3" />) : (- <SquarePen className="mr-1.5 h-4 w-4" />+ <SquarePen className="h-4 w-4" />)}- <span>Annotate</span>+ <span className="text-sm">Annotate</span>{isModernSessionEnabled && annotationCount > 0 ? (<span className="ml-1"><ActionButtonCountBadge count={annotationCount} />@@ -1717,388 +1888,235 @@ const LoadedSessionEventsPage: React.FC<{{({ disabled, totalCount, Trigger }) => (<Trigger asChild><Button- variant="outline"+ variant="ghost"+ size="sm"disabled={disabled !== undefined}- className="rounded-l-none rounded-r-md border-l-2"+ className="w-full justify-start gap-2 font-normal">- <span className="relative mr-1 text-xs">- <ChevronDown className="h-3 w-3" />- {totalCount > 0 && (- <AnnotationQueueItemCountBadge- totalCount={totalCount}- layout="toolbar"- />- )}- </span>+ <Plus className="h-4 w-4" />+ <span className="text-sm">Add to</span>+ {totalCount > 0 && (+ <AnnotationQueueItemCountBadge+ totalCount={totalCount}+ layout="menu"+ />+ )}</Button></Trigger>)}</AnnotationQueueItemDropdownMenuController>- </div>- {!isModernSessionEnabled ? (- <label className="flex items-center gap-1.5">- <Switch- checked={showCorrections}- onCheckedChange={setShowCorrectionsForSession}- size="sm"- />- <span className="text-muted-foreground text-xs">- Show corrections- </span>- </label>- ) : (- <ModernSessionHeaderActionsController- projectId={projectId}- sessionId={sessionId}- isPublic={session.public}- {...(!isSessionTimelineEnabled- ? {- showCorrections,- showInlineToolCalls,- showSystemPrompt,- onShowCorrectionsChange: setShowCorrectionsForSession,- onShowInlineToolCallsChange:- setInlineToolCallsForSession,- onShowSystemPromptChange: setShowSystemPromptForSession,- }- : {})}- >- <DropdownMenuTrigger asChild>- <Button- variant="outline"- size="icon"- aria-label="Session actions"- >- <MoreVertical className="h-4 w-4" />- </Button>- </DropdownMenuTrigger>- </ModernSessionHeaderActionsController>- )}- </>- ),- // Mobile compact header: the same session actions as full-width- // labeled menu rows for the `⋯` overflow popover, instead of the- // inline icon toolbar. Session-to-session nav stays desktop-only.- actionButtonsMenu: (- <>- <PublishSessionSwitch- projectId={projectId}- sessionId={sessionId}- isPublic={session.public}- label="Share"- />- <CopySessionIdButton sessionId={sessionId} layout="menu" />- <CommentDrawerController- projectId={projectId}- count={getNumberFromMap(sessionCommentCounts.data, sessionId)}- >- {({ disabled, openDrawer }) => (- <Button- type="button"- variant="ghost"- size="sm"- disabled={disabled}- onClick={() =>- openDrawer({- type: "comments",- objectId: sessionId,- objectType: "SESSION",- })- }- className="w-full justify-start gap-2 font-normal"- >- {disabled ? (- <MessageSquareOff className="text-muted-foreground h-4 w-4" />- ) : (- <MessageSquare className="h-4 w-4" />- )}- <span className="text-sm">Add comment</span>- {!disabled &&- getNumberFromMap(sessionCommentCounts.data, sessionId) ? (- <ActionButtonCountBadge- count={- getNumberFromMap(- sessionCommentCounts.data,- sessionId,- ) ?? 0- }- />- ) : null}- </Button>- )}- </CommentDrawerController>- <AnnotateDrawerController projectId={projectId}>- {({ disabled, openDrawer }) => (- <Button- variant="ghost"- size="sm"- disabled={disabled}- className="w-full justify-start gap-2 font-normal"- onClick={() =>- openDrawer({- scoreTarget: { type: "session", sessionId },- scores: session.scores,- analyticsData: {- type: "trace",- source: "TraceDetail",- isV4: true,- },- scoreMetadata: {- projectId,- environment: session.environment,- },- })- }- >- {disabled ? (- <LockIcon className="h-3 w-3" />- ) : (- <SquarePen className="h-4 w-4" />- )}- <span className="text-sm">Annotate</span>- {isModernSessionEnabled && annotationCount > 0 ? (- <span className="ml-1">- <ActionButtonCountBadge count={annotationCount} />- </span>- ) : null}- </Button>+ {webCalloutAction && (+ <WebCalloutButton action={webCalloutAction} layout="menu" />)}- </AnnotateDrawerController>- <AnnotationQueueItemDropdownMenuController- projectId={projectId}- objectId={sessionId}- objectType="SESSION"- analyticsData={{ source: "SessionDetail", isV4: true }}- >- {({ disabled, totalCount, Trigger }) => (- <Trigger asChild>- <Button- variant="ghost"+ {!isModernSessionEnabled || !isSessionTimelineEnabled ? (+ <label className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5">+ <span className="text-sm">Show corrections</span>+ <Switch+ checked={showCorrections}+ onCheckedChange={setShowCorrectionsForSession}size="sm"- disabled={disabled !== undefined}- className="w-full justify-start gap-2 font-normal"- >- <ListPlus className="h-4 w-4" />- <span className="text-sm">- Add to human annotation queue- </span>- {totalCount > 0 && (- <AnnotationQueueItemCountBadge- totalCount={totalCount}- layout="menu"- />- )}- </Button>- </Trigger>- )}- </AnnotationQueueItemDropdownMenuController>- {webCalloutAction && (- <WebCalloutButton action={webCalloutAction} layout="menu" />- )}- {!isModernSessionEnabled || !isSessionTimelineEnabled ? (- <label className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5">- <span className="text-sm">Show corrections</span>- <Switch- checked={showCorrections}- onCheckedChange={setShowCorrectionsForSession}- size="sm"- />- </label>- ) : null}- {isModernSessionEnabled && !isSessionTimelineEnabled ? (- <label className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5">- <span className="text-sm">Show system prompt</span>- <Switch- checked={showSystemPrompt}- onCheckedChange={setShowSystemPromptForSession}- size="sm"- />- </label>- ) : null}- </>- ),- }}- >- <div- className={- isModernSessionEnabled- ? "flex h-full min-h-0 flex-col overflow-hidden"- : "flex h-full flex-col overflow-auto"- }+ />+ </label>+ ) : null}+ {isModernSessionEnabled && !isSessionTimelineEnabled ? (+ <label className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5">+ <span className="text-sm">Show system prompt</span>+ <Switch+ checked={showSystemPrompt}+ onCheckedChange={setShowSystemPromptForSession}+ size="sm"+ />+ </label>+ ) : null}+ </>+ ),+ }}>- {!isModernSessionEnabled && hasSessionControls ? (- <SessionControlsBar- isMobile={isMobile && !isModernSessionEnabled}- desktopClassName="bg-background sticky top-0 z-40 flex flex-wrap items-center gap-2 border-b p-4"- summary={- <>- <span className="text-sm font-bold">Session controls</span>- <span- className="text-muted-foreground min-w-0 truncate text-xs"- title={`${session.countTraces} traces · ${usdFormatter(- session.totalCost ?? 0,- 2,- )}`}- >- {session.countTraces} traces ·{" "}- {usdFormatter(session.totalCost ?? 0, 2)}- </span>- </>+ <SessionReviewWorkspace projectId={projectId}>+ <div+ className={+ isModernSessionEnabled+ ? "flex h-full min-h-0 flex-col overflow-hidden"+ : "flex h-full flex-col overflow-auto"}>- {/* Saved Views */}- {!isModernSessionEnabled ? (- <TableViewPresetsDrawer- viewConfig={{- tableName: TableViewPresetTableName.SessionDetail,- projectId,- controllers: viewControllers,- }}- currentState={{- orderBy: null,- filters: queryFilter.filterState,- columnOrder,- columnVisibility,- searchQuery: "",- }}- systemFilterPresets={SESSION_DETAIL_SYSTEM_PRESETS}- triggerId={SESSION_DETAIL_VIEW_TRIGGER_ID}- />- ) : null}+ {!isModernSessionEnabled && hasSessionControls ? (+ <SessionControlsBar+ isMobile={isMobile && !isModernSessionEnabled}+ desktopClassName="bg-background sticky top-0 z-40 flex flex-wrap items-center gap-2 border-b p-4"+ summary={+ <>+ <span className="text-sm font-bold">+ Session controls+ </span>+ <span+ className="text-muted-foreground min-w-0 truncate text-xs"+ title={`${session.countTraces} traces · ${usdFormatter(+ session.totalCost ?? 0,+ 2,+ )}`}+ >+ {session.countTraces} traces ·{" "}+ {usdFormatter(session.totalCost ?? 0, 2)}+ </span>+ </>+ }+ >+ {/* Saved Views */}+ {!isModernSessionEnabled ? (+ <TableViewPresetsDrawer+ viewConfig={{+ tableName: TableViewPresetTableName.SessionDetail,+ projectId,+ controllers: viewControllers,+ }}+ currentState={{+ orderBy: null,+ filters: queryFilter.filterState,+ columnOrder,+ columnVisibility,+ searchQuery: "",+ }}+ systemFilterPresets={SESSION_DETAIL_SYSTEM_PRESETS}+ triggerId={SESSION_DETAIL_VIEW_TRIGGER_ID}+ />+ ) : null}- {/* Refines the selected view by filtering observations within each+ {/* Refines the selected view by filtering observations within eachtrace (it does not filter the list of traces) — labelled to sayso (LFE-10520). */}- {!isModernSessionEnabled ? (- <PopoverFilterBuilder- key={viewControllers.filterEditorResetKey}- columns={filterColumns}- filterState={visibleFilterState}- onChange={queryFilter.setFilterState}- columnsWithCustomSelect={filterColumnsWithCustomSelect}- label="Filter observations"- // Analytics (LFE-10781): session-detail observation refinement is a- // v3/legacy surface (the v4 events table filters via the grammar bar).- tableName="session-detail"- isV4={false}- />- ) : null}+ {!isModernSessionEnabled ? (+ <PopoverFilterBuilder+ key={viewControllers.filterEditorResetKey}+ columns={filterColumns}+ filterState={visibleFilterState}+ onChange={queryFilter.setFilterState}+ columnsWithCustomSelect={filterColumnsWithCustomSelect}+ label="Filter observations"+ // Analytics (LFE-10781): session-detail observation refinement is a+ // v3/legacy surface (the v4 events table filters via the grammar bar).+ tableName="session-detail"+ isV4={false}+ />+ ) : null}- {/* Separator */}- {!isModernSessionEnabled ? (- <Separator orientation="vertical" className="h-6" />- ) : null}+ {/* Separator */}+ {!isModernSessionEnabled ? (+ <Separator orientation="vertical" className="h-6" />+ ) : null}- {/* Stats stay in the toolbar for the existing card layout. Modern+ {/* Stats stay in the toolbar for the existing card layout. ModernSession shows trace count and cost in its minimap header. */}- {!isModernSessionEnabled ? (- <>- <Badge variant="outline">- Total traces: {session.countTraces}- </Badge>- <Badge variant="outline">- Total cost: {usdFormatter(session.totalCost ?? 0, 2)}- </Badge>- </>+ {!isModernSessionEnabled ? (+ <>+ <Badge variant="outline">+ Total traces: {session.countTraces}+ </Badge>+ <Badge variant="outline">+ Total cost: {usdFormatter(session.totalCost ?? 0, 2)}+ </Badge>+ </>+ ) : null}++ {/* Users */}+ {session.users?.length ? (+ <SessionUsers projectId={projectId} users={session.users} />+ ) : null}++ {/* Scores */}+ <SessionScores scores={session.scores} />+ </SessionControlsBar>) : null}-- {/* Users */}- {session.users?.length ? (- <SessionUsers projectId={projectId} users={session.users} />- ) : null}-- {/* Scores */}- <SessionScores scores={session.scores} />- </SessionControlsBar>- ) : null}- {!isModernSessionEnabled ? (- <div ref={parentRef} className="flex-1 overflow-auto p-4">- <div- style={{- height: `${virtualizer.getTotalSize()}px`,- width: "100%",- position: "relative",- }}- >- {virtualItems.map((virtualItem) => {- const trace = traces?.[virtualItem.index];- if (!trace) return null;-- return (- <SessionVirtualizedRow- key={virtualItem.key}- itemKey={String(virtualItem.key)}- measurementKey={`${String(virtualItem.key)}:${showCorrections}:${visibleFilterMeasurementKey}`}- source="events"- virtualItem={virtualItem}- virtualizer={virtualizer}- >- <LazySessionTraceEventsRow- trace={trace}- projectId={projectId}- sessionId={sessionId}- openPeek={openPeek}- traceCommentCounts={asCommentCounts(- traceCommentCounts.data,- )}- index={virtualItem.index}- filterState={visibleFilterState}- viewLabel={viewLabel}- />- </SessionVirtualizedRow>- );- })}- </div>+ {!isModernSessionEnabled ? (+ <div ref={parentRef} className="flex-1 overflow-auto p-4">+ <div+ style={{+ height: `${virtualizer.getTotalSize()}px`,+ width: "100%",+ position: "relative",+ }}+ >+ {virtualItems.map((virtualItem) => {+ const trace = traces?.[virtualItem.index];+ if (!trace) return null;++ return (+ <SessionVirtualizedRow+ key={virtualItem.key}+ itemKey={String(virtualItem.key)}+ measurementKey={`${String(virtualItem.key)}:${showCorrections}:${visibleFilterMeasurementKey}`}+ source="events"+ virtualItem={virtualItem}+ virtualizer={virtualizer}+ >+ <LazySessionTraceEventsRow+ trace={trace}+ projectId={projectId}+ sessionId={sessionId}+ openPeek={openPeek}+ traceCommentCounts={asCommentCounts(+ traceCommentCounts.data,+ )}+ index={virtualItem.index}+ filterState={visibleFilterState}+ viewLabel={viewLabel}+ />+ </SessionVirtualizedRow>+ );+ })}+ </div>+ </div>+ ) : (+ <ModernSession+ isTimelineEnabled={isSessionTimelineEnabled}+ session={session}+ tracesState={+ isTracesSuccess+ ? { type: "loaded", traces: traces ?? [] }+ : { type: "loading" }+ }+ projectId={projectId}+ sessionId={sessionId}+ openPeek={openPeek}+ traceCommentCounts={asCommentCounts(traceCommentCounts.data)}+ filterState={visibleFilterState}+ filterMeasurementKey={visibleFilterMeasurementKey}+ viewLabel={viewLabel}+ showInlineToolCalls={showInlineToolCalls}+ showSystemPrompt={showSystemPrompt}+ filterControlsProps={{+ projectId,+ filterState: visibleFilterState,+ filterColumns,+ filterColumnsWithCustomSelect,+ onChange: queryFilter.setFilterState,+ viewControllers,+ currentViewState: {+ orderBy: null,+ filters: queryFilter.filterState,+ columnOrder,+ columnVisibility,+ searchQuery: "",+ },+ }}+ onFilterObservationByName={filterObservationsByName}+ />+ )}</div>- ) : (- <ModernSession- isTimelineEnabled={isSessionTimelineEnabled}- session={session}- tracesState={- isTracesSuccess- ? { type: "loaded", traces: traces ?? [] }- : { type: "loading" }- }- projectId={projectId}- sessionId={sessionId}- openPeek={openPeek}- traceCommentCounts={asCommentCounts(traceCommentCounts.data)}- filterState={visibleFilterState}- filterMeasurementKey={visibleFilterMeasurementKey}- viewLabel={viewLabel}- showInlineToolCalls={showInlineToolCalls}- showSystemPrompt={showSystemPrompt}- filterControlsProps={{- projectId,- filterState: visibleFilterState,- filterColumns,- filterColumnsWithCustomSelect,- onChange: queryFilter.setFilterState,- viewControllers,- currentViewState: {- orderBy: null,- filters: queryFilter.filterState,- columnOrder,- columnVisibility,- searchQuery: "",- },- }}- onFilterObservationByName={filterObservationsByName}- />- )}- </div>- <TablePeekViewTraceDetail- itemType="TRACE"- detailNavigationKey="traces"- closePeek={closePeek}- expandPeek={expandPeek}- resolveDetailNavigationPath={resolveDetailNavigationPath}- tableName="session-events"- isV4={true}- projectId={projectId}- layout={isModernSessionEnabled ? "observation-focused" : "default"}- />- </Page>+ </SessionReviewWorkspace>+ </Page>+ </TraceReviewPanelProvider>+ <TablePeekViewTraceDetail+ itemType="TRACE"+ detailNavigationKey="traces"+ closePeek={closePeek}+ expandPeek={expandPeek}+ resolveDetailNavigationPath={resolveDetailNavigationPath}+ tableName="session-events"+ isV4={true}+ projectId={projectId}+ layout={isModernSessionEnabled ? "observation-focused" : "default"}+ /></SessionDetailStoreProvider>);};diff --git a/web/src/features/sessions/SessionReviewWorkspace.clienttest.tsx b/web/src/features/sessions/SessionReviewWorkspace.clienttest.tsxnew file mode 100644index 0000000000..e7c62ba3d2--- /dev/null+++ b/web/src/features/sessions/SessionReviewWorkspace.clienttest.tsx@@ -0,0 +1,250 @@+/** @vitest-environment jsdom */+import { useState, type ReactNode } from "react";+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ TraceReviewPanelProvider,+ useTraceReviewPanel,+} from "@/src/features/traces/contexts/TraceReviewPanelContext";+import { SessionReviewWorkspace } from "./SessionReviewWorkspace";++const { groupRef, router } = vi.hoisted(() => ({+ groupRef: { current: { setLayout: vi.fn() } },+ router: { query: {}, pathname: "/sessions/session", replace: vi.fn() },+}));++vi.mock("next/router", () => ({ useRouter: () => router }));+vi.mock("react-resizable-panels", () => ({+ useGroupRef: () => groupRef,+ Group: ({+ children,+ orientation,+ }: {+ children: ReactNode;+ orientation: string;+ }) => (+ <div data-testid="workspace-panels" data-orientation={orientation}>+ {children}+ </div>+ ),+ Panel: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ Separator: () => <div />,+}));+vi.mock("@/src/features/comments/CommentList", () => ({+ CommentList: ({ objectId }: { objectId: string }) => (+ <input aria-label={`Comment on ${objectId}`} defaultValue="" />+ ),+}));+vi.mock("@/src/features/scores/components/AnnotationPanelContent", () => ({+ AnnotationPanelContent: () => (+ <input aria-label="Annotation draft" defaultValue="" />+ ),+}));++function TraceCommentAction() {+ const store = useTraceReviewPanel();+ return (+ <button+ onClick={() =>+ store.getState().actions.openComments({+ target: {+ type: "comments",+ objectType: "TRACE",+ objectId: "trace",+ },+ confirmDiscard: () => true,+ })+ }+ >+ Comment on trace+ </button>+ );+}++function SessionContent() {+ const [draft, setDraft] = useState("");+ const [showTrace, setShowTrace] = useState(true);+ const store = useTraceReviewPanel();+ const actions = store.getState().actions;+ return (+ <>+ <input+ aria-label="Session state"+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ />+ <button+ onClick={() =>+ actions.openComments({+ target: {+ type: "comments",+ objectType: "SESSION",+ objectId: "session",+ },+ confirmDiscard: () => true,+ })+ }+ >+ Session comments+ </button>+ <button+ onClick={() =>+ actions.openAnnotation({+ scoreTarget: { type: "session", sessionId: "session" },+ scoreMetadata: { projectId: "project" },+ scores: [],+ analyticsData: {+ type: "session",+ source: "SessionDetail",+ isV4: true,+ },+ })+ }+ >+ Annotate session+ </button>+ <button onClick={actions.close}>Close review</button>+ <button onClick={() => setShowTrace(false)}>Unmount trace row</button>+ {showTrace ? <TraceCommentAction /> : null}+ </>+ );+}++function Harness() {+ return (+ <TraceReviewPanelProvider projectId="project">+ <SessionReviewWorkspace projectId="project">+ <SessionContent />+ </SessionReviewWorkspace>+ </TraceReviewPanelProvider>+ );+}++let width = 1200;+const observers = new Set<() => void>();++function resize(nextWidth: number) {+ width = nextWidth;+ act(() => observers.forEach((callback) => callback()));+}++beforeEach(() => {+ width = 1200;+ vi.stubGlobal(+ "ResizeObserver",+ class {+ constructor(private callback: () => void) {}+ observe() {+ observers.add(this.callback);+ }+ disconnect() {+ observers.delete(this.callback);+ }+ },+ );+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(+ () => ({+ width,+ height: 800,+ x: 0,+ y: 0,+ top: 0,+ left: 0,+ bottom: 800,+ right: width,+ toJSON() {},+ }),+ );+});++afterEach(() => {+ cleanup();+ observers.clear();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe("session review workspace", () => {+ it("brings an opened stacked editor into its own scrollport", async () => {+ width = 320;+ const { container } = render(<Harness />);+ const root = container.querySelector<HTMLElement>(+ "[data-review-orientation]",+ )!;+ const review = container.querySelector<HTMLElement>(+ "[data-trace-review-panel]",+ )!.parentElement!;+ Object.defineProperty(root, "clientHeight", { value: 400 });+ Object.defineProperty(review, "clientHeight", { value: 320 });+ const bounds = root.getBoundingClientRect();+ Object.defineProperty(root, "getBoundingClientRect", {+ value: () => ({ ...bounds, top: 100 }),+ });+ Object.defineProperty(review, "getBoundingClientRect", {+ value: () => ({ ...bounds, top: 500 }),+ });++ fireEvent.click(screen.getByRole("button", { name: "Annotate session" }));++ await waitFor(() => expect(root.scrollTop).toBeGreaterThan(0));+ expect(document.documentElement.scrollTop).toBe(0);+ });++ it("preserves session state and both drafts across resizing, switching modes, and closing", () => {+ render(<Harness />);+ const sessionInput = screen.getByLabelText("Session state");+ fireEvent.change(sessionInput, { target: { value: "session draft" } });+ fireEvent.click(screen.getByRole("button", { name: "Session comments" }));+ const commentInput = screen.getByLabelText("Comment on session");+ fireEvent.change(commentInput, { target: { value: "unsent comment" } });++ fireEvent.click(screen.getByRole("button", { name: "Annotate session" }));+ const annotationInput = screen.getByLabelText("Annotation draft");+ fireEvent.change(annotationInput, { target: { value: "score draft" } });+ resize(600);+ expect(screen.getByTestId("workspace-panels")).toHaveAttribute(+ "data-orientation",+ "vertical",+ );+ expect(screen.getByLabelText("Annotation draft")).toBe(annotationInput);+ expect(annotationInput).toHaveValue("score draft");++ fireEvent.click(screen.getByRole("button", { name: "Close review" }));+ expect(annotationInput).not.toBeVisible();+ resize(1200);+ fireEvent.click(screen.getByRole("button", { name: "Session comments" }));+ expect(screen.getByTestId("workspace-panels")).toHaveAttribute(+ "data-orientation",+ "horizontal",+ );+ expect(screen.getByLabelText("Comment on session")).toBe(commentInput);+ expect(commentInput).toBeVisible();+ expect(commentInput).toHaveValue("unsent comment");+ expect(screen.getByLabelText("Session state")).toBe(sessionInput);+ expect(sessionInput).toHaveValue("session draft");+ });++ it("keeps a trace comment editor alive when its virtualized row unmounts", () => {+ const result = render(<Harness />);+ fireEvent.click(screen.getByRole("button", { name: "Comment on trace" }));+ const commentInput = screen.getByLabelText("Comment on trace");+ fireEvent.change(commentInput, { target: { value: "review note" } });+ fireEvent.click(screen.getByRole("button", { name: "Unmount trace row" }));++ expect(+ screen.queryByRole("button", { name: "Comment on trace" }),+ ).not.toBeInTheDocument();+ expect(screen.getByLabelText("Comment on trace")).toBe(commentInput);+ expect(commentInput).toBeVisible();+ expect(commentInput).toHaveValue("review note");+ result.unmount();+ expect(observers.size).toBe(0);+ });+});diff --git a/web/src/features/sessions/SessionReviewWorkspace.tsx b/web/src/features/sessions/SessionReviewWorkspace.tsxnew file mode 100644index 0000000000..ceadd40198--- /dev/null+++ b/web/src/features/sessions/SessionReviewWorkspace.tsx@@ -0,0 +1,100 @@+import { useLayoutEffect, useRef, type ReactNode } from "react";+import { Group, Panel, Separator, useGroupRef } from "react-resizable-panels";+import { useStore } from "zustand";+import { TraceReviewPanel } from "@/src/features/traces/components/TraceReviewPanel";+import { useTraceReviewPanel } from "@/src/features/traces/contexts/TraceReviewPanelContext";+import { useElementSize } from "@/src/hooks/useElementSize";+import { cn } from "@/src/utils/tailwind";++export function SessionReviewWorkspace({+ projectId,+ children,+}: {+ projectId: string;+ children: ReactNode;+}) {+ const store = useTraceReviewPanel();+ const active = useStore(store, (state) => state.active);+ const open = active !== null;+ const [rootRef, size] = useElementSize<HTMLDivElement>();+ const reviewRef = useRef<HTMLDivElement>(null);+ const groupRef = useGroupRef();+ const vertical = (size?.width ?? 0) < 762;+ const sessionMinimum = vertical ? "360px" : "400px";+ const reviewMinimum = vertical ? "320px" : "360px";++ useLayoutEffect(() => {+ let cancelled = false;+ queueMicrotask(() => {+ if (cancelled) return;+ groupRef.current?.setLayout({+ session: open ? 60 : 100,+ review: open ? 40 : 0,+ });+ });+ return () => {+ cancelled = true;+ };+ }, [open, vertical, groupRef]);++ useLayoutEffect(() => {+ if (!active || !vertical) return;+ const frame = requestAnimationFrame(() => {+ const root = rootRef.current;+ const review = reviewRef.current;+ if (!root || !review) return;+ const offset =+ review.getBoundingClientRect().top - root.getBoundingClientRect().top;+ root.scrollTop +=+ offset - Math.max(0, root.clientHeight - review.clientHeight);+ });+ return () => cancelAnimationFrame(frame);+ }, [active, vertical, rootRef]);++ return (+ <div+ ref={rootRef}+ className="h-full min-h-0 min-w-0 overflow-y-auto"+ data-trace-review-open={open || undefined}+ data-review-orientation={vertical ? "vertical" : "horizontal"}+ >+ <Group+ groupRef={groupRef}+ orientation={vertical ? "vertical" : "horizontal"}+ className={cn(+ "h-full min-h-0 min-w-0",+ open && (vertical ? "min-h-[681px]" : "min-h-[320px]"),+ )}+ >+ <Panel+ id="session"+ defaultSize="100%"+ minSize={open ? sessionMinimum : "0%"}+ >+ <div className="@container/session-workspace h-full min-h-0 min-w-0">+ {children}+ </div>+ </Panel>+ <Separator+ disabled={!open}+ aria-label="Resize review panel"+ className={cn(+ "bg-border",+ vertical ? "h-px" : "w-px",+ !open && "hidden",+ )}+ />+ <Panel+ id="review"+ defaultSize="0%"+ minSize={open ? reviewMinimum : "0%"}+ maxSize={open ? "75%" : "0%"}+ >+ <div ref={reviewRef} className="h-full min-h-0" hidden={!open}>+ <TraceReviewPanel projectId={projectId} />+ </div>+ </Panel>+ </Group>+ </div>+ );+}diff --git a/web/src/features/sessions/SessionTraceActionButtons.tsx b/web/src/features/sessions/SessionTraceActionButtons.tsxindex 8470bb2ed1..a1e3dc786b 100644--- a/web/src/features/sessions/SessionTraceActionButtons.tsx+++ b/web/src/features/sessions/SessionTraceActionButtons.tsx@@ -1,4 +1,3 @@-/* eslint-disable no-nested-ternary *//* eslint-disable @repo/no-style-props */import { api, type RouterOutputs } from "@/src/utils/api";import { getNumberFromMap } from "@/src/utils/map-utils";@@ -6,16 +5,10 @@ import { ActionButtonCountBadge } from "@/src/components/ui/action-button-count-import { Button } from "@/src/components/ui/button";import { AnnotateDrawerController } from "@/src/features/scores";import { CommentDrawerController } from "@/src/features/comments";-import {- ExistingDatasetItemsDropdownMenuController,- NewDatasetItemFromExistingObjectDialogController,- useDatasetItemFromTraceOrObservation,-} from "@/src/features/datasets";-import { AnnotationQueueItemDropdownMenuController } from "@/src/features/annotation-queues";+import { ConnectedTraceObservationAddToDropdownMenuController } from "@/src/features/traces/components/ConnectedTraceObservationAddToDropdownMenuController";import { cn } from "@/src/utils/tailwind";import {ChevronDown,- ListPlus,LockIcon,MessageSquare,MessageSquareOff,@@ -66,77 +59,32 @@ export function SessionTraceActionButtons({refetchOnMount: false,},);- const {- existingDatasetItems,- hasAccess: hasDatasetAccess,- captureNewDatasetItemFormOpen,- } = useDatasetItemFromTraceOrObservation({- projectId,- traceId,- enabled: Boolean(trace.data),- });- const datasetCount = existingDatasetItems.length;- const hasExistingDatasetItems = datasetCount > 0;return (<div className={cn("flex flex-wrap items-start gap-2", className)}>{trace.data ? (- <NewDatasetItemFromExistingObjectDialogController projectId={projectId}>- {({ openDialog }) => (- <ExistingDatasetItemsDropdownMenuController- projectId={projectId}- datasetItems={existingDatasetItems}- disabled={!hasDatasetAccess}- onOpenDialog={() =>- openDialog({- traceId,- input: trace.data.input ?? null,- output: trace.data.output ?? null,- metadata: trace.data.metadata ?? null,- })- }+ <ConnectedTraceObservationAddToDropdownMenuController+ projectId={projectId}+ traceId={traceId}+ variant="trace"+ input={trace.data.input}+ output={trace.data.output}+ metadata={trace.data.metadata ?? null}+ analyticsData={{ source: "SessionDetail", isV4 }}+ >+ {({ getTriggerProps }) => (+ <Button+ variant="outline"+ size={size}+ className="gap-1.5"+ {...getTriggerProps()}>- {({ Anchor, openDropdown }) => (- <Anchor>- <Button- onClick={() => {- if (hasExistingDatasetItems) {- openDropdown();- return;- }-- captureNewDatasetItemFormOpen();- openDialog({- traceId,- input: trace.data.input ?? null,- output: trace.data.output ?? null,- metadata: trace.data.metadata ?? null,- });- }}- variant={hasExistingDatasetItems ? "secondary" : "outline"}- size={size}- disabled={!hasDatasetAccess}- >- {!hasExistingDatasetItems && hasDatasetAccess ? (- <PlusIcon- className="mr-1.5 -ml-0.5 h-4 w-4"- aria-hidden="true"- />- ) : null}- {hasExistingDatasetItems- ? `In ${datasetCount} dataset(s)`- : "Add to datasets"}- {hasExistingDatasetItems ? (- <ChevronDown className="ml-2 h-3 w-3" />- ) : !hasDatasetAccess ? (- <LockIcon className="ml-1.5 h-3 w-3" aria-hidden="true" />- ) : null}- </Button>- </Anchor>- )}- </ExistingDatasetItemsDropdownMenuController>+ <PlusIcon className="h-4 w-4" />+ <span>Add to</span>+ <ChevronDown className="h-3 w-3" />+ </Button>)}- </NewDatasetItemFromExistingObjectDialogController>+ </ConnectedTraceObservationAddToDropdownMenuController>) : null}<div className="flex flex-wrap items-start gap-2"><AnnotateDrawerController projectId={projectId}>@@ -170,30 +118,6 @@ export function SessionTraceActionButtons({</Button>)}</AnnotateDrawerController>- <AnnotationQueueItemDropdownMenuController- projectId={projectId}- objectId={traceId}- objectType="TRACE"- analyticsData={{ source: "SessionDetail", isV4 }}- >- {({ disabled, totalCount, Trigger }) => (- <Trigger asChild>- <Button- variant="outline"- size={size}- disabled={disabled !== undefined}- className="gap-1.5"- >- <ListPlus className="h-4 w-4" />- <span>Add to human annotation queue</span>- {totalCount > 0 && (- <ActionButtonCountBadge count={totalCount} />- )}- <ChevronDown className="h-3 w-3" />- </Button>- </Trigger>- )}- </AnnotationQueueItemDropdownMenuController></div><CommentDrawerController projectId={projectId} count={commentCount}>{({ disabled, openDrawer }) => (@@ -216,7 +140,7 @@ export function SessionTraceActionButtons({) : (<><MessageSquare className="h-4 w-4" />- <span>Add comment</span>+ <span>Comments</span>{!!commentCount ? (<ActionButtonCountBadge count={commentCount} />) : null}diff --git a/web/src/features/traces/README.md b/web/src/features/traces/README.mdnew file mode 100644index 0000000000..e3437c6055--- /dev/null+++ b/web/src/features/traces/README.md@@ -0,0 +1,42 @@+# Trace review workspace++`Trace` owns the trace data and selection providers. Desktop peek and full trace views create one+`TraceReviewPanelProvider` per project and trace, above the selected detail view.+Header actions send annotation/comment targets to its local store; they do not+own the opened panel or its lifetime.++- `traceReviewPanelStore` owns the active mode, retained target sessions, comment+ draft guards, and trigger focus restoration. Query data stays in React Query.+- `TraceReviewPanel` mounts the comment thread and annotation form once per target+ session, hides inactive content, and gates keyboard/mention behavior. Closing+ the panel preserves the draft while this trace remains mounted.+- `TraceReviewLayout` owns the responsive review split. Automatic navigation is+ visible when the available display can fit three comfortable columns. An explicit+ tree toggle overrides that default and is remembered. The review pane stacks below+ the trace when minimum column widths cannot fit; both editors stay mounted.+- `TraceLayoutDesktop` owns the tree/detail split. Its temporary review sizes do+ not overwrite the normal saved layout. Closing review restores that layout after+ the outer panel and its resize observer settle. Navigation stays mounted while+ collapsed, preserving tree scroll and timeline zoom.+- Peek content advertises its temporary minimum width with `data-peek-layout`.+ The shell caps it at the sidebar edge and restores its saved width on close.+- Comment and annotation controllers use the workspace when present. Other+ surfaces, including the queue workspace with its own score pane, retain their+ existing overlay presentation and permission checks.++Changing comment targets confirms discarding an unsent draft. Selecting another+trace destroys the workspace; drafts are not shared between traces or projects.++Same-target annotation reopening passes the fresh header snapshot through the+mounted form's imperative refresh handle. The form action reconciles by target+and config, updating clean fields in place while preserving pending writes,+invalid inputs, and row-local comment drafts. An unchanged pre-save snapshot+cannot undo a confirmed local save. This refresh belongs to the open action;+query updates do not reset mounted editors.++Mobile detail headers compose review, Add to, and utility actions into one+design-system dropdown. The feature controllers expose prepared items through+`renderMenu` while retaining ownership of permissions, queries, and dialogs.+Dialog controllers stay outside the menu's mount lifetime; selecting an action+closes the menu without unmounting its destination. Review actions remember the+stable More actions trigger for keyboard focus return.diff --git a/web/src/features/traces/components/ConnectedTraceObservationAddToDropdownMenuController.tsx b/web/src/features/traces/components/ConnectedTraceObservationAddToDropdownMenuController.tsxindex 9dc6c62d4d..ff04036985 100644--- a/web/src/features/traces/components/ConnectedTraceObservationAddToDropdownMenuController.tsx+++ b/web/src/features/traces/components/ConnectedTraceObservationAddToDropdownMenuController.tsx@@ -1,7 +1,12 @@import { AnnotationQueueObjectType, type Prisma } from "@langfuse/shared";import { Database, ListPlus, PlusIcon, Terminal } from "lucide-react";import { useSession } from "next-auth/react";-import { type ComponentProps, useCallback, useMemo } from "react";+import {+ type ComponentProps,+ type ReactNode,+ useCallback,+ useMemo,+} from "react";import {DropdownMenu,@@ -31,27 +36,37 @@ type QueueRemoval = {queueName: string;};-type ConnectedTraceObservationAddToDropdownMenuControllerProps = {- projectId: string;- input: Prisma.JsonValue | null;- output: Prisma.JsonValue | null;- metadata: MetadataDomainClient;- analyticsData: Pick<AnalyticsData, "source" | "isV4">;- children: ComponentProps<typeof DropdownMenu>["children"];-} & (+type MenuPresentation =| {- variant: "trace";- traceId: string;- observationId?: never;- generation?: never;+ children: ComponentProps<typeof DropdownMenu>["children"];+ renderMenu?: never;}| {- variant: "observation";- traceId: string;- observationId: string;- generation?: PlaygroundGeneration;- }-);+ children?: never;+ renderMenu: (items: DropdownMenuItemDefinition[]) => ReactNode;+ };++type ConnectedTraceObservationAddToDropdownMenuControllerProps =+ MenuPresentation & {+ projectId: string;+ input: Prisma.JsonValue | null;+ output: Prisma.JsonValue | null;+ metadata: MetadataDomainClient;+ analyticsData: Pick<AnalyticsData, "source" | "isV4">;+ } & (+ | {+ variant: "trace";+ traceId: string;+ observationId?: never;+ generation?: never;+ }+ | {+ variant: "observation";+ traceId: string;+ observationId: string;+ generation?: PlaygroundGeneration;+ }+ );export function ConnectedTraceObservationAddToDropdownMenuController(props: ConnectedTraceObservationAddToDropdownMenuControllerProps,@@ -148,6 +163,7 @@ function ConnectedTraceObservationAddToDropdownMenuControllerContent({analyticsData,generation,children,+ renderMenu,createDatasetDisabled,createQueueDisabled,openDatasetDialog,@@ -339,7 +355,11 @@ function ConnectedTraceObservationAddToDropdownMenuControllerContent({type: "item" as const,id: dataset.id,title: dataset.name,- onClick: () =>+ onClick: () => {+ capture("dataset_item:new_from_trace_form_open", {+ object: variant,+ ...analyticsData,+ });openDatasetItemDialog({traceId,observationId,@@ -347,7 +367,8 @@ function ConnectedTraceObservationAddToDropdownMenuControllerContent({output,metadata,datasetId: dataset.id,- }),+ });+ },})),...((datasets.data?.length ?? 0) === 0? [@@ -417,6 +438,9 @@ function ConnectedTraceObservationAddToDropdownMenuControllerContent({return items;}, [+ analyticsData,+ capture,+ variant,createDatasetDisabled,createQueueDisabled,datasets.data,@@ -442,6 +466,8 @@ function ConnectedTraceObservationAddToDropdownMenuControllerContent({traceId,]);+ if (renderMenu) return renderMenu(items);+return (<DropdownMenu items={items} maxHeight="24rem" placement="bottom-start">{children}diff --git a/web/src/features/traces/components/DetailHeaderActionsMenuController.tsx b/web/src/features/traces/components/DetailHeaderActionsMenuController.tsxindex fc0abc8e84..f15bfdb3b8 100644--- a/web/src/features/traces/components/DetailHeaderActionsMenuController.tsx+++ b/web/src/features/traces/components/DetailHeaderActionsMenuController.tsx@@ -19,7 +19,7 @@ type IdItem = {id: string;};-type DetailHeaderActionsMenuControllerProps = {+type DetailHeaderActionsProps = {idItems: IdItem[];isAdmin: boolean;observationType?: ObservationType;@@ -31,19 +31,32 @@ type DetailHeaderActionsMenuControllerProps = {};spanName?: string;webCalloutAction?: ReturnType<typeof useWebCalloutAction>;- children: ComponentProps<typeof DropdownMenu>["children"];};+type MenuPresentation =+ | {+ children: ComponentProps<typeof DropdownMenu>["children"];+ renderMenu?: never;+ }+ | {+ children?: never;+ renderMenu: (items: DropdownMenuItemDefinition[]) => ReactNode;+ };++type DetailHeaderActionsMenuControllerProps = DetailHeaderActionsProps &+ MenuPresentation;+type ConnectedDetailHeaderActionsMenuControllerProps = Omit<- DetailHeaderActionsMenuControllerProps,+ DetailHeaderActionsProps,"isAdmin" | "webCalloutAction"-> & {- webCallout?: {- traceId: string | null;- observationId?: string | null;- sessionId?: string | null;+> &+ MenuPresentation & {+ webCallout?: {+ traceId: string | null;+ observationId?: string | null;+ sessionId?: string | null;+ };};-};function buildObservationClickHouseQuery(projectId: string,@@ -131,6 +144,7 @@ export function DetailHeaderActionsMenuController({observation,spanName,children,+ renderMenu,webCalloutAction,}: DetailHeaderActionsMenuControllerProps) {const router = useRouter();@@ -232,6 +246,8 @@ export function DetailHeaderActionsMenuController({: []),];+ if (renderMenu) return renderMenu(items);+return (<DropdownMenu items={items} placement="bottom-end">{children}diff --git a/web/src/features/traces/components/ObservationDetailView/components/ObservationDetailViewHeader/ObservationDetailViewHeader.tsx b/web/src/features/traces/components/ObservationDetailView/components/ObservationDetailViewHeader/ObservationDetailViewHeader.tsxindex 9d2e36d418..f2374ca29c 100644--- a/web/src/features/traces/components/ObservationDetailView/components/ObservationDetailViewHeader/ObservationDetailViewHeader.tsx+++ b/web/src/features/traces/components/ObservationDetailView/components/ObservationDetailViewHeader/ObservationDetailViewHeader.tsx@@ -9,8 +9,7 @@* Memoized to prevent unnecessary re-renders when tab state changes.*/-import { memo, useMemo } from "react";-import { usePostHogClientCapture } from "@/src/features/posthog-analytics";+import { memo, useMemo, useRef } from "react";import {type ObservationType,isGenerationLike,@@ -19,10 +18,7 @@ import {} from "@langfuse/shared";import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";import { ItemBadge } from "@/src/components/ItemBadge";-import {- AnnotateDrawerController,- DualAnnotationContent,-} from "@/src/features/scores";+import { AnnotateDrawerController } from "@/src/features/scores";import { ConnectedTraceObservationAddToDropdownMenuController } from "@/src/features/traces/components/ConnectedTraceObservationAddToDropdownMenuController";import { PromptBadge } from "@/src/features/traces/components/PromptBadge";import {@@ -59,17 +55,7 @@ import {PlusIcon,SquarePen,} from "lucide-react";-import {- Drawer,- DrawerContent,- DrawerTrigger,-} from "@/src/components/ui/drawer";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/src/components/ui/popover";-import { useHasProjectAccess } from "@/src/features/rbac";+import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";import { CollapsibleBadgeRow } from "@/src/features/traces/components/CollapsibleBadgeRow";import { useIsMobile } from "@/src/hooks/use-mobile";import { cn } from "@/src/utils/tailwind";@@ -115,16 +101,8 @@ export const ObservationDetailViewHeader = memo(}: ObservationDetailViewHeaderProps) {const { isAnnotationMode } = useViewPreferences();const isMobile = useIsMobile();+ const mobileActionsTriggerRef = useRef<HTMLButtonElement>(null);const { isV4: isV4Enabled } = useReadPath();- const capture = usePostHogClientCapture();- const captureAnnotationEntry = () =>- capture("annotation:entry_click", {- type: "trace",- entryPoint: "annotate_button",- source: "TraceDetail",- targetType: "observation",- isV4: isV4Enabled,- });const { trace, serverScores } = useTraceData();// Get trace-level scores for V4 dual annotation@@ -133,11 +111,6 @@ export const ObservationDetailViewHeader = memo([serverScores],);- // Access check for annotation drawer- const hasAnnotationAccess = useHasProjectAccess({- projectId,- scope: "scores:CUD",- });// Format cost and usage valuesconst totalCost = observation.totalCost;const totalUsage = observation.totalUsage;@@ -208,196 +181,159 @@ export const ObservationDetailViewHeader = memo(>{observation.name || observation.id}</span>- {/* Mobile: collapse the action-button cluster into a `⋯` overflow of- full-width labeled rows, next to the `⋮` utility menu. */}- {isMobile && (- <Popover>- <PopoverTrigger asChild>- <Button- variant="outline"- size="icon"- aria-label="More actions"- className="ml-auto shrink-0"- >- <MoreHorizontal className="h-4 w-4" />- </Button>- </PopoverTrigger>- <PopoverContent- align="end"- // forceMount + hide-when-closed: CommentDrawerController lives in- // here, and its deep-link auto-open effect (?comments=open) and- // controlled inline-selection flow only work while mounted. A- // default Popover unmounts its content when closed (the default- // state), silently breaking both. Keep it mounted, just hidden.- forceMount- className="flex w-auto min-w-44 flex-col gap-0.5 p-1 data-[state=closed]:hidden"- >- {observationWithIO && (- <ConnectedTraceObservationAddToDropdownMenuController- analyticsData={{- source: "TraceDetail",- isV4: isV4Enabled,- }}- projectId={projectId}- traceId={traceId}- variant="observation"- observationId={observation.id}- input={observationWithIO.input}- output={observationWithIO.output}- metadata={observationWithIO.metadata}- generation={- isGenerationLike(observationWithIO.type)- ? observationWithIO- : undefined- }- >- {({ getTriggerProps }) => (- <Button- variant="ghost"- size="sm"- className="w-full justify-start gap-2 font-normal"- {...getTriggerProps()}- >- <PlusIcon className="h-4 w-4" />- <span>Add to</span>- <ChevronDown className="ml-auto h-3 w-3" />- </Button>- )}- </ConnectedTraceObservationAddToDropdownMenuController>- )}- {!isAnnotationMode && (- <>- {isV4Enabled ? (- <Drawer- key={"annotation-drawer-menu-" + observation.id}- >- <DrawerTrigger asChild>- <Button- variant="ghost"- size="sm"- disabled={!hasAnnotationAccess}- onClick={captureAnnotationEntry}- className="w-full justify-start gap-2 font-normal"- >- {!hasAnnotationAccess ? (- <LockIcon className="h-3 w-3" />- ) : (- <SquarePen className="h-4 w-4" />- )}- <span className="text-sm">Annotate</span>- </Button>- </DrawerTrigger>- <DrawerContent className="p-3">- <DualAnnotationContent- isV4={isV4Enabled}- projectId={projectId}- traceId={traceId}- observationId={observation.id}- traceEnvironment={trace.environment}- observationEnvironment={observation.environment}- observationScores={observationScores}- traceScores={traceScores}- />- </DrawerContent>- </Drawer>- ) : (- <AnnotateDrawerController projectId={projectId}>- {({ disabled, openDrawer }) => (- <Button- variant="ghost"- size="sm"- disabled={disabled}- className="w-full justify-start gap-2 font-normal"- onClick={() =>- openDrawer({- scoreTarget: {- type: "trace",- traceId,- observationId: observation.id,- },- scores: observationScores,- analyticsData: {- type: "trace",- source: "TraceDetail",- isV4: isV4Enabled,- },- scoreMetadata: {- projectId,- environment: observation.environment,- },- })- }- >- {disabled ? (- <LockIcon className="h-3 w-3" />- ) : (- <SquarePen className="h-4 w-4" />- )}- <span className="text-sm">Annotate</span>- </Button>- )}- </AnnotateDrawerController>- )}- </>- )}- <Button- type="button"- variant="ghost"- size="sm"- disabled={commentDrawerControl.disabled}- onClick={commentDrawerControl.openDrawer}- className="w-full justify-start gap-2 font-normal"- >- {commentDrawerControl.disabled ? (- <MessageSquareOff className="text-muted-foreground h-4 w-4" />- ) : (- <MessageSquare className="h-4 w-4" />- )}- <span className="text-sm">Comment</span>- {!commentDrawerControl.disabled && commentCount ? (- <ActionButtonCountBadge count={commentCount} />- ) : null}- </Button>- </PopoverContent>- </Popover>- )}{isMobile && (- <ConnectedDetailHeaderActionsMenuController- idItems={[- { id: traceId, name: "Trace ID" },- { id: observation.id, name: "Observation ID" },- ]}- observationType={observation.type}+ <ConnectedTraceObservationAddToDropdownMenuController+ analyticsData={{ source: "TraceDetail", isV4: isV4Enabled }}projectId={projectId}- observation={- isV4Enabled- ? {- id: observation.id,- traceId,- startTime: observation.startTime,- }+ traceId={traceId}+ variant="observation"+ observationId={observation.id}+ input={observationWithIO?.input ?? null}+ output={observationWithIO?.output ?? null}+ metadata={observationWithIO?.metadata ?? null}+ generation={+ observationWithIO && isGenerationLike(observationWithIO.type)+ ? observationWithIO: undefined}- spanName={observation.name ?? ""}- webCallout={{- traceId,- observationId: observation.id,- sessionId: observation.sessionId ?? null,- }}- >- {({ getTriggerProps }) => (- <Button- aria-label="Options"- className="shrink-0"- size="icon"- title="Options"- variant="secondary"- {...getTriggerProps()}- >- <EllipsisVertical className="h-4 w-4" />- </Button>+ renderMenu={(addToItems) => (+ <AnnotateDrawerController projectId={projectId}>+ {({ disabled: annotationDisabled, openDrawer }) => (+ <ConnectedDetailHeaderActionsMenuController+ idItems={[+ { id: traceId, name: "Trace ID" },+ { id: observation.id, name: "Observation ID" },+ ]}+ observationType={observation.type}+ projectId={projectId}+ observation={+ isV4Enabled+ ? {+ id: observation.id,+ traceId,+ startTime: observation.startTime,+ }+ : undefined+ }+ spanName={observation.name ?? ""}+ webCallout={{+ traceId,+ observationId: observation.id,+ sessionId: observation.sessionId ?? null,+ }}+ renderMenu={(utilityItems) => (+ <DropdownMenu+ placement="bottom-end"+ maxHeight="min(24rem, calc(100dvh - 2rem))"+ items={[+ ...(!isAnnotationMode+ ? [+ {+ type: "item" as const,+ id: "annotate",+ title: "Annotate",+ icon: annotationDisabled+ ? LockIcon+ : SquarePen,+ disabled: annotationDisabled+ ? {+ reason:+ "You don't have permission to annotate.",+ }+ : undefined,+ onClick: () => {+ mobileActionsTriggerRef.current?.focus({+ preventScroll: true,+ });+ openDrawer({+ scoreTarget: {+ type: "trace",+ traceId,+ observationId: observation.id,+ },+ scores: observationScores,+ companionTrace: isV4Enabled+ ? {+ environment: trace.environment,+ scores: traceScores,+ }+ : undefined,+ analyticsData: {+ type: "trace",+ source: "TraceDetail",+ isV4: isV4Enabled,+ },+ scoreMetadata: {+ projectId,+ environment:+ observation.environment,+ },+ });+ },+ },+ ]+ : []),+ {+ type: "item",+ id: "comments",+ title:+ !commentDrawerControl.disabled && commentCount+ ? `Comments (${commentCount})`+ : "Comments",+ icon: commentDrawerControl.disabled+ ? MessageSquareOff+ : MessageSquare,+ disabled: commentDrawerControl.disabled+ ? {+ reason:+ "You don't have permission to comment.",+ }+ : undefined,+ onClick: () => {+ mobileActionsTriggerRef.current?.focus({+ preventScroll: true,+ });+ commentDrawerControl.openDrawer();+ },+ },+ ...(observationWithIO+ ? [+ {+ type: "submenu" as const,+ id: "add-to",+ title: "Add to",+ icon: PlusIcon,+ items: addToItems,+ },+ ]+ : []),+ {+ id: "review-actions-separator",+ type: "separator",+ },+ ...utilityItems,+ ]}+ >+ {({ getTriggerProps }) => (+ <Button+ variant="outline"+ size="icon"+ aria-label="More actions"+ className="ml-auto shrink-0"+ {...getTriggerProps({+ ref: mobileActionsTriggerRef,+ })}+ >+ <MoreHorizontal className="h-4 w-4" />+ </Button>+ )}+ </DropdownMenu>+ )}+ />+ )}+ </AnnotateDrawerController>)}- </ConnectedDetailHeaderActionsMenuController>+ />)}</div>{/* Action buttons (desktop inline cluster) */}@@ -435,73 +371,49 @@ export const ObservationDetailViewHeader = memo(</ConnectedTraceObservationAddToDropdownMenuController>)}{/* Hide annotation buttons in annotation mode (panel shown separately) */}- {!isAnnotationMode &&- (isV4Enabled ? (- <Drawer key={"annotation-drawer-" + observation.id}>- <DrawerTrigger asChild>- <Button- variant="secondary"- size="sm"- disabled={!hasAnnotationAccess}- >- {!hasAnnotationAccess ? (- <LockIcon className="mr-1.5 h-3 w-3" />- ) : (- <SquarePen className="mr-1.5 h-3.5 w-3.5" />- )}- <span>Annotate</span>- </Button>- </DrawerTrigger>- <DrawerContent className="p-3">- <DualAnnotationContent- isV4={isV4Enabled}- projectId={projectId}- traceId={traceId}- observationId={observation.id}- traceEnvironment={trace.environment}- observationEnvironment={observation.environment}- observationScores={observationScores}- traceScores={traceScores}- />- </DrawerContent>- </Drawer>- ) : (- <AnnotateDrawerController projectId={projectId}>- {({ disabled, openDrawer }) => (- <Button- variant="secondary"- size="sm"- disabled={disabled}- onClick={() =>- openDrawer({- scoreTarget: {- type: "trace",- traceId,- observationId: observation.id,- },- scores: observationScores,- analyticsData: {- type: "trace",- source: "TraceDetail",- isV4: isV4Enabled,- },- scoreMetadata: {- projectId,- environment: observation.environment,- },- })- }- >- {disabled ? (- <LockIcon className="mr-1.5 h-3 w-3" />- ) : (- <SquarePen className="mr-1.5 h-3.5 w-3.5" />- )}- <span>Annotate</span>- </Button>- )}- </AnnotateDrawerController>- ))}+ {!isAnnotationMode && (+ <AnnotateDrawerController projectId={projectId}>+ {({ disabled, openDrawer }) => (+ <Button+ variant="secondary"+ size="sm"+ disabled={disabled}+ onClick={() =>+ openDrawer({+ scoreTarget: {+ type: "trace",+ traceId,+ observationId: observation.id,+ },+ scores: observationScores,+ companionTrace: isV4Enabled+ ? {+ environment: trace.environment,+ scores: traceScores,+ }+ : undefined,+ analyticsData: {+ type: "trace",+ source: "TraceDetail",+ isV4: isV4Enabled,+ },+ scoreMetadata: {+ projectId,+ environment: observation.environment,+ },+ })+ }+ >+ {disabled ? (+ <LockIcon className="mr-1.5 h-3 w-3" />+ ) : (+ <SquarePen className="mr-1.5 h-3.5 w-3.5" />+ )}+ <span>Annotate</span>+ </Button>+ )}+ </AnnotateDrawerController>+ )}<Buttontype="button"variant="secondary"@@ -515,7 +427,7 @@ export const ObservationDetailViewHeader = memo() : (<><MessageSquare className="h-3.5 w-3.5" />- <span>Comment</span>+ <span>Comments</span>{!!commentCount ? (<ActionButtonCountBadge count={commentCount} />) : null}diff --git a/web/src/features/traces/components/Trace.tsx b/web/src/features/traces/components/Trace.tsxindex e622f10fdb..2c8f1166af 100644--- a/web/src/features/traces/components/Trace.tsx+++ b/web/src/features/traces/components/Trace.tsx@@ -1,7 +1,10 @@import { type TraceDomain, type ScoreDomain } from "@langfuse/shared";import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";-import { TraceDataProvider } from "@/src/features/traces/contexts/TraceDataContext";+import {+ TraceDataProvider,+ useTraceData,+} from "@/src/features/traces/contexts/TraceDataContext";import { ViewPreferencesProvider } from "@/src/features/traces/contexts/ViewPreferencesContext";import {SelectionProvider,@@ -27,7 +30,15 @@ import { useIsMobile } from "@/src/hooks/use-mobile";import { useTraceComments } from "@/src/features/traces/hooks/useTraceComments";import { TraceGraphView } from "@/src/features/traces/components/TraceGraphView/TraceGraphView";-import { useMemo } from "react";+import { useMemo, type ReactNode } from "react";+import { useStore } from "zustand";+import { useRouter } from "next/router";+import { getCommentDrawerInitialStateFromUrl } from "@/src/features/comments/CommentDrawerController";+import {+ TraceReviewPanelProvider,+ useTraceReviewPanel,+} from "@/src/features/traces/contexts/TraceReviewPanelContext";+import { TraceReviewPanel } from "./TraceReviewPanel";export type TraceProps = {observations: Array<ObservationReturnTypeWithMetadata>;@@ -222,18 +233,71 @@ function DesktopTraceContent({}: {desktopLayout: DesktopLayout;}) {+ const { trace } = useTraceData();+ const router = useRouter();+ if (desktopLayout.groupId === DESKTOP_LAYOUTS.annotation.groupId) {+ return <DesktopTraceWorkspace desktopLayout={desktopLayout} />;+ }return (- <TraceLayoutDesktop key={desktopLayout.groupId} {...desktopLayout}>- <TraceLayoutDesktop.NavigationPanel>- <TracePanelNavigationLayoutDesktop>- <TracePanelNavigation />- </TracePanelNavigationLayoutDesktop>- </TraceLayoutDesktop.NavigationPanel>- <TraceLayoutDesktop.ResizeHandle />- <TraceLayoutDesktop.DetailPanel>- <TracePanelDetail />- </TraceLayoutDesktop.DetailPanel>- </TraceLayoutDesktop>+ <TraceReviewPanelProvider+ key={`${trace.projectId}:${trace.id}`}+ projectId={trace.projectId}+ initialComments={getCommentDrawerInitialStateFromUrl(router.query)}+ >+ <DesktopTraceReviewWorkspace+ desktopLayout={desktopLayout}+ projectId={trace.projectId}+ />+ </TraceReviewPanelProvider>+ );+}++function DesktopTraceReviewWorkspace({+ desktopLayout,+ projectId,+}: {+ desktopLayout: DesktopLayout;+ projectId: string;+}) {+ const store = useTraceReviewPanel();+ const reviewOpen = useStore(store, (state) => state.active !== null);+ return (+ <DesktopTraceWorkspace+ desktopLayout={desktopLayout}+ reviewOpen={reviewOpen}+ reviewPanel={<TraceReviewPanel projectId={projectId} />}+ />+ );+}++function DesktopTraceWorkspace({+ desktopLayout,+ reviewOpen = false,+ reviewPanel,+}: {+ desktopLayout: DesktopLayout;+ reviewOpen?: boolean;+ reviewPanel?: ReactNode;+}) {+ return (+ <div className="h-full" data-trace-review-open={reviewOpen || undefined}>+ <TraceLayoutDesktop+ key={desktopLayout.groupId}+ {...desktopLayout}+ reviewOpen={reviewOpen}+ reviewPanel={reviewPanel}+ >+ <TraceLayoutDesktop.NavigationPanel>+ <TracePanelNavigationLayoutDesktop>+ <TracePanelNavigation />+ </TracePanelNavigationLayoutDesktop>+ </TraceLayoutDesktop.NavigationPanel>+ <TraceLayoutDesktop.ResizeHandle />+ <TraceLayoutDesktop.DetailPanel>+ <TracePanelDetail />+ </TraceLayoutDesktop.DetailPanel>+ </TraceLayoutDesktop>+ </div>);}diff --git a/web/src/features/traces/components/TraceDetailView/components/TraceDetailViewHeader.tsx b/web/src/features/traces/components/TraceDetailView/components/TraceDetailViewHeader.tsxindex be9f21a6c5..a232ffd6ca 100644--- a/web/src/features/traces/components/TraceDetailView/components/TraceDetailViewHeader.tsx+++ b/web/src/features/traces/components/TraceDetailView/components/TraceDetailViewHeader.tsx@@ -10,7 +10,7 @@* Memoized to prevent unnecessary re-renders when tab state changes.*/-import { memo } from "react";+import { memo, useRef } from "react";import { useReadPath } from "@/src/features/events";import {type TraceDomain,@@ -44,11 +44,7 @@ import {PlusIcon,SquarePen,} from "lucide-react";-import {- Popover,- PopoverContent,- PopoverTrigger,-} from "@/src/components/ui/popover";+import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";import { cn } from "@/src/utils/tailwind";import { buildLocalIsoDatePresentation } from "@/src/utils/dates";@@ -79,6 +75,7 @@ export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({const { isAnnotationMode } = useViewPreferences();const { isV4 } = useReadPath();const isMobile = useIsMobile();+ const mobileActionsTriggerRef = useRef<HTMLButtonElement>(null);const targetTraceId =trace.environment === LangfuseInternalTraceEnvironment.LLMJudge? resolveEvalExecutionMetadata(parsedMetadata)@@ -101,132 +98,149 @@ export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({>{trace.name || trace.id}</span>- <ConnectedDetailHeaderActionsMenuController- idItems={[{ id: trace.id, name: "Trace ID" }]}- projectId={projectId}- webCallout={{- traceId: trace.id,- sessionId: trace.sessionId ?? null,- }}- >- {({ getTriggerProps }) => (- <Button- aria-label="Options"- className="mt-0.5 shrink-0"- size="icon-xs"- title="Options"- variant="ghost"- {...getTriggerProps()}- >- <EllipsisVertical className="h-4 w-4" />- </Button>- )}- </ConnectedDetailHeaderActionsMenuController>- {/* Mobile: collapse the action-button cluster into a `⋯` overflow of- full-width labeled rows, next to the `⋮` utility menu. */}- {isMobile && (- <Popover>- <PopoverTrigger asChild>+ {!isMobile && (+ <ConnectedDetailHeaderActionsMenuController+ idItems={[{ id: trace.id, name: "Trace ID" }]}+ projectId={projectId}+ webCallout={{+ traceId: trace.id,+ sessionId: trace.sessionId ?? null,+ }}+ >+ {({ getTriggerProps }) => (<Button- variant="outline"- size="icon"- aria-label="More actions"- className="ml-auto shrink-0"+ aria-label="Options"+ className="mt-0.5 shrink-0"+ size="icon-xs"+ title="Options"+ variant="ghost"+ {...getTriggerProps()}>- <MoreHorizontal className="h-4 w-4" />+ <EllipsisVertical className="h-4 w-4" /></Button>- </PopoverTrigger>- <PopoverContent- align="end"- // forceMount + hide-when-closed: CommentDrawerController lives in- // here, and its deep-link auto-open effect (?comments=open) and- // controlled inline-selection flow only work while mounted. A- // default Popover unmounts its content when closed (the default- // state), silently breaking both. Keep it mounted, just hidden.- forceMount- className="flex w-auto min-w-44 flex-col gap-0.5 p-1 data-[state=closed]:hidden"- >- <ConnectedTraceObservationAddToDropdownMenuController- analyticsData={{ source: "TraceDetail", isV4 }}- projectId={projectId}- traceId={trace.id}- variant="trace"- input={trace.input}- output={trace.output}- metadata={trace.metadata}- >- {({ getTriggerProps }) => (- <Button- variant="ghost"- size="sm"- className="w-full justify-start gap-2 font-normal"- {...getTriggerProps()}- >- <PlusIcon className="h-4 w-4" />- <span>Add to</span>- <ChevronDown className="ml-auto h-3 w-3" />- </Button>- )}- </ConnectedTraceObservationAddToDropdownMenuController>- {!isAnnotationMode && (- <>- <AnnotateDrawerController projectId={projectId}>- {({ disabled, openDrawer }) => (- <Button- variant="ghost"- size="sm"- disabled={disabled}- className="w-full justify-start gap-2 font-normal"- onClick={() =>- openDrawer({- scoreTarget: {- type: "trace",- traceId: trace.id,- },- scores: traceScores,- analyticsData: {- type: "trace",- source: "TraceDetail",- isV4,- },- scoreMetadata: {- projectId,- environment: trace.environment,+ )}+ </ConnectedDetailHeaderActionsMenuController>+ )}+ {isMobile && (+ <ConnectedTraceObservationAddToDropdownMenuController+ analyticsData={{ source: "TraceDetail", isV4 }}+ projectId={projectId}+ traceId={trace.id}+ variant="trace"+ input={trace.input}+ output={trace.output}+ metadata={trace.metadata}+ renderMenu={(addToItems) => (+ <AnnotateDrawerController projectId={projectId}>+ {({ disabled: annotationDisabled, openDrawer }) => (+ <ConnectedDetailHeaderActionsMenuController+ idItems={[{ id: trace.id, name: "Trace ID" }]}+ projectId={projectId}+ webCallout={{+ traceId: trace.id,+ sessionId: trace.sessionId ?? null,+ }}+ renderMenu={(utilityItems) => (+ <DropdownMenu+ placement="bottom-end"+ maxHeight="min(24rem, calc(100dvh - 2rem))"+ items={[+ ...(!isAnnotationMode+ ? [+ {+ type: "item" as const,+ id: "annotate",+ title: "Annotate",+ icon: annotationDisabled+ ? LockIcon+ : SquarePen,+ disabled: annotationDisabled+ ? {+ reason:+ "You don't have permission to annotate.",+ }+ : undefined,+ onClick: () => {+ mobileActionsTriggerRef.current?.focus({+ preventScroll: true,+ });+ openDrawer({+ scoreTarget: {+ type: "trace",+ traceId: trace.id,+ },+ scores: traceScores,+ analyticsData: {+ type: "trace",+ source: "TraceDetail",+ isV4,+ },+ scoreMetadata: {+ projectId,+ environment: trace.environment,+ },+ });+ },+ },+ ]+ : []),+ {+ type: "item",+ id: "comments",+ title:+ !commentDrawerControl.disabled && commentCount+ ? `Comments (${commentCount})`+ : "Comments",+ icon: commentDrawerControl.disabled+ ? MessageSquareOff+ : MessageSquare,+ disabled: commentDrawerControl.disabled+ ? {+ reason:+ "You don't have permission to comment.",+ }+ : undefined,+ onClick: () => {+ mobileActionsTriggerRef.current?.focus({+ preventScroll: true,+ });+ commentDrawerControl.openDrawer();},- })- }+ },+ {+ type: "submenu" as const,+ id: "add-to",+ title: "Add to",+ icon: PlusIcon,+ items: addToItems,+ },+ {+ id: "review-actions-separator",+ type: "separator",+ },+ ...utilityItems,+ ]}>- {disabled ? (- <LockIcon className="h-3 w-3" />- ) : (- <SquarePen className="h-4 w-4" />+ {({ getTriggerProps }) => (+ <Button+ variant="outline"+ size="icon"+ aria-label="More actions"+ className="ml-auto shrink-0"+ {...getTriggerProps({+ ref: mobileActionsTriggerRef,+ })}+ >+ <MoreHorizontal className="h-4 w-4" />+ </Button>)}- <span className="text-sm">Annotate</span>- </Button>+ </DropdownMenu>)}- </AnnotateDrawerController>- </>- )}- <Button- type="button"- variant="ghost"- size="sm"- disabled={commentDrawerControl.disabled}- onClick={commentDrawerControl.openDrawer}- className="w-full justify-start gap-2 font-normal"- >- {commentDrawerControl.disabled ? (- <MessageSquareOff className="text-muted-foreground h-4 w-4" />- ) : (- <MessageSquare className="h-4 w-4" />+ />)}- <span className="text-sm">Comment</span>- {!commentDrawerControl.disabled && commentCount ? (- <ActionButtonCountBadge count={commentCount} />- ) : null}- </Button>- </PopoverContent>- </Popover>+ </AnnotateDrawerController>+ )}+ />)}</div>{/* Action buttons (desktop inline cluster) */}@@ -304,7 +318,7 @@ export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({) : (<><MessageSquare className="h-3.5 w-3.5" />- <span>Comment</span>+ <span>Comments</span>{!!commentCount ? (<ActionButtonCountBadge count={commentCount} />) : null}diff --git a/web/src/features/traces/components/TraceLayoutDesktop.tsx b/web/src/features/traces/components/TraceLayoutDesktop.tsxindex 9098abc3cf..da252d8374 100644--- a/web/src/features/traces/components/TraceLayoutDesktop.tsx+++ b/web/src/features/traces/components/TraceLayoutDesktop.tsx@@ -11,6 +11,8 @@ import {import {useState,useEffect,+ useLayoutEffect,+ useRef,useMemo,createContext,useContext,@@ -21,6 +23,7 @@ import { Button } from "@/src/components/ui/button";import { cn } from "@/src/utils/tailwind";import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";import { useSelection } from "@/src/features/traces/contexts/SelectionContext";+import { TraceReviewLayout } from "./TraceReviewLayout";import { resolveEffectiveWidthFraction } from "@/src/components/table/peek/store/peekPanelStore";const RESIZABLE_PANEL_HANDLE_ID = "trace-layout-handle";@@ -135,6 +138,7 @@ function isPanelCollapsedInLayout(// Context for sharing panel state with compound componentsinterface TraceLayoutDesktopContext {+ reviewOpen: boolean;isNavigationPanelCollapsed: boolean;setIsNavigationPanelCollapsed: (collapsed: boolean) => void;panelRef: React.RefObject<PanelImperativeHandle | null>;@@ -170,16 +174,48 @@ export function useDesktopLayoutContextOptional() {return useContext(LayoutContext);}-export function TraceLayoutDesktop({- children,- groupId,- defaultNavigationCollapsed,- expandDetailOnMount,-}: {+type TraceLayoutDesktopProps = {children: ReactNode;groupId: string;defaultNavigationCollapsed: boolean;expandDetailOnMount: boolean;+ reviewOpen: boolean;+ reviewPanel: ReactNode;+};++export function TraceLayoutDesktop(props: TraceLayoutDesktopProps) {+ const { reviewPanel, ...layoutProps } = props;+ return (+ <TraceReviewLayout open={props.reviewOpen} review={reviewPanel}>+ {({ collapsed, toggle }) => (+ <TraceNavigationDetailLayout+ {...layoutProps}+ reviewNavigationCollapsed={collapsed}+ toggleReviewNavigation={toggle}+ />+ )}+ </TraceReviewLayout>+ );+}++function TraceNavigationDetailLayout({+ children,+ groupId,+ defaultNavigationCollapsed,+ expandDetailOnMount,+ reviewOpen,+ reviewNavigationCollapsed,+ toggleReviewNavigation,+}: Pick<+ TraceLayoutDesktopProps,+ | "children"+ | "groupId"+ | "defaultNavigationCollapsed"+ | "expandDetailOnMount"+ | "reviewOpen"+> & {+ reviewNavigationCollapsed: boolean;+ toggleReviewNavigation: () => void;}) {// Get current view mode from URLconst [viewMode] = useQueryParam("view", StringParam);@@ -271,6 +307,56 @@ export function TraceLayoutDesktop({// expand()+resize() imperatives (those validate against a momentarily stale// store and silently no-op on a narrow peek).const groupRef = useGroupRef();+ const normalLayout = useRef(defaultLayout ?? computedDefaultLayout);+ const appliedReviewMode = useRef(false);+ // Synchronize the panel library after its constraints register. Normal+ // navigation sizes remain separate from the temporary review layout.+ useLayoutEffect(() => {+ let cancelled = false;+ let outerFrame = 0;+ let innerFrame = 0;+ const element = document.getElementById(groupId);+ const applyLayout = () => {+ const group = groupRef.current;+ if (cancelled || !group) return;+ if (reviewOpen) {+ const width = element?.clientWidth ?? 0;+ if (!width) return;+ const navigationWidth = reviewNavigationCollapsed+ ? COLLAPSED_PANEL_PX+ : Math.max(+ NAVIGATION_PANEL_MIN_PX,+ Math.min(340, width - DETAIL_PANEL_MIN_PX),+ );+ const navigationPercent = (navigationWidth / width) * 100;+ group.setLayout({+ [RESIZABLE_PANEL_NAVIGATION_ID]: navigationPercent,+ [RESIZABLE_PANEL_PREVIEW_ID]: 100 - navigationPercent,+ });+ } else if (appliedReviewMode.current && normalLayout.current) {+ group.setLayout(normalLayout.current);+ }+ appliedReviewMode.current = reviewOpen;+ };+ if (reviewOpen) queueMicrotask(applyLayout);+ // The outer split must finish expanding before the library validates the+ // restored percentages against the inner panel's minimum widths.+ else if (appliedReviewMode.current) {+ outerFrame = requestAnimationFrame(() => {+ innerFrame = requestAnimationFrame(applyLayout);+ });+ }+ const observer = reviewOpen+ ? new ResizeObserver(() => queueMicrotask(applyLayout))+ : null;+ if (element) observer?.observe(element);+ return () => {+ cancelled = true;+ cancelAnimationFrame(outerFrame);+ cancelAnimationFrame(innerFrame);+ observer?.disconnect();+ };+ }, [reviewOpen, reviewNavigationCollapsed, groupRef, groupId]);// Which collapsed panel a click asked to open, awaiting room. We pin the group// (below) for it, let React commit the wider min-width to the DOM, then run@@ -314,6 +400,10 @@ export function TraceLayoutDesktop({// mins + horizontal scroll); on a wide peek it's a true 50/50.useEffect(() => {if (!pendingExpand) return;+ if (reviewOpen) {+ setPendingExpand(null);+ return;+ }const target = pendingExpand;let innerRaf = 0;const outerRaf = requestAnimationFrame(() => {@@ -383,12 +473,12 @@ export function TraceLayoutDesktop({cancelAnimationFrame(outerRaf);cancelAnimationFrame(innerRaf);};- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [pendingExpand]);+ }, [pendingExpand, reviewOpen, groupRef, panelRef, detailPanelRef, groupId]);// Guarded so it's a no-op (not a resize) when already open — safe to call on// every row click, which is how re-selecting the same node reopens it.const expandDetailPanel = () => {+ if (reviewOpen) return;if (!detailPanelRef.current?.isCollapsed()) return;setPendingExpand("detail");};@@ -426,6 +516,10 @@ export function TraceLayoutDesktop({// a too-narrow peek scrolls horizontally rather than collapsing the detail// panel (LFE-10550).const handleTogglePanel = () => {+ if (reviewOpen) {+ toggleReviewNavigation();+ return;+ }if (!panelRef.current) return;if (panelRef.current.isCollapsed()) {@@ -451,16 +545,23 @@ export function TraceLayoutDesktop({}, [isTimelineView]);const contextValue: TraceLayoutDesktopContext = {- isNavigationPanelCollapsed,+ reviewOpen,+ isNavigationPanelCollapsed: reviewOpen+ ? reviewNavigationCollapsed+ : isNavigationPanelCollapsed,setIsNavigationPanelCollapsed,panelRef,handleTogglePanel,shouldPulseToggle,detailPanelRef,- isDetailPanelCollapsed,+ isDetailPanelCollapsed: reviewOpen ? false : isDetailPanelCollapsed,setIsDetailPanelCollapsed,expandDetailPanel,};+ const pinNavigation = reviewOpen+ ? !reviewNavigationCollapsed+ : bothPanelsOpen;+ const minimumGroupWidth = BOTH_PANELS_MIN_WIDTH_PX;return (<LayoutContext.Provider value={contextValue}>@@ -477,12 +578,18 @@ export function TraceLayoutDesktop({id={groupId}groupRef={groupRef}defaultLayout={defaultLayout ?? computedDefaultLayout}- onLayoutChanged={onLayoutChanged}- className={bothPanelsOpen ? undefined : "min-w-0"}+ onLayoutChanged={(layout) => {+ if (reviewOpen || appliedReviewMode.current !== reviewOpen) return;+ normalLayout.current = layout;+ onLayoutChanged({+ [RESIZABLE_PANEL_NAVIGATION_ID]:+ layout[RESIZABLE_PANEL_NAVIGATION_ID]!,+ [RESIZABLE_PANEL_PREVIEW_ID]: layout[RESIZABLE_PANEL_PREVIEW_ID]!,+ });+ }}+ className={pinNavigation ? undefined : "min-w-0"}style={- bothPanelsOpen- ? { minWidth: `${BOTH_PANELS_MIN_WIDTH_PX}px` }- : undefined+ pinNavigation ? { minWidth: `${minimumGroupWidth}px` } : undefined}>{children}@@ -502,35 +609,45 @@ TraceLayoutDesktop.NavigationPanel = function Navigation({}: {children: ReactNode;}) {- const { setIsNavigationPanelCollapsed, panelRef } = useLayoutContext();+ const {+ setIsNavigationPanelCollapsed,+ panelRef,+ reviewOpen,+ isNavigationPanelCollapsed,+ } = useLayoutContext();+ const collapsedForReview = reviewOpen && isNavigationPanelCollapsed;return (<Panelid={RESIZABLE_PANEL_NAVIGATION_ID}panelRef={panelRef}- collapsible={true}+ collapsible={!reviewOpen}collapsedSize="40px"- minSize={`${NAVIGATION_PANEL_MIN_PX}px`}+ minSize={collapsedForReview ? "40px" : `${NAVIGATION_PANEL_MIN_PX}px`}+ maxSize={collapsedForReview ? "40px" : "100%"}// SSR/no-width fallback only — the computed percentage `defaultLayout`// on the Group drives the real default split. Detail carries no default// so it fills the remainder.defaultSize="40%"onResize={() => {+ if (reviewOpen) return;setIsNavigationPanelCollapsed(panelRef.current?.isCollapsed() ?? false);}}>- {children}+ <div className="h-full">{children}</div></Panel>);};// Compound component: Resize handleTraceLayoutDesktop.ResizeHandle = function ResizeHandle() {- const { handleTogglePanel } = useLayoutContext();+ const { handleTogglePanel, reviewOpen, isNavigationPanelCollapsed } =+ useLayoutContext();return (<Separatorid={RESIZABLE_PANEL_HANDLE_ID}+ disabled={reviewOpen && isNavigationPanelCollapsed}className="bg-border relative w-px transition-colors duration-200 after:absolute after:inset-y-0 after:left-0 after:w-1 after:bg-blue-200 after:opacity-0 after:transition-opacity after:duration-200 hover:after:opacity-100 active:after:opacity-100"onDoubleClick={handleTogglePanel}/>@@ -548,6 +665,7 @@ TraceLayoutDesktop.DetailPanel = function Detail({setIsDetailPanelCollapsed,isDetailPanelCollapsed,expandDetailPanel,+ reviewOpen,} = useLayoutContext();return (@@ -559,10 +677,11 @@ TraceLayoutDesktop.DetailPanel = function Detail({<Panelid={RESIZABLE_PANEL_PREVIEW_ID}panelRef={detailPanelRef}- collapsible={true}+ collapsible={!reviewOpen}collapsedSize="40px"minSize={`${DETAIL_PANEL_MIN_PX}px`}onResize={() => {+ if (reviewOpen) return;setIsDetailPanelCollapsed(detailPanelRef.current?.isCollapsed() ?? false,);@@ -571,10 +690,15 @@ TraceLayoutDesktop.DetailPanel = function Detail({{/* Keep the detail content MOUNTED while collapsed (just hidden), so itsscroll position, local state, and in-progress comment/annotationdrafts survive a collapse → expand round-trip. */}- <div className={cn("h-full w-full", isDetailPanelCollapsed && "hidden")}>+ <div+ className={cn(+ "h-full w-full",+ !reviewOpen && isDetailPanelCollapsed && "hidden",+ )}+ >{children}</div>- {isDetailPanelCollapsed && (+ {!reviewOpen && isDetailPanelCollapsed && (<div className="flex h-full w-full flex-col items-center p-2"><Buttonvariant="ghost"diff --git a/web/src/features/traces/components/TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop.tsx b/web/src/features/traces/components/TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop.tsxindex 7a113f1a95..e5930a1f43 100644--- a/web/src/features/traces/components/TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop.tsx+++ b/web/src/features/traces/components/TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop.tsx@@ -15,6 +15,7 @@ import { useDesktopLayoutContext } from "../TraceLayoutDesktop";import { TracePanelNavigationHeader } from "../TracePanelNavigationHeader/TracePanelNavigationHeader";import { TracePanelNavigationHiddenNotice } from "./components/TracePanelNavigationHiddenNotice";import { TraceTruncationNotice } from "@/src/features/traces/components/TraceTruncationNotice";+import { cn } from "@/src/utils/tailwind";export function TracePanelNavigationLayoutDesktop({children,@@ -31,13 +32,17 @@ export function TracePanelNavigationLayoutDesktop({onTogglePanel={handleTogglePanel}shouldPulseToggle={shouldPulseToggle}/>- {!isNavigationPanelCollapsed && (- <>- <TraceTruncationNotice />- <TracePanelNavigationHiddenNotice />- <div className="flex-1 overflow-hidden">{children}</div>- </>- )}+ <div+ className={cn(+ "min-h-0 flex-1 flex-col",+ isNavigationPanelCollapsed ? "hidden" : "flex",+ )}+ inert={isNavigationPanelCollapsed}+ >+ <TraceTruncationNotice />+ <TracePanelNavigationHiddenNotice />+ <div className="flex-1 overflow-hidden">{children}</div>+ </div></div>);}diff --git a/web/src/features/traces/components/TraceReviewLayout.clienttest.tsx b/web/src/features/traces/components/TraceReviewLayout.clienttest.tsxnew file mode 100644index 0000000000..a66429d9b1--- /dev/null+++ b/web/src/features/traces/components/TraceReviewLayout.clienttest.tsx@@ -0,0 +1,200 @@+/** @vitest-environment jsdom */+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useState, type ReactNode } from "react";+import { TraceReviewLayout } from "./TraceReviewLayout";+import { TracePanelNavigationLayoutDesktop } from "./TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop";++const { navigationContext } = vi.hoisted(() => ({+ navigationContext: {+ isNavigationPanelCollapsed: false,+ handleTogglePanel: vi.fn(),+ shouldPulseToggle: false,+ },+}));++vi.mock("./TraceLayoutDesktop", () => ({+ useDesktopLayoutContext: () => navigationContext,+}));+vi.mock("./TracePanelNavigationHeader/TracePanelNavigationHeader", () => ({+ TracePanelNavigationHeader: () => <div />,+}));+vi.mock(+ "./TracePanelNavigationLayoutDesktop/components/TracePanelNavigationHiddenNotice",+ () => ({ TracePanelNavigationHiddenNotice: () => <div /> }),+);+vi.mock("./TraceTruncationNotice", () => ({+ TraceTruncationNotice: () => <div />,+}));++vi.mock("react-resizable-panels", () => ({+ useGroupRef: () => ({ current: { setLayout: vi.fn() } }),+ Group: ({+ children,+ orientation,+ }: {+ children: ReactNode;+ orientation: string;+ }) => (+ <div data-testid="group" data-orientation={orientation}>+ {children}+ </div>+ ),+ Panel: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ Separator: () => <div />,+}));++function Harness({ open = true }: { open?: boolean }) {+ return (+ <div data-peek-content>+ <TraceReviewLayout+ open={open}+ review={<input aria-label="Review draft" />}+ >+ {({ collapsed, toggle }) => (+ <div>+ <button onClick={toggle}>+ {collapsed ? "Show navigation" : "Hide navigation"}+ </button>+ <input aria-label="Trace draft" />+ </div>+ )}+ </TraceReviewLayout>+ </div>+ );+}++let width = 1120;+function resize(viewport: number, container: number) {+ width = container;+ act(() => {+ window.innerWidth = viewport;+ window.dispatchEvent(new Event("resize"));+ });+}++beforeEach(() => {+ localStorage.clear();+ navigationContext.isNavigationPanelCollapsed = false;+ width = 1120;+ window.innerWidth = 1920;+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ disconnect() {}+ },+ );+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(+ () => ({+ width,+ height: 800,+ x: 0,+ y: 0,+ top: 0,+ left: 0,+ bottom: 800,+ right: width,+ toJSON() {},+ }),+ );+});+afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe("trace review responsive workspace", () => {+ it("keeps the real navigator mounted with its editable state through collapse and reopening", () => {+ function NavigatorDraft() {+ const [draft, setDraft] = useState("");+ return (+ <input+ aria-label="Navigator draft"+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ />+ );+ }+ const renderNavigation = () => (+ <TracePanelNavigationLayoutDesktop>+ <NavigatorDraft />+ </TracePanelNavigationLayoutDesktop>+ );+ const view = render(renderNavigation());+ const draft = screen.getByLabelText("Navigator draft");+ fireEvent.change(draft, { target: { value: "Keep my navigation state" } });++ navigationContext.isNavigationPanelCollapsed = true;+ view.rerender(renderNavigation());+ expect(draft).toBeInTheDocument();+ expect(draft.closest("[inert]")).not.toBeNull();++ navigationContext.isNavigationPanelCollapsed = false;+ view.rerender(renderNavigation());+ expect(screen.getByLabelText("Navigator draft")).toBe(draft);+ expect(draft).toHaveValue("Keep my navigation state");+ expect(draft.closest("[inert]")).toBeNull();+ });++ it("uses available space automatically and retains both editors through reflow and close/reopen", () => {+ const view = render(<Harness />);+ const trace = screen.getByLabelText("Trace draft");+ const review = screen.getByLabelText("Review draft");+ fireEvent.change(trace, { target: { value: "trace edit" } });+ fireEvent.change(review, { target: { value: "unsent comment" } });+ expect(+ screen.getByRole("button", { name: "Hide navigation" }),+ ).toBeTruthy();+ expect(screen.getByTestId("group").getAttribute("data-orientation")).toBe(+ "horizontal",+ );++ resize(700, 700);+ expect(+ screen.getByRole("button", { name: "Show navigation" }),+ ).toBeTruthy();+ expect(screen.getByTestId("group").getAttribute("data-orientation")).toBe(+ "vertical",+ );+ resize(2560, 1280);+ expect(+ screen.getByRole("button", { name: "Hide navigation" }),+ ).toBeTruthy();+ view.rerender(<Harness open={false} />);+ view.rerender(<Harness />);+ expect(screen.getByLabelText("Trace draft")).toBe(trace);+ expect(screen.getByLabelText("Review draft")).toBe(review);+ expect((review as HTMLInputElement).value).toBe("unsent comment");+ expect((trace as HTMLInputElement).value).toBe("trace edit");+ });++ it("keeps an explicit navigation choice across screen changes and later trace workspaces", () => {+ const view = render(<Harness />);+ fireEvent.click(screen.getByRole("button", { name: "Hide navigation" }));+ resize(2560, 1280);+ expect(+ screen.getByRole("button", { name: "Show navigation" }),+ ).toBeTruthy();+ view.unmount();+ render(<Harness />);+ expect(+ screen.getByRole("button", { name: "Show navigation" }),+ ).toBeTruthy();+ resize(700, 700);+ fireEvent.click(screen.getByRole("button", { name: "Show navigation" }));+ expect(+ screen.getByRole("button", { name: "Hide navigation" }),+ ).toBeTruthy();+ expect(screen.getByTestId("group").getAttribute("data-orientation")).toBe(+ "vertical",+ );+ });+});diff --git a/web/src/features/traces/components/TraceReviewLayout.tsx b/web/src/features/traces/components/TraceReviewLayout.tsxnew file mode 100644index 0000000000..49c8d08cc1--- /dev/null+++ b/web/src/features/traces/components/TraceReviewLayout.tsx@@ -0,0 +1,157 @@+import { useLayoutEffect, useRef, useState, type ReactNode } from "react";+import { Group, Panel, Separator, useGroupRef } from "react-resizable-panels";+import { cn } from "@/src/utils/tailwind";++const NAVIGATION_PREFERENCE_KEY = "trace-review-navigation-collapsed";++function readNavigationPreference(): boolean | null {+ if (typeof window === "undefined") return null;+ try {+ const value = localStorage.getItem(NAVIGATION_PREFERENCE_KEY);+ if (value === "true") return true;+ if (value === "false") return false;+ return null;+ } catch {+ return null;+ }+}++/** Keeps the trace and review editors mounted across responsive layout changes. */+export function TraceReviewLayout({+ open,+ review,+ children,+}: {+ open: boolean;+ review: ReactNode;+ children: (navigation: {+ collapsed: boolean;+ toggle: () => void;+ }) => ReactNode;+}) {+ const rootRef = useRef<HTMLDivElement>(null);+ const groupRef = useGroupRef();+ const [size, setSize] = useState({+ width: 0,+ availableWidth: 0,+ isPeek: false,+ });+ const [navigationPreference, setNavigationPreference] = useState(+ readNavigationPreference,+ );++ useLayoutEffect(() => {+ const root = rootRef.current;+ if (!root) return;+ const sidebar = document.querySelector('[data-sidebar="sidebar"]');+ const measure = () => {+ const width = root.getBoundingClientRect().width;+ const sidebarRect = sidebar?.getBoundingClientRect();+ const sidebarWidth =+ sidebarRect && sidebarRect.left < 100 ? sidebarRect.right : 0;+ const isPeek = Boolean(root.closest("[data-peek-content]"));+ const availableWidth = isPeek ? window.innerWidth - sidebarWidth : width;+ setSize((previous) =>+ previous.width === width &&+ previous.availableWidth === availableWidth &&+ previous.isPeek === isPeek+ ? previous+ : { width, availableWidth, isPeek },+ );+ };+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(root);+ if (sidebar) observer.observe(sidebar);+ window.addEventListener("resize", measure);+ return () => {+ observer.disconnect();+ window.removeEventListener("resize", measure);+ };+ }, []);++ const collapsed = navigationPreference ?? size.availableWidth < 1120;+ // Account for the shell's CSS expansion in the first open render, before+ // ResizeObserver reports that width, so the pane doesn't switch axes on entry.+ const reviewWidth =+ open && size.isPeek+ ? Math.min(+ size.availableWidth,+ Math.max(size.width, collapsed ? 800 : 1120),+ )+ : size.width;+ const vertical = reviewWidth < (collapsed ? 762 : 983);+ const openLayout = collapsed ? "review" : "review-navigation";+ const horizontalWorkspaceMinimum = collapsed ? "400px" : "621px";+ const workspaceMinimum = vertical ? "240px" : horizontalWorkspaceMinimum;+ const reviewMinimum = vertical ? "320px" : "360px";++ useLayoutEffect(() => {+ let cancelled = false;+ queueMicrotask(() => {+ if (cancelled) return;+ groupRef.current?.setLayout({+ workspace: open ? 60 : 100,+ review: open ? 40 : 0,+ });+ });+ return () => {+ cancelled = true;+ };+ }, [open, vertical, groupRef]);++ const toggle = () => {+ const next = !collapsed;+ setNavigationPreference(next);+ try {+ localStorage.setItem(NAVIGATION_PREFERENCE_KEY, String(next));+ } catch {+ // The preference remains available for this mounted workspace.+ }+ };++ return (+ <div+ ref={rootRef}+ className="h-full min-h-0 min-w-0 overflow-y-auto"+ data-peek-layout={open ? openLayout : undefined}+ data-review-orientation={vertical ? "vertical" : "horizontal"}+ >+ <Group+ groupRef={groupRef}+ orientation={vertical ? "vertical" : "horizontal"}+ className={cn(+ "h-full min-h-0 min-w-0",+ open && (vertical ? "min-h-[561px]" : "min-h-[320px]"),+ )}+ >+ <Panel+ id="workspace"+ defaultSize="100%"+ minSize={open ? workspaceMinimum : "0%"}+ >+ {children({ collapsed, toggle })}+ </Panel>+ <Separator+ disabled={!open}+ aria-label="Resize review panel"+ className={cn(+ "bg-border",+ vertical ? "h-px" : "w-px",+ !open && "hidden",+ )}+ />+ <Panel+ id="review"+ defaultSize="0%"+ minSize={open ? reviewMinimum : "0%"}+ maxSize={open ? "75%" : "0%"}+ >+ <div className="h-full min-h-0" hidden={!open}>+ {review}+ </div>+ </Panel>+ </Group>+ </div>+ );+}diff --git a/web/src/features/traces/components/TraceReviewPanel.tsx b/web/src/features/traces/components/TraceReviewPanel.tsxnew file mode 100644index 0000000000..44e3379889--- /dev/null+++ b/web/src/features/traces/components/TraceReviewPanel.tsx@@ -0,0 +1,154 @@+import { useStore } from "zustand";+import { useEffect, useRef } from "react";+import { useRouter, type NextRouter } from "next/router";+import { X } from "lucide-react";+import { Button } from "@/src/components/ui/button";+import { CommentList } from "@/src/features/comments/CommentList";+import { AnnotationPanelContent } from "@/src/features/scores/components/AnnotationPanelContent";+import { hasBlockingOverlay } from "@/src/features/scores/lib/keyboardShortcuts";+import { useTraceReviewPanel } from "../contexts/TraceReviewPanelContext";+import { type TraceReviewPanelStore } from "../state/traceReviewPanelStore";++function closeReviewPanel(store: TraceReviewPanelStore, router: NextRouter) {+ store.getState().actions.close();+ if (router.query.comments !== "open") return;+ const { comments, commentObjectType, commentObjectId, ...query } =+ router.query;+ router.replace({ pathname: router.pathname, query }, undefined, {+ shallow: true,+ });+}++function CloseReviewPanelButton() {+ const store = useTraceReviewPanel();+ const router = useRouter();+ return (+ <Button+ variant="ghost"+ size="icon"+ aria-label="Close side panel"+ onClick={() => closeReviewPanel(store, router)}+ >+ <X className="size-4" />+ </Button>+ );+}++function TraceCommentsPanel({ projectId }: { projectId: string }) {+ const store = useTraceReviewPanel();+ const target = useStore(store, (state) => state.comments!.target);+ const sessionKey = useStore(store, (state) => state.comments!.key);+ const onCommentChange = useStore(+ store,+ (state) => state.comments!.onCommentChange,+ );+ const active = useStore(store, (state) => state.active === "comments");+ const actions = store.getState().actions;+ return (+ <section+ aria-label="Comments"+ className="flex h-full min-h-0 flex-col"+ hidden={!active}+ >+ <div className="flex shrink-0 items-center justify-between border-b px-4 py-2">+ <h2 className="text-sm font-bold">Comments</h2>+ <CloseReviewPanelButton />+ </div>+ <div className="min-h-0 flex-1">+ <CommentList+ projectId={projectId}+ objectId={target.objectId}+ objectType={target.objectType}+ objectStartTime={target.objectStartTime}+ pendingSelection={+ target.type === "inline-comment" ? target.selection : null+ }+ onSelectionUsed={() => actions.consumeCommentsSelection(sessionKey)}+ onDraftChange={(hasDraft) =>+ actions.setCommentsDraft(sessionKey, hasDraft)+ }+ onMentionDropdownChange={(open) =>+ actions.setCommentsMentionsOpen(sessionKey, open)+ }+ onCommentChange={onCommentChange}+ isDrawerOpen={active}+ isActive={active}+ />+ </div>+ </section>+ );+}++function TraceAnnotationPanel() {+ const store = useTraceReviewPanel();+ const annotation = useStore(store, (state) => state.annotation!);+ const active = useStore(store, (state) => state.active === "annotate");+ return (+ <section+ aria-label="Annotate"+ className="h-full overflow-y-auto p-4 [--annotation-surface:var(--background)]"+ hidden={!active}+ >+ <AnnotationPanelContent+ data={annotation.data}+ refreshRef={store.annotationFormRef}+ actionButtons={<CloseReviewPanelButton />}+ isActive={active}+ />+ </section>+ );+}++export function TraceReviewPanel({ projectId }: { projectId: string }) {+ const store = useTraceReviewPanel();+ const rootRef = useRef<HTMLDivElement>(null);+ const active = useStore(store, (state) => state.active);+ const commentsKey = useStore(store, (state) => state.comments?.key);+ const annotationKey = useStore(store, (state) => state.annotation?.key);+ const router = useRouter();++ useEffect(() => {+ if (!active) return;+ const handleEscape = (event: KeyboardEvent) => {+ if (event.key !== "Escape" || event.defaultPrevented) return;+ const root = rootRef.current;+ if (!root || hasBlockingOverlay(root)) return;+ const workspace = root.closest("[data-trace-review-open]");+ if (+ event.target instanceof Node &&+ event.target !== document.body &&+ !workspace?.contains(event.target)+ )+ return;+ if (active === "comments" && store.getState().comments?.mentionsOpen)+ return;+ if (+ active === "annotate" &&+ (event.target instanceof HTMLInputElement ||+ event.target instanceof HTMLTextAreaElement)+ )+ return;+ event.preventDefault();+ event.stopImmediatePropagation();+ closeReviewPanel(store, router);+ };+ // Capture before the parent peek's document-level dismissal handler.+ window.addEventListener("keydown", handleEscape, true);+ return () => window.removeEventListener("keydown", handleEscape, true);+ }, [active, router, store]);++ return (+ <div+ ref={rootRef}+ className="bg-background h-full min-h-0 overflow-hidden"+ data-trace-review-panel+ >+ {commentsKey !== undefined ? (+ <TraceCommentsPanel key={commentsKey} projectId={projectId} />+ ) : null}+ {annotationKey !== undefined ? (+ <TraceAnnotationPanel key={annotationKey} />+ ) : null}+ </div>+ );+}diff --git a/web/src/features/traces/contexts/TraceReviewPanelContext.tsx b/web/src/features/traces/contexts/TraceReviewPanelContext.tsxnew file mode 100644index 0000000000..b825c0a9e0--- /dev/null+++ b/web/src/features/traces/contexts/TraceReviewPanelContext.tsx@@ -0,0 +1,43 @@+import { createContext, useContext, useState, type ReactNode } from "react";+import { type CommentTarget } from "@/src/features/comments/state/commentOverlayStore";+import {+ createTraceReviewPanelStore,+ type TraceReviewPanelStore,+} from "../state/traceReviewPanelStore";++const TraceReviewPanelContext = createContext<TraceReviewPanelStore | null>(+ null,+);++export function TraceReviewPanelProvider({+ projectId,+ initialComments,+ children,+}: {+ projectId: string;+ initialComments?: CommentTarget;+ children: ReactNode;+}) {+ const [store] = useState(() =>+ createTraceReviewPanelStore({ projectId, initialComments }),+ );++ return (+ <TraceReviewPanelContext.Provider value={store}>+ {children}+ </TraceReviewPanelContext.Provider>+ );+}++export function useTraceReviewPanelOptional() {+ return useContext(TraceReviewPanelContext);+}++export function useTraceReviewPanel() {+ const store = useTraceReviewPanelOptional();+ if (!store)+ throw new Error(+ "useTraceReviewPanel must be used within a TraceReviewPanelProvider",+ );+ return store;+}diff --git a/web/src/features/traces/state/traceReviewPanelStore.clienttest.ts b/web/src/features/traces/state/traceReviewPanelStore.clienttest.tsnew file mode 100644index 0000000000..eb0a95bf01--- /dev/null+++ b/web/src/features/traces/state/traceReviewPanelStore.clienttest.ts@@ -0,0 +1,186 @@+import { type CommentTarget } from "@/src/features/comments/state/commentOverlayStore";+import { type AnnotationPanelData } from "@/src/features/scores/types";+import { createTraceReviewPanelStore } from "./traceReviewPanelStore";++const target: CommentTarget = {+ type: "comments",+ objectId: "trace",+ objectType: "TRACE",+};+const selection = {+ dataField: "output" as const,+ path: ["$"],+ rangeStart: [0],+ rangeEnd: [4],+ selectedText: "text",+ anchorRect: null,+};+const annotation: AnnotationPanelData = {+ scoreTarget: { type: "trace", traceId: "trace", observationId: "span" },+ scoreMetadata: { projectId: "project" },+ analyticsData: { type: "trace", source: "TraceDetail", isV4: true },+ scores: [],+ companionTrace: { environment: "default", scores: [] },+};++describe("trace review panel sessions", () => {+ it("keeps a comment draft and its session when closed and reopened", () => {+ const store = createTraceReviewPanelStore({ projectId: "project" });+ const actions = store.getState().actions;+ const confirmDiscard = vi.fn(() => false);+ actions.openComments({ target, confirmDiscard });+ const key = store.getState().comments!.key;+ actions.setCommentsDraft(key, true);+ actions.close();+ expect(store.getState().active).toBeNull();+ expect(store.getState().comments?.hasDraft).toBe(true);++ actions.openComments({ target: { ...target }, confirmDiscard });+ expect(store.getState().active).toBe("comments");+ expect(store.getState().comments).toMatchObject({ key, hasDraft: true });+ expect(confirmDiscard).not.toHaveBeenCalled();+ });++ it("preserves both sessions while switching modes and refreshing score data", () => {+ const store = createTraceReviewPanelStore({+ projectId: "project",+ initialComments: target,+ });+ const actions = store.getState().actions;+ const commentsKey = store.getState().comments!.key;+ actions.setCommentsDraft(commentsKey, true);+ actions.openAnnotation(annotation);+ const annotationSession = store.getState().annotation;+ const refresh = vi.fn();+ const focus = vi.fn();+ store.annotationFormRef.current = { refresh, focus };+ actions.openComments({ target, confirmDiscard: () => false });+ const refreshed = { ...annotation, scores: [] };+ actions.openAnnotation(refreshed);++ expect(store.getState().active).toBe("annotate");+ expect(store.getState().comments).toMatchObject({+ key: commentsKey,+ hasDraft: true,+ });+ expect(store.getState().annotation?.key).toBe(annotationSession?.key);+ expect(store.getState().annotation?.data).toBe(refreshed);+ expect(refresh).toHaveBeenCalledExactlyOnceWith(refreshed);+ expect(focus).not.toHaveBeenCalled();+ actions.openAnnotation(refreshed);+ expect(focus).toHaveBeenCalledOnce();+ });++ it("returns focus to a connected trigger on close and ignores a removed trigger", () => {+ const store = createTraceReviewPanelStore({ projectId: "project" });+ const actions = store.getState().actions;+ const trigger = document.createElement("button");+ const focus = vi.spyOn(trigger, "focus");+ document.body.appendChild(trigger);+ try {+ actions.rememberTrigger(trigger);+ actions.openComments({ target, confirmDiscard: () => true });+ actions.close();+ expect(focus).toHaveBeenCalledWith({ preventScroll: true });+ focus.mockClear();+ trigger.remove();+ actions.openComments({ target, confirmDiscard: () => true });+ actions.close();+ expect(focus).not.toHaveBeenCalled();+ } finally {+ trigger.remove();+ }+ });++ it("asks before replacing another target's unsent comment, even when hidden", () => {+ const store = createTraceReviewPanelStore({+ projectId: "project",+ initialComments: target,+ });+ const actions = store.getState().actions;+ const key = store.getState().comments!.key;+ actions.setCommentsDraft(key, true);+ actions.setCommentsMentionsOpen(key, true);+ actions.openAnnotation(annotation);+ const before = store.getState();+ const nextTarget: CommentTarget = {+ ...target,+ objectId: "span",+ objectType: "OBSERVATION",+ };+ const confirmDiscard = vi.fn(() => false);+ actions.openComments({ target: nextTarget, confirmDiscard });+ expect(store.getState()).toBe(before);+ expect(confirmDiscard).toHaveBeenCalledOnce();++ actions.openComments({ target: nextTarget, confirmDiscard: () => true });+ expect(store.getState().active).toBe("comments");+ expect(store.getState().comments).toMatchObject({+ target: nextTarget,+ hasDraft: false,+ mentionsOpen: false,+ });+ expect(store.getState().comments?.key).not.toBe(key);+ });++ it("ignores old session callbacks and consumes a hidden selection without reopening", () => {+ const store = createTraceReviewPanelStore({+ projectId: "project",+ initialComments: target,+ });+ const actions = store.getState().actions;+ const oldKey = store.getState().comments!.key;+ actions.openComments({+ target: {+ ...target,+ objectId: "other",+ type: "inline-comment",+ selection,+ },+ confirmDiscard: () => true,+ });+ const key = store.getState().comments!.key;+ actions.setCommentsDraft(key, true);+ const before = store.getState();+ actions.setCommentsDraft(oldKey, false);+ actions.setCommentsMentionsOpen(oldKey, true);+ actions.consumeCommentsSelection(oldKey);+ expect(store.getState()).toBe(before);++ actions.close();+ actions.setCommentsDraft(key, false);+ actions.consumeCommentsSelection(key);+ expect(store.getState().active).toBeNull();+ expect(store.getState().comments).toMatchObject({+ key,+ target: { type: "comments", objectId: "other" },+ hasDraft: false,+ });+ expect(store.getState().comments?.target).not.toHaveProperty("selection");+ });++ it("keeps an unsent inline selection on same-target reopen and accepts new selections once consumed", () => {+ const store = createTraceReviewPanelStore({+ projectId: "project",+ initialComments: { ...target, type: "inline-comment", selection },+ });+ const actions = store.getState().actions;+ const key = store.getState().comments!.key;+ actions.setCommentsDraft(key, true);+ const nextSelection = { ...selection, selectedText: "next" };+ const nextTarget: CommentTarget = {+ ...target,+ type: "inline-comment",+ selection: nextSelection,+ };+ actions.openComments({ target: nextTarget, confirmDiscard: () => false });+ expect(store.getState().comments?.target).toMatchObject({ selection });+ actions.setCommentsDraft(key, false);+ actions.consumeCommentsSelection(key);+ actions.openComments({ target: nextTarget, confirmDiscard: () => true });+ expect(store.getState().comments).toMatchObject({+ key,+ target: { selection: nextSelection },+ });+ });+});diff --git a/web/src/features/traces/state/traceReviewPanelStore.ts b/web/src/features/traces/state/traceReviewPanelStore.tsnew file mode 100644index 0000000000..6a07322207--- /dev/null+++ b/web/src/features/traces/state/traceReviewPanelStore.ts@@ -0,0 +1,153 @@+import { createStore } from "zustand/vanilla";+import { type CommentTarget } from "@/src/features/comments/state/commentOverlayStore";+import {+ type AnnotationPanelData,+ type AnnotationRefreshHandle,+} from "@/src/features/scores/types";++export type TraceCommentsSession = {+ key: number;+ target: CommentTarget;+ onCommentChange?: () => void | Promise<void>;+ hasDraft: boolean;+ mentionsOpen: boolean;+};++type TraceAnnotationSession = {+ key: string;+ data: AnnotationPanelData;+};++type TraceReviewPanelState = {+ active: "comments" | "annotate" | null;+ comments: TraceCommentsSession | null;+ annotation: TraceAnnotationSession | null;+ actions: {+ openComments: (input: {+ target: CommentTarget;+ onCommentChange?: () => void | Promise<void>;+ confirmDiscard: () => boolean;+ }) => void;+ openAnnotation: (data: AnnotationPanelData) => void;+ rememberTrigger: (element: HTMLElement | null) => void;+ close: () => void;+ setCommentsDraft: (key: number, hasDraft: boolean) => void;+ setCommentsMentionsOpen: (key: number, open: boolean) => void;+ consumeCommentsSelection: (key: number) => void;+ };+};++export function createTraceReviewPanelStore({+ projectId,+ initialComments,+}: {+ projectId: string;+ initialComments?: CommentTarget;+}) {+ let commentsKey = 0;+ const annotationFormRef: { current: AnnotationRefreshHandle | null } = {+ current: null,+ };+ let trigger: HTMLElement | null = null;+ const createCommentsSession = (+ target: CommentTarget,+ onCommentChange?: TraceCommentsSession["onCommentChange"],+ ): TraceCommentsSession => ({+ key: ++commentsKey,+ target,+ onCommentChange,+ hasDraft: false,+ mentionsOpen: false,+ });++ const store = createStore<TraceReviewPanelState>((set, get) => ({+ active: initialComments ? "comments" : null,+ comments: initialComments ? createCommentsSession(initialComments) : null,+ annotation: null,+ actions: {+ openComments({ target, onCommentChange, confirmDiscard }) {+ const current = get().comments;+ const sameTarget =+ current?.target.objectId === target.objectId &&+ current.target.objectType === target.objectType;+ if (sameTarget) {+ // Reopening an object keeps its composer and any unsent selection.+ const nextTarget =+ !current.hasDraft && target.type === "inline-comment"+ ? target+ : current.target;+ set({+ active: "comments",+ comments:+ current.target === nextTarget &&+ current.onCommentChange === onCommentChange+ ? current+ : { ...current, target: nextTarget, onCommentChange },+ });+ return;+ }+ if (current?.hasDraft && !confirmDiscard()) return;+ set({+ active: "comments",+ comments: createCommentsSession(target, onCommentChange),+ });+ },+ openAnnotation(data) {+ const target = data.scoreTarget;+ const key = JSON.stringify([+ projectId,+ target.type,+ target.type === "trace" ? target.traceId : target.sessionId,+ target.type === "trace" ? (target.observationId ?? null) : null,+ data.scoreMetadata.queueId ?? null,+ Boolean(data.companionTrace),+ ]);+ const current = get().annotation;+ if (current?.key === key) {+ annotationFormRef.current?.refresh(data);+ if (get().active === "annotate") annotationFormRef.current?.focus();+ }+ set({+ active: "annotate",+ annotation: { key, data },+ });+ },+ rememberTrigger(element) {+ trigger = element;+ },+ close() {+ if (get().active === null) return;+ set({ active: null });+ if (trigger?.isConnected) trigger.focus({ preventScroll: true });+ },+ setCommentsDraft(key, hasDraft) {+ const current = get().comments;+ if (current?.key !== key || current.hasDraft === hasDraft) return;+ set({ comments: { ...current, hasDraft } });+ },+ setCommentsMentionsOpen(key, mentionsOpen) {+ const current = get().comments;+ if (current?.key !== key || current.mentionsOpen === mentionsOpen)+ return;+ set({ comments: { ...current, mentionsOpen } });+ },+ consumeCommentsSelection(key) {+ const current = get().comments;+ if (current?.key !== key || current.target.type !== "inline-comment")+ return;+ const { objectId, objectType, objectStartTime } = current.target;+ set({+ comments: {+ ...current,+ target: { type: "comments", objectId, objectType, objectStartTime },+ },+ });+ },+ },+ }));+ return Object.assign(store, { annotationFormRef });+}++export type TraceReviewPanelStore = ReturnType<+ typeof createTraceReviewPanelStore+>;