🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(sessions): New session header (#15841)
Ben Bachem4787f4e0921f
diff --git a/web/src/components/SingleLineOverflowList.tsx b/web/src/components/SingleLineOverflowList.tsxnew file mode 100644index 0000000000..3c3536f246--- /dev/null+++ b/web/src/components/SingleLineOverflowList.tsx@@ -0,0 +1,130 @@+import { type ReactNode, useEffect, useRef, useState } from "react";++/**+ * Renders keyed items on one line and moves items that do not fit into a+ * caller-rendered overflow control. The component owns DOM measurement and+ * remeasures when its width, item widths, or overflow-control width changes.+ * `additionalOverflowCount` reserves the control for paginated or virtualized+ * entries that should not be mounted in the measurement row. Item and overflow+ * presentation remain entirely caller-defined.+ */+export function SingleLineOverflowList<TItem>({+ items,+ additionalOverflowCount,+ getKey,+ renderItem,+ renderOverflow,+}: {+ items: readonly TItem[];+ additionalOverflowCount: number;+ getKey: (item: TItem) => string;+ renderItem: (item: TItem) => ReactNode;+ renderOverflow: (props: {+ hiddenItems: readonly TItem[];+ overflowItemCount: number;+ }) => ReactNode;+}) {+ const measurementRowRef = useRef<HTMLDivElement>(null);+ const overflowRef = useRef<HTMLDivElement>(null);+ const [hiddenKeys, setHiddenKeys] = useState<string[]>([]);+ const itemKeys = items.map(getKey);+ const itemKeySignature = itemKeys.join("\u0000");+ const hiddenKeySet = new Set(hiddenKeys);+ const visibleItems = items.filter((item) => !hiddenKeySet.has(getKey(item)));+ const hiddenItems = items.filter((item) => hiddenKeySet.has(getKey(item)));+ const overflowItemCount = hiddenItems.length + additionalOverflowCount;++ useEffect(() => {+ const measurementRow = measurementRowRef.current;+ if (!measurementRow) return;++ const measure = () => {+ const itemElements = Array.from(measurementRow.children) as HTMLElement[];+ const lastItem = itemElements.at(-1);+ const contentWidth = lastItem+ ? lastItem.offsetLeft + lastItem.offsetWidth+ : 0;+ const hasOverflow =+ additionalOverflowCount > 0 ||+ contentWidth > measurementRow.clientWidth - 1;+ const gap = Number.parseFloat(+ window.getComputedStyle(measurementRow).columnGap,+ );+ const availableWidth = hasOverflow+ ? measurementRow.clientWidth -+ (overflowRef.current?.offsetWidth ?? 0) -+ (Number.isFinite(gap) ? gap : 0)+ : measurementRow.clientWidth;+ const nextHiddenKeys = itemElements.flatMap((element) => {+ const key = element.dataset.overflowItemKey;+ return key &&+ element.offsetLeft + element.offsetWidth > availableWidth - 1+ ? [key]+ : [];+ });++ setHiddenKeys((current) =>+ current.length === nextHiddenKeys.length &&+ current.every((key, index) => key === nextHiddenKeys[index])+ ? current+ : nextHiddenKeys,+ );+ };++ measure();+ if (typeof ResizeObserver === "undefined") return;++ const resizeObserver = new ResizeObserver(measure);+ resizeObserver.observe(measurementRow);+ for (const child of measurementRow.children) {+ resizeObserver.observe(child);+ }+ if (overflowRef.current) {+ resizeObserver.observe(overflowRef.current);+ }++ return () => resizeObserver.disconnect();+ }, [additionalOverflowCount, itemKeySignature, overflowItemCount]);++ return (+ <div className="relative flex min-w-0 flex-1 items-center gap-2 overflow-hidden">+ <div+ ref={measurementRowRef}+ aria-hidden="true"+ className="invisible absolute inset-x-0 flex items-center gap-2 [&>*]:shrink-0"+ >+ {items.map((item) => {+ const key = getKey(item);+ return (+ <span+ key={key}+ data-overflow-item-key={key}+ className="flex items-center"+ >+ {renderItem(item)}+ </span>+ );+ })}+ </div>+ <div className="flex min-w-0 items-center gap-2 overflow-hidden [&>*]:shrink-0">+ {visibleItems.map((item) => {+ const key = getKey(item);+ return (+ <span+ key={key}+ data-overflow-visible-item="true"+ className="flex items-center"+ >+ {renderItem(item)}+ </span>+ );+ })}+ </div>+ {overflowItemCount > 0 ? (+ <div ref={overflowRef} className="flex shrink-0 items-center">+ {renderOverflow({ hiddenItems, overflowItemCount })}+ </div>+ ) : null}+ </div>+ );+}diff --git a/web/src/components/session/ModernSessionHeader.stories.tsx b/web/src/components/session/ModernSessionHeader.stories.tsxnew file mode 100644index 0000000000..d57d5da57f--- /dev/null+++ b/web/src/components/session/ModernSessionHeader.stories.tsx@@ -0,0 +1,181 @@+import { type ComponentProps } from "react";+import { expect, userEvent, waitFor, within } from "storybook/test";++import preview from "../../../.storybook/preview";+import { ModernSessionHeader } from "@/src/components/session/ModernSessionHeader";++const scores = [+ {+ id: "score-helpfulness",+ name: "Helpfulness",+ value: 0.86,+ stringValue: null,+ dataType: "NUMERIC",+ },+] satisfies ComponentProps<typeof ModernSessionHeader>["scores"];++const overflowScores = Array.from({ length: 16 }, (_, index) => ({+ id: `score-quality-${index + 1}`,+ name: `Quality ${index + 1}`,+ value: (index + 1) / 20,+ stringValue: null,+ dataType: "NUMERIC" as const,+})) satisfies ComponentProps<typeof ModernSessionHeader>["scores"];++const manyUsers = Array.from(+ { length: 1_000 },+ (_, index) => `user-${index + 1}@example.com`,+);++const defaultArgs = {+ projectId: "project-1",+ countTraces: 24,+ traces: {+ state: "loaded",+ data: [+ { latencyMs: 1_240, observationCount: 42 },+ { latencyMs: 2_310, observationCount: 38 },+ { latencyMs: 4_620, observationCount: 51 },+ { latencyMs: 8_760, observationCount: 55 },+ ],+ },+ tokensIn: 18_420,+ tokensOut: 6_310,+ totalTokens: 24_730,+ totalCost: 0.084291,+ environment: "production",+ users: ["[email protected]", "[email protected]"],+ scores,+} satisfies ComponentProps<typeof ModernSessionHeader>;++const meta = preview.meta({+ component: ModernSessionHeader,+ parameters: { layout: "fullscreen", a11y: { test: "error" } },+});++export default meta;++export const Default = meta.story({ args: defaultArgs });++export const Minimal = meta.story({+ args: {+ ...defaultArgs,+ traces: { state: "loading" },+ tokensIn: 0,+ tokensOut: 0,+ totalTokens: 0,+ environment: null,+ users: [],+ scores: [],+ },+});++export const Overflow = meta.story({+ args: {+ ...defaultArgs,+ scores: overflowScores,+ },+});++export const TestSearchesHiddenPills = meta.story({+ name: "(Test) Searches hidden pills",+ args: {+ ...defaultArgs,+ scores: overflowScores,+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await waitFor(() =>+ expect(+ canvas.getByRole("button", {+ name: /show \d+ hidden session details/i,+ }),+ ).toBeInTheDocument(),+ );+ const overflowButton = canvas.getByRole("button", {+ name: /show \d+ hidden session details/i,+ });+ const visiblePills = canvasElement.querySelectorAll<HTMLElement>(+ "[data-overflow-visible-item='true'] [data-session-header-pill='true']",+ );+ const lastVisiblePill = visiblePills.item(visiblePills.length - 1);+ await expect(+ overflowButton.getBoundingClientRect().left -+ lastVisiblePill.getBoundingClientRect().right,+ ).toBeLessThanOrEqual(8);+ const overflowButtonRect = overflowButton.getBoundingClientRect();+ const lastVisiblePillRect = lastVisiblePill.getBoundingClientRect();+ await expect(+ Math.abs(+ overflowButtonRect.top ++ overflowButtonRect.height / 2 -+ (lastVisiblePillRect.top + lastVisiblePillRect.height / 2),+ ),+ ).toBeLessThanOrEqual(0.5);++ await userEvent.click(overflowButton);++ const body = within(canvasElement.ownerDocument.body);+ const searchInput = await body.findByRole("textbox", {+ name: "Search session details",+ });+ const dialog = body.getByRole("dialog");+ await expect(within(dialog).queryByText(/traces/i)).not.toBeInTheDocument();++ await userEvent.type(searchInput, "Quality 16");+ await expect(within(dialog).getByText("Quality 16")).toBeInTheDocument();+ await expect(+ within(dialog).queryByText("Quality 1"),+ ).not.toBeInTheDocument();+ },+});++export const TestBoundsManyUsers = meta.story({+ name: "(Test) Bounds many users",+ args: {+ ...defaultArgs,+ users: manyUsers,+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ await waitFor(() =>+ expect(+ canvasElement.querySelectorAll('a[href*="/users/"]').length,+ ).toBeLessThanOrEqual(6),+ );++ await userEvent.click(+ canvas.getByRole("button", {+ name: /show \d+ hidden session details/i,+ }),+ );+ const body = within(canvasElement.ownerDocument.body);+ const detailsDialog = body.getByRole("dialog", {+ name: "All session details",+ });+ const results = within(detailsDialog).getByRole("region", {+ name: "Session detail results",+ });+ const initialUserCount = within(results).getAllByRole("link").length;+ await expect(initialUserCount).toBeLessThanOrEqual(53);++ results.scrollTop = results.scrollHeight;+ results.dispatchEvent(new Event("scroll", { bubbles: true }));+ await waitFor(() =>+ expect(within(results).getAllByRole("link").length).toBeGreaterThan(+ initialUserCount,+ ),+ );++ const searchInput = within(detailsDialog).getByRole("textbox", {+ name: "Search session details",+ });+ await userEvent.clear(searchInput);+ await userEvent.type(searchInput, "[email protected]");+ await expect(+ within(results).getByRole("link", {+ name: "user [email protected]",+ }),+ ).toBeInTheDocument();+ },+});diff --git a/web/src/components/session/ModernSessionHeader.tsx b/web/src/components/session/ModernSessionHeader.tsxnew file mode 100644index 0000000000..b64d2ade25--- /dev/null+++ b/web/src/components/session/ModernSessionHeader.tsx@@ -0,0 +1,344 @@+import { percentile, type ScoreDomain } from "@langfuse/shared";+import { ArrowUpRight, Search } from "lucide-react";+import { type ReactNode, useState } from "react";++import { SingleLineOverflowList } from "@/src/components/SingleLineOverflowList";+import { ModernSessionHeaderPill } from "@/src/components/session/ModernSessionHeaderPill";+import {+ INITIAL_SESSION_USERS_DISPLAY_COUNT,+ SESSION_USERS_PER_PAGE,+} from "@/src/components/session/sessionUsers";+import { Input } from "@/src/components/ui/input";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";+import { formatIntervalSeconds } from "@/src/utils/dates";+import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";+import { numberFormatter, usdFormatter } from "@/src/utils/numbers";++type ModernSessionHeaderProps = {+ projectId: string;+ countTraces: number;+ traces:+ | { state: "loading" }+ | {+ state: "loaded";+ data: ReadonlyArray<{+ latencyMs: number | null;+ observationCount: number;+ }>;+ };+ tokensIn: number;+ tokensOut: number;+ totalTokens: number;+ totalCost: number;+ environment: string | null;+ users: readonly string[];+ scores: ReadonlyArray<+ Pick<+ WithStringifiedMetadata<ScoreDomain>,+ "id" | "name" | "dataType" | "value" | "stringValue"+ >+ >;+};++const ChipValue = ({ children }: { children: React.ReactNode }) => (+ <span className="text-foreground">{children}</span>+);++const ChipDot = () => <span className="text-foreground-tertiary">·</span>;++const scoreChipValue = (+ score: Pick<WithStringifiedMetadata<ScoreDomain>, "stringValue" | "value">,+) => {+ if (score.stringValue) return score.stringValue;+ if (score.value === null || score.value === undefined) return "—";+ return Number.isInteger(score.value)+ ? String(score.value)+ : score.value.toFixed(2);+};++const UserChip = ({ projectId, user }: { projectId: string; user: string }) => (+ <ModernSessionHeaderPill+ variant="link"+ href={`/project/${projectId}/users/${encodeURIComponent(user)}`}+ title={user}+ >+ user{" "}+ <span+ className="text-foreground group-hover:text-link truncate"+ title={user}+ >+ {user}+ </span>+ <ArrowUpRight className="text-link h-3 w-3 shrink-0" />+ </ModernSessionHeaderPill>+);++export function ModernSessionHeader({+ projectId,+ countTraces,+ traces,+ tokensIn,+ tokensOut,+ totalTokens,+ totalCost,+ environment,+ users,+ scores,+}: ModernSessionHeaderProps) {+ const [search, setSearch] = useState("");+ const [visibleUserCount, setVisibleUserCount] = useState(+ SESSION_USERS_PER_PAGE,+ );+ const latencies =+ traces.state === "loaded"+ ? traces.data.flatMap((trace) =>+ trace.latencyMs !== null && trace.latencyMs > 0+ ? [trace.latencyMs]+ : [],+ )+ : [];+ const spanCount =+ traces.state === "loaded"+ ? traces.data.reduce((total, trace) => total + trace.observationCount, 0)+ : null;+ const p50LatencyMs = latencies.length > 0 ? percentile(latencies, 0.5) : null;+ const p95LatencyMs =+ latencies.length > 0 ? percentile(latencies, 0.95) : null;+ const pills: Array<{ key: string; searchText: string; content: ReactNode }> =+ [+ {+ key: "traces",+ searchText: `traces ${countTraces} spans ${spanCount ?? ""}`,+ content: (+ <ModernSessionHeaderPill variant="display">+ <span>+ <ChipValue>{numberFormatter(countTraces, 0)}</ChipValue> traces+ </span>+ {spanCount !== null ? (+ <>+ <ChipDot />+ <span>+ <ChipValue>{numberFormatter(spanCount, 0)}</ChipValue> spans+ </span>+ </>+ ) : null}+ </ModernSessionHeaderPill>+ ),+ },+ ];++ if (p50LatencyMs !== null) {+ pills.push({+ key: "latency",+ searchText: `latency p50 ${p50LatencyMs} p95 ${p95LatencyMs ?? ""}`,+ content: (+ <ModernSessionHeaderPill variant="display">+ <span>+ p50{" "}+ <ChipValue>{formatIntervalSeconds(p50LatencyMs / 1000)}</ChipValue>+ </span>+ {p95LatencyMs !== null ? (+ <>+ <ChipDot />+ <span>+ p95{" "}+ <ChipValue>+ {formatIntervalSeconds(p95LatencyMs / 1000)}+ </ChipValue>+ </span>+ </>+ ) : null}+ </ModernSessionHeaderPill>+ ),+ });+ }++ if (totalTokens > 0) {+ pills.push({+ key: "tokens",+ searchText: `tokens ${tokensIn} ${tokensOut} ${totalTokens}`,+ content: (+ <ModernSessionHeaderPill variant="display">+ <span>+ tokens{" "}+ <ChipValue>+ {numberFormatter(tokensIn, 0)} → {numberFormatter(tokensOut, 0)}{" "}+ (Σ {numberFormatter(totalTokens, 0)})+ </ChipValue>+ </span>+ </ModernSessionHeaderPill>+ ),+ });+ }++ pills.push({+ key: "cost",+ searchText: `cost ${totalCost}`,+ content: (+ <ModernSessionHeaderPill+ variant="display"+ title={`exact $${totalCost.toFixed(6)}`}+ >+ <span>+ cost <ChipValue>{usdFormatter(totalCost, 2, 3)}</ChipValue>+ </span>+ </ModernSessionHeaderPill>+ ),+ });++ scores.forEach((score) => {+ const value = scoreChipValue(score);+ const isFraction =+ score.dataType === "NUMERIC" &&+ score.value !== null &&+ score.value !== undefined &&+ score.value >= 0 &&+ score.value <= 1;+ pills.push({+ key: `score-${score.id}`,+ searchText: `score ${score.name} ${value}`,+ content: (+ <ModernSessionHeaderPill variant="display" title={score.name}>+ {isFraction ? (+ <span className="bg-dark-yellow h-1.5 w-1.5 shrink-0 rounded-[1px]" />+ ) : null}+ <span className="max-w-40 truncate" title={score.name}>+ {score.name}+ </span>+ <ChipValue>{value}</ChipValue>+ </ModernSessionHeaderPill>+ ),+ });+ });++ if (environment) {+ pills.push({+ key: "environment",+ searchText: `environment env ${environment}`,+ content: (+ <ModernSessionHeaderPill variant="display">+ <span>+ env <ChipValue>{environment}</ChipValue>+ </span>+ </ModernSessionHeaderPill>+ ),+ });+ }++ users.slice(0, INITIAL_SESSION_USERS_DISPLAY_COUNT).forEach((user) => {+ pills.push({+ key: `user-${user}`,+ searchText: `user ${user}`,+ content: <UserChip projectId={projectId} user={user} />,+ });+ });+ const remainingUsers = users.slice(INITIAL_SESSION_USERS_DISPLAY_COUNT);++ return (+ <div className="bg-header border-b px-4 py-2">+ <SingleLineOverflowList+ items={pills}+ additionalOverflowCount={remainingUsers.length}+ getKey={(pill) => pill.key}+ renderItem={(pill) => pill.content}+ renderOverflow={({ hiddenItems: hiddenPills, overflowItemCount }) => {+ const normalizedSearch = search.trim().toLocaleLowerCase();+ const filteredPills = normalizedSearch+ ? hiddenPills.filter((pill) =>+ pill.searchText.toLocaleLowerCase().includes(normalizedSearch),+ )+ : hiddenPills;+ const filteredUsers = normalizedSearch+ ? remainingUsers.filter((user) =>+ user.toLocaleLowerCase().includes(normalizedSearch),+ )+ : remainingUsers;+ const visibleUsers = filteredUsers.slice(0, visibleUserCount);+ const hasResults =+ filteredPills.length > 0 || visibleUsers.length > 0;++ return (+ <Popover+ onOpenChange={(open) => {+ if (open) return;+ setSearch("");+ setVisibleUserCount(SESSION_USERS_PER_PAGE);+ }}+ >+ <PopoverTrigger asChild>+ <ModernSessionHeaderPill+ variant="button"+ ariaLabel={`Show ${overflowItemCount} hidden session details`}+ >+ +{overflowItemCount}+ </ModernSessionHeaderPill>+ </PopoverTrigger>+ <PopoverContent+ align="end"+ className="w-80 p-0"+ aria-label="All session details"+ >+ <div className="relative border-b p-2">+ <Search className="text-muted-foreground absolute top-1/2 left-4 h-3.5 w-3.5 -translate-y-1/2" />+ <Input+ value={search}+ onChange={(event) => {+ setSearch(event.target.value);+ setVisibleUserCount(SESSION_USERS_PER_PAGE);+ }}+ placeholder="Search session details"+ aria-label="Search session details"+ className="h-8 pl-8 text-xs"+ />+ </div>+ <div+ role="region"+ aria-label="Session detail results"+ className="flex max-h-72 flex-col items-start gap-2 overflow-y-auto p-2"+ onScroll={(event) => {+ const element = event.currentTarget;+ const isAtBottom =+ element.scrollHeight -+ element.scrollTop -+ element.clientHeight <=+ 16;+ if (!isAtBottom) return;+ setVisibleUserCount((current) =>+ Math.min(+ current + SESSION_USERS_PER_PAGE,+ filteredUsers.length,+ ),+ );+ }}+ >+ {hasResults ? (+ <>+ {filteredPills.map((pill) => (+ <div key={pill.key}>{pill.content}</div>+ ))}+ {visibleUsers.map((user) => (+ <UserChip+ key={user}+ projectId={projectId}+ user={user}+ />+ ))}+ </>+ ) : (+ <p className="text-muted-foreground px-2 py-4 text-xs">+ No session details found.+ </p>+ )}+ </div>+ </PopoverContent>+ </Popover>+ );+ }}+ />+ </div>+ );+}diff --git a/web/src/components/session/ModernSessionHeaderActionsController.clienttest.tsx b/web/src/components/session/ModernSessionHeaderActionsController.clienttest.tsxnew file mode 100644index 0000000000..661bf961b0--- /dev/null+++ b/web/src/components/session/ModernSessionHeaderActionsController.clienttest.tsx@@ -0,0 +1,123 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { type MouseEventHandler, type ReactNode } from "react";+import { vi } from "vitest";++import { ModernSessionHeaderActionsController } from "@/src/components/session/ModernSessionHeaderActionsController";+import { DropdownMenuTrigger } from "@/src/components/ui/dropdown-menu";++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: ({+ children,+ checked,+ onClick,+ }: {+ children: ReactNode;+ checked: boolean;+ onClick: MouseEventHandler<HTMLButtonElement>;+ }) => (+ <button+ type="button"+ role="menuitemcheckbox"+ aria-checked={checked}+ onClick={onClick}+ >+ {children}+ </button>+ ),+ DropdownMenuSub: ({ children }: { children: ReactNode }) => <>{children}</>,+ DropdownMenuSubTrigger: ({ children }: { children: ReactNode }) => (+ <div>{children}</div>+ ),+ DropdownMenuSubContent: ({ children }: { children: ReactNode }) => (+ <div>{children}</div>+ ),+ DropdownMenuSeparator: () => <hr />,+}));++vi.mock("@/src/features/posthog-analytics/usePostHogClientCapture", () => ({+ usePostHogClientCapture: () => vi.fn(),+}));++vi.mock("@/src/features/rbac/utils/checkProjectAccess", () => ({+ useHasProjectAccess: () => true,+}));++vi.mock("@/src/hooks/useCopyToClipboard", () => ({+ useCopyToClipboard: () => ({ copy: vi.fn() }),+}));++vi.mock("@/src/utils/api", () => ({+ api: {+ useUtils: () => ({ sessions: { invalidate: vi.fn() } }),+ sessions: {+ bookmark: {+ useMutation: () => ({ mutate: vi.fn(), isPending: false }),+ },+ publish: {+ useMutation: () => ({ mutate: vi.fn(), isPending: false }),+ },+ },+ },+}));++describe("ModernSessionHeaderActionsController", () => {+ it("keeps all display settings reachable from the actions menu", () => {+ const onShowCorrectionsChange = vi.fn();+ const onShowInlineToolCallsChange = vi.fn();+ const onShowSystemPromptChange = vi.fn();++ render(+ <ModernSessionHeaderActionsController+ projectId="project-id"+ sessionId="session-id"+ bookmarked={false}+ isPublic={false}+ showCorrections={false}+ showInlineToolCalls={false}+ showSystemPrompt={false}+ onShowCorrectionsChange={onShowCorrectionsChange}+ onShowInlineToolCallsChange={onShowInlineToolCallsChange}+ onShowSystemPromptChange={onShowSystemPromptChange}+ >+ <DropdownMenuTrigger asChild>+ <button type="button">Actions</button>+ </DropdownMenuTrigger>+ </ModernSessionHeaderActionsController>,+ );++ expect(screen.getByText("Display")).toBeInTheDocument();+ fireEvent.click(+ screen.getByRole("menuitemcheckbox", { name: "Show corrections" }),+ );+ fireEvent.click(+ screen.getByRole("menuitemcheckbox", { name: "Show tool calls" }),+ );+ fireEvent.click(+ screen.getByRole("menuitemcheckbox", { name: "Show system prompt" }),+ );++ expect(onShowCorrectionsChange).toHaveBeenCalledWith(true);+ expect(onShowInlineToolCallsChange).toHaveBeenCalledWith(true);+ expect(onShowSystemPromptChange).toHaveBeenCalledWith(true);+ });+});diff --git a/web/src/components/session/ModernSessionHeaderActionsController.tsx b/web/src/components/session/ModernSessionHeaderActionsController.tsxnew file mode 100644index 0000000000..cf30ca113c--- /dev/null+++ b/web/src/components/session/ModernSessionHeaderActionsController.tsx@@ -0,0 +1,146 @@+import { CopyIcon, Share2, Star } from "lucide-react";+import { type ReactNode } from "react";++import {+ DropdownMenu,+ DropdownMenuCheckboxItem,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,+} from "@/src/components/ui/dropdown-menu";+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { useCopyToClipboard } from "@/src/hooks/useCopyToClipboard";+import { api } from "@/src/utils/api";++export function ModernSessionHeaderActionsController({+ projectId,+ sessionId,+ bookmarked,+ isPublic,+ showCorrections,+ showInlineToolCalls,+ showSystemPrompt,+ onShowCorrectionsChange,+ onShowInlineToolCallsChange,+ onShowSystemPromptChange,+ children,+}: {+ projectId: string;+ sessionId: string;+ bookmarked: boolean;+ isPublic: boolean;+ showCorrections: boolean;+ showInlineToolCalls: boolean;+ showSystemPrompt: boolean;+ onShowCorrectionsChange: (isEnabled: boolean) => void;+ onShowInlineToolCallsChange: (isEnabled: boolean) => void;+ onShowSystemPromptChange: (isEnabled: boolean) => void;+ children: ReactNode;+}) {+ const capture = usePostHogClientCapture();+ const { copy } = useCopyToClipboard();+ const utils = api.useUtils();+ const hasBookmarkAccess = useHasProjectAccess({+ projectId,+ scope: "objects:bookmark",+ });+ const hasPublishAccess = useHasProjectAccess({+ projectId,+ scope: "objects:publish",+ });+ const bookmarkMutation = api.sessions.bookmark.useMutation({+ onSuccess: () => utils.sessions.invalidate(),+ });+ const publishMutation = api.sessions.publish.useMutation({+ onSuccess: () => utils.sessions.invalidate(),+ });++ return (+ <DropdownMenu>+ {children}+ <DropdownMenuContent align="end">+ <DropdownMenuItem+ disabled={!hasBookmarkAccess || bookmarkMutation.isPending}+ onClick={() => {+ capture("table:bookmark_button_click", {+ table: "sessions",+ id: sessionId,+ value: !bookmarked,+ });+ bookmarkMutation.mutate({+ projectId,+ sessionId,+ bookmarked: !bookmarked,+ });+ }}+ >+ <Star+ className="mr-2 h-3.5 w-3.5"+ fill={bookmarked ? "currentColor" : "none"}+ />+ {bookmarked ? "Remove from favourites" : "Add to favourites"}+ </DropdownMenuItem>+ <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>+ <DropdownMenuSeparator />+ <DropdownMenuSub>+ <DropdownMenuSubTrigger>Display</DropdownMenuSubTrigger>+ <DropdownMenuSubContent>+ <DropdownMenuCheckboxItem+ checked={showCorrections}+ onClick={(event) => {+ event.preventDefault();+ onShowCorrectionsChange(!showCorrections);+ }}+ >+ Show corrections+ </DropdownMenuCheckboxItem>+ <DropdownMenuCheckboxItem+ checked={showInlineToolCalls}+ onClick={(event) => {+ event.preventDefault();+ onShowInlineToolCallsChange(!showInlineToolCalls);+ }}+ >+ Show tool calls+ </DropdownMenuCheckboxItem>+ <DropdownMenuCheckboxItem+ checked={showSystemPrompt}+ onClick={(event) => {+ event.preventDefault();+ onShowSystemPromptChange(!showSystemPrompt);+ }}+ >+ Show system prompt+ </DropdownMenuCheckboxItem>+ </DropdownMenuSubContent>+ </DropdownMenuSub>+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/web/src/components/session/ModernSessionHeaderPill.tsx b/web/src/components/session/ModernSessionHeaderPill.tsxnew file mode 100644index 0000000000..ade924c466--- /dev/null+++ b/web/src/components/session/ModernSessionHeaderPill.tsx@@ -0,0 +1,74 @@+import Link from "next/link";+import { type ComponentPropsWithoutRef, type ReactNode, type Ref } from "react";++const PILL_CLASS_NAME =+ "text-muted-foreground inline-flex h-[22px] shrink-0 items-center rounded-sm border px-2 py-0 font-mono text-[11px] leading-none whitespace-nowrap";++type ModernSessionHeaderPillProps = {+ children: ReactNode;+} & (+ | {+ variant: "display";+ title?: string;+ }+ | {+ variant: "link";+ href: ComponentPropsWithoutRef<typeof Link>["href"];+ title: string;+ }+ | ({+ variant: "button";+ ariaLabel: string;+ ref?: Ref<HTMLButtonElement>;+ "data-state"?: string;+ } & Pick<+ ComponentPropsWithoutRef<"button">,+ | "aria-controls"+ | "aria-expanded"+ | "aria-haspopup"+ | "onClick"+ | "onKeyDown"+ | "onPointerDown"+ >)+);++export function ModernSessionHeaderPill(props: ModernSessionHeaderPillProps) {+ if (props.variant === "display") {+ return (+ <span+ title={props.title}+ data-session-header-pill="true"+ className={`${PILL_CLASS_NAME} gap-1.5`}+ >+ {props.children}+ </span>+ );+ }++ if (props.variant === "link") {+ return (+ <Link+ href={props.href}+ title={props.title}+ data-session-header-pill="true"+ className={`${PILL_CLASS_NAME} hover:border-link hover:text-link group max-w-[280px] min-w-0 gap-1.5`}+ >+ {props.children}+ </Link>+ );+ }++ const { variant, children, ariaLabel, ref, ...interactionProps } = props;+ return (+ <button+ ref={ref}+ {...interactionProps}+ type="button"+ aria-label={ariaLabel}+ data-session-header-pill="true"+ className={`${PILL_CLASS_NAME} hover:bg-accent justify-center`}+ >+ {children}+ </button>+ );+}diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsxindex 3bf68ce053..f07ad0e1f4 100644--- a/web/src/components/session/index.tsx+++ b/web/src/components/session/index.tsx@@ -26,6 +26,7 @@ import {CopyIcon,Download,ExternalLinkIcon,+ MoreVertical,} from "lucide-react";import { useCopyToClipboard } from "@/src/hooks/useCopyToClipboard";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -85,6 +86,9 @@ import { SessionDetailStoreProvider } from "@/src/components/session/SessionDetaimport { SessionVirtualizedRow } from "@/src/components/session/SessionVirtualizedRow";import { createSessionDetailStore } from "@/src/components/session/sessionDetailStore";import { ModernSession } from "@/src/components/session/ModernSession";+import { ModernSessionHeader } from "@/src/components/session/ModernSessionHeader";+import { DropdownMenuTrigger } from "@/src/components/ui/dropdown-menu";+import { ModernSessionHeaderActionsController } from "@/src/components/session/ModernSessionHeaderActionsController";import { ModernSessionFilterControls } from "@/src/components/session/ModernSessionFilterControls";import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";import { useIsMobile } from "@/src/hooks/use-mobile";@@ -101,10 +105,12 @@ import {type LegacySessionTrace,} from "@/src/components/session/sessionDetailPageTypes";import { getSessionFilterOptionsStartTimeFilters } from "@/src/components/session/sessionFilterOptions";+import {+ INITIAL_SESSION_USERS_DISPLAY_COUNT,+ SESSION_USERS_PER_PAGE,+} from "@/src/components/session/sessionUsers";// some projects have thousands of users in a session, paginate to avoid rendering all at once-const INITIAL_USERS_DISPLAY_COUNT = 3;-const USERS_PER_PAGE_IN_POPOVER = 50;// Keep this near TanStack's default to avoid waking too many lazy row loaders.const SESSION_VIRTUALIZER_OVERSCAN = 5;@@ -119,8 +125,8 @@ export function SessionUsers({if (!users) return null;- const initialUsers = users?.slice(0, INITIAL_USERS_DISPLAY_COUNT);- const remainingUsers = users?.slice(INITIAL_USERS_DISPLAY_COUNT);+ const initialUsers = users?.slice(0, INITIAL_SESSION_USERS_DISPLAY_COUNT);+ const remainingUsers = users?.slice(INITIAL_SESSION_USERS_DISPLAY_COUNT);return (<div className="flex flex-wrap items-center gap-2">@@ -157,8 +163,8 @@ export function SessionUsers({<div className="flex flex-col gap-2 p-2">{remainingUsers.slice(- page * USERS_PER_PAGE_IN_POPOVER,- (page + 1) * USERS_PER_PAGE_IN_POPOVER,+ page * SESSION_USERS_PER_PAGE,+ (page + 1) * SESSION_USERS_PER_PAGE,).map((userId: string) => {const userBadgeText = `User ID: ${userId}`;@@ -182,7 +188,7 @@ export function SessionUsers({})}</div></ScrollArea>- {remainingUsers.length > USERS_PER_PAGE_IN_POPOVER && (+ {remainingUsers.length > SESSION_USERS_PER_PAGE && (<div className="flex items-center justify-between border-t p-2 pt-4"><Buttonvariant="outline"@@ -194,15 +200,14 @@ export function SessionUsers({</Button><span className="text-muted-foreground text-sm">Page {page + 1} of{" "}- {Math.ceil(remainingUsers.length / USERS_PER_PAGE_IN_POPOVER)}+ {Math.ceil(remainingUsers.length / SESSION_USERS_PER_PAGE)}</span><Buttonvariant="outline"size="sm"onClick={() => setPage((p) => p + 1)}disabled={- (page + 1) * USERS_PER_PAGE_IN_POPOVER >=- remainingUsers.length+ (page + 1) * SESSION_USERS_PER_PAGE >= remainingUsers.length}>Next@@ -290,6 +295,7 @@ const SessionScores = ({</div>);};+const CopySessionIdButton: React.FC<{sessionId: string;/** "menu" renders a full-width labeled row for the mobile ⋯ overflow;@@ -895,24 +901,6 @@ const LoadedSessionEventsPage: React.FC<{sessionDetailStore.getState().actions.setShowSystemPrompt(isEnabled);};- const displayOptions = [- {- label: "corrections",- checked: showCorrections,- onCheckedChange: setShowCorrectionsForSession,- },- {- label: "tool calls",- checked: showInlineToolCalls,- onCheckedChange: setInlineToolCallsForSession,- },- {- label: "system prompt",- checked: showSystemPrompt,- onCheckedChange: setShowSystemPromptForSession,- },- ];-const sessionCommentCounts = api.comments.getCountByObjectId.useQuery({projectId,@@ -1391,7 +1379,7 @@ const LoadedSessionEventsPage: React.FC<{href: `/project/${projectId}/sessions`,},],- actionButtonsLeft: (+ actionButtonsLeft: !isModernSessionEnabled ? (<div className="flex items-center gap-0"><StarSessionTogglekey="star"@@ -1409,7 +1397,7 @@ const LoadedSessionEventsPage: React.FC<{/><CopySessionIdButton key="copy-id" sessionId={sessionId} /></div>- ),+ ) : undefined,actionButtonsRight: (<><WebCalloutButton@@ -1418,66 +1406,6 @@ const LoadedSessionEventsPage: React.FC<{observationId={null}sessionId={sessionId}/>- {isModernSessionEnabled ? (- <>- <div className="hidden items-center gap-3 pr-2 min-[1900px]:flex">- <span className="text-muted-foreground text-xs">Show:</span>- {displayOptions.map(- ({ label, checked, onCheckedChange }) => (- <label- key={label}- className="flex items-center gap-1.5"- >- <Switch- checked={checked}- onCheckedChange={onCheckedChange}- size="sm"- />- <span className="text-muted-foreground text-xs">- {label}- </span>- </label>- ),- )}- </div>- <div className="flex items-center gap-1.5 pr-2 min-[1900px]:hidden">- <span className="text-muted-foreground text-xs">Show:</span>- <Popover>- <PopoverTrigger asChild>- <Button- variant="outline"- size="sm"- className="h-8 gap-1 px-2"- >- Options- <ChevronDown className="h-3.5 w-3.5" />- </Button>- </PopoverTrigger>- <PopoverContent align="end" className="w-52 p-2">- <div className="flex flex-col gap-1">- {displayOptions.map(- ({ label, checked, onCheckedChange }) => (- <label- key={label}- className="hover:bg-muted flex items-center justify-between gap-4 rounded-md px-2 py-1.5"- >- <span className="text-sm capitalize">- {label}- </span>- <Switch- checked={checked}- onCheckedChange={onCheckedChange}- size="sm"- />- </label>- ),- )}- </div>- </PopoverContent>- </Popover>- </div>- </>- ) : null}{!router.query.peek && (<DetailPageNavkey="nav"@@ -1528,7 +1456,30 @@ const LoadedSessionEventsPage: React.FC<{Show corrections</span></label>- ) : null}+ ) : (+ <ModernSessionHeaderActionsController+ projectId={projectId}+ sessionId={sessionId}+ bookmarked={session.bookmarked}+ isPublic={session.public}+ showCorrections={showCorrections}+ showInlineToolCalls={showInlineToolCalls}+ showSystemPrompt={showSystemPrompt}+ onShowCorrectionsChange={setShowCorrectionsForSession}+ onShowInlineToolCallsChange={setInlineToolCallsForSession}+ onShowSystemPromptChange={setShowSystemPromptForSession}+ >+ <DropdownMenuTrigger asChild>+ <Button+ variant="outline"+ size="icon"+ aria-label="Session actions"+ >+ <MoreVertical className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ </ModernSessionHeaderActionsController>+ )}</>),// Mobile compact header: the same session actions as full-width@@ -1585,21 +1536,7 @@ const LoadedSessionEventsPage: React.FC<{sessionId={sessionId}layout="menu"/>- {isModernSessionEnabled ? (- displayOptions.map(({ label, checked, onCheckedChange }) => (- <label- key={label}- className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5"- >- <span className="text-sm capitalize">{label}</span>- <Switch- checked={checked}- onCheckedChange={onCheckedChange}- size="sm"- />- </label>- ))- ) : (+ {!isModernSessionEnabled ? (<label className="hover:bg-accent flex w-full items-center justify-between gap-4 rounded-md px-2 py-1.5"><span className="text-sm">Show corrections</span><Switch@@ -1608,7 +1545,7 @@ const LoadedSessionEventsPage: React.FC<{size="sm"/></label>- )}+ ) : null}</>),}}@@ -1620,7 +1557,25 @@ const LoadedSessionEventsPage: React.FC<{: "flex h-full flex-col overflow-auto"}>- {hasSessionControls ? (+ {isModernSessionEnabled ? (+ <ModernSessionHeader+ projectId={projectId}+ countTraces={session.countTraces}+ traces={+ isTracesSuccess+ ? { state: "loaded", data: traces ?? [] }+ : { state: "loading" }+ }+ tokensIn={session.inputUsage}+ tokensOut={session.outputUsage}+ totalTokens={session.totalTokens}+ totalCost={session.totalCost ?? 0}+ environment={session.environment ?? null}+ users={session.users ?? []}+ scores={session.scores}+ />+ ) : null}+ {!isModernSessionEnabled && hasSessionControls ? (<SessionControlsBarisMobile={isMobile && !isModernSessionEnabled}desktopClassName="bg-background sticky top-0 z-40 flex flex-wrap items-center gap-2 border-b p-4"diff --git a/web/src/components/session/sessionUsers.ts b/web/src/components/session/sessionUsers.tsnew file mode 100644index 0000000000..97b56f1c57--- /dev/null+++ b/web/src/components/session/sessionUsers.ts@@ -0,0 +1,2 @@+export const INITIAL_SESSION_USERS_DISPLAY_COUNT = 3;+export const SESSION_USERS_PER_PAGE = 50;diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.tsindex 1359afe250..4c9974e0e6 100644--- a/web/src/server/api/routers/sessions.ts+++ b/web/src/server/api/routers/sessions.ts@@ -762,6 +762,9 @@ export const sessionRouter = createTRPCRouter({totalCost: sessionMetrics? Number(sessionMetrics.session_total_cost): 0,+ inputUsage: Number(sessionMetrics.session_input_usage),+ outputUsage: Number(sessionMetrics.session_output_usage),+ totalTokens: Number(sessionMetrics.session_total_usage),minTimestamp: parseClickhouseUTCDateTimeFormat(sessionMetrics.min_timestamp,),diff --git a/web/storybook/docs/WritingGoodStories.mdx b/web/storybook/docs/WritingGoodStories.mdxindex a9bd60b45c..9725e588ad 100644--- a/web/storybook/docs/WritingGoodStories.mdx+++ b/web/storybook/docs/WritingGoodStories.mdx@@ -40,6 +40,7 @@ Keep the existing component, but update it to use the newly created component fo- Name stories after the state they represent, not the implementation. Also do not include the component name in the story name.- Prefer: `Default`, `Empty`, `WithLongName`, `Error`, `Disabled`, `Loading`- Avoid: `Test1`, `CustomRenderExample`, `ButtonWithLongNameAndIcon`+- Do not create separate light-mode or dark-mode stories when the component state is otherwise identical. Use Storybook's global theme toggle to review existing stories in either theme.- Set callbacks up as Storybook Actions by default:```ts