🪢 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): render media refs in compact table rows (#14703)
Tobias Wochinger04c54a0f070f
diff --git a/web/src/components/editor/mediaTagWidget.tsx b/web/src/components/editor/mediaTagWidget.tsxindex 46e115a68f..6760ec32d9 100644--- a/web/src/components/editor/mediaTagWidget.tsx+++ b/web/src/components/editor/mediaTagWidget.tsx@@ -12,15 +12,12 @@ import { useMemo, useState, useSyncExternalStore } from "react";import { createPortal } from "react-dom";import { MEDIA_REFERENCE_PATTERN } from "@langfuse/shared";import {- classifyMediaLeaf,- type MediaLeafDescriptor,-} from "@/src/components/ui/media/classifyMediaLeaf";+ classifyMediaValue,+ type MediaDescriptor,+} from "@/src/components/ui/media/mediaUtils";import { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";-type LangfuseRefDescriptor = Extract<- MediaLeafDescriptor,- { kind: "langfuseRef" }->;+type LangfuseRefDescriptor = Extract<MediaDescriptor, { kind: "langfuseRef" }>;type MediaAnchor = {id: number;@@ -151,7 +148,7 @@ function createMediaTagWidgetExtension(store: MediaTagWidgetStore): Extension {// the shared pattern's lastIndex isn't mutated across uses.regexp: new RegExp(`"(${MEDIA_REFERENCE_PATTERN.source})"`, "g"),decoration: (match) => {- const descriptor = classifyMediaLeaf(match[1]);+ const descriptor = classifyMediaValue(match[1]);if (descriptor?.kind !== "langfuseRef") return null;return Decoration.replace({widget: new MediaTagWidget(store, descriptor),diff --git a/web/src/components/table/ValueCell.tsx b/web/src/components/table/ValueCell.tsxindex 5b4fa46aeb..59f8f4974c 100644--- a/web/src/components/table/ValueCell.tsx+++ b/web/src/components/table/ValueCell.tsx@@ -3,7 +3,7 @@ import { useRouter } from "next/router";import { type Row } from "@tanstack/react-table";import { urlRegex } from "@langfuse/shared";import { type JsonTableRow } from "@/src/components/table/utils/jsonExpansionUtils";-import { classifyMediaLeaf } from "@/src/components/ui/media/classifyMediaLeaf";+import { classifyMediaValue } from "@/src/components/ui/media/mediaUtils";import { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";import { copyTextToClipboard } from "@/src/utils/clipboard";import { Button } from "@/src/components/ui/button";@@ -379,7 +379,7 @@ export const ValueCell = memo(// Render previewable media (Langfuse refs, data URIs, media URLs) as a// hover-to-peek chip instead of the raw string.- const mediaDescriptor = classifyMediaLeaf(stringValue);+ const mediaDescriptor = classifyMediaValue(stringValue);if (mediaDescriptor) {return {content: <JsonMediaTag descriptor={mediaDescriptor} />,diff --git a/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsx b/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsxindex 8b05bb8a2d..a73161c288 100644--- a/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsx+++ b/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsx@@ -17,7 +17,7 @@ import {TooltipContent,TooltipTrigger,} from "@/src/components/ui/tooltip";-import { classifyMediaLeaf } from "@/src/components/ui/media/classifyMediaLeaf";+import { classifyMediaValue } from "@/src/components/ui/media/mediaUtils";import { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";export function JsonValue({@@ -113,7 +113,7 @@ export function JsonValue({// Render previewable media as a hover-to-peek chip only when the existing// text highlighter found no search/comment overlays to preserve.- const mediaDescriptor = classifyMediaLeaf(str);+ const mediaDescriptor = classifyMediaValue(str);if (mediaDescriptor && segments.every((segment) => segment.type === null)) {return <JsonMediaTag descriptor={mediaDescriptor} />;}diff --git a/web/src/components/ui/CodeJsonViewer.tsx b/web/src/components/ui/CodeJsonViewer.tsxindex b2b446837d..8624eff872 100644--- a/web/src/components/ui/CodeJsonViewer.tsx+++ b/web/src/components/ui/CodeJsonViewer.tsx@@ -18,7 +18,7 @@ import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePosimport { useMarkdownContext } from "@/src/features/theming/useMarkdownContext";import { type MediaReturnType } from "@/src/features/media/validation";import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";-import { classifyMediaLeaf } from "@/src/components/ui/media/classifyMediaLeaf";+import { classifyMediaValue } from "@/src/components/ui/media/mediaUtils";import { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";import { MarkdownJsonViewHeader } from "@/src/components/ui/MarkdownJsonView";import {@@ -146,7 +146,7 @@ export function JSONView(props: {// as a hover-to-peek chip instead of the raw string; everything// else falls through to the default value rendering.customizeNode={({ node }) => {- const descriptor = classifyMediaLeaf(node);+ const descriptor = classifyMediaValue(node);return descriptor ? (<JsonMediaTag descriptor={descriptor} />) : undefined;diff --git a/web/src/components/ui/IOTableCell.tsx b/web/src/components/ui/IOTableCell.tsxindex c4b80d01e0..282e91fb76 100644--- a/web/src/components/ui/IOTableCell.tsx+++ b/web/src/components/ui/IOTableCell.tsx@@ -4,6 +4,8 @@ import {IO_TABLE_CHAR_LIMIT,JSONView,} from "@/src/components/ui/CodeJsonViewer";+import { splitStringByMediaReferences } from "@/src/components/ui/media/mediaUtils";+import { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";import { cn } from "@/src/utils/tailwind";import { memo } from "react";import {@@ -20,6 +22,25 @@ const ioTableCellPaddingClassNames: Record<IOTableCellPadding, string> = {compact: "px-1 py-1",};+function renderStringWithMediaReferences(value: string) {+ const segments = splitStringByMediaReferences(value);++ if (segments.length === 1 && segments[0]?.type === "text") {+ return value;+ }++ return segments.map((segment, index) =>+ segment.type === "media" ? (+ <JsonMediaTag+ key={`${segment.value}-${index}`}+ descriptor={segment.descriptor}+ />+ ) : (+ segment.value+ ),+ );+}+const IOTableCellContent = ({data,singleLine,@@ -52,7 +73,7 @@ const IOTableCellContent = ({)}title={singleLineText}>- {singleLineText}+ {singleLineText ? renderStringWithMediaReferences(singleLineText) : null}</div>) : shouldTruncate ? (<div className="grid h-full grid-cols-1">diff --git a/web/src/components/ui/media/JsonMediaTag.tsx b/web/src/components/ui/media/JsonMediaTag.tsxindex 28c245e22b..597c1aa304 100644--- a/web/src/components/ui/media/JsonMediaTag.tsx+++ b/web/src/components/ui/media/JsonMediaTag.tsx@@ -1,23 +1,16 @@import { useState } from "react";import { MediaTag } from "./MediaTag";import { useResolvedMedia } from "./useResolvedMedia";-import { type MediaLeafDescriptor } from "./classifyMediaLeaf";+import { type MediaDescriptor } from "./mediaUtils";-type LangfuseRefDescriptor = Extract<- MediaLeafDescriptor,- { kind: "langfuseRef" }->;+type LangfuseRefDescriptor = Extract<MediaDescriptor, { kind: "langfuseRef" }>;/**- * Container that connects a classified media leaf to the pure `MediaTag`: it+ * Container that connects a classified media value to the pure `MediaTag`: it* arms the lazy fetch the first time the peek opens (hover/focus) and keeps it* armed so re-hovers read from the query cache instead of re-fetching.*/-export function JsonMediaTag({- descriptor,-}: {- descriptor: MediaLeafDescriptor;-}) {+export function JsonMediaTag({ descriptor }: { descriptor: MediaDescriptor }) {if (descriptor.kind !== "langfuseRef") {return (<MediaTagdiff --git a/web/src/components/ui/media/classifyMediaLeaf.clienttest.ts b/web/src/components/ui/media/classifyMediaLeaf.clienttest.tsdeleted file mode 100644index 094aeaa929..0000000000--- a/web/src/components/ui/media/classifyMediaLeaf.clienttest.ts+++ /dev/null@@ -1,54 +0,0 @@-import { describe, expect, it } from "vitest";-import { classifyMediaLeaf } from "@/src/components/ui/media/classifyMediaLeaf";--describe("classifyMediaLeaf", () => {- const ref =- "@@@langfuseMedia:type=image/png|id=cc48838a-3da8-4ca4-a007-2cf8df930e69|source=bytes@@@";-- it("parses a Langfuse media reference", () => {- expect(classifyMediaLeaf(ref)).toEqual({- kind: "langfuseRef",- contentType: "image/png",- mediaId: "cc48838a-3da8-4ca4-a007-2cf8df930e69",- referenceString: ref,- });- });-- it("parses a data URI by its MIME head, not the whole payload", () => {- const src = "data:image/jpeg;base64," + "A".repeat(5000);- expect(classifyMediaLeaf(src)).toEqual({- kind: "dataUri",- contentType: "image/jpeg",- src,- });- });-- it("ignores non-previewable data URIs", () => {- expect(classifyMediaLeaf("data:text/plain,hello")).toBeNull();- });-- it("classifies image/audio/video URLs by extension", () => {- expect(classifyMediaLeaf("https://x.com/a/b.png")?.contentType).toBe(- "image/png",- );- expect(- classifyMediaLeaf("https://x.com/a/song.mp3?sig=1")?.contentType,- ).toBe("audio/mpeg");- });-- it("ignores non-media and malformed inputs", () => {- expect(classifyMediaLeaf("https://example.com/page")).toBeNull();- expect(classifyMediaLeaf("just a string")).toBeNull();- expect(classifyMediaLeaf(`Compare ${ref} against this.`)).toBeNull();- expect(classifyMediaLeaf("@@@langfuseMedia:garbage@@@")).toBeNull();- expect(classifyMediaLeaf(42)).toBeNull();- expect(classifyMediaLeaf(null)).toBeNull();- expect(classifyMediaLeaf("")).toBeNull();- });-- it("does not parse oversized malformed media references", () => {- expect(- classifyMediaLeaf(`@@@langfuseMedia:${"x".repeat(1000)}@@@`),- ).toBeNull();- });-});diff --git a/web/src/components/ui/media/mediaUtils.clienttest.ts b/web/src/components/ui/media/mediaUtils.clienttest.tsnew file mode 100644index 0000000000..7584be4cd9--- /dev/null+++ b/web/src/components/ui/media/mediaUtils.clienttest.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from "vitest";+import {+ classifyMediaValue,+ splitStringByMediaReferences,+} from "@/src/components/ui/media/mediaUtils";++describe("classifyMediaValue", () => {+ const ref =+ "@@@langfuseMedia:type=image/png|id=cc48838a-3da8-4ca4-a007-2cf8df930e69|source=bytes@@@";++ it("parses a Langfuse media reference", () => {+ expect(classifyMediaValue(ref)).toEqual({+ kind: "langfuseRef",+ contentType: "image/png",+ mediaId: "cc48838a-3da8-4ca4-a007-2cf8df930e69",+ referenceString: ref,+ });+ });++ it("parses a data URI by its MIME head, not the whole payload", () => {+ const src = "data:image/jpeg;base64," + "A".repeat(5000);+ expect(classifyMediaValue(src)).toEqual({+ kind: "dataUri",+ contentType: "image/jpeg",+ src,+ });+ });++ it("ignores non-previewable data URIs", () => {+ expect(classifyMediaValue("data:text/plain,hello")).toBeNull();+ });++ it("classifies image/audio/video URLs by extension", () => {+ expect(classifyMediaValue("https://x.com/a/b.png")?.contentType).toBe(+ "image/png",+ );+ expect(+ classifyMediaValue("https://x.com/a/song.mp3?sig=1")?.contentType,+ ).toBe("audio/mpeg");+ });++ it("ignores non-media and malformed inputs", () => {+ expect(classifyMediaValue("https://example.com/page")).toBeNull();+ expect(classifyMediaValue("just a string")).toBeNull();+ expect(classifyMediaValue(`Compare ${ref} against this.`)).toBeNull();+ expect(classifyMediaValue("@@@langfuseMedia:garbage@@@")).toBeNull();+ expect(classifyMediaValue(42)).toBeNull();+ expect(classifyMediaValue(null)).toBeNull();+ expect(classifyMediaValue("")).toBeNull();+ });++ it("does not parse oversized malformed media references", () => {+ expect(+ classifyMediaValue(`@@@langfuseMedia:${"x".repeat(1000)}@@@`),+ ).toBeNull();+ });++ it("splits valid media references out of larger strings", () => {+ expect(splitStringByMediaReferences(`{"image":"${ref}"}`)).toEqual([+ { type: "text", value: '{"image":"' },+ {+ type: "media",+ value: ref,+ descriptor: {+ kind: "langfuseRef",+ contentType: "image/png",+ mediaId: "cc48838a-3da8-4ca4-a007-2cf8df930e69",+ referenceString: ref,+ },+ },+ { type: "text", value: '"}' },+ ]);+ });+});diff --git a/web/src/components/ui/media/classifyMediaLeaf.ts b/web/src/components/ui/media/mediaUtils.tssimilarity index 61%rename from web/src/components/ui/media/classifyMediaLeaf.tsrename to web/src/components/ui/media/mediaUtils.tsindex 38e87bd79e..34b0e8e6ad 100644--- a/web/src/components/ui/media/classifyMediaLeaf.ts+++ b/web/src/components/ui/media/mediaUtils.ts@@ -1,22 +1,7 @@import { MediaReferenceStringSchema } from "@langfuse/shared";-/**- * A JSON string leaf classified as previewable media. `contentType` is always- * known here without any fetch, so the collapsed chip can render from it alone.- * Langfuse refs resolve their URL lazily (via `useResolvedMedia`); data URIs- * and plain URLs carry their own `src`.- */-export type MediaLeafDescriptor =- | {- kind: "langfuseRef";- contentType: string;- mediaId: string;- referenceString: string;- }- | { kind: "dataUri"; contentType: string; src: string }- | { kind: "url"; contentType: string; src: string };-const LANGFUSE_MEDIA_PREFIX = "@@@langfuseMedia:";+const LANGFUSE_MEDIA_REFERENCE_PATTERN = /@@@langfuseMedia:[^@]*@@@/g;const DATA_URI_PREFIX = "data:";const MAX_LANGFUSE_REFERENCE_LENGTH = 512;@@ -50,15 +35,15 @@ const URL_EXTENSION_TO_MIME: Record<string, string> = {// data: URIs are only surfaced for genuinely-previewable top-level types.const PREVIEWABLE_TOP_LEVEL = new Set(["image", "audio", "video"]);-// Guards the per-leaf hot path: bail before parsing a URL out of long strings.+// Guards the per-value hot path: bail before parsing a URL out of long strings.const MAX_URL_LENGTH = 2048;/**- * Classifies a JSON string leaf as previewable media, or returns null. Pure and+ * Classifies a string value as previewable media, or returns null. Pure and* cheap: a prefix check gates every branch so non-media strings (the common* case, possibly thousands per view) cost only a couple of `startsWith` calls.*/-export function classifyMediaLeaf(value: unknown): MediaLeafDescriptor | null {+export function classifyMediaValue(value: unknown) {if (typeof value !== "string" || value.length === 0) return null;if (value.startsWith(LANGFUSE_MEDIA_PREFIX)) {@@ -66,7 +51,7 @@ export function classifyMediaLeaf(value: unknown): MediaLeafDescriptor | null {const parsed = MediaReferenceStringSchema.safeParse(value);if (!parsed.success) return null;return {- kind: "langfuseRef",+ kind: "langfuseRef" as const,contentType: parsed.data.type,mediaId: parsed.data.id,referenceString: parsed.data.referenceString,@@ -79,20 +64,62 @@ export function classifyMediaLeaf(value: unknown): MediaLeafDescriptor | null {const contentType = match?.[1];if (!contentType) return null;if (!PREVIEWABLE_TOP_LEVEL.has(contentType.split("/")[0]!)) return null;- return { kind: "dataUri", contentType, src: value };+ return { kind: "dataUri" as const, contentType, src: value };}if (value.startsWith("http://") || value.startsWith("https://")) {if (value.length > MAX_URL_LENGTH) return null;const contentType = mimeFromUrl(value);if (!contentType) return null;- return { kind: "url", contentType, src: value };+ return { kind: "url" as const, contentType, src: value };}return null;}-function mimeFromUrl(url: string): string | null {+export type MediaDescriptor = NonNullable<+ ReturnType<typeof classifyMediaValue>+>;++export function splitStringByMediaReferences(value: string) {+ const segments: Array<+ | { type: "text"; value: string }+ | {+ type: "media";+ value: string;+ descriptor: MediaDescriptor;+ }+ > = [];+ let lastIndex = 0;++ for (const match of value.matchAll(LANGFUSE_MEDIA_REFERENCE_PATTERN)) {+ const reference = match[0];+ const index = match.index ?? 0;+ const descriptor = classifyMediaValue(reference);++ if (!descriptor) continue;++ if (index > lastIndex) {+ segments.push({ type: "text", value: value.slice(lastIndex, index) });+ }++ segments.push({ type: "media", value: reference, descriptor });+ lastIndex = index + reference.length;+ }++ if (segments.length === 0) {+ segments.push({ type: "text", value });+ return segments;+ }++ if (lastIndex < value.length) {+ segments.push({ type: "text", value: value.slice(lastIndex) });+ }++ return segments;+}++function mimeFromUrl(url: string) {let pathname: string;try {pathname = new URL(url).pathname;diff --git a/web/src/components/ui/media/useResolvedMedia.ts b/web/src/components/ui/media/useResolvedMedia.tsindex 50fb4d89d2..57948cfcf5 100644--- a/web/src/components/ui/media/useResolvedMedia.ts+++ b/web/src/components/ui/media/useResolvedMedia.ts@@ -1,12 +1,9 @@import { api } from "@/src/utils/api";import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";-import { type MediaLeafDescriptor } from "./classifyMediaLeaf";+import { type MediaDescriptor } from "./mediaUtils";import { type MediaTagStatus } from "./MediaTag";-type LangfuseRefDescriptor = Extract<- MediaLeafDescriptor,- { kind: "langfuseRef" }->;+type LangfuseRefDescriptor = Extract<MediaDescriptor, { kind: "langfuseRef" }>;/*** Resolves the previewable URL for a media descriptor.