Skip to content

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

fix(web): Clean up `ValueCell` (#19100)

Ben Bachem82b95144cd6e
diff --git a/web/src/components/table/ValueCell.tsx b/web/src/components/table/ValueCell.tsx
index feeb13cde4..0bd89a3e5f 100644
--- a/web/src/components/table/ValueCell.tsx
+++ b/web/src/components/table/ValueCell.tsx
@@ -1,5 +1,4 @@
-import { memo, type JSX, useState } from "react";
-import { useRouter } from "next/router";
+import { memo, type ComponentProps, type JSX, useState } from "react";
import { type Row } from "@tanstack/react-table";
import { urlRegex } from "@langfuse/shared";
import {
@@ -13,34 +12,9 @@ import { MediaReferenceTag } from "@/src/components/ui/media/MediaReferenceTag";
import { copyTextToClipboard } from "@/src/utils/clipboard";
import { Button } from "@/src/components/ui/button";
import { Button as TextButton } from "@/src/components/design-system/Button/Button";
-import {
- DropdownMenuController,
- DropdownMenuItem,
- DropdownMenuSeparator,
-} from "@/src/components/ui/dropdown-menu";
+import { DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";
import { cn } from "@/src/utils/tailwind";
-import {
- buildEventsTablePathForMetadataFilter,
- type MetadataFilterOperator,
-} from "@/src/features/events";
-import {
- Copy,
- Check,
- EllipsisVertical,
- Filter,
- FilterX,
-} from "@langfuse/icons";
-
-/**
- * Enables the per-row actions menu in a metadata JSON view: copy value/
- * structure/path plus "Include in / Exclude from filter" shortcuts that land on
- * the matching events table. Passed only by the metadata view, so input/output
- * cells keep their plain one-click copy button.
- */
-export type MetadataFilterActions = {
- projectId: string;
- filterTarget: "observations" | "traces";
-};
+import { Copy, Check, EllipsisVertical } from "@langfuse/icons";
const MAX_STRING_LENGTH_FOR_LINK_DETECTION = 1500;
const MAX_CELL_DISPLAY_CHARS = 2000;
@@ -51,7 +25,6 @@ const PREVIEW_TEXT_CLASSES = "text-gray-500 dark:text-gray-400";
const ROW_ACTION_BUTTON_CLASSES =
"text-muted-foreground absolute top-0 h-5 w-5 rounded-sm p-0 opacity-0 transition-opacity duration-200 group-hover/value-cell:opacity-100 hover:bg-transparent hover:text-foreground";
const ROW_COPY_OFFSET = "-right-0.5";
-const ROW_MENU_OFFSET = "-right-1.5";
function renderStringWithLinks(text: string): React.ReactNode {
if (text.length >= MAX_STRING_LENGTH_FOR_LINK_DETECTION) {
@@ -202,167 +175,22 @@ export function getCopyValue(value: unknown): string {
}
}
-/** Walks up to the top-level (level 0) ancestor key for a metadata row. */
-function resolveTopLevelMetadataKey(row: Row<JsonTableRow>): string {
- let cursor: Row<JsonTableRow> | undefined = row;
- while (cursor && cursor.original.level > 0) {
- cursor = cursor.getParentRow() ?? undefined;
- }
- return cursor?.original.key ?? row.original.key;
-}
-
-/**
- * Builds the dotted key path from the row's actual keys (root → leaf). Unlike
- * `convertRowIdToKeyPath`, which reconstructs the path from the hyphen-joined
- * row id, this is lossless for keys that themselves contain `-` (e.g.
- * `x-request-id`).
- */
-function resolveKeyPath(row: Row<JsonTableRow>): string {
- const keys: string[] = [];
- let cursor: Row<JsonTableRow> | undefined = row;
- while (cursor) {
- keys.unshift(String(cursor.original.key));
- cursor = cursor.getParentRow() ?? undefined;
- }
- return keys.join(".");
-}
-
-/**
- * The per-row overflow menu shown in metadata views. Containers offer "Copy
- * structure"; scalar leaves offer "Copy value" plus filter shortcuts. Rendered
- * only when `metadataActions` is provided, so `useRouter` stays off the hot
- * path for the (far more numerous) input/output JSON cells.
- */
-function ValueCellActionsMenuContent({
- row,
- metadataActions,
-}: {
- row: Row<JsonTableRow>;
- metadataActions: MetadataFilterActions;
-}) {
- const router = useRouter();
- const { value, type, hasChildren, level } = row.original;
-
- const filterValue = String(value);
- // A nested value is matched as a substring of its JSON-ENCODED top-level
- // branch, but `filterValue` is the JSON-parsed (unescaped) form shown in the
- // tree. When the value carries JSON-escapable characters (quotes,
- // backslashes, newlines) the two differ, so `contains` would never match —
- // hide the shortcut rather than build a confidently-wrong filter.
- //
- // Top-level scalars are *usually* stored raw (ingestion keeps top-level
- // strings as-is), so we skip the check there. This heuristic misses the rare
- // case of a top-level value that was itself JSON-encoded with escapes; we
- // accept that miss because the alternative — always applying the check —
- // would wrongly hide the far more common top-level raw string with literal
- // newlines (which filters fine), since its encoded form also differs.
- const valueMatchesStoredForm =
- level === 0 || JSON.stringify(filterValue).slice(1, -1) === filterValue;
- const isScalarLeaf =
- !hasChildren &&
- (type === "string" || type === "number" || type === "boolean") &&
- // Skip empty values: `contains ""` matches every row (ClickHouse
- // position(x, "") === 1, and Map[missingKey] defaults to "") while
- // `does not contain ""` matches none — both shortcuts would be no-ops.
- filterValue.length > 0 &&
- valueMatchesStoredForm;
-
- // Metadata is a flat Map(String, String), so a nested value can only be
- // matched as a substring of its top-level branch. We use contains/does not
- // contain uniformly (top-level included) so Include and Exclude stay exact
- // complements — stringObject has no "!=" to invert an exact "=".
- const metadataKey = resolveTopLevelMetadataKey(row);
- const includeOperator: MetadataFilterOperator = "contains";
- const excludeOperator: MetadataFilterOperator = "does not contain";
- const displayValue = type === "string" ? `"${filterValue}"` : filterValue;
-
- const handleCopyData = () => {
- copyTextToClipboard(getCopyValue(value));
- };
- const handleCopyPath = () => {
- copyTextToClipboard(resolveKeyPath(row));
- };
- const navigateWithFilter = (operator: MetadataFilterOperator) => {
- router.push(
- buildEventsTablePathForMetadataFilter({
- currentPath: router.asPath,
- projectId: metadataActions.projectId,
- metadataKey,
- value: filterValue,
- operator,
- target: metadataActions.filterTarget,
- }),
- );
- };
-
- const includeFilterText = `metadata.${metadataKey} ${includeOperator} ${displayValue}`;
- const excludeFilterText = `metadata.${metadataKey} ${excludeOperator} ${displayValue}`;
-
- return (
- <>
- <DropdownMenuItem className="text-xs" onSelect={handleCopyData}>
- <Copy size="base" color="default" __rawClassName="mr-2" />
- {hasChildren ? "Copy structure" : "Copy value"}
- </DropdownMenuItem>
- <DropdownMenuItem className="text-xs" onSelect={handleCopyPath}>
- <Copy size="base" color="default" __rawClassName="mr-2" />
- Copy path
- </DropdownMenuItem>
- {isScalarLeaf && (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- className="text-xs"
- onSelect={() => navigateWithFilter(includeOperator)}
- >
- <Filter size="base" color="default" __rawClassName="mr-2" />
- <span className="flex min-w-0 flex-col">
- <span>Include in filter</span>
- <span
- className="text-muted-foreground truncate font-mono"
- title={includeFilterText}
- >
- {includeFilterText}
- </span>
- </span>
- </DropdownMenuItem>
- <DropdownMenuItem
- className="text-xs"
- onSelect={() => navigateWithFilter(excludeOperator)}
- >
- <FilterX size="base" color="default" __rawClassName="mr-2" />
- <span className="flex min-w-0 flex-col">
- <span>Exclude from filter</span>
- <span
- className="text-muted-foreground truncate font-mono"
- title={excludeFilterText}
- >
- {excludeFilterText}
- </span>
- </span>
- </DropdownMenuItem>
- </>
- )}
- </>
- );
-}
-
export const ValueCell = memo(
({
row,
expandedCells,
toggleCellExpansion,
preserveStringWhitespace = false,
- metadataActions,
rowActions,
}: {
row: Row<JsonTableRow>;
expandedCells: Set<string>;
toggleCellExpansion: (cellId: string) => void;
preserveStringWhitespace?: boolean;
- metadataActions?: MetadataFilterActions;
- /** Replaces the built-in menu, for tables with their own row actions. */
- rowActions?: (row: Row<JsonTableRow>) => React.ReactNode;
+ /** Shows an actions menu instead of the default one-click copy button. */
+ rowActions?: (
+ row: Row<JsonTableRow>,
+ ) => ComponentProps<typeof DropdownMenu>["items"];
}) => {
const { value, type } = row.original;
const cellId = `${row.id}-value`;
@@ -533,29 +361,15 @@ export const ValueCell = memo(
</div>
)}
- {/* Hover affordance: a one-click copy by default, or an actions menu
- (copy + filter shortcuts) in metadata views. */}
- {rowActions || metadataActions ? (
- <DropdownMenuController
- align="end"
- maxWidth="320px"
- renderMenu={() => {
- if (rowActions) {
- return rowActions(row);
- }
- if (metadataActions) {
- return (
- <ValueCellActionsMenuContent
- row={row}
- metadataActions={metadataActions}
- />
- );
- }
- return null;
- }}
- >
- {({ isOpen, Trigger }) => (
- <Trigger asChild>
+ {rowActions ? (
+ // Portal clicks still bubble through React to the expandable table row.
+ <span onClick={(event) => event.stopPropagation()}>
+ <DropdownMenu
+ items={rowActions(row)}
+ placement="bottom-end"
+ ariaLabel="Value actions"
+ >
+ {({ getTriggerProps }) => (
<Button
variant="ghost"
size="icon"
@@ -563,16 +377,15 @@ export const ValueCell = memo(
title="Actions"
className={cn(
ROW_ACTION_BUTTON_CLASSES,
- ROW_MENU_OFFSET,
- isOpen && "opacity-100",
+ "-right-1.5 aria-expanded:opacity-100",
)}
- onClick={(event) => event.stopPropagation()}
+ {...getTriggerProps()}
>
<EllipsisVertical size="base" color="default" />
</Button>
- </Trigger>
- )}
- </DropdownMenuController>
+ )}
+ </DropdownMenu>
+ </span>
) : (
<Button
variant="ghost"
diff --git a/web/src/components/ui/PrettyJsonView.tsx b/web/src/components/ui/PrettyJsonView.tsx
index 21b72acaae..a7be516bef 100644
--- a/web/src/components/ui/PrettyJsonView.tsx
+++ b/web/src/components/ui/PrettyJsonView.tsx
@@ -61,7 +61,6 @@ import {
import {
ValueCell,
getValueStringLength,
- type MetadataFilterActions,
} from "@/src/components/table/ValueCell";
import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";
import { isLargeRenderString } from "@/src/components/ui/largeStringGate";
@@ -384,7 +383,6 @@ function JsonPrettyTable({
toggleCellExpansion,
stickyTopLevelKey = false,
showObservationTypeBadge = false,
- metadataActions,
rowActions,
}: {
data: JsonTableRow[];
@@ -402,8 +400,7 @@ function JsonPrettyTable({
toggleCellExpansion: (cellId: string) => void;
stickyTopLevelKey?: boolean;
showObservationTypeBadge?: boolean;
- metadataActions?: MetadataFilterActions;
- rowActions?: (row: Row<JsonTableRow>) => React.ReactNode;
+ rowActions?: React.ComponentProps<typeof ValueCell>["rowActions"];
/** Drop the Path / Value header row. */
}) {
const topLevelRowRef = useRef<HTMLTableRowElement>(null);
@@ -496,7 +493,6 @@ function JsonPrettyTable({
expandedCells={expandedCells}
toggleCellExpansion={toggleCellExpansion}
preserveStringWhitespace={row.original.key === "code_eval_source_code"}
- metadataActions={metadataActions}
rowActions={rowActions}
/>
);
@@ -717,11 +713,8 @@ export function PrettyJsonView(props: {
/** Controlled collapsed state; long system prompts still follow their rule. */
collapsed?: boolean;
onCollapsedChange?: (collapsed: boolean) => void;
- /** When set, rows show an actions menu with copy + add-to-filter shortcuts
- (metadata views only). */
- metadataActions?: MetadataFilterActions;
- /** Replaces the built-in row menu, for tables with their own actions. */
- rowActions?: (row: Row<JsonTableRow>) => React.ReactNode;
+ /** Shows an actions menu instead of the default one-click copy button. */
+ rowActions?: React.ComponentProps<typeof ValueCell>["rowActions"];
/** Long system prompts start collapsed (from raw `role === "system"`,
since the title can carry a message `name` instead of the role). */
isSystemPrompt?: boolean;
@@ -1284,7 +1277,6 @@ export function PrettyJsonView(props: {
toggleCellExpansion={toggleCellExpansion}
stickyTopLevelKey={props.stickyTopLevelKey}
showObservationTypeBadge={props.showObservationTypeBadge}
- metadataActions={props.metadataActions}
rowActions={props.rowActions}
/>
)}
diff --git a/web/src/features/traces/components/DetailAttributesTab.clienttest.tsx b/web/src/features/traces/components/DetailAttributesTab.clienttest.tsx
index 0312a945ae..20c9256904 100644
--- a/web/src/features/traces/components/DetailAttributesTab.clienttest.tsx
+++ b/web/src/features/traces/components/DetailAttributesTab.clienttest.tsx
@@ -12,8 +12,11 @@ vi.mock("@/src/components/ui/PrettyJsonView", () => ({
vi.mock("@/src/features/feature-flags", () => ({
useInternalFeaturesEnabled: () => false,
}));
-vi.mock("./ObservationDetailView/AttributeRowActions", () => ({
- AttributeRowActions: () => null,
+vi.mock("next/router", () => ({
+ useRouter: () => ({ asPath: "/project/project/traces", push: vi.fn() }),
+}));
+vi.mock("@/src/features/posthog-analytics", () => ({
+ usePostHogClientCapture: () => vi.fn(),
}));
afterEach(() => {
diff --git a/web/src/features/traces/components/DetailAttributesTab.tsx b/web/src/features/traces/components/DetailAttributesTab.tsx
index 51194db304..507fd5e296 100644
--- a/web/src/features/traces/components/DetailAttributesTab.tsx
+++ b/web/src/features/traces/components/DetailAttributesTab.tsx
@@ -1,14 +1,16 @@
/** Trace metadata, or observation attributes, model parameters and metadata. */
import { useMemo } from "react";
+import { useRouter } from "next/router";
import { type MediaReturnType } from "@/src/features/media";
import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
import { IOSection } from "@/src/components/ui/IOSection";
import { cn } from "@/src/utils/tailwind";
import { IO_STICKY_HEADERS_CLASS } from "@/src/features/traces/constants/ioSectionClasses";
-import { type MetadataFilterActions } from "@/src/components/table/ValueCell";
-import { AttributeRowActions } from "./ObservationDetailView/AttributeRowActions";
+import { getMetadataRowActions } from "@/src/features/traces/fns/getMetadataRowActions";
+import { getAttributeRowActions } from "@/src/features/traces/fns/getAttributeRowActions";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
import { LargeJsonFieldFallback } from "@/src/features/traces/components/IOPreview/components/LargeJsonFieldFallback";
import {
JSON_VIEW_RENDER_CHAR_LIMIT,
@@ -45,10 +47,8 @@ export function DetailAttributesTab({
jsonMetadataExpanded?: boolean;
onJsonMetadataExpandedChange?: (expanded: boolean) => void;
}) {
- const metadataActions: MetadataFilterActions = {
- projectId,
- filterTarget: observation ? "observations" : "traces",
- };
+ const router = useRouter();
+ const capture = usePostHogClientCapture();
const hasAttributes =
observation && Object.keys(observation.attributes).length > 0;
const hasMetadata =
@@ -72,15 +72,17 @@ export function DetailAttributesTab({
title="Attributes"
json={observation.attributes}
currentView={currentView}
- rowActions={(row) => (
- <AttributeRowActions
- row={row}
- projectId={projectId}
- filterTarget="observations"
- anchorTime={observation.attributesAnchorTime}
- analyticsTable="attributes"
- />
- )}
+ rowActions={(row) =>
+ getAttributeRowActions({
+ row,
+ projectId,
+ filterTarget: "observations",
+ anchorTime: observation.attributesAnchorTime,
+ analyticsTable: "attributes",
+ router,
+ capture,
+ })
+ }
/>
) : null}
{observation?.modelParameters ? (
@@ -109,7 +111,14 @@ export function DetailAttributesTab({
json={metadata}
parsedJson={parsedMetadata}
currentView={currentView}
- metadataActions={metadataActions}
+ rowActions={(row) =>
+ getMetadataRowActions({
+ row,
+ projectId,
+ filterTarget: observation ? "observations" : "traces",
+ router,
+ })
+ }
media={media?.filter(
(attachment) => attachment.field === "metadata",
)}
diff --git a/web/src/features/traces/components/ObservationDetailView/AttributeRowActions.tsx b/web/src/features/traces/components/ObservationDetailView/AttributeRowActions.tsx
deleted file mode 100644
index c311fa60d0..0000000000
--- a/web/src/features/traces/components/ObservationDetailView/AttributeRowActions.tsx
+++ /dev/null
@@ -1,125 +0,0 @@
-/** Row menu for the Attributes table: copy, then include / exclude via the
- * attribute's own table column. */
-
-import { useRouter } from "next/router";
-import { Copy, Filter, FilterX } from "@langfuse/icons";
-import { type Row } from "@tanstack/react-table";
-import { type FilterState } from "@langfuse/shared";
-
-import {
- DropdownMenuItem,
- DropdownMenuSeparator,
-} from "@/src/components/ui/dropdown-menu";
-import { getCopyValue } from "@/src/components/table/ValueCell";
-import { type JsonTableRow } from "@/src/components/table/utils/jsonExpansionUtils";
-import { copyTextToClipboard } from "@/src/utils/clipboard";
-import { buildEventsTablePathForColumnFilter } from "@/src/features/events";
-import { attributeColumnFilter } from "@/src/features/traces/fns/attributeColumnFilter";
-import { attributeGrammar } from "@/src/features/traces/fns/attributeGrammar";
-import { usePostHogClientCapture } from "@/src/features/posthog-analytics";
-
-export type AttributeTableAction = "copy" | "include_filter" | "exclude_filter";
-
-export function AttributeRowActions({
- row,
- projectId,
- filterTarget,
- anchorTime,
- analyticsTable,
-}: {
- row: Row<JsonTableRow>;
- projectId: string;
- filterTarget: "observations" | "traces";
- /** Keeps the target table's window covering the source row. */
- anchorTime?: Date | null;
- analyticsTable: "attributes" | "metadata";
-}) {
- const router = useRouter();
- const capture = usePostHogClientCapture();
- const { key, value, hasChildren } = row.original;
- const valueText = String(value);
- const filter =
- hasChildren || key == null
- ? null
- : attributeColumnFilter(key, valueText, filterTarget);
- const includeText = filter ? attributeGrammar(key ?? "", valueText) : null;
- const excludeClause = filter?.exclude;
-
- const track = (action: AttributeTableAction) =>
- capture("trace_detail:attribute_table_action", {
- table: analyticsTable,
- action,
- });
-
- const navigate = (
- clause: FilterState[number],
- target: "observations" | "traces",
- ) =>
- router.push(
- buildEventsTablePathForColumnFilter({
- currentPath: router.asPath,
- projectId,
- target,
- filter: clause,
- coverTime: anchorTime ?? undefined,
- }),
- );
-
- return (
- <>
- <DropdownMenuItem
- className="text-xs"
- onSelect={() => {
- track("copy");
- copyTextToClipboard(getCopyValue(value));
- }}
- >
- <Copy size="base" color="default" __rawClassName="mr-2" />
- {hasChildren ? "Copy structure" : "Copy value"}
- </DropdownMenuItem>
- {filter && includeText ? (
- <>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- className="text-xs"
- onSelect={() => {
- track("include_filter");
- navigate(filter.include, filter.target);
- }}
- >
- <Filter size="base" color="default" __rawClassName="mr-2" />
- <span className="flex min-w-0 flex-col">
- <span>Include in filter</span>
- <span
- className="text-muted-foreground truncate font-mono"
- title={includeText}
- >
- {includeText}
- </span>
- </span>
- </DropdownMenuItem>
- {excludeClause ? (
- <DropdownMenuItem
- className="text-xs"
- onSelect={() => {
- track("exclude_filter");
- navigate(excludeClause, filter.target);
- }}
- >
- <FilterX size="base" color="default" __rawClassName="mr-2" />
- <span className="flex min-w-0 flex-col">
- <span>Exclude from filter</span>
- <span
- className="text-muted-foreground truncate font-mono"
- title={`-${includeText}`}
- >
- -{includeText}
- </span>
- </span>
- </DropdownMenuItem>
- ) : null}
- </>
- ) : null}
- </>
- );
-}
diff --git a/web/src/features/traces/fns/getAttributeRowActions.ts b/web/src/features/traces/fns/getAttributeRowActions.ts
new file mode 100644
index 0000000000..627d239e97
--- /dev/null
+++ b/web/src/features/traces/fns/getAttributeRowActions.ts
@@ -0,0 +1,115 @@
+/** Row menu for the Attributes table: copy, then include / exclude via the
+ * attribute's own table column. */
+
+import Router, { type NextRouter } from "next/router";
+import { type ComponentProps } from "react";
+import { Copy, Filter, FilterX } from "@langfuse/icons";
+import { type Row } from "@tanstack/react-table";
+import { type FilterState } from "@langfuse/shared";
+
+import { getCopyValue } from "@/src/components/table/ValueCell";
+import { type DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";
+import { type JsonTableRow } from "@/src/components/table/utils/jsonExpansionUtils";
+import { copyTextToClipboard } from "@/src/utils/clipboard";
+import { buildEventsTablePathForColumnFilter } from "@/src/features/events";
+import { attributeColumnFilter } from "@/src/features/traces/fns/attributeColumnFilter";
+import { attributeGrammar } from "@/src/features/traces/fns/attributeGrammar";
+import { type usePostHogClientCapture } from "@/src/features/posthog-analytics";
+
+export function getAttributeRowActions({
+ row,
+ projectId,
+ filterTarget,
+ anchorTime,
+ analyticsTable,
+ router,
+ capture,
+}: {
+ row: Row<JsonTableRow>;
+ projectId: string;
+ filterTarget: "observations" | "traces";
+ /** Keeps the target table's window covering the source row. */
+ anchorTime?: Date | null;
+ analyticsTable: "attributes" | "metadata";
+ router: Pick<NextRouter, "asPath" | "push">;
+ capture: ReturnType<typeof usePostHogClientCapture>;
+}) {
+ const { key, value, hasChildren } = row.original;
+ const isScalar =
+ typeof value === "string" ||
+ typeof value === "number" ||
+ typeof value === "boolean";
+ const valueText = isScalar ? String(value) : "";
+ const filter =
+ !isScalar || hasChildren || key == null
+ ? null
+ : attributeColumnFilter(key, valueText, filterTarget);
+ const includeText = filter ? attributeGrammar(key ?? "", valueText) : null;
+ const excludeClause = filter?.exclude;
+
+ const track = (action: "copy" | "include_filter" | "exclude_filter") =>
+ capture("trace_detail:attribute_table_action", {
+ table: analyticsTable,
+ action,
+ });
+
+ const navigate = (
+ clause: FilterState[number],
+ target: "observations" | "traces",
+ ) =>
+ router.push(
+ buildEventsTablePathForColumnFilter({
+ currentPath: Router.asPath,
+ projectId,
+ target,
+ filter: clause,
+ coverTime: anchorTime ?? undefined,
+ }),
+ );
+
+ const items: ComponentProps<typeof DropdownMenu>["items"] = [
+ {
+ type: "item",
+ id: "copy-value",
+ title: hasChildren ? "Copy structure" : "Copy value",
+ icon: Copy,
+ onClick: () => {
+ track("copy");
+ copyTextToClipboard(getCopyValue(value));
+ },
+ },
+ ];
+
+ if (filter && includeText) {
+ items.push(
+ { type: "separator", id: "filter-separator" },
+ {
+ type: "item",
+ id: "include-filter",
+ title: "Include in filter",
+ tooltip: includeText,
+ icon: Filter,
+ onClick: () => {
+ track("include_filter");
+ navigate(filter.include, filter.target);
+ },
+ },
+ );
+
+ if (excludeClause) {
+ items.push({
+ type: "item",
+ id: "exclude-filter",
+ title: "Exclude from filter",
+ tooltip: `-${includeText}`,
+ icon: FilterX,
+ onClick: () => {
+ track("exclude_filter");
+ navigate(excludeClause, filter.target);
+ },
+ });
+ }
+ }
+
+ return items;
+}
diff --git a/web/src/features/traces/fns/getMetadataRowActions.ts b/web/src/features/traces/fns/getMetadataRowActions.ts
new file mode 100644
index 0000000000..22891f9273
--- /dev/null
+++ b/web/src/features/traces/fns/getMetadataRowActions.ts
@@ -0,0 +1,134 @@
+import Router, { type NextRouter } from "next/router";
+import { type Row } from "@tanstack/react-table";
+import { Copy, Filter, FilterX } from "@langfuse/icons";
+import { type ComponentProps } from "react";
+import { type JsonTableRow } from "@/src/components/table/utils/jsonExpansionUtils";
+import { getCopyValue } from "@/src/components/table/ValueCell";
+import { type DropdownMenu } from "@/src/components/design-system/DropdownMenu/DropdownMenu";
+import { copyTextToClipboard } from "@/src/utils/clipboard";
+import {
+ buildEventsTablePathForMetadataFilter,
+ type MetadataFilterOperator,
+} from "@/src/features/events";
+
+/** Walks up to the top-level (level 0) ancestor key for a metadata row. */
+function resolveTopLevelMetadataKey(row: Row<JsonTableRow>): string {
+ let cursor: Row<JsonTableRow> | undefined = row;
+ while (cursor && cursor.original.level > 0) {
+ cursor = cursor.getParentRow() ?? undefined;
+ }
+ return cursor?.original.key ?? row.original.key;
+}
+
+/** Uses actual keys rather than hyphen-joined row IDs, preserving keys like x-request-id. */
+function resolveKeyPath(row: Row<JsonTableRow>): string {
+ const keys: string[] = [];
+ let cursor: Row<JsonTableRow> | undefined = row;
+ while (cursor) {
+ keys.unshift(String(cursor.original.key));
+ cursor = cursor.getParentRow() ?? undefined;
+ }
+ return keys.join(".");
+}
+
+export function getMetadataRowActions({
+ row,
+ projectId,
+ filterTarget,
+ router,
+}: {
+ row: Row<JsonTableRow>;
+ projectId: string;
+ filterTarget: "observations" | "traces";
+ router: Pick<NextRouter, "asPath" | "push">;
+}) {
+ const { value, type, hasChildren, level } = row.original;
+
+ const isScalar =
+ typeof value === "string" ||
+ typeof value === "number" ||
+ typeof value === "boolean";
+ const filterValue = isScalar ? String(value) : "";
+ // Nested values are matched against their JSON-encoded top-level branch.
+ // Hide shortcuts when escaping would make the displayed value fail to match.
+ // Top-level scalars are usually stored raw, including literal newlines.
+ const valueMatchesStoredForm =
+ level === 0 || JSON.stringify(filterValue).slice(1, -1) === filterValue;
+ const isScalarLeaf =
+ isScalar &&
+ !hasChildren &&
+ (type === "string" || type === "number" || type === "boolean") &&
+ // contains "" matches every row, including missing keys; its inverse matches none.
+ filterValue.length > 0 &&
+ valueMatchesStoredForm;
+
+ // Metadata is a flat Map(String, String), so nested values match a substring
+ // of their top-level branch. These operators keep Include and Exclude complements.
+ const metadataKey = resolveTopLevelMetadataKey(row);
+ const includeOperator: MetadataFilterOperator = "contains";
+ const excludeOperator: MetadataFilterOperator = "does not contain";
+ const displayValue = type === "string" ? `"${filterValue}"` : filterValue;
+
+ const handleCopyData = () => {
+ copyTextToClipboard(getCopyValue(value));
+ };
+ const handleCopyPath = () => {
+ copyTextToClipboard(resolveKeyPath(row));
+ };
+ const navigateWithFilter = (operator: MetadataFilterOperator) => {
+ router.push(
+ buildEventsTablePathForMetadataFilter({
+ currentPath: Router.asPath,
+ projectId,
+ metadataKey,
+ value: filterValue,
+ operator,
+ target: filterTarget,
+ }),
+ );
+ };
+
+ const includeFilterText = `metadata.${metadataKey} ${includeOperator} ${displayValue}`;
+ const excludeFilterText = `metadata.${metadataKey} ${excludeOperator} ${displayValue}`;
+
+ const items: ComponentProps<typeof DropdownMenu>["items"] = [
+ {
+ type: "item",
+ id: "copy-value",
+ title: hasChildren ? "Copy structure" : "Copy value",
+ icon: Copy,
+ onClick: handleCopyData,
+ },
+ {
+ type: "item",
+ id: "copy-path",
+ title: "Copy path",
+ icon: Copy,
+ onClick: handleCopyPath,
+ },
+ ];
+
+ if (isScalarLeaf) {
+ items.push(
+ { type: "separator", id: "filter-separator" },
+ {
+ type: "item",
+ id: "include-filter",
+ title: "Include in filter",
+ tooltip: includeFilterText,
+ icon: Filter,
+ onClick: () => navigateWithFilter(includeOperator),
+ },
+ {
+ type: "item",
+ id: "exclude-filter",
+ title: "Exclude from filter",
+ tooltip: excludeFilterText,
+ icon: FilterX,
+ onClick: () => navigateWithFilter(excludeOperator),
+ },
+ );
+ }
+
+ return items;
+}