🪢 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
fix(web): update trace and session header actions (#17765)
Trang Nguyend491a6e26158
diff --git a/web/src/components/HeaderActionButton.tsx b/web/src/components/HeaderActionButton.tsxnew file mode 100644index 0000000000..0bf9d23c12--- /dev/null+++ b/web/src/components/HeaderActionButton.tsx@@ -0,0 +1,55 @@+import * as React from "react";++import { type KeyboardKey } from "@/src/components/design-system/KeyboardShortcut/KeyboardShortcut";+import { Button, type ButtonProps } from "@/src/components/ui/button";+import { InputCommandShortcut } from "@/src/components/ui/input-command";+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from "@/src/components/ui/tooltip";+import { cn } from "@/src/utils/tailwind";++type HeaderActionButtonProps = Omit<+ ButtonProps,+ "variant" | "size" | "className" | "children" | "title"+> & {+ label: string;+ icon: React.ReactNode;+ shortcut?: KeyboardKey;+ active?: boolean;+};++export const HeaderActionButton = React.forwardRef<+ HTMLButtonElement,+ HeaderActionButtonProps+>(function HeaderActionButton(+ { label, icon, shortcut, active = false, ...props },+ ref,+) {+ return (+ <Tooltip>+ <TooltipTrigger asChild onFocus={(event) => event.preventDefault()}>+ <Button+ ref={ref}+ variant="ghost"+ size="icon"+ aria-label={label}+ className={cn(+ "text-foreground-secondary hover:text-foreground-secondary h-7 w-7",+ active && "bg-accent/60 ring-primary/20 ring-2",+ )}+ {...props}+ >+ {icon}+ </Button>+ </TooltipTrigger>+ <TooltipContent>+ <span>{label}</span>+ {shortcut && (+ <InputCommandShortcut className="ml-2" keys={[shortcut]} />+ )}+ </TooltipContent>+ </Tooltip>+ );+});diff --git a/web/src/components/HeaderActionMenuRow.tsx b/web/src/components/HeaderActionMenuRow.tsxnew file mode 100644index 0000000000..f53224daf3--- /dev/null+++ b/web/src/components/HeaderActionMenuRow.tsx@@ -0,0 +1,75 @@+import * as React from "react";++import { type DropdownMenuItemDefinition } from "@/src/components/design-system/DropdownMenu/DropdownMenu";+import { Button, type ButtonProps } from "@/src/components/ui/button";+import { cn } from "@/src/utils/tailwind";++type HeaderActionMenuRowProps = Omit<+ ButtonProps,+ "variant" | "size" | "className" | "children" | "title"+> & {+ label: string;+ icon?: React.ReactNode;+ badge?: React.ReactNode;+ variant?: "default" | "destructive";+ disabledReason?: string;+};++/** Full-width labeled row for the mobile header overflow menu. */+export const HeaderActionMenuRow = React.forwardRef<+ HTMLButtonElement,+ HeaderActionMenuRowProps+>(function HeaderActionMenuRow(+ { label, icon, badge, variant = "default", disabledReason, ...props },+ ref,+) {+ return (+ <Button+ ref={ref}+ type="button"+ variant="ghost"+ size="sm"+ className={cn(+ "w-full justify-start gap-2 font-normal",+ variant === "destructive" && "text-destructive hover:text-destructive",+ )}+ title={disabledReason}+ {...props}+ >+ {icon}+ {label}+ {badge}+ </Button>+ );+});++type MenuItem = Extract<DropdownMenuItemDefinition, { type: "item" }>;++const isMenuItem = (item: DropdownMenuItemDefinition): item is MenuItem =>+ item.type === "item";++/** Renders the clickable items of a dropdown definition as menu rows. */+export function HeaderActionMenuRows({+ items,+}: {+ items: DropdownMenuItemDefinition[];+}) {+ return (+ <>+ {items.filter(isMenuItem).map((item) => {+ const Icon = item.icon;+ return (+ <HeaderActionMenuRow+ key={item.id}+ label={item.title}+ icon={Icon && <Icon className="h-4 w-4" />}+ variant={item.variant}+ disabled={item.disabled !== undefined}+ disabledReason={item.disabled?.reason}+ onClick={item.onClick}+ />+ );+ })}+ </>+ );+}diff --git a/web/src/components/SingleLineOverflowList.tsx b/web/src/components/SingleLineOverflowList.tsxindex d1eff9c9ea..3333efb640 100644--- a/web/src/components/SingleLineOverflowList.tsx+++ b/web/src/components/SingleLineOverflowList.tsx@@ -13,10 +13,10 @@ import { type ReactNode, useEffect, useRef, useState } from "react";// Rows of boxed pills read fine at gap-2; rows of mostly-plain text (the// session header's metrics/attributes/links) need more air to scan as-// separate facts, matching the trace headers' gap-6; bordered chips pull to 4px.+// separate facts, matching the trace headers' gap-4; bordered chips pull to 4px.const SPACING_CLASS = {compact: "gap-2",- comfortable: "gap-6",+ comfortable: "gap-4",} as const;export function SingleLineOverflowList<TItem>({items,@@ -139,7 +139,7 @@ export function SingleLineOverflowList<TItem>({data-tight={isTightItem?.(item) ? "true" : undefined}className={cn("flex items-center",- isTightItem?.(item) && "[[data-tight]+&]:-ml-5",+ isTightItem?.(item) && "[[data-tight]+&]:-ml-3",)}>{renderItem(item)}@@ -159,7 +159,7 @@ export function SingleLineOverflowList<TItem>({data-tight={isTightItem?.(item) ? "true" : undefined}className={cn("flex items-center",- isTightItem?.(item) && "[[data-tight]+&]:-ml-5",+ isTightItem?.(item) && "[[data-tight]+&]:-ml-3",)}>{renderItem(item)}diff --git a/web/src/components/deleteButton.tsx b/web/src/components/deleteButton.tsxindex 9540a7b6c0..19e3ff25f9 100644--- a/web/src/components/deleteButton.tsx+++ b/web/src/components/deleteButton.tsx@@ -15,7 +15,6 @@ import { type ProjectScope } from "@langfuse/shared";import { api } from "@/src/utils/api";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";import { showSuccessToast } from "@/src/features/notifications";-import { useHasEntitlement } from "@/src/features/entitlements";import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";export type DeleteButtonProps = {@@ -240,55 +239,6 @@ export function DeleteButton({);}-export function DeleteTraceButton(props: DeleteButtonProps) {- const utils = api.useUtils();- const {- itemId,- projectId,- scope = "traces:delete",- invalidateFunc = () => utils.traces.all.invalidate(),- } = props;- const traceMutation = api.traces.deleteMany.useMutation();- const executeDeleteMutation = async (onSuccess: () => void) => {- try {- await traceMutation.mutateAsync({- traceIds: [itemId],- projectId,- });- } catch (error) {- return Promise.reject(error);- }- showSuccessToast({- title: "Trace deleted",- description:- "Selected trace will be deleted. Traces are removed asynchronously and may continue to be visible for up to 24 hours.",- });- onSuccess();- };- const hasTraceDeletionEntitlement = useHasEntitlement("trace-deletion");- return (- <DeleteButton- {...props}- scope={scope}- invalidateFunc={invalidateFunc}- captureDeleteOpen={(capture, isTableAction) =>- capture("trace:delete_form_open", {- source: isTableAction ? "table-single-row" : "trace detail",- })- }- captureDeleteSuccess={(capture, isTableAction) =>- capture("trace:delete", {- source: isTableAction ? "table-single-row" : "trace",- })- }- entityToDeleteName="trace"- executeDeleteMutation={executeDeleteMutation}- isDeleteMutationLoading={traceMutation.isPending}- enabled={hasTraceDeletionEntitlement}- />- );-}-/** DeleteMonitorButton deletes a monitor through the shared confirm-then-delete pattern. */export function DeleteMonitorButton(props: DeleteButtonProps) {const utils = api.useUtils();diff --git a/web/src/components/design-system/Badge/Badge.tsx b/web/src/components/design-system/Badge/Badge.tsxindex 7a3c8e11c9..be56e58d5d 100644--- a/web/src/components/design-system/Badge/Badge.tsx+++ b/web/src/components/design-system/Badge/Badge.tsx@@ -9,6 +9,10 @@ const badgeVariants = cva("inline-flex w-fit max-w-full min-w-0 shrink-0 items-center rounded-sm border pb-px text-xs leading-none font-normal",{variants: {+ size: {+ default: "h-5.5 gap-1.5 pr-1.5 pl-2",+ sm: "h-4.5 gap-1 px-1.5",+ },color: {primary: "border-border bg-transparent text-foreground-secondary",red: "border-transparent bg-light-red/60 text-dark-red/90 dark:bg-light-red/40 dark:text-dark-red/90",@@ -20,13 +24,9 @@ const badgeVariants = cva(ghost: "border-0 bg-transparent px-0 text-foreground-secondary",},interactive: {- true: "decoration-border-contrast underline decoration-dashed underline-offset-[3px]",+ true: "decoration-border-contrast underline decoration-dashed decoration-1 underline-offset-[3px]",false: "",},- size: {- default: "h-5.5 gap-1.5 pr-1.5 pl-2",- sm: "h-4.5 gap-1 px-1.5",- },},defaultVariants: {color: "primary",@@ -58,7 +58,7 @@ export function BadgeShell({return (<Component- className={badgeVariants({ color, size, interactive })}+ className={cn(badgeVariants({ color, size, interactive }))}{...props}/>);@@ -90,9 +90,9 @@ export function Badge({className={cn("overflow-x-clip overflow-y-visible text-ellipsis whitespace-nowrap",interactive &&- "decoration-border-contrast underline decoration-dashed underline-offset-[3px]",+ "decoration-border-contrast underline decoration-dashed decoration-1 underline-offset-[3px]",)}- title={title ?? text}+ title={title ?? (interactive ? undefined : text)}>{text}</span>diff --git a/web/src/components/publish-object-switch.tsx b/web/src/components/publish-object-switch.tsxindex 94bebbce36..9b8db3b2dc 100644--- a/web/src/components/publish-object-switch.tsx+++ b/web/src/components/publish-object-switch.tsx@@ -19,41 +19,69 @@ import { copyTextToClipboard } from "@/src/utils/clipboard";import { cn } from "@/src/utils/tailwind";import { trpcErrorToast } from "@/src/utils/trpcErrorToast";import { type RouterInput } from "@/src/utils/types";+import { useMutation } from "@tanstack/react-query";import { CheckIcon, Globe, Link, Share2 } from "lucide-react";import { useState } from "react";-export const PublishTraceSwitch = (props: {- traceId: string;+type PublishObjectProps = {+ kind: "trace" | "session";projectId: string;+ objectId: string;timestamp?: Date;- isPublic: boolean;- shareUrl?: string;- size?: "icon" | "icon-xs";- /** When set, render as a full-width labeled menu item instead of an icon. */- label?: string;- /** Hover tooltip for the icon button (suppressed while the popover is open). */- tooltip?: string;-}) => {+};++/** Publish toggle for a trace or a session with optimistic detail-query updates. */+export function usePublishObject(props: PublishObjectProps) {+ const { kind, projectId, objectId, timestamp } = props;const { isV4 } = useReadPath();const capture = usePostHogClientCapture();const hasAccess = useHasProjectAccess({- projectId: props.projectId,+ projectId,scope: "objects:publish",});const utils = api.useUtils();const traceQueryInput: RouterInput["traces"]["byIdWithObservationsAndScores"] =- {- projectId: props.projectId,- traceId: props.traceId,- timestamp: props.timestamp,- };+ { projectId, traceId: objectId, timestamp };const eventsTraceQueryInput: RouterInput["events"]["byTraceId"] = {- projectId: props.projectId,- traceId: props.traceId,- timestamp: props.timestamp,+ projectId,+ traceId: objectId,+ timestamp,};- const mut = api.traces.publish.useMutation({- onMutate: async (input) => {+ const sessionQueryInput = { projectId, sessionId: objectId };++ const mutation = useMutation({+ mutationFn: (isPublic: boolean) =>+ kind === "trace"+ ? utils.client.traces.publish.mutate({+ projectId,+ traceId: objectId,+ public: isPublic,+ })+ : utils.client.sessions.publish.mutate({+ projectId,+ sessionId: objectId,+ public: isPublic,+ }),+ onMutate: async (isPublic) => {+ if (kind === "session") {+ await Promise.all([+ utils.sessions.byIdWithScores.cancel(sessionQueryInput),+ utils.sessions.byIdWithScoresFromEvents.cancel(sessionQueryInput),+ ]);+ const previousSession =+ utils.sessions.byIdWithScores.getData(sessionQueryInput);+ const previousSessionFromEvents =+ utils.sessions.byIdWithScoresFromEvents.getData(sessionQueryInput);+ utils.sessions.byIdWithScores.setData(sessionQueryInput, (old) =>+ old ? { ...old, public: isPublic } : old,+ );+ utils.sessions.byIdWithScoresFromEvents.setData(+ sessionQueryInput,+ (old) => (old ? { ...old, public: isPublic } : old),+ );+ return { previousSession, previousSessionFromEvents };+ }+if (isV4) {await utils.events.byTraceId.cancel(eventsTraceQueryInput);@@ -68,7 +96,7 @@ export const PublishTraceSwitch = (props: {...old,observations: old.observations.map((observation) =>!observation.parentObservationId- ? { ...observation, public: input.public }+ ? { ...observation, public: isPublic }: observation,),};@@ -84,13 +112,22 @@ export const PublishTraceSwitch = (props: {utils.traces.byIdWithObservationsAndScores.setData(traceQueryInput,- (old) => (old ? { ...old, public: input.public } : old),+ (old) => (old ? { ...old, public: isPublic } : old),);return { previousTrace };},onError: (err, _input, context) => {- if (isV4) {+ if (kind === "session") {+ utils.sessions.byIdWithScores.setData(+ sessionQueryInput,+ context?.previousSession,+ );+ utils.sessions.byIdWithScoresFromEvents.setData(+ sessionQueryInput,+ context?.previousSessionFromEvents,+ );+ } else if (isV4) {utils.events.byTraceId.setData(eventsTraceQueryInput,context?.previousEvents,@@ -104,33 +141,25 @@ export const PublishTraceSwitch = (props: {trpcErrorToast(err);},onSuccess: async () => {- if (!isV4) {+ if (kind === "session") {+ await utils.sessions.invalidate();+ } else if (!isV4) {await utils.traces.all.invalidate();}},});- return (- <Base- itemName="trace"- isPublic={props.isPublic}- shareUrl={props.shareUrl}- size={props.size}- label={props.label}- tooltip={props.tooltip}- onChange={(val) => {- capture("trace_detail:publish_button_click");- return mut.mutateAsync({- projectId: props.projectId,- traceId: props.traceId,- public: val,- });- }}- isLoading={mut.isPending}- disabled={!hasAccess}- />- );-};+ const toggle = (isPublic: boolean) => {+ capture(+ kind === "trace"+ ? "trace_detail:publish_button_click"+ : "session_detail:publish_button_click",+ );+ return mutation.mutateAsync(isPublic);+ };++ return { hasAccess, isPending: mutation.isPending, toggle };+}export const PublishSessionSwitch = (props: {sessionId: string;@@ -140,19 +169,10 @@ export const PublishSessionSwitch = (props: {/** When set, render as a full-width labeled menu item instead of an icon. */label?: string;}) => {- const capture = usePostHogClientCapture();- const hasAccess = useHasProjectAccess({+ const publish = usePublishObject({+ kind: "session",projectId: props.projectId,- scope: "objects:publish",- });- const utils = api.useUtils();- const mut = api.sessions.publish.useMutation({- onError: (err) => {- trpcErrorToast(err);- },- onSuccess: async () => {- await utils.sessions.invalidate();- },+ objectId: props.sessionId,});return (@@ -161,16 +181,9 @@ export const PublishSessionSwitch = (props: {isPublic={props.isPublic}size={props.size}label={props.label}- onChange={(val) => {- capture("session_detail:publish_button_click");- return mut.mutateAsync({- projectId: props.projectId,- sessionId: props.sessionId,- public: val,- });- }}- isLoading={mut.isPending}- disabled={!hasAccess}+ onChange={publish.toggle}+ isLoading={publish.isPending}+ disabled={!publish.hasAccess}/>);};@@ -187,6 +200,14 @@ const getShareUrlWithBasePath = (shareUrl: string) => {return shouldPrependBasePath ? `${basePath}${shareUrl}` : shareUrl;};+export const getShareUrl = (shareUrl?: string) =>+ shareUrl+ ? new URL(+ getShareUrlWithBasePath(shareUrl),+ window.location.origin,+ ).toString()+ : window.location.href;+const Base = (props: {itemName: string;onChange: (value: boolean) => Promise<unknown>;@@ -203,14 +224,7 @@ const Base = (props: {const copyUrl = () => {setIsCopied(true);- copyTextToClipboard(- props.shareUrl- ? new URL(- getShareUrlWithBasePath(props.shareUrl),- window.location.origin,- ).toString()- : window.location.href,- );+ copyTextToClipboard(getShareUrl(props.shareUrl));setTimeout(() => setIsCopied(false), 2500);};diff --git a/web/src/components/table/peek.tsx b/web/src/components/table/peek.tsxindex f49478e4d9..f8b8bd9bd8 100644--- a/web/src/components/table/peek.tsx+++ b/web/src/components/table/peek.tsx@@ -91,6 +91,7 @@ type TablePeekViewProps = Pick<* overflow "…" menu when the peek is too narrow for the inline icon row.*/actionsMenu?: React.ReactNode;+ hideExpandToggle?: boolean;// Content/*** The content to display in the peek view.@@ -273,7 +274,7 @@ function TablePeekViewComponent(props: TablePeekViewProps) {actions={props.actions}actionsMenu={props.actionsMenu}expand={- isHandheld+ isHandheld || props.hideExpandToggle? undefined: {isExpanded: panel.isExpanded,diff --git a/web/src/components/table/peek/PeekHeader.tsx b/web/src/components/table/peek/PeekHeader.tsxindex 629c33f97d..5fe90c9387 100644--- a/web/src/components/table/peek/PeekHeader.tsx+++ b/web/src/components/table/peek/PeekHeader.tsx@@ -1,5 +1,6 @@import { useLayoutEffect, useRef, useState } from "react";import { Badge } from "@/src/components/design-system/Badge/Badge";+import { HeaderActionButton } from "@/src/components/HeaderActionButton";import { Button } from "@/src/components/ui/button";import {Popover,@@ -53,13 +54,12 @@ type PeekHeaderProps = {// The title keeps at least this much width before anything else collapses; the// type badge falls back to this width when icon-only; the "…" trigger is an-// icon-xs button. Tuned by eye — planner `safety` covers inter-control gaps.+// icon button. Tuned by eye — planner `safety` covers inter-control gaps.const MIN_TITLE_PX = 240;const BADGE_ICON_PX = 32;-const MORE_BUTTON_PX = 32;+const MORE_BUTTON_PX = 36;const BADGE_LABEL_FALLBACK_PX = 72;-const NAV_FULL_FALLBACK_PX = 92;-const NAV_COMPACT_FALLBACK_PX = 52;+const NAV_FALLBACK_PX = 68;const samePlan = (a: PeekHeaderPlan, b: PeekHeaderPlan) =>a.foldActions === b.foldActions &&@@ -76,33 +76,6 @@ const FULL: PeekHeaderPlan = {// Header tooltips appear quickly and share one style (Radix Tooltip, not the// slow/inconsistent native `title`).-const TOOLTIP_DELAY_MS = 300;--function HeaderIconButton({- label,- onClick,- children,-}: {- label: string;- onClick: () => void;- children: React.ReactNode;-}) {- return (- <Tooltip>- <TooltipTrigger asChild>- <Button- variant="ghost"- size="icon-xs"- aria-label={label}- onClick={onClick}- >- {children}- </Button>- </TooltipTrigger>- <TooltipContent>{label}</TooltipContent>- </Tooltip>- );-}/*** Visible peek chrome shared by the desktop sheet and the mobile drawer. The@@ -111,8 +84,8 @@ function HeaderIconButton({** The header adapts to the PEEK's own width (measured, not screen breakpoints):* it keeps the title readable and, as the peek narrows, folds the trace actions- * into a labeled "…" menu, shrinks the type badge to icon-only, compacts the- * prev/next nav, then folds open-in-tab — see {@link planPeekHeaderLayout}.+ * into a labeled "…" menu, shrinks the type badge to icon-only, then folds+ * open-in-tab — see {@link planPeekHeaderLayout}.*/export function PeekHeader({itemType,@@ -136,6 +109,7 @@ export function PeekHeader({const openInTabRef = useRef<HTMLDivElement>(null);const navRef = useRef<HTMLDivElement>(null);const pinnedRef = useRef<HTMLDivElement>(null);+ const closeRef = useRef<HTMLDivElement>(null);// Cached widths survive a part being folded / collapsed (it can't be// re-measured while hidden, in the closed popover, or in the other nav mode).const widthsRef = useRef<{@@ -172,10 +146,13 @@ export function PeekHeader({if (pinnedRef.current) {const navW = hasNav && navRef.current ? navRef.current.offsetWidth : 0;if (hasNav) {- if (plan.navCompact) widthsRef.current.navCompact = navW;- else widthsRef.current.navFull = navW;+ widthsRef.current.navCompact = navW;+ widthsRef.current.navFull = navW;}- widthsRef.current.otherPinned = pinnedRef.current.offsetWidth - navW;+ widthsRef.current.otherPinned =+ pinnedRef.current.offsetWidth -+ navW ++ (closeRef.current?.offsetWidth ?? 0);}const next = planPeekHeaderLayout({@@ -183,11 +160,9 @@ export function PeekHeader({minTitle: MIN_TITLE_PX,badgeLabelWidth: widthsRef.current.badgeLabel ?? BADGE_LABEL_FALLBACK_PX,badgeIconWidth: BADGE_ICON_PX,- navFullWidth: hasNav- ? (widthsRef.current.navFull ?? NAV_FULL_FALLBACK_PX)- : 0,+ navFullWidth: hasNav ? (widthsRef.current.navFull ?? NAV_FALLBACK_PX) : 0,navCompactWidth: hasNav- ? (widthsRef.current.navCompact ?? NAV_COMPACT_FALLBACK_PX)+ ? (widthsRef.current.navCompact ?? NAV_FALLBACK_PX): 0,otherPinnedWidth: widthsRef.current.otherPinned ?? 0,moreWidth: MORE_BUTTON_PX,@@ -210,7 +185,7 @@ export function PeekHeader({const anyFolded = plan.foldActions || plan.foldOpenInTab;return (- <TooltipProvider delayDuration={TOOLTIP_DELAY_MS}>+ <TooltipProvider><divref={headerRef}className="bg-muted flex min-h-11 shrink-0 flex-row flex-nowrap items-center justify-between gap-2 overflow-hidden px-2 py-1"@@ -236,6 +211,52 @@ export function PeekHeader({ref={clusterRef}className="flex shrink-0 flex-row items-center gap-1">+ {hasOpenInTab && !plan.foldOpenInTab && openInNewTab ? (+ <div ref={openInTabRef}>+ <HeaderActionButton+ label="Open in new tab"+ icon={<ExternalLink className="h-4 w-4" />}+ onClick={openInNewTab}+ />+ </div>+ ) : null}++ {/* Pinned block: expand, nav (keeps K/J live). */}+ <div+ ref={pinnedRef}+ className="flex h-full flex-row items-center gap-1"+ >+ {expand && (+ <HeaderActionButton+ label={expand.isExpanded ? "Collapse" : "Expand"}+ icon={+ expand.isExpanded ? (+ <Minimize2 className="h-4 w-4" />+ ) : (+ <Maximize2 className="h-4 w-4" />+ )+ }+ onClick={expand.onToggle}+ />+ )}+ {hasNav && (+ <div ref={navRef} className="flex flex-row items-center">+ <DetailPageNav+ currentId={itemId}+ path={resolveDetailNavigationPath!}+ listKey={detailNavigationKey!}+ compact+ />+ </div>+ )}+ </div>++ {hasActions && !plan.foldActions ? (+ <div ref={actionsRef} className="flex flex-row items-center gap-1">+ {actions}+ </div>+ ) : null}+{/* Overflow: a labeled menu of whatever folded away. */}{anyFolded && (<Popover>@@ -244,8 +265,9 @@ export function PeekHeader({<PopoverTrigger asChild><Buttonvariant="ghost"- size="icon-xs"+ size="icon"aria-label="More actions"+ className="text-foreground-secondary hover:text-foreground-secondary"><MoreHorizontal className="h-4 w-4" /></Button>@@ -272,50 +294,12 @@ export function PeekHeader({</Popover>)}- {hasActions && !plan.foldActions ? (- <div ref={actionsRef} className="flex flex-row items-center gap-1">- {actions}- </div>- ) : null}-- {hasOpenInTab && !plan.foldOpenInTab && openInNewTab ? (- <div ref={openInTabRef}>- <HeaderIconButton label="Open in new tab" onClick={openInNewTab}>- <ExternalLink className="h-4 w-4" />- </HeaderIconButton>- </div>- ) : null}-- {/* Pinned block: nav (keeps K/J live), expand, close. */}- <div- ref={pinnedRef}- className="flex h-full flex-row items-center gap-1"- >- {hasNav && (- <div ref={navRef} className="flex flex-row items-center">- <DetailPageNav- currentId={itemId}- path={resolveDetailNavigationPath!}- listKey={detailNavigationKey!}- compact={plan.navCompact}- />- </div>- )}- {expand && (- <HeaderIconButton- label={expand.isExpanded ? "Collapse" : "Expand"}- onClick={expand.onToggle}- >- {expand.isExpanded ? (- <Minimize2 className="h-4 w-4" />- ) : (- <Maximize2 className="h-4 w-4" />- )}- </HeaderIconButton>- )}- <HeaderIconButton label="Close" onClick={onClose}>- <X className="h-4 w-4" />- </HeaderIconButton>+ <div ref={closeRef}>+ <HeaderActionButton+ label="Close"+ icon={<X className="h-4 w-4" />}+ onClick={onClose}+ /></div></div></div>diff --git a/web/src/components/table/peek/peek-observation-detail.tsx b/web/src/components/table/peek/peek-observation-detail.tsxindex da6e3fa103..e84833d1d2 100644--- a/web/src/components/table/peek/peek-observation-detail.tsx+++ b/web/src/components/table/peek/peek-observation-detail.tsx@@ -42,9 +42,8 @@ export const TablePeekViewObservationDetail = (const actionProps = trace.data? {- traceId: trace.data.id,- projectId: trace.data.projectId,- isPublic: trace.data.public,+ trace: trace.data,+ traceContext: "peek" as const,shareUrl: buildTracePath({projectId: trace.data.projectId,traceId: trace.data.id,@@ -55,7 +54,6 @@ export const TablePeekViewObservationDetail = (timestamp:typeof router.query.traceId === "string" ? undefined : timestamp,}),- name: trace.data.name,timestamp,onAfterDelete: (deletedTraceId: string) => {if (shouldClosePeekAfterDelete(traceIdRef.current, deletedTraceId)) {@@ -69,6 +67,7 @@ export const TablePeekViewObservationDetail = (<TablePeekView{...props}title={traceId}+ hideExpandToggleactions={actionProps ? <TraceDetailActions {...actionProps} /> : undefined}diff --git a/web/src/components/table/peek/peek-trace-detail.tsx b/web/src/components/table/peek/peek-trace-detail.tsxindex fa41bb6406..5cb448054a 100644--- a/web/src/components/table/peek/peek-trace-detail.tsx+++ b/web/src/components/table/peek/peek-trace-detail.tsx@@ -43,15 +43,13 @@ export const TablePeekViewTraceDetail = (const actionProps = trace.data? {- traceId: trace.data.id,- projectId: trace.data.projectId,- isPublic: trace.data.public,+ trace: trace.data,+ traceContext: "peek" as const,shareUrl: buildTracePath({projectId: trace.data.projectId,traceId: trace.data.id,timestamp,}),- name: trace.data.name,timestamp,onAfterDelete: (deletedTraceId: string) => {if (shouldClosePeekAfterDelete(peekIdRef.current, deletedTraceId)) {@@ -65,6 +63,7 @@ export const TablePeekViewTraceDetail = (<TablePeekView{...tablePeekViewProps}title={traceId}+ hideExpandToggleactions={actionProps ? <TraceDetailActions {...actionProps} /> : undefined}diff --git a/web/src/components/ui/tooltip.tsx b/web/src/components/ui/tooltip.tsxindex c86155c8df..1865429855 100644--- a/web/src/components/ui/tooltip.tsx+++ b/web/src/components/ui/tooltip.tsx@@ -7,7 +7,15 @@ import * as TooltipPrimitive from "@radix-ui/react-tooltip";import { cn } from "@/src/utils/tailwind";import { useLayerContainer } from "@/src/context/LayerContext/LayerContext";-const TooltipProvider = TooltipPrimitive.Provider;+const TOOLTIP_DELAY_MS = 300;++/** Nested providers reset the delay, so every provider carries the app default. */+const TooltipProvider = ({+ delayDuration = TOOLTIP_DELAY_MS,+ ...props+}: React.ComponentProps<typeof TooltipPrimitive.Provider>) => (+ <TooltipPrimitive.Provider delayDuration={delayDuration} {...props} />+);const Tooltip = TooltipPrimitive.Root;diff --git a/web/src/components/useShareMenuItems.ts b/web/src/components/useShareMenuItems.tsnew file mode 100644index 0000000000..cf5b687b5c--- /dev/null+++ b/web/src/components/useShareMenuItems.ts@@ -0,0 +1,88 @@+import { Globe, Link, Share2 } from "lucide-react";++import { type DropdownMenuItemDefinition } from "@/src/components/design-system/DropdownMenu/DropdownMenu";+import {+ getShareUrl,+ usePublishObject,+} from "@/src/components/publish-object-switch";+import { showSuccessToast } from "@/src/features/notifications";+import { copyTextToClipboard } from "@/src/utils/clipboard";++/**+ * Share menu items for a trace or session detail header: Share while private,+ * Copy share link + Unshare while public. Sharing copies the link and toasts.+ */+export function useShareMenuItems({+ kind,+ projectId,+ objectId,+ isPublic,+ shareUrl,+ timestamp,+}: {+ kind: "trace" | "session";+ projectId: string;+ objectId: string;+ isPublic: boolean;+ shareUrl?: string;+ timestamp?: Date;+}): DropdownMenuItemDefinition[] {+ const publish = usePublishObject({ kind, projectId, objectId, timestamp });+ const label = kind === "trace" ? "Trace" : "Session";++ let disabled: { reason: string } | undefined;+ if (!publish.hasAccess) {+ disabled = { reason: `You don't have permission to share this ${kind}.` };+ } else if (publish.isPending) {+ disabled = { reason: "Updating sharing status." };+ }++ const toggle = (nextPublic: boolean) => {+ // Clipboard writes must happen inside the click; copy before the request.+ if (nextPublic) copyTextToClipboard(getShareUrl(shareUrl));+ publish+ .toggle(nextPublic)+ .then(() => {+ if (!nextPublic) return;+ showSuccessToast({+ title: `${label} shared publicly`,+ description:+ "Anyone with the link can view it. Link copied to clipboard.",+ });+ })+ .catch(() => undefined);+ };++ if (isPublic) {+ return [+ {+ type: "item",+ id: "copy-share-link",+ title: "Copy share link",+ icon: Link,+ onClick: () => {+ copyTextToClipboard(getShareUrl(shareUrl));+ },+ },+ {+ type: "item",+ id: "unshare",+ title: "Unshare",+ icon: Globe,+ disabled,+ onClick: () => toggle(false),+ },+ ];+ }++ return [+ {+ type: "item",+ id: "share",+ title: "Share",+ icon: Share2,+ disabled,+ onClick: () => toggle(true),+ },+ ];+}diff --git a/web/src/features/annotation-queues/components/AnnotationQueueSubmenuItemController.tsx b/web/src/features/annotation-queues/components/AnnotationQueueSubmenuItemController.tsxnew file mode 100644index 0000000000..76a2e3896c--- /dev/null+++ b/web/src/features/annotation-queues/components/AnnotationQueueSubmenuItemController.tsx@@ -0,0 +1,254 @@+import { type AnnotationQueueObjectType } from "@langfuse/shared";+import { ListPlus, PlusIcon } from "lucide-react";+import { useSession } from "next-auth/react";+import { type ReactNode, useCallback, useMemo } from "react";++import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";+import { type DropdownMenuItemDefinition } from "@/src/components/design-system/DropdownMenu/DropdownMenu";+import { AnnotationQueueFormDialogController } from "@/src/features/annotation-queues/components/AnnotationQueueFormDialogController";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics";+import { useHasProjectAccess } from "@/src/features/rbac";+import { type AnalyticsData } from "@/src/features/scores/types";+import { api, reportNonTrpcError } from "@/src/utils/api";++type QueueRemoval = {+ itemId: string;+ queueName: string;+};++type AnnotationQueueSubmenuItemControllerProps = {+ projectId: string;+ objectId: string;+ objectType: AnnotationQueueObjectType;+ analyticsData: Pick<AnalyticsData, "source" | "isV4">;+ children: (control: {+ item: DropdownMenuItemDefinition;+ totalCount: number;+ }) => ReactNode;+};++const TARGET_TYPE_BY_OBJECT_TYPE = {+ TRACE: "trace",+ OBSERVATION: "observation",+ SESSION: "session",+} as const;++function getQueueAnalyticsContext(+ objectType: AnnotationQueueObjectType,+ analyticsData: Pick<AnalyticsData, "source" | "isV4">,+) {+ return {+ ...analyticsData,+ type: objectType === "SESSION" ? ("session" as const) : ("trace" as const),+ targetType: TARGET_TYPE_BY_OBJECT_TYPE[objectType],+ objectType,+ queueCount: 1,+ };+}++export function AnnotationQueueSubmenuItemController(+ props: AnnotationQueueSubmenuItemControllerProps,+) {+ const { projectId, objectId, objectType, analyticsData } = props;+ const capture = usePostHogClientCapture();+ const utils = api.useUtils();+ const removeFromQueueMutation =+ api.annotationQueueItems.deleteMany.useMutation();++ return (+ <AnnotationQueueFormDialogController+ projectId={projectId}+ mode="create"+ onSuccess={() => undefined}+ >+ {({ disabled: createQueueDisabled, openDialog: openQueueDialog }) => (+ <ConfirmationDialogController<QueueRemoval>+ title="Remove from annotation queue"+ text={({ queueName }) =>+ `Are you sure you want to remove this item from the queue "${queueName}"?`+ }+ confirmLabel="Remove"+ variant="destructive"+ loading={removeFromQueueMutation.isPending}+ error={removeFromQueueMutation.error?.message}+ onConfirm={async ({ itemId }) => {+ const result = await removeFromQueueMutation.mutateAsync({+ projectId,+ itemIds: [itemId],+ });+ if (result.deletedCount > 0) {+ capture(+ "annotation_queues:item_removed",+ getQueueAnalyticsContext(objectType, analyticsData),+ );+ }+ await utils.annotationQueues.byObjectId.invalidate({+ projectId,+ objectId,+ objectType,+ });+ }}+ >+ {({ openDialog: openRemoveQueueDialog }) => (+ <AnnotationQueueSubmenuItemControllerContent+ {...props}+ createQueueDisabled={createQueueDisabled}+ openQueueDialog={openQueueDialog}+ openRemoveQueueDialog={openRemoveQueueDialog}+ />+ )}+ </ConfirmationDialogController>+ )}+ </AnnotationQueueFormDialogController>+ );+}++function AnnotationQueueSubmenuItemControllerContent({+ projectId,+ objectId,+ objectType,+ analyticsData,+ children,+ createQueueDisabled,+ openQueueDialog,+ openRemoveQueueDialog,+}: AnnotationQueueSubmenuItemControllerProps & {+ createQueueDisabled: { reason: string } | undefined;+ openQueueDialog: () => void;+ openRemoveQueueDialog: (queueRemoval: QueueRemoval) => void;+}) {+ const capture = usePostHogClientCapture();+ const session = useSession();+ const queues = api.annotationQueues.byObjectId.useQuery(+ { projectId, objectId, objectType },+ {+ enabled:+ session.status === "authenticated" &&+ Boolean(projectId) &&+ Boolean(objectId),+ },+ );+ const utils = api.useUtils();+ const addToQueueMutation = api.annotationQueueItems.createMany.useMutation();+ const hasAnnotationQueueAccess = useHasProjectAccess({+ projectId,+ scope: "annotationQueues:CUD",+ });++ const handleQueueItemToggle = useCallback(+ async (queueId: string, queueName: string, itemId?: string) => {+ try {+ if (!itemId) {+ const result = await addToQueueMutation.mutateAsync({+ projectId,+ objectIds: [objectId],+ objectType,+ queueId,+ });+ if (result.createdCount > 0) {+ capture(+ "annotation_queues:item_added",+ getQueueAnalyticsContext(objectType, analyticsData),+ );+ }+ } else {+ openRemoveQueueDialog({ itemId, queueName });+ return;+ }++ await utils.annotationQueues.byObjectId.invalidate({+ projectId,+ objectId,+ objectType,+ });+ } catch (error) {+ reportNonTrpcError(error, "annotation-queues");+ }+ },+ [+ addToQueueMutation,+ analyticsData,+ capture,+ objectId,+ objectType,+ openRemoveQueueDialog,+ projectId,+ utils.annotationQueues,+ ],+ );++ const queuesAreLoading =+ session.status !== "authenticated" || queues.isLoading;++ const item = useMemo<DropdownMenuItemDefinition>(+ () => ({+ type: "submenu",+ id: "annotation-queue",+ title: "Annotation queue",+ icon: ListPlus,+ search: { placeholder: "Search annotation queues…" },+ disabled:+ !hasAnnotationQueueAccess || queuesAreLoading+ ? {+ reason: !hasAnnotationQueueAccess+ ? "You don't have permission to add items to annotation queues."+ : "Annotation queues are loading.",+ }+ : undefined,+ items: queuesAreLoading+ ? [{ id: "queues-loading", type: "loading" }]+ : [+ ...(queues.data?.queues ?? []).map((queue) => ({+ type: "checkbox" as const,+ id: queue.id,+ title: queue.name,+ checked: Boolean(queue.itemId),+ closeOnCheckedChange: Boolean(queue.itemId),+ onCheckedChange: () => {+ handleQueueItemToggle(queue.id, queue.name, queue.itemId).catch(+ () => undefined,+ );+ },+ })),+ ...((queues.data?.queues.length ?? 0) === 0+ ? [+ {+ id: "no-queues",+ type: "item" as const,+ title: "No queues defined",+ disabled: {+ reason: "No annotation queues are defined.",+ },+ onClick: () => undefined,+ },+ ]+ : []),+ ...(createQueueDisabled === undefined+ ? [+ {+ id: "queues-separator",+ type: "separator" as const,+ },+ {+ id: "create-queue",+ type: "item" as const,+ title: "Create new queue",+ icon: PlusIcon,+ onClick: openQueueDialog,+ },+ ]+ : []),+ ],+ }),+ [+ createQueueDisabled,+ handleQueueItemToggle,+ hasAnnotationQueueAccess,+ openQueueDialog,+ queues.data?.queues,+ queuesAreLoading,+ ],+ );++ return children({ item, totalCount: queues.data?.totalCount ?? 0 });+}diff --git a/web/src/features/annotation-queues/index.ts b/web/src/features/annotation-queues/index.tsindex 91dd4f0214..dbc34bdedc 100644--- a/web/src/features/annotation-queues/index.ts+++ b/web/src/features/annotation-queues/index.ts@@ -7,5 +7,6 @@export { AddTracesToAnnotationQueueDialogController } from "@/src/features/annotation-queues/components/AddTracesToAnnotationQueueDialogController";export { AnnotationQueueItemCountBadge } from "@/src/features/annotation-queues/components/AnnotationQueueItemCountBadge";export { AnnotationQueueItemDropdownMenuController } from "@/src/features/annotation-queues/components/AnnotationQueueItemDropdownMenuController";+export { AnnotationQueueSubmenuItemController } from "@/src/features/annotation-queues/components/AnnotationQueueSubmenuItemController";export { CreateOrEditAnnotationQueueButton } from "@/src/features/annotation-queues/components/CreateOrEditAnnotationQueueButton";export { CommentsSection } from "@/src/features/annotation-queues/components/shared/CommentsSection";diff --git a/web/src/features/navigate-detail-pages/DetailPageNav.tsx b/web/src/features/navigate-detail-pages/DetailPageNav.tsxindex 17ec15cc0b..6d333be351 100644--- a/web/src/features/navigate-detail-pages/DetailPageNav.tsx+++ b/web/src/features/navigate-detail-pages/DetailPageNav.tsx@@ -1,5 +1,6 @@/* eslint-disable @repo/no-null-render */import { Button, type ButtonProps } from "@/src/components/ui/button";+import { HeaderActionButton } from "@/src/components/HeaderActionButton";import { InputCommandShortcut } from "@/src/components/ui/input-command";import { KeyboardShortcut } from "@/src/components/design-system/KeyboardShortcut/KeyboardShortcut";import {@@ -30,9 +31,8 @@ export const DetailPageNav = (props: {/** Button size; defaults to the cva default. Pass "sm" to match icon-xs rows. */size?: ButtonProps["size"];/**- * Compact mode for dense toolbars (e.g. the peek header): icon-only ghost- * arrows with the K/J hint moved to the tooltip, so the buttons match a row- * of icon-xs controls instead of standing out. Shortcuts still work.+ * Compact mode for header action rows: icon-only ghost arrows with the K/J+ * hint moved to the tooltip. Shortcuts still work.*/compact?: boolean;}) => {@@ -138,10 +138,39 @@ export const DetailPageNav = (props: {}, [previousPageEntry, nextPageEntry, navigateToEntry, pulseShortcut]);if (entries.length > 1) {+ if (compact) {+ return (+ <div className="flex flex-row gap-1">+ <HeaderActionButton+ label="Navigate up"+ shortcut="K"+ icon={<ArrowUp className="h-4 w-4" />}+ active={shortcutPulse === "previous"}+ disabled={!previousPageEntry}+ onClick={() => {+ if (previousPageEntry) {+ navigateToEntry(previousPageEntry, "previous", "button");+ }+ }}+ />+ <HeaderActionButton+ label="Navigate down"+ shortcut="J"+ icon={<ArrowDown className="h-4 w-4" />}+ active={shortcutPulse === "next"}+ disabled={!nextPageEntry}+ onClick={() => {+ if (nextPageEntry) {+ navigateToEntry(nextPageEntry, "next", "button");+ }+ }}+ />+ </div>+ );+ }const buttonClassName = (active: boolean) =>cn(- "transition-[background-color,border-color,box-shadow,color] duration-150",- !compact && "gap-1.5 px-2",+ "gap-1.5 px-2 transition-[background-color,border-color,box-shadow,color] duration-150",active && "border-primary/60 bg-accent/60 ring-primary/20 ring-2",);return (@@ -149,9 +178,9 @@ export const DetailPageNav = (props: {<Tooltip><TooltipTrigger asChild><Button- variant={compact ? "ghost" : "outline"}+ variant="outline"type="button"- size={compact ? "icon-xs" : size}+ size={size}className={buttonClassName(shortcutPulse === "previous")}disabled={!previousPageEntry}onClick={() => {@@ -161,11 +190,9 @@ export const DetailPageNav = (props: {}}><ArrowUp className="h-4 w-4" />- {!compact && (- <span className="hidden md:inline-flex">- <KeyboardShortcut keys={["K"]} />- </span>- )}+ <span className="hidden md:inline-flex">+ <KeyboardShortcut keys={["K"]} />+ </span></Button></TooltipTrigger><TooltipContent>@@ -177,9 +204,9 @@ export const DetailPageNav = (props: {<Tooltip><TooltipTrigger asChild><Button- variant={compact ? "ghost" : "outline"}+ variant="outline"type="button"- size={compact ? "icon-xs" : size}+ size={size}className={buttonClassName(shortcutPulse === "next")}disabled={!nextPageEntry}onClick={() => {@@ -189,11 +216,9 @@ export const DetailPageNav = (props: {}}><ArrowDown className="h-4 w-4" />- {!compact && (- <span className="hidden md:inline-flex">- <KeyboardShortcut keys={["J"]} />- </span>- )}+ <span className="hidden md:inline-flex">+ <KeyboardShortcut keys={["J"]} />+ </span></Button></TooltipTrigger><TooltipContent>diff --git a/web/src/features/sessions/ConnectedSessionAddToDropdownMenuController.tsx b/web/src/features/sessions/ConnectedSessionAddToDropdownMenuController.tsxnew file mode 100644index 0000000000..1df2282560--- /dev/null+++ b/web/src/features/sessions/ConnectedSessionAddToDropdownMenuController.tsx@@ -0,0 +1,37 @@+import { AnnotationQueueObjectType } from "@langfuse/shared";+import { type ComponentProps, type ReactNode } from "react";++import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";+import { AnnotationQueueSubmenuItemController } from "@/src/features/annotation-queues";+import { type AnalyticsData } from "@/src/features/scores/types";++type TriggerControls = Parameters<+ ComponentProps<typeof DropdownMenu>["children"]+>[0];++export function ConnectedSessionAddToDropdownMenuController({+ projectId,+ sessionId,+ analyticsData,+ children,+}: {+ projectId: string;+ sessionId: string;+ analyticsData: Pick<AnalyticsData, "source" | "isV4">;+ children: (controls: TriggerControls & { totalCount: number }) => ReactNode;+}) {+ return (+ <AnnotationQueueSubmenuItemController+ projectId={projectId}+ objectId={sessionId}+ objectType={AnnotationQueueObjectType.SESSION}+ analyticsData={analyticsData}+ >+ {({ item, totalCount }) => (+ <DropdownMenu items={[item]} maxHeight="24rem" placement="bottom-start">+ {({ getTriggerProps }) => children({ getTriggerProps, totalCount })}+ </DropdownMenu>+ )}+ </AnnotationQueueSubmenuItemController>+ );+}diff --git a/web/src/features/sessions/ModernSessionHeader.stories.tsx b/web/src/features/sessions/ModernSessionHeader.stories.tsxindex 1197346fa1..08bcd4b2f4 100644--- a/web/src/features/sessions/ModernSessionHeader.stories.tsx+++ b/web/src/features/sessions/ModernSessionHeader.stories.tsx@@ -151,7 +151,7 @@ export const TestSearchesHiddenPills = meta.story({await expect(overflowButton.getBoundingClientRect().left -lastVisiblePill.getBoundingClientRect().right,- ).toBeLessThanOrEqual(24);+ ).toBeLessThanOrEqual(16);const overflowButtonRect = overflowButton.getBoundingClientRect();const lastVisiblePillRect = lastVisiblePill.getBoundingClientRect();await expect(@@ -168,7 +168,7 @@ export const TestSearchesHiddenPills = meta.story({trailingButton.getBoundingClientRect().left -overflowButton.getBoundingClientRect().right;await expect(trailingGap).toBeGreaterThanOrEqual(0);- await expect(trailingGap).toBeLessThanOrEqual(24);+ await expect(trailingGap).toBeLessThanOrEqual(16);await userEvent.click(overflowButton);diff --git a/web/src/features/sessions/ModernSessionHeader.tsx b/web/src/features/sessions/ModernSessionHeader.tsxindex 1eb2302920..9a95bb59a1 100644--- a/web/src/features/sessions/ModernSessionHeader.tsx+++ b/web/src/features/sessions/ModernSessionHeader.tsx@@ -422,7 +422,7 @@ export function ModernSessionHeader({});});return (- <div className="border-b px-4 pt-0 pb-1.5">+ <div className="border-b px-3 pt-1 pb-1.5"><SingleLineOverflowListspacing="comfortable"items={pills}diff --git a/web/src/features/sessions/ModernSessionHeaderActionsController.clienttest.tsx b/web/src/features/sessions/ModernSessionHeaderActionsController.clienttest.tsxindex adcec57826..188210592b 100644--- a/web/src/features/sessions/ModernSessionHeaderActionsController.clienttest.tsx+++ b/web/src/features/sessions/ModernSessionHeaderActionsController.clienttest.tsx@@ -1,88 +1,104 @@import { fireEvent, render, screen } from "@testing-library/react";-import { type MouseEventHandler, type ReactNode } from "react";+import { type ReactNode } from "react";import { vi } from "vitest";+import { type DropdownMenuItemDefinition } from "@/src/components/design-system/DropdownMenu/DropdownMenu";import { ModernSessionHeaderActionsController } from "@/src/features/sessions/ModernSessionHeaderActionsController";-import { DropdownMenuTrigger } from "@/src/components/ui/dropdown-menu";-const { mockUseSession, copy } = vi.hoisted(() => ({+const { mockUseSession, copy, copyTextToClipboard } = vi.hoisted(() => ({mockUseSession: vi.fn(),copy: vi.fn(),+ copyTextToClipboard: vi.fn(),}));vi.mock("next-auth/react", () => ({ useSession: mockUseSession }));-vi.mock("@/src/components/ui/dropdown-menu", () => ({- DropdownMenu: ({ children }: { children: ReactNode }) => <>{children}</>,- DropdownMenuTrigger: ({ children }: { children: ReactNode }) => (- <>{children}</>- ),- DropdownMenuContent: ({ children }: { children: ReactNode }) => (- <div>{children}</div>- ),- DropdownMenuItem: ({- children,- disabled,- onClick,- }: {- children: ReactNode;- disabled?: boolean;- onClick?: MouseEventHandler<HTMLButtonElement>;- }) => (- <button type="button" disabled={disabled} onClick={onClick}>- {children}- </button>- ),- DropdownMenuCheckboxItem: ({+vi.mock("next/router", () => ({+ useRouter: () => ({ asPath: "/", push: vi.fn() }),+}));++function FlatMenu({ items }: { items: DropdownMenuItemDefinition[] }) {+ return (+ <div>+ {items.map((item) => {+ if (item.type === "item") {+ return (+ <button+ key={item.id}+ type="button"+ disabled={item.disabled !== undefined}+ onClick={item.onClick}+ >+ {item.title}+ </button>+ );+ }+ if (item.type === "checkbox") {+ return (+ <button+ key={item.id}+ type="button"+ role="menuitemcheckbox"+ aria-checked={item.checked}+ onClick={() => item.onCheckedChange(!item.checked)}+ >+ {item.title}+ </button>+ );+ }+ if (item.type === "submenu") {+ return (+ <div key={item.id}>+ <div>{item.title}</div>+ <FlatMenu items={item.items} />+ </div>+ );+ }+ return <hr key={item.id} />;+ })}+ </div>+ );+}++vi.mock("@/src/components/design-system/DropdownMenu/DropdownMenu", () => ({+ DropdownMenu: ({+ items,children,- checked,- onClick,}: {- children: ReactNode;- checked: boolean;- onClick: MouseEventHandler<HTMLButtonElement>;+ items: DropdownMenuItemDefinition[];+ children: (controls: { getTriggerProps: () => object }) => ReactNode;}) => (- <button- type="button"- role="menuitemcheckbox"- aria-checked={checked}- onClick={onClick}- >- {children}- </button>+ <>+ {children({ getTriggerProps: () => ({}) })}+ <FlatMenu items={items} />+ </>),- DropdownMenuSub: ({ children }: { children: ReactNode }) => <>{children}</>,- DropdownMenuSubTrigger: ({ children }: { children: ReactNode }) => (- <div>{children}</div>- ),- DropdownMenuSubContent: ({ children }: { children: ReactNode }) => (- <div>{children}</div>+}));++vi.mock("@/src/components/HeaderActionButton", () => ({+ HeaderActionButton: ({ label }: { label: string }) => (+ <button type="button" aria-label={label} />),- DropdownMenuSeparator: () => <hr />,}));-vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({- usePostHogClientCapture: () => vi.fn(),+vi.mock("@/src/components/publish-object-switch", () => ({+ getShareUrl: () => "https://example.com",+ usePublishObject: () => ({+ hasAccess: true,+ isPending: false,+ toggle: vi.fn(() => Promise.resolve()),+ }),}));-vi.mock("@/src/features/rbac/utils/checkProjectAccess", () => ({- useHasProjectAccess: () => true,+vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({+ usePostHogClientCapture: () => vi.fn(),}));vi.mock("@/src/hooks/useCopyToClipboard", () => ({useCopyToClipboard: () => ({ copy }),}));-vi.mock("@/src/utils/api", () => ({- api: {- useUtils: () => ({ sessions: { invalidate: vi.fn() } }),- sessions: {- publish: {- useMutation: () => ({ mutate: vi.fn(), isPending: false }),- },- },- },-}));+vi.mock("@/src/utils/clipboard", () => ({ copyTextToClipboard }));describe("ModernSessionHeaderActionsController", () => {beforeEach(() => {@@ -99,9 +115,7 @@ describe("ModernSessionHeaderActionsController", () => {projectId={"project'\\id"}sessionId={"session'\\id"}isPublic={false}- >- <button type="button">Actions</button>- </ModernSessionHeaderActionsController>,+ />,);fireEvent.click(@@ -141,9 +155,7 @@ describe("ModernSessionHeaderActionsController", () => {projectId="project-id"sessionId="session-id"isPublic={false}- >- <button type="button">Actions</button>- </ModernSessionHeaderActionsController>,+ />,);expect(@@ -153,7 +165,7 @@ describe("ModernSessionHeaderActionsController", () => {screen.queryByRole("button", { name: "Copy events_core query" }),).not.toBeInTheDocument();fireEvent.click(screen.getByRole("button", { name: "Copy session ID" }));- expect(copy).toHaveBeenCalledExactlyOnceWith("session-id");+ expect(copyTextToClipboard).toHaveBeenCalledExactlyOnceWith("session-id");},);@@ -167,11 +179,7 @@ describe("ModernSessionHeaderActionsController", () => {isPublic={false}showSystemPrompt={false}onShowSystemPromptChange={onShowSystemPromptChange}- >- <DropdownMenuTrigger asChild>- <button type="button">Actions</button>- </DropdownMenuTrigger>- </ModernSessionHeaderActionsController>,+ />,);expect(screen.getByText("Display")).toBeInTheDocument();@@ -194,11 +202,7 @@ describe("ModernSessionHeaderActionsController", () => {showSystemPrompt={false}onShowInlineToolCallsChange={onShowInlineToolCallsChange}onShowSystemPromptChange={vi.fn()}- >- <DropdownMenuTrigger asChild>- <button type="button">Actions</button>- </DropdownMenuTrigger>- </ModernSessionHeaderActionsController>,+ />,);fireEvent.click(diff --git a/web/src/features/sessions/ModernSessionHeaderActionsController.tsx b/web/src/features/sessions/ModernSessionHeaderActionsController.tsxindex c5d1bf80ed..57e7bc01ed 100644--- a/web/src/features/sessions/ModernSessionHeaderActionsController.tsx+++ b/web/src/features/sessions/ModernSessionHeaderActionsController.tsx@@ -1,21 +1,16 @@-import { CopyIcon, Share2 } from "lucide-react";+import { CopyIcon, MoreVertical } from "lucide-react";import { useSession } from "next-auth/react";-import { type ReactNode } from "react";+import { HeaderActionButton } from "@/src/components/HeaderActionButton";+import { HeaderActionMenuRows } from "@/src/components/HeaderActionMenuRow";import {DropdownMenu,- DropdownMenuCheckboxItem,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuSub,- DropdownMenuSubContent,- DropdownMenuSubTrigger,-} from "@/src/components/ui/dropdown-menu";+ type DropdownMenuItemDefinition,+} from "@/src/components/design-system/DropdownMenu/DropdownMenu";+import { useShareMenuItems } from "@/src/components/useShareMenuItems";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";-import { useHasProjectAccess } from "@/src/features/rbac";+import { ConnectedDetailHeaderActionsMenuController } from "@/src/features/traces/components/DetailHeaderActionsMenuController";import { useCopyToClipboard } from "@/src/hooks/useCopyToClipboard";-import { api } from "@/src/utils/api";function buildSessionClickHouseQuery(table: "events_full" | "events_core",@@ -49,131 +44,150 @@ WHERE project_id = target_project_idORDER BY start_time ASC, event_ts DESC;`;}-export function ModernSessionHeaderActionsController({- projectId,- sessionId,- isPublic,+type DisplaySettingProps = {+ showCorrections?: boolean;+ showInlineToolCalls?: boolean;+ showSystemPrompt?: boolean;+ onShowCorrectionsChange?: (isEnabled: boolean) => void;+ onShowInlineToolCallsChange?: (isEnabled: boolean) => void;+ onShowSystemPromptChange?: (isEnabled: boolean) => void;+};++function buildDisplayItems({showCorrections,showInlineToolCalls,showSystemPrompt,onShowCorrectionsChange,onShowInlineToolCallsChange,onShowSystemPromptChange,- children,-}: {+}: DisplaySettingProps): DropdownMenuItemDefinition[] {+ const settings = [+ {+ id: "show-corrections",+ title: "Show corrections",+ checked: showCorrections,+ onChange: onShowCorrectionsChange,+ },+ {+ id: "show-tool-calls",+ title: "Show tool calls",+ checked: showInlineToolCalls,+ onChange: onShowInlineToolCallsChange,+ },+ {+ id: "show-system-prompt",+ title: "Show system prompt",+ checked: showSystemPrompt,+ onChange: onShowSystemPromptChange,+ },+ ];++ return settings.flatMap(({ id, title, checked, onChange }) =>+ checked !== undefined && onChange+ ? [+ {+ type: "checkbox" as const,+ id,+ title,+ checked,+ onCheckedChange: onChange,+ },+ ]+ : [],+ );+}++/**+ * Session header kebab: share items, Copy session ID, admin-only ClickHouse+ * query copies and a Display submenu. `layout="menu"` renders the clickable+ * items as full-width rows for the mobile header overflow menu.+ */+export function ModernSessionHeaderActionsController({+ projectId,+ sessionId,+ isPublic,+ layout = "toolbar",+ ...displaySettings+}: DisplaySettingProps & {projectId: string;sessionId: string;isPublic: boolean;- showCorrections?: boolean;- showInlineToolCalls?: boolean;- showSystemPrompt?: boolean;- onShowCorrectionsChange?: (isEnabled: boolean) => void;- onShowInlineToolCallsChange?: (isEnabled: boolean) => void;- onShowSystemPromptChange?: (isEnabled: boolean) => void;- children: ReactNode;+ layout?: "toolbar" | "menu";}) {const session = useSession();const capture = usePostHogClientCapture();const { copy } = useCopyToClipboard();- const utils = api.useUtils();- const hasPublishAccess = useHasProjectAccess({+ const shareItems = useShareMenuItems({+ kind: "session",projectId,- scope: "objects:publish",- });- const publishMutation = api.sessions.publish.useMutation({- onSuccess: () => utils.sessions.invalidate(),+ objectId: sessionId,+ isPublic,});- const hasDisplaySettings =- (showCorrections !== undefined && onShowCorrectionsChange) ||- (showInlineToolCalls !== undefined && onShowInlineToolCallsChange) ||- (showSystemPrompt !== undefined && onShowSystemPromptChange);+ const displayItems = buildDisplayItems(displaySettings);++ const adminItems: DropdownMenuItemDefinition[] =+ session.data?.user?.admin === true+ ? (["events_full", "events_core"] as const).map((table) => ({+ type: "item" as const,+ id: `copy-${table}-query`,+ title: `Copy ${table} query`,+ icon: CopyIcon,+ onClick: async () => {+ await copy(+ buildSessionClickHouseQuery(table, projectId, sessionId),+ );+ },+ }))+ : [];return (- <DropdownMenu>- {children}- <DropdownMenuContent align="end">- <DropdownMenuItem- disabled={!hasPublishAccess || publishMutation.isPending}- onClick={() => {- capture("session_detail:publish_button_click");- publishMutation.mutate({- projectId,- sessionId,- public: !isPublic,- });- }}- >- <Share2 className="mr-2 h-3.5 w-3.5" />- {isPublic ? "Unshare (make private)" : "Share (make public)"}- </DropdownMenuItem>- <DropdownMenuItem- onClick={async () => {- capture("session_detail:copy_session_id_click");- await copy(sessionId);- }}- >- <CopyIcon className="mr-2 h-3.5 w-3.5" />- Copy session ID- </DropdownMenuItem>- {session.data?.user?.admin === true &&- (["events_full", "events_core"] as const).map((table) => (- <DropdownMenuItem- key={table}- onClick={async () => {- await copy(- buildSessionClickHouseQuery(table, projectId, sessionId),- );- }}- >- <CopyIcon className="mr-2 h-3.5 w-3.5" />- Copy {table} query- </DropdownMenuItem>- ))}- {hasDisplaySettings ? (- <>- <DropdownMenuSeparator />- <DropdownMenuSub>- <DropdownMenuSubTrigger>Display</DropdownMenuSubTrigger>- <DropdownMenuSubContent>- {showCorrections !== undefined && onShowCorrectionsChange ? (- <DropdownMenuCheckboxItem- checked={showCorrections}- onClick={(event) => {- event.preventDefault();- onShowCorrectionsChange(!showCorrections);- }}- >- Show corrections- </DropdownMenuCheckboxItem>- ) : null}- {showInlineToolCalls !== undefined &&- onShowInlineToolCallsChange ? (- <DropdownMenuCheckboxItem- checked={showInlineToolCalls}- onClick={(event) => {- event.preventDefault();- onShowInlineToolCallsChange(!showInlineToolCalls);- }}- >- Show tool calls- </DropdownMenuCheckboxItem>- ) : null}- {showSystemPrompt !== undefined && onShowSystemPromptChange ? (- <DropdownMenuCheckboxItem- checked={showSystemPrompt}- onClick={(event) => {- event.preventDefault();- onShowSystemPromptChange(!showSystemPrompt);- }}- >- Show system prompt- </DropdownMenuCheckboxItem>- ) : null}- </DropdownMenuSubContent>- </DropdownMenuSub>- </>- ) : null}- </DropdownMenuContent>- </DropdownMenu>+ <ConnectedDetailHeaderActionsMenuController+ idItems={[{ id: sessionId, name: "session ID" }]}+ projectId={projectId}+ renderMenu={(copyItems) => {+ const items: DropdownMenuItemDefinition[] = [+ ...shareItems,+ ...copyItems.map((item) =>+ item.type === "item" && item.onClick+ ? {+ ...item,+ onClick: () => {+ capture("session_detail:copy_session_id_click");+ item.onClick();+ },+ }+ : item,+ ),+ ...adminItems,+ ...(displayItems.length > 0+ ? [+ { id: "display-separator", type: "separator" as const },+ {+ type: "submenu" as const,+ id: "display",+ title: "Display",+ items: displayItems,+ },+ ]+ : []),+ ];++ if (layout === "menu") {+ return <HeaderActionMenuRows items={items} />;+ }++ return (+ <DropdownMenu items={items} placement="bottom-end">+ {({ getTriggerProps }) => (+ <HeaderActionButton+ label="Session actions"+ icon={<MoreVertical className="h-4 w-4" />}+ {...getTriggerProps()}+ />+ )}+ </DropdownMenu>+ );+ }}+ />);}diff --git a/web/src/features/sessions/SessionPages.tsx b/web/src/features/sessions/SessionPages.tsxindex ab4efb4088..155bec88a8 100644--- a/web/src/features/sessions/SessionPages.tsx+++ b/web/src/features/sessions/SessionPages.tsx@@ -44,7 +44,6 @@ import {MessageSquare,MessageSquareOff,Plus,- MoreVertical,SquarePen,} from "lucide-react";import { useCopyToClipboard } from "@/src/hooks/useCopyToClipboard";@@ -114,8 +113,9 @@ import { SessionDetailStoreProvider } from "@/src/features/sessions/SessionDetaiimport { SessionVirtualizedRow } from "@/src/features/sessions/SessionVirtualizedRow";import { createSessionDetailStore } from "@/src/features/sessions/sessionDetailStore";import { ModernSession } from "@/src/features/sessions/ModernSession";-import { DropdownMenuTrigger } from "@/src/components/ui/dropdown-menu";+import { HeaderActionMenuRow } from "@/src/components/HeaderActionMenuRow";import { ModernSessionHeaderActionsController } from "@/src/features/sessions/ModernSessionHeaderActionsController";+import { ConnectedSessionAddToDropdownMenuController } from "@/src/features/sessions/ConnectedSessionAddToDropdownMenuController";import { useIsFeatureEnabled } from "@/src/features/feature-flags";import { useIsMobile } from "@/src/hooks/use-mobile";import { useStore } from "zustand";@@ -324,6 +324,8 @@ const SessionScores = ({);};+const HEADER_ACTION_CLASS =+ "text-foreground-secondary hover:bg-accent hover:text-foreground-secondary";type SessionAnnotatePayload = AnnotateDrawerPayload<{type: "session";sessionId: string;@@ -731,29 +733,26 @@ export const SessionPage: React.FC<{</Button>)}</AnnotateDrawerController>- <AnnotationQueueItemDropdownMenuController+ <ConnectedSessionAddToDropdownMenuControllerprojectId={projectId}- objectId={sessionId}- objectType="SESSION"+ sessionId={sessionId}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>+ {({ getTriggerProps, totalCount }) => (+ <Button+ variant="outline"+ className="gap-1.5"+ {...getTriggerProps()}+ >+ <Plus className="h-4 w-4" />+ <span>Add to</span>+ {totalCount > 0 && (+ <ActionButtonCountBadge count={totalCount} />+ )}+ <ChevronDown className="h-3 w-3" />+ </Button>)}- </AnnotationQueueItemDropdownMenuController>+ </ConnectedSessionAddToDropdownMenuController></div><div className="flex items-center"><div className="mx-1">@@ -1715,16 +1714,62 @@ const LoadedSessionEventsPage: React.FC<{{webCalloutAction && (<WebCalloutButton action={webCalloutAction} />)}- {!router.query.peek && (- <DetailPageNav- key="nav"- currentId={encodeURIComponent(sessionId)}- path={(entry) =>- `/project/${projectId}/sessions/${encodeURIComponent(entry.id)}`- }- listKey="sessions"- />- )}+ <ConnectedSessionAddToDropdownMenuController+ projectId={projectId}+ sessionId={sessionId}+ analyticsData={{ source: "SessionDetail", isV4: true }}+ >+ {({ getTriggerProps, totalCount }) => (+ <Button+ variant="ghost"+ size="sm"+ className={cn(HEADER_ACTION_CLASS, "gap-1.5")}+ {...getTriggerProps()}+ >+ <Plus className="h-3.5 w-3.5" aria-hidden="true" />+ Add to+ {totalCount > 0 && (+ <ActionButtonCountBadge count={totalCount} />+ )}+ <ChevronDown className="h-3 w-3" aria-hidden="true" />+ </Button>+ )}+ </ConnectedSessionAddToDropdownMenuController>+ <AnnotateDrawerController projectId={projectId}>+ {({ disabled, openDrawer }) => (+ <Button+ variant="ghost"+ size="sm"+ disabled={disabled}+ className={cn(HEADER_ACTION_CLASS, "gap-1.5")}+ onClick={() =>+ openDrawer({+ scoreTarget: { type: "session", sessionId },+ scores: session.scores,+ analyticsData: {+ type: "session",+ source: "SessionDetail",+ isV4: true,+ },+ scoreMetadata: {+ projectId,+ environment: session.environment,+ },+ })+ }+ >+ {disabled ? (+ <LockIcon className="h-3 w-3" />+ ) : (+ <Plus className="h-3.5 w-3.5" />+ )}+ Score+ {isModernSessionEnabled && annotationCount > 0 ? (+ <ActionButtonCountBadge count={annotationCount} />+ ) : null}+ </Button>+ )}+ </AnnotateDrawerController><CommentDrawerControllerkey="comment"projectId={projectId}@@ -1733,8 +1778,10 @@ const LoadedSessionEventsPage: React.FC<{{({ disabled, openDrawer }) => (<Buttontype="button"- variant="outline"+ variant="ghost"+ size="sm"disabled={disabled}+ className={cn(HEADER_ACTION_CLASS, "gap-1.5")}onClick={() =>openDrawer({type: "comments",@@ -1742,100 +1789,42 @@ const LoadedSessionEventsPage: React.FC<{objectType: "SESSION",})}- className="gap-1">{disabled ? (- <MessageSquareOff className="text-muted-foreground h-4 w-4" />+ <MessageSquareOff className="h-3.5 w-3.5" />) : (- <>- <MessageSquare className="h-4 w-4" />- <span>- {getNumberFromMap(+ <MessageSquare className="h-3.5 w-3.5" />+ )}+ {getNumberFromMap(sessionCommentCounts.data, sessionId)+ ? "Comments"+ : "Comment"}+ {getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ ) ? (+ <ActionButtonCountBadge+ count={+ getNumberFromMap(sessionCommentCounts.data,sessionId,- )- ? "Comments"- : "Comment"}- </span>- {getNumberFromMap(- sessionCommentCounts.data,- sessionId,- ) ? (- <ActionButtonCountBadge- count={- getNumberFromMap(- sessionCommentCounts.data,- sessionId,- ) ?? 0- }- />- ) : null}- </>- )}+ ) ?? 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>- )}- </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>+ {!router.query.peek && (+ <DetailPageNav+ key="nav"+ currentId={encodeURIComponent(sessionId)}+ path={(entry) =>+ `/project/${projectId}/sessions/${encodeURIComponent(entry.id)}`+ }+ listKey="sessions"+ compact+ />+ )}{!isModernSessionEnabled ? (<label className="flex items-center gap-1.5"><Switch@@ -1864,17 +1853,7 @@ const LoadedSessionEventsPage: React.FC<{setShowSystemPromptForSession,}: {})}- >- <DropdownMenuTrigger asChild>- <Button- variant="outline"- size="icon"- aria-label="Session actions"- >- <MoreVertical className="h-4 w-4" />- </Button>- </DropdownMenuTrigger>- </ModernSessionHeaderActionsController>+ />)}</>),@@ -1883,62 +1862,64 @@ const LoadedSessionEventsPage: React.FC<{// inline icon toolbar. Session-to-session nav stays desktop-only.actionButtonsMenu: ({ closeMenu }) => (<>- <PublishSessionSwitch+ <ModernSessionHeaderActionsControllerprojectId={projectId}sessionId={sessionId}isPublic={session.public}- label="Share"+ layout="menu"/>- <CopySessionIdButton sessionId={sessionId} layout="menu" /><CommentDrawerControllerprojectId={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">- {getNumberFromMap(sessionCommentCounts.data, sessionId)- ? "Comments"- : "Comment"}- </span>- {!disabled &&- getNumberFromMap(sessionCommentCounts.data, sessionId) ? (- <ActionButtonCountBadge- count={- getNumberFromMap(- sessionCommentCounts.data,- sessionId,- ) ?? 0- }- />- ) : null}- </Button>- )}+ {({ disabled, openDrawer }) => {+ const commentCount = getNumberFromMap(+ sessionCommentCounts.data,+ sessionId,+ );+ return (+ <HeaderActionMenuRow+ label={commentCount ? "Comments" : "Comment"}+ icon={+ disabled ? (+ <MessageSquareOff className="h-4 w-4" />+ ) : (+ <MessageSquare className="h-4 w-4" />+ )+ }+ badge={+ !disabled && commentCount ? (+ <ActionButtonCountBadge count={commentCount} />+ ) : null+ }+ disabled={disabled}+ onClick={() => {+ closeMenu({ handoffFocus: true });+ openDrawer({+ type: "comments",+ objectId: sessionId,+ objectType: "SESSION",+ });+ }}+ />+ );+ }}</CommentDrawerController>- <Button- variant="ghost"- size="sm"+ <HeaderActionMenuRow+ label="Score"+ icon={+ annotateDisabled ? (+ <LockIcon className="h-4 w-4" />+ ) : (+ <Plus className="h-4 w-4" />+ )+ }+ badge={+ isModernSessionEnabled && annotationCount > 0 ? (+ <ActionButtonCountBadge count={annotationCount} />+ ) : null+ }disabled={annotateDisabled}- className="w-full justify-start gap-2 font-normal"onClick={() => {closeMenu({ handoffFocus: true });openAnnotateRef.current({@@ -1955,45 +1936,25 @@ const LoadedSessionEventsPage: React.FC<{},});}}- >- {annotateDisabled ? (- <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>- <AnnotationQueueItemDropdownMenuController+ />+ <ConnectedSessionAddToDropdownMenuControllerprojectId={projectId}- objectId={sessionId}- objectType="SESSION"+ sessionId={sessionId}analyticsData={{ source: "SessionDetail", isV4: true }}>- {({ disabled, totalCount, Trigger }) => (- <Trigger asChild>- <Button- variant="ghost"- size="sm"- disabled={disabled !== undefined}- className="w-full justify-start gap-2 font-normal"- >- <Plus className="h-4 w-4" />- <span className="text-sm">Add to</span>- {totalCount > 0 && (- <AnnotationQueueItemCountBadge- totalCount={totalCount}- layout="menu"- />- )}- </Button>- </Trigger>+ {({ getTriggerProps, totalCount }) => (+ <HeaderActionMenuRow+ label="Add to"+ icon={<Plus className="h-4 w-4" />}+ badge={+ totalCount > 0 ? (+ <ActionButtonCountBadge count={totalCount} />+ ) : null+ }+ {...getTriggerProps()}+ />)}- </AnnotationQueueItemDropdownMenuController>+ </ConnectedSessionAddToDropdownMenuController>{webCalloutAction && (<WebCalloutButton action={webCalloutAction} layout="menu" />)}diff --git a/web/src/features/sessions/SessionReviewWorkspace.tsx b/web/src/features/sessions/SessionReviewWorkspace.tsxindex c6af9a31fb..f77c60a8d4 100644--- a/web/src/features/sessions/SessionReviewWorkspace.tsx+++ b/web/src/features/sessions/SessionReviewWorkspace.tsx@@ -93,7 +93,7 @@ export function SessionReviewWorkspace({><divref={leadingRef}- className="bg-header sticky top-0 z-30 w-full shrink-0 empty:hidden"+ className="bg-background sticky top-0 z-30 w-full shrink-0 empty:hidden"/><GroupgroupRef={groupRef}diff --git a/web/src/features/traces/TracePage.tsx b/web/src/features/traces/TracePage.tsxindex ee78466578..b01564cf08 100644--- a/web/src/features/traces/TracePage.tsx+++ b/web/src/features/traces/TracePage.tsx@@ -88,6 +88,7 @@ export function TracePage({}return undefined;})();+ const traceContext = router.query.peek !== undefined ? "peek" : "fullscreen";const sharedBadge = showPublicIndicators ? (<Badge variant="outline" className="text-xs font-bold">Public@@ -135,13 +136,11 @@ export function TracePage({return `/project/${projectId as string}/traces/${entry.id}${finalQueryString}`;}}listKey="traces"- size="sm"+ compact/><TraceDetailActions- traceId={trace.data.id}- projectId={trace.data.projectId}- isPublic={trace.data.public}- name={trace.data.name}+ trace={trace.data}+ traceContext={traceContext}timestamp={timestamp}deleteRedirectUrl={`/project/${router.query.projectId as string}/traces`}/>@@ -152,10 +151,8 @@ export function TracePage({// inline icon toolbar. Trace-to-trace nav is desktop-only.actionButtonsMenu: (<TraceDetailActions- traceId={trace.data.id}- projectId={trace.data.projectId}- isPublic={trace.data.public}- name={trace.data.name}+ trace={trace.data}+ traceContext={traceContext}timestamp={timestamp}deleteRedirectUrl={`/project/${router.query.projectId as string}/traces`}layout="menu"@@ -166,7 +163,7 @@ export function TracePage({<div className="flex max-h-full min-h-0 flex-1 overflow-hidden"><TraceDetailBodytrace={trace.data}- context={router.query.peek !== undefined ? "peek" : "fullscreen"}+ context={traceContext}truncatedAtObservations={trace.truncatedAtObservations}/></div>diff --git a/web/src/features/traces/components/CollapsibleBadgeRow.tsx b/web/src/features/traces/components/CollapsibleBadgeRow.tsxindex 01407e6be2..78a355c22f 100644--- a/web/src/features/traces/components/CollapsibleBadgeRow.tsx+++ b/web/src/features/traces/components/CollapsibleBadgeRow.tsx@@ -28,7 +28,7 @@ export function CollapsibleBadgeRow({// Desktop: unchanged full wrapped badge row.if (!isMobile) {return (- <div className={cn("flex flex-wrap items-center gap-6", className)}>+ <div className={cn("flex flex-wrap items-center gap-4", className)}>{children}</div>);@@ -39,7 +39,7 @@ export function CollapsibleBadgeRow({<div className="flex items-start gap-1"><divclassName={cn(- "flex min-w-0 flex-1 items-center gap-6",+ "flex min-w-0 flex-1 items-center gap-4",// Collapsed: one clipped line. `[&>*]:shrink-0` stops flex from// squeezing badges below their content width (which made long ones// like "Time to first token" wrap vertically into a multi-line row);diff --git a/web/src/features/traces/components/ConnectedTraceObservationAddToDropdownMenuController.tsx b/web/src/features/traces/components/ConnectedTraceObservationAddToDropdownMenuController.tsxindex ff04036985..3aeec1afe1 100644--- a/web/src/features/traces/components/ConnectedTraceObservationAddToDropdownMenuController.tsx+++ b/web/src/features/traces/components/ConnectedTraceObservationAddToDropdownMenuController.tsx@@ -1,19 +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,- type ReactNode,- useCallback,- useMemo,-} from "react";+import { Database, PlusIcon, Terminal } from "lucide-react";+import { type ComponentProps, type ReactNode, useMemo } from "react";import {DropdownMenu,type DropdownMenuItemDefinition,} from "@/src/components/design-system/DropdownMenu/DropdownMenu";-import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";-import { AnnotationQueueFormDialogController } from "@/src/features/annotation-queues/components/AnnotationQueueFormDialogController";+import { AnnotationQueueSubmenuItemController } from "@/src/features/annotation-queues";import { CreateDatasetDialogController } from "@/src/features/datasets/components/CreateDatasetDialogController";import { NewDatasetItemFromExistingObjectDialogController } from "@/src/features/datasets";import {@@ -23,7 +16,7 @@ import {import { useHasProjectAccess } from "@/src/features/rbac";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";import { type AnalyticsData } from "@/src/features/scores/types";-import { api, reportNonTrpcError } from "@/src/utils/api";+import { api } from "@/src/utils/api";import type { MetadataDomainClient } from "@/src/utils/clientSideDomainTypes";type PlaygroundGeneration = Extract<@@ -31,11 +24,6 @@ type PlaygroundGeneration = Extract<{ source: "generation" }>["generation"];-type QueueRemoval = {- itemId: string;- queueName: string;-};-type MenuPresentation =| {children: ComponentProps<typeof DropdownMenu>["children"];@@ -71,82 +59,44 @@ type ConnectedTraceObservationAddToDropdownMenuControllerProps =export function ConnectedTraceObservationAddToDropdownMenuController(props: ConnectedTraceObservationAddToDropdownMenuControllerProps,) {- const capture = usePostHogClientCapture();const objectId =props.variant === "observation" ? props.observationId : props.traceId;const objectType =props.variant === "observation"? AnnotationQueueObjectType.OBSERVATION: AnnotationQueueObjectType.TRACE;- const utils = api.useUtils();- const removeFromQueueMutation =- api.annotationQueueItems.deleteMany.useMutation();return (<NewDatasetItemFromExistingObjectDialogControllerprojectId={props.projectId}>{({ openDialog: openDatasetItemDialog }) => (- <AnnotationQueueFormDialogController+ <CreateDatasetDialogControllerprojectId={props.projectId}- mode="create"- onSuccess={() => undefined}+ target={{ type: "root" }}>- {({ disabled: createQueueDisabled, openDialog: openQueueDialog }) => (- <CreateDatasetDialogController+ {({+ disabled: createDatasetDisabled,+ openDialog: openDatasetDialog,+ }) => (+ <AnnotationQueueSubmenuItemControllerprojectId={props.projectId}- target={{ type: "root" }}+ objectId={objectId}+ objectType={objectType}+ analyticsData={props.analyticsData}>- {({- disabled: createDatasetDisabled,- openDialog: openDatasetDialog,- }) => (- <ConfirmationDialogController<QueueRemoval>- title="Remove from annotation queue"- text={({ queueName }) =>- `Are you sure you want to remove this item from the queue "${queueName}"?`- }- confirmLabel="Remove"- variant="destructive"- loading={removeFromQueueMutation.isPending}- error={removeFromQueueMutation.error?.message}- onConfirm={async ({ itemId }) => {- const result = await removeFromQueueMutation.mutateAsync({- projectId: props.projectId,- itemIds: [itemId],- });- if (result.deletedCount > 0) {- capture("annotation_queues:item_removed", {- ...props.analyticsData,- type: "trace",- targetType: props.variant,- objectType,- queueCount: 1,- });- }- await utils.annotationQueues.byObjectId.invalidate({- projectId: props.projectId,- objectId,- objectType,- });- }}- >- {({ openDialog: openRemoveQueueDialog }) => (- <ConnectedTraceObservationAddToDropdownMenuControllerContent- {...props}- createDatasetDisabled={createDatasetDisabled}- createQueueDisabled={createQueueDisabled}- openDatasetDialog={openDatasetDialog}- openDatasetItemDialog={openDatasetItemDialog}- openQueueDialog={openQueueDialog}- openRemoveQueueDialog={openRemoveQueueDialog}- />- )}- </ConfirmationDialogController>+ {({ item: annotationQueueItem }) => (+ <ConnectedTraceObservationAddToDropdownMenuControllerContent+ {...props}+ annotationQueueItem={annotationQueueItem}+ createDatasetDisabled={createDatasetDisabled}+ openDatasetDialog={openDatasetDialog}+ openDatasetItemDialog={openDatasetItemDialog}+ />)}- </CreateDatasetDialogController>+ </AnnotationQueueSubmenuItemController>)}- </AnnotationQueueFormDialogController>+ </CreateDatasetDialogController>)}</NewDatasetItemFromExistingObjectDialogController>);@@ -164,47 +114,22 @@ function ConnectedTraceObservationAddToDropdownMenuControllerContent({generation,children,renderMenu,+ annotationQueueItem,createDatasetDisabled,- createQueueDisabled,openDatasetDialog,openDatasetItemDialog,- openQueueDialog,- openRemoveQueueDialog,}: ConnectedTraceObservationAddToDropdownMenuControllerProps & {+ annotationQueueItem: DropdownMenuItemDefinition;createDatasetDisabled: { reason: string } | undefined;- createQueueDisabled: { reason: string } | undefined;openDatasetDialog: () => void;openDatasetItemDialog: Parameters<ComponentProps<typeof NewDatasetItemFromExistingObjectDialogController>["children"]>[0]["openDialog"];- openQueueDialog: () => void;- openRemoveQueueDialog: (queueRemoval: QueueRemoval) => void;}) {const capture = usePostHogClientCapture();- const session = useSession();- const objectId = variant === "observation" ? observationId : traceId;- const objectType =- variant === "observation"- ? AnnotationQueueObjectType.OBSERVATION- : AnnotationQueueObjectType.TRACE;- const queues = api.annotationQueues.byObjectId.useQuery(- { projectId, objectId, objectType },- {- enabled:- session.status === "authenticated" &&- Boolean(projectId) &&- Boolean(objectId),- },- );const datasets = api.datasets.allDatasetMeta.useQuery({ projectId });- const utils = api.useUtils();- const addToQueueMutation = api.annotationQueueItems.createMany.useMutation();- const hasAnnotationQueueAccess = useHasProjectAccess({- projectId,- scope: "annotationQueues:CUD",- });const hasDatasetAccess = useHasProjectAccess({projectId,scope: "datasets:CUD",@@ -222,182 +147,67 @@ function ConnectedTraceObservationAddToDropdownMenuControllerContent({title: playgroundTitle,} = playground;- const handleQueueItemToggle = useCallback(- async (queueId: string, queueName: string, itemId?: string) => {- try {- if (!itemId) {- const result = await addToQueueMutation.mutateAsync({- projectId,- objectIds: [objectId],- objectType,- queueId,- });- if (result.createdCount > 0) {- capture("annotation_queues:item_added", {- ...analyticsData,- type: "trace",- targetType: variant,- objectType,- queueCount: 1,- });- }- } else {- openRemoveQueueDialog({ itemId, queueName });- return;- }-- await utils.annotationQueues.byObjectId.invalidate({- projectId,- objectId,- objectType,- });- } catch (error) {- reportNonTrpcError(error, "annotation-queues");- }- },- [- addToQueueMutation,- analyticsData,- capture,- objectId,- objectType,- openRemoveQueueDialog,- projectId,- utils.annotationQueues,- variant,- ],- );-- const queuesAreLoading =- session.status !== "authenticated" || queues.isLoading;-const items = useMemo(() => {- const [annotationQueueItem, datasetItem]: [- DropdownMenuItemDefinition,- DropdownMenuItemDefinition,- ] = [- {- type: "submenu",- id: "annotation-queue",- title: "Annotation queue",- icon: ListPlus,- search: { placeholder: "Search annotation queues…" },- disabled:- !hasAnnotationQueueAccess || queuesAreLoading- ? {- reason: !hasAnnotationQueueAccess- ? "You don't have permission to add items to annotation queues."- : "Annotation queues are loading.",- }- : undefined,- items: queuesAreLoading- ? [{ id: "queues-loading", type: "loading" }]- : [- ...(queues.data?.queues ?? []).map((queue) => ({- type: "checkbox" as const,- id: queue.id,- title: queue.name,- checked: Boolean(queue.itemId),- closeOnCheckedChange: Boolean(queue.itemId),- onCheckedChange: () => {- handleQueueItemToggle(- queue.id,- queue.name,- queue.itemId,- ).catch(() => undefined);- },- })),- ...((queues.data?.queues.length ?? 0) === 0- ? [- {- id: "no-queues",- type: "item" as const,- title: "No queues defined",- disabled: {- reason: "No annotation queues are defined.",- },- onClick: () => undefined,- },- ]- : []),- ...(createQueueDisabled === undefined- ? [- {- id: "queues-separator",- type: "separator" as const,- },- {- id: "create-queue",- type: "item" as const,- title: "Create new queue",- icon: PlusIcon,- onClick: openQueueDialog,- },- ]- : []),- ],- },- {- type: "submenu",- id: "dataset",- title: "Dataset",- icon: Database,- search: { placeholder: "Search datasets…" },- disabled: !hasDatasetAccess- ? {- reason: "You don't have permission to add items to datasets.",- }- : undefined,- items: datasets.isLoading- ? [{ id: "datasets-loading", type: "loading" }]- : [- ...(datasets.data ?? []).map((dataset) => ({- type: "item" as const,- id: dataset.id,- title: dataset.name,- onClick: () => {- capture("dataset_item:new_from_trace_form_open", {- object: variant,- ...analyticsData,- });- openDatasetItemDialog({- traceId,- observationId,- input,- output,- metadata,- datasetId: dataset.id,- });- },- })),- ...((datasets.data?.length ?? 0) === 0- ? [- {- id: "no-datasets",- type: "item" as const,- title: "No datasets defined",- disabled: {- reason: "No datasets are defined.",- },- onClick: () => undefined,- },- ]- : []),- {- id: "datasets-separator",- type: "separator" as const,- },- {- type: "item" as const,- id: "create-dataset",- title: "Create new dataset",- icon: PlusIcon,- disabled: createDatasetDisabled,- onClick: openDatasetDialog,+ const datasetItem: DropdownMenuItemDefinition = {+ type: "submenu",+ id: "dataset",+ title: "Dataset",+ icon: Database,+ search: { placeholder: "Search datasets…" },+ disabled: !hasDatasetAccess+ ? {+ reason: "You don't have permission to add items to datasets.",+ }+ : undefined,+ items: datasets.isLoading+ ? [{ id: "datasets-loading", type: "loading" }]+ : [+ ...(datasets.data ?? []).map((dataset) => ({+ type: "item" as const,+ id: dataset.id,+ title: dataset.name,+ onClick: () => {+ capture("dataset_item:new_from_trace_form_open", {+ object: variant,+ ...analyticsData,+ });+ openDatasetItemDialog({+ traceId,+ observationId,+ input,+ output,+ metadata,+ datasetId: dataset.id,+ });},- ],- },- ];+ })),+ ...((datasets.data?.length ?? 0) === 0+ ? [+ {+ id: "no-datasets",+ type: "item" as const,+ title: "No datasets defined",+ disabled: {+ reason: "No datasets are defined.",+ },+ onClick: () => undefined,+ },+ ]+ : []),+ {+ id: "datasets-separator",+ type: "separator" as const,+ },+ {+ type: "item" as const,+ id: "create-dataset",+ title: "Create new dataset",+ icon: PlusIcon,+ disabled: createDatasetDisabled,+ onClick: openDatasetDialog,+ },+ ],+ };const items = [datasetItem, annotationQueueItem];@@ -439,15 +249,13 @@ function ConnectedTraceObservationAddToDropdownMenuControllerContent({return items;}, [analyticsData,+ annotationQueueItem,capture,variant,createDatasetDisabled,- createQueueDisabled,datasets.data,datasets.isLoading,generation,- handleQueueItemToggle,- hasAnnotationQueueAccess,hasDatasetAccess,input,includeOutput,@@ -455,13 +263,10 @@ function ConnectedTraceObservationAddToDropdownMenuControllerContent({observationId,openDatasetDialog,openDatasetItemDialog,- openQueueDialog,output,handlePlaygroundAction,playgroundDisabled,playgroundTitle,- queues.data?.queues,- queuesAreLoading,setIncludeOutput,traceId,]);diff --git a/web/src/features/traces/components/DeleteTraceDialogController.tsx b/web/src/features/traces/components/DeleteTraceDialogController.tsxnew file mode 100644index 0000000000..1c103ea4d6--- /dev/null+++ b/web/src/features/traces/components/DeleteTraceDialogController.tsx@@ -0,0 +1,81 @@+import { useRouter } from "next/router";+import { type ReactNode, useState } from "react";++import { ConfirmationDialogController } from "@/src/components/design-system/ConfirmationDialogController/ConfirmationDialogController";+import { useHasEntitlement } from "@/src/features/entitlements";+import { showSuccessToast } from "@/src/features/notifications";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics";+import { useHasProjectAccess } from "@/src/features/rbac";+import { api } from "@/src/utils/api";++export function DeleteTraceDialogController({+ projectId,+ traceId,+ traceName,+ redirectUrl,+ onAfterDelete,+ children,+}: {+ projectId: string;+ traceId: string;+ traceName?: string | null;+ redirectUrl?: string;+ onAfterDelete?: (deletedTraceId: string) => void;+ children: (control: {+ disabled: { reason: string } | undefined;+ openDialog: () => void;+ }) => ReactNode;+}) {+ const router = useRouter();+ const capture = usePostHogClientCapture();+ const utils = api.useUtils();+ const [isDeleted, setIsDeleted] = useState(false);+ const hasAccess = useHasProjectAccess({ projectId, scope: "traces:delete" });+ const hasEntitlement = useHasEntitlement("trace-deletion");+ const deleteMutation = api.traces.deleteMany.useMutation();++ let disabled: { reason: string } | undefined;+ if (!hasAccess) {+ disabled = { reason: "You don't have permission to delete this trace." };+ } else if (!hasEntitlement) {+ disabled = { reason: "Trace deletion is not available on your plan." };+ }++ return (+ <ConfirmationDialogController+ title="Delete trace?"+ text="This action cannot be undone. It removes all the data associated with this trace. If this is the project default, it will be deleted for all users."+ confirmationText={traceName || undefined}+ confirmLabel="Delete trace"+ variant="destructive"+ loading={deleteMutation.isPending || isDeleted}+ error={deleteMutation.error?.message}+ onConfirm={async () => {+ await deleteMutation.mutateAsync({ traceIds: [traceId], projectId });+ setIsDeleted(true);+ showSuccessToast({+ title: "Trace deleted",+ description:+ "Selected trace will be deleted. Traces are removed asynchronously and may continue to be visible for up to 24 hours.",+ });+ capture("trace:delete", { source: "trace" });+ if (redirectUrl) {+ router.push(redirectUrl).catch(() => undefined);+ return;+ }+ utils.invalidate();+ onAfterDelete?.(traceId);+ }}+ >+ {({ openDialog }) =>+ children({+ disabled,+ openDialog: () => {+ capture("trace:delete_form_open", { source: "trace detail" });+ openDialog();+ },+ })+ }+ </ConfirmationDialogController>+ );+}diff --git a/web/src/features/traces/components/TraceDetailActions.tsx b/web/src/features/traces/components/TraceDetailActions.tsxindex da3263b271..ee903bbafc 100644--- a/web/src/features/traces/components/TraceDetailActions.tsx+++ b/web/src/features/traces/components/TraceDetailActions.tsx@@ -1,112 +1,145 @@-import { api } from "@/src/utils/api";-import { PublishTraceSwitch } from "@/src/components/publish-object-switch";-import { DeleteTraceButton } from "@/src/components/deleteButton";+import { Download, Loader2, MoreVertical, TrashIcon } from "lucide-react";++import { HeaderActionButton } from "@/src/components/HeaderActionButton";+import {+ HeaderActionMenuRow,+ HeaderActionMenuRows,+} from "@/src/components/HeaderActionMenuRow";+import {+ DropdownMenu,+ type DropdownMenuItemDefinition,+} from "@/src/components/design-system/DropdownMenu/DropdownMenu";+import { useShareMenuItems } from "@/src/components/useShareMenuItems";+import { ConnectedDetailHeaderActionsMenuController } from "@/src/features/traces/components/DetailHeaderActionsMenuController";+import { DeleteTraceDialogController } from "@/src/features/traces/components/DeleteTraceDialogController";+import { useDownloadTraceAsJson } from "@/src/features/traces/hooks/useDownloadTraceAsJson";+import { type useTraceDetailData } from "@/src/features/traces/hooks/useTraceDetailData";++type TraceDetailData = NonNullable<+ ReturnType<typeof useTraceDetailData>["data"]+>;/**- * Trace-level header actions (publish / delete) shared by the peek and- * the standalone trace page, so both surfaces expose the same controls. Each- * sub-component renders DISABLED (not hidden) when the user lacks the relevant- * project scope, matching the page's long-standing behavior.+ * Trace-level header actions shared by the peek and the standalone trace page.*- * `layout="toolbar"` (default) is the inline icon row; `layout="menu"` renders- * the same controls as full-width labeled rows for the peek's overflow popover- * (whole row clickable) — Share keeps its URL popover, Delete its confirm.+ * `layout="toolbar"` (default) renders the icon row: Download JSON plus a kebab+ * holding Share, Copy trace ID, Copy trace name and Delete. `layout="menu"`+ * renders the same actions as full-width labeled rows for the mobile header+ * menu.*- * Delete always targets the whole trace (same as the page, even when reached- * from an observation/event row — the surface shows that trace). Behavior- * differs only by surface:+ * Delete always targets the whole trace. Behavior differs only by surface:* - **page**: pass `deleteRedirectUrl` → navigates to the list after delete.* - **peek**: pass `onAfterDelete` (e.g. `closePeek`) → closes in place. It* receives the deleted trace id so the peek can stay open if K/J-navigation- * already moved on to another trace (LFE-10535). We invalidate broadly- * because the peek is hosted over many different lists (traces, observations,- * events, sessions, experiments, datasets), each backed by a different query- * — so the deleted row disappears everywhere.+ * already moved on to another trace. We invalidate broadly because the peek+ * is hosted over many different lists, each backed by a different query.*/export function TraceDetailActions({- traceId,- projectId,- isPublic,+ trace,+ traceContext,shareUrl,- name,timestamp,deleteRedirectUrl,onAfterDelete,- size = "icon-xs",layout = "toolbar",}: {- traceId: string;- projectId: string;- isPublic: boolean;+ trace: TraceDetailData;+ traceContext: "fullscreen" | "peek";shareUrl?: string;- name?: string | null;timestamp?: Date;deleteRedirectUrl?: string;onAfterDelete?: (deletedTraceId: string) => void;- size?: "icon" | "icon-xs";layout?: "toolbar" | "menu";}) {- const utils = api.useUtils();- const isMenu = layout === "menu";+ const shareItems = useShareMenuItems({+ kind: "trace",+ projectId: trace.projectId,+ objectId: trace.id,+ isPublic: trace.public,+ shareUrl,+ timestamp,+ });+ const [handleDownload, isDownloading] = useDownloadTraceAsJson({+ trace,+ observations: trace.observations,+ traceContext,+ });- // The page path navigates away (redirectUrl) and never calls this. The peek- // path is hosted over many different lists, so invalidate all queries to- // refresh whichever list is behind the peek, then close it. We hand the- // deleted trace id to onAfterDelete so the peek can skip closing when it has- // already navigated to a different trace (LFE-10535).- const onDeleteInvalidate = () => {- utils.invalidate();- onAfterDelete?.(traceId);- };+ const idItems = [+ { id: trace.id, name: "trace ID" },+ ...(trace.name ? [{ id: trace.name, name: "trace name" }] : []),+ ];- if (isMenu) {- return (- <div className="flex w-full flex-col gap-0.5">- <PublishTraceSwitch- projectId={projectId}- traceId={traceId}- timestamp={timestamp}- isPublic={isPublic}- shareUrl={shareUrl}- label="Share"- />- <DeleteTraceButton- itemId={traceId}- projectId={projectId}- redirectUrl={deleteRedirectUrl}- invalidateFunc={onDeleteInvalidate}- deleteConfirmation={name ?? ""}- variant="ghost"- size="sm"- className="w-full justify-start font-normal"- />- </div>- );- }+ const downloadIcon = isDownloading ? (+ <Loader2 className="h-4 w-4 animate-spin" />+ ) : (+ <Download className="h-4 w-4" />+ );return (- <div className="flex flex-row items-center gap-1">- <PublishTraceSwitch- projectId={projectId}- traceId={traceId}- timestamp={timestamp}- isPublic={isPublic}- shareUrl={shareUrl}- size={size}- tooltip={isPublic ? "Shared (public)" : "Share"}- />- <DeleteTraceButton- itemId={traceId}- projectId={projectId}- redirectUrl={deleteRedirectUrl}- invalidateFunc={onDeleteInvalidate}- deleteConfirmation={name ?? ""}- icon- // Match Publish so both icons share one row height and a ghost (not- // boxed "outline") style.- size={size}- variant="ghost"- />- </div>+ <DeleteTraceDialogController+ projectId={trace.projectId}+ traceId={trace.id}+ traceName={trace.name}+ redirectUrl={deleteRedirectUrl}+ onAfterDelete={onAfterDelete}+ >+ {({ disabled: deleteDisabled, openDialog: openDeleteDialog }) => (+ <ConnectedDetailHeaderActionsMenuController+ idItems={idItems}+ projectId={trace.projectId}+ renderMenu={(copyItems) => {+ const items: DropdownMenuItemDefinition[] = [+ ...shareItems,+ ...copyItems,+ { id: "delete-separator", type: "separator" },+ {+ type: "item",+ id: "delete",+ title: "Delete",+ icon: TrashIcon,+ variant: "destructive",+ disabled: deleteDisabled,+ onClick: openDeleteDialog,+ },+ ];++ if (layout === "menu") {+ return (+ <div className="flex w-full flex-col gap-0.5">+ <HeaderActionMenuRow+ label="Download JSON"+ icon={downloadIcon}+ disabled={isDownloading}+ onClick={() => handleDownload()}+ />+ <HeaderActionMenuRows items={items} />+ </div>+ );+ }++ return (+ <div className="flex flex-row items-center gap-1">+ <HeaderActionButton+ label="Download JSON"+ icon={downloadIcon}+ disabled={isDownloading}+ onClick={() => handleDownload()}+ />+ <DropdownMenu items={items} placement="bottom-end">+ {({ getTriggerProps }) => (+ <HeaderActionButton+ label="More actions"+ icon={<MoreVertical className="h-4 w-4" />}+ {...getTriggerProps()}+ />+ )}+ </DropdownMenu>+ </div>+ );+ }}+ />+ )}+ </DeleteTraceDialogController>);}diff --git a/web/src/features/traces/components/TraceHeader.tsx b/web/src/features/traces/components/TraceHeader.tsxindex d248c5aac3..47d90470fc 100644--- a/web/src/features/traces/components/TraceHeader.tsx+++ b/web/src/features/traces/components/TraceHeader.tsx@@ -45,11 +45,11 @@ export function TraceHeader() {return (<divclassName={cn(- "shrink-0 border-b px-3",- traceContext === "fullscreen" ? "pt-0 pb-1.5" : "py-2",+ "shrink-0 border-b",+ traceContext === "fullscreen" ? "px-3 pt-1 pb-1.5" : "px-2 py-2",)}>- <div className="flex flex-wrap items-center gap-6">+ <div className="flex flex-wrap items-center gap-4"><LatencyBadge latencySeconds={trace.latency ?? null} />{aggregatedMetrics.totalCost != null &&aggregatedMetrics.costDetails && (diff --git a/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx b/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsxindex b4c8d95e34..454b8e8917 100644--- a/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx+++ b/web/src/features/traces/components/TracePanelNavigationHeader/TracePanelNavigationHeader.tsx@@ -4,7 +4,7 @@** Responsibilities:* - Render search input- * - Render toolbar buttons (expand/collapse, settings, download, timeline)+ * - Render toolbar buttons (expand/collapse, settings, timeline)* - Manage search input state via SearchContext** Search moves to a second row when space is tight, while keeping the same DOM@@ -21,15 +21,12 @@ import {TooltipContent,TooltipTrigger,} from "@/src/components/ui/tooltip";-import { useReadPath } from "@/src/features/events";import { Command, CommandInput } from "@/src/components/ui/command";import { Button } from "@/src/components/ui/button";import {ChevronDown,FoldVertical,UnfoldVertical,- Download,- Loader2,MoreHorizontal,} from "lucide-react";import {@@ -49,17 +46,10 @@ import {TraceSettingsDropdown,TraceViewOptionsMenuItems,} from "../TraceSettingsDropdown";-import {- downloadLegacyTraceAsJson,- downloadServerTraceAsJson,-} from "../../fns/downloadTrace";import { TracePanelNavigationButton } from "./components/TracePanelNavigationButton";import { useDesktopLayoutContextOptional } from "../TraceLayoutDesktop";import { usePostHogClientCapture } from "@/src/features/posthog-analytics";import { useTraceAnalyticsDimensions } from "@/src/features/traces/hooks/useTraceAnalyticsDimensions";-import { toast } from "sonner";-import { TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD } from "@/src/features/traces/constants/traceDownloadConfig";-import { useWatchedPromiseCallback } from "@/src/hooks/useWatchedPromiseCallback";import { useElementSize } from "@/src/hooks/useElementSize";interface TracePanelNavigationHeaderProps {@@ -97,13 +87,12 @@ function TracePanelNavigationHeaderExpanded({const { searchInputValue, setSearchInputValue, setSearchQueryImmediate } =useSearch();const { expandAll, collapseAll, collapsedNodes } = useSelection();- const { roots, trace, observations } = useTraceData();+ const { roots } = useTraceData();const {isGraphViewAvailable,graphAvailability,isLoading: isGraphLoading,} = useTraceGraphData();- const { isV4 } = useReadPath();const [viewMode, setViewMode] = useQueryParam("view", StringParam);const capture = usePostHogClientCapture();const analyticsDimensions = useTraceAnalyticsDimensions();@@ -157,37 +146,6 @@ function TracePanelNavigationHeaderExpanded({analyticsDimensions,]);- const [handleDownload, isDownloading] =- useWatchedPromiseCallback(async () => {- capture("trace_detail:download_button_click", analyticsDimensions);- try {- if (!isV4) {- downloadLegacyTraceAsJson({- trace,- observations,- });- return;- }-- await downloadServerTraceAsJson({- traceId: trace.id,- projectId: trace.projectId,- });-- if (observations.length >= TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD) {- toast.warning(- `Trace download excludes IO, metadata, toolDefinitions, and toolCalls for traces with ${TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD}+ observations.`,- );- }- } catch (error) {- toast.error(- error instanceof Error- ? error.message- : "Failed to download trace JSON",- );- }- }, [isV4, observations, trace, capture, analyticsDimensions]);-// Hold the Graph segment while its query loads, else it vanishes and returns// on every trace switch. Stale ?view=graph then falls back to tree.const graphResolved = isGraphViewAvailable || isGraphLoading;@@ -223,13 +181,6 @@ function TracePanelNavigationHeaderExpanded({)}{isEverythingCollapsed ? "Expand all" : "Collapse all"}</DropdownMenuItem>- <DropdownMenuItem- onSelect={() => handleDownload()}- disabled={isDownloading}- >- <Download className="mr-2 h-3.5 w-3.5" />- Download trace as JSON- </DropdownMenuItem><DropdownMenuSeparator /><TraceViewOptionsMenuItems /></>@@ -299,21 +250,6 @@ function TracePanelNavigationHeaderExpanded({</Button><TraceSettingsDropdown />-- <Button- variant="ghost"- size="icon"- onClick={handleDownload}- disabled={isDownloading}- title="Download trace as JSON"- className="h-7 w-7"- >- {isDownloading ? (- <Loader2 className="h-3.5 w-3.5 animate-spin" />- ) : (- <Download className="h-3.5 w-3.5" />- )}- </Button></div><div className="@min-[510px]/navheader:hidden">diff --git a/web/src/features/traces/hooks/useDownloadTraceAsJson.ts b/web/src/features/traces/hooks/useDownloadTraceAsJson.tsnew file mode 100644index 0000000000..9c6084d7c1--- /dev/null+++ b/web/src/features/traces/hooks/useDownloadTraceAsJson.ts@@ -0,0 +1,75 @@+import { useMemo } from "react";+import { toast } from "sonner";+import { StringParam, useQueryParam } from "use-query-params";++import { useReadPath } from "@/src/features/events";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics";+import { TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD } from "@/src/features/traces/constants/traceDownloadConfig";+import {+ downloadLegacyTraceAsJson,+ downloadServerTraceAsJson,+} from "@/src/features/traces/fns/downloadTrace";+import { dedupeObservationsById } from "@/src/features/traces/fns/treeBuilding";+import { useSelectedObservation } from "@/src/features/traces/hooks/useSelectedObservation";+import { useWatchedPromiseCallback } from "@/src/hooks/useWatchedPromiseCallback";+import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";++export function useDownloadTraceAsJson({+ trace,+ observations: loadedObservations,+ traceContext,+}: {+ trace: { id: string; projectId: string; [key: string]: unknown };+ observations: ObservationReturnTypeWithMetadata[];+ traceContext: "fullscreen" | "peek" | "annotation";+}) {+ const { isV4 } = useReadPath();+ const capture = usePostHogClientCapture();+ const [selectedObservationId] = useQueryParam("observation", StringParam);+ const selected = useSelectedObservation({+ selectedNodeId: selectedObservationId ?? null,+ traceId: trace.id,+ projectId: trace.projectId,+ observations: loadedObservations,+ });+ const detachedObservation =+ selected.kind === "observation" && selected.isOutsideLoadedList+ ? selected.observation+ : null;+ const observations = useMemo(+ () =>+ dedupeObservationsById(+ detachedObservation+ ? [...loadedObservations, detachedObservation]+ : loadedObservations,+ ),+ [loadedObservations, detachedObservation],+ );++ return useWatchedPromiseCallback(async () => {+ capture("trace_detail:download_button_click", { traceContext, isV4 });+ try {+ if (!isV4) {+ downloadLegacyTraceAsJson({ trace, observations });+ return;+ }++ await downloadServerTraceAsJson({+ traceId: trace.id,+ projectId: trace.projectId,+ });++ if (observations.length >= TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD) {+ toast.warning(+ `Trace download excludes IO, metadata, toolDefinitions, and toolCalls for traces with ${TRACE_DOWNLOAD_OMIT_LARGE_FIELDS_THRESHOLD}+ observations.`,+ );+ }+ } catch (error) {+ toast.error(+ error instanceof Error+ ? error.message+ : "Failed to download trace JSON",+ );+ }+ }, [isV4, observations, trace, capture, traceContext]);+}diff --git a/web/src/pages/_app.tsx b/web/src/pages/_app.tsxindex 8f34761242..251e0c99ed 100644--- a/web/src/pages/_app.tsx+++ b/web/src/pages/_app.tsx@@ -195,7 +195,7 @@ const MyApp: AppType<{ session: Session | null }> = ({adapter={NextAdapterPagesWithReadyGuard}options={{ enableBatching: true }}>- <TooltipProvider delayDuration={300}>+ <TooltipProvider><CommandMenuProvider><PostHogProvider client={posthog}><SessionProvider