🪢 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(web): polish media tags in json viewers (#14630)
Tobias Wochinger6af9e64b3b47
diff --git a/packages/shared/scripts/seeder/seed-postgres.ts b/packages/shared/scripts/seeder/seed-postgres.tsindex 48ec152ada..408d3933c8 100644--- a/packages/shared/scripts/seeder/seed-postgres.ts+++ b/packages/shared/scripts/seeder/seed-postgres.ts@@ -36,7 +36,6 @@ import {} from "./utils/seed-helpers";import { seedInAppAgentDemoConversation } from "./utils/in-app-agent-seed";import { seedDatasetVersions } from "./seed-dataset-versions";-import { seedMediaTraces } from "./seed-media";const options = {environment: { type: "string" },@@ -386,9 +385,6 @@ async function main() {await createDashboardsAndWidgets([project1, project2]);await seedDatasetVersions(prisma, [project1.id, project2.id]);- // Seed media test traces (uploads to MinIO + creates Media/TraceMedia records)- await seedMediaTraces(project1.id);-await prisma.llmSchema.createMany({data: [{diff --git a/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts b/packages/shared/scripts/seeder/utils/seeder-orchestrator.tsindex a2fd8c2771..fd3ff09b9f 100644--- a/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts+++ b/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts@@ -7,7 +7,11 @@ import { DataGenerator } from "./data-generators";import { ClickHouseQueryBuilder } from "./clickhouse-builder";import { FrameworkTraceLoader } from "./framework-traces/framework-trace-loader";import { EVAL_TRACE_COUNT, SEED_DATASETS } from "./postgres-seed-constants";-import { MEDIA_TEST_TRACE_IDS, getSeedMediaFixture } from "../seed-media";+import {+ MEDIA_TEST_TRACE_IDS,+ getSeedMediaFixture,+ seedMediaTraces,+} from "../seed-media";import {clickhouseClient,createTrace,@@ -484,6 +488,7 @@ export class SeederOrchestrator {for (const projectId of projectIds) {logger.info(`Processing media test traces for project ${projectId}`);+ await seedMediaTraces(projectId);const traces: TraceRecordInsertType[] = [// Trace 1: Image only (in input)diff --git a/web/src/components/editor/mediaTagWidget.tsx b/web/src/components/editor/mediaTagWidget.tsxnew file mode 100644index 0000000000..46e115a68f--- /dev/null+++ b/web/src/components/editor/mediaTagWidget.tsx@@ -0,0 +1,218 @@+import {+ Decoration,+ type DecorationSet,+ EditorView,+ MatchDecorator,+ ViewPlugin,+ type ViewUpdate,+ WidgetType,+} from "@uiw/react-codemirror";+import { type Extension } from "@codemirror/state";+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";+import { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";++type LangfuseRefDescriptor = Extract<+ MediaLeafDescriptor,+ { kind: "langfuseRef" }+>;++type MediaAnchor = {+ id: number;+ dom: HTMLElement;+ descriptor: LangfuseRefDescriptor;+ detachedFrames: number;+};++const EMPTY: MediaAnchor[] = [];++/**+ * Tracks the live media-chip anchor nodes a CodeMirror editor has created.+ * The CodeMirror widget can only produce a detached DOM node — which has no+ * access to the app's React providers (tRPC, router, layers) — so instead of+ * mounting React there, the widget registers an empty anchor here and the+ * in-tree portal host (`MediaTagWidgetPortals`) renders `JsonMediaTag` into it,+ * keeping the hover-peek's lazy fetch and popover working.+ */+class MediaTagWidgetStore {+ private anchors = new Map<number, MediaAnchor>();+ private listeners = new Set<() => void>();+ private nextId = 0;+ private snapshot: MediaAnchor[] = EMPTY;+ private emitScheduled = false;+ private sweepScheduled = false;++ register(dom: HTMLElement, descriptor: LangfuseRefDescriptor) {+ const id = this.nextId++;+ this.anchors.set(id, { id, dom, descriptor, detachedFrames: 0 });+ this.queueEmit();+ return id;+ }++ subscribe = (onChange: () => void) => {+ this.listeners.add(onChange);+ return () => this.listeners.delete(onChange);+ };++ getSnapshot = () => this.snapshot;++ private queueEmit() {+ if (this.emitScheduled) return;+ this.emitScheduled = true;+ queueMicrotask(() => {+ this.emitScheduled = false;+ this.emit();+ });+ }++ scheduleDetachedSweep() {+ if (this.sweepScheduled) return;+ this.sweepScheduled = true;+ const schedule =+ typeof requestAnimationFrame === "function"+ ? requestAnimationFrame+ : (callback: FrameRequestCallback) => window.setTimeout(callback, 0);++ schedule(() => {+ this.sweepScheduled = false;+ let changed = false;+ let hasDetachedAnchors = false;++ for (const [id, anchor] of this.anchors) {+ if (anchor.dom.isConnected) {+ anchor.detachedFrames = 0;+ continue;+ }++ anchor.detachedFrames += 1;+ hasDetachedAnchors = true;+ if (anchor.detachedFrames >= 3) {+ this.anchors.delete(id);+ changed = true;+ }+ }++ if (changed) this.queueEmit();+ if (hasDetachedAnchors) this.scheduleDetachedSweep();+ });+ }++ private emit() {+ this.snapshot = Array.from(this.anchors.values());+ this.listeners.forEach((l) => l());+ }+}++class MediaTagWidget extends WidgetType {+ private id?: number;++ constructor(+ private readonly store: MediaTagWidgetStore,+ private readonly descriptor: LangfuseRefDescriptor,+ ) {+ super();+ }++ eq(other: MediaTagWidget) {+ return other.descriptor.referenceString === this.descriptor.referenceString;+ }++ toDOM() {+ const dom = document.createElement("span");+ dom.style.verticalAlign = "middle";+ this.id = this.store.register(dom, this.descriptor);+ return dom;+ }++ destroy() {+ // CodeMirror may destroy/rebuild widget views during bracket/cursor+ // decoration updates. Treat destroy as a hint and only clean up anchors that+ // remain detached across frames, so transient redraws do not drop the+ // React portal that makes the chip hoverable.+ this.store.scheduleDetachedSweep();+ }++ // Let hover/focus reach the chip's React HoverCard rather than the editor.+ ignoreEvent() {+ return true;+ }+}++function createMediaTagWidgetExtension(store: MediaTagWidgetStore): Extension {+ const matcher = new MatchDecorator({+ // Swallow the surrounding JSON quotes into the replaced range so the chip+ // stands in for `"<tag>"` as a whole — otherwise the quotes render around+ // it. The tag itself (capture group) is what we classify. Fresh RegExp so+ // 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]);+ if (descriptor?.kind !== "langfuseRef") return null;+ return Decoration.replace({+ widget: new MediaTagWidget(store, descriptor),+ });+ },+ });++ return ViewPlugin.fromClass(+ class {+ decorations: DecorationSet;++ constructor(view: EditorView) {+ this.decorations = matcher.createDeco(view);+ }++ update(update: ViewUpdate) {+ this.decorations = matcher.updateDeco(update, this.decorations);+ store.scheduleDetachedSweep();+ }+ },+ {+ decorations: (plugin) => plugin.decorations,+ provide: (plugin) =>+ EditorView.atomicRanges.of(+ (view) => view.plugin(plugin)?.decorations ?? Decoration.none,+ ),+ },+ );+}++function MediaTagWidgetPortals({ store }: { store: MediaTagWidgetStore }) {+ const anchors = useSyncExternalStore(+ store.subscribe,+ store.getSnapshot,+ () => EMPTY,+ );+ return (+ <>+ {anchors.map((anchor) =>+ createPortal(+ <JsonMediaTag descriptor={anchor.descriptor} />,+ anchor.dom,+ String(anchor.id),+ ),+ )}+ </>+ );+}++/**+ * Renders Langfuse media reference tags in a CodeMirror editor as inline,+ * hover-to-peek chips. Spread `extension` into the editor's `extensions` and+ * render `portals` anywhere inside the component (it must stay within the app's+ * providers). The underlying tag text is preserved and treated atomically.+ */+export function useMediaTagChips() {+ const [store] = useState(() => new MediaTagWidgetStore());+ const extension = useMemo(+ () => createMediaTagWidgetExtension(store),+ [store],+ );+ const portals = <MediaTagWidgetPortals store={store} />;+ return { extension, portals };+}diff --git a/web/src/components/table/ValueCell.tsx b/web/src/components/table/ValueCell.tsxindex a6c4f35ceb..0eda1302b7 100644--- a/web/src/components/table/ValueCell.tsx+++ b/web/src/components/table/ValueCell.tsx@@ -3,6 +3,8 @@ 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 { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";import { copyTextToClipboard } from "@/src/utils/clipboard";import { Button } from "@/src/components/ui/button";import {@@ -365,6 +367,17 @@ export const ValueCell = memo(switch (type) {case "string": {const stringValue = String(value);++ // Render previewable media (Langfuse refs, data URIs, media URLs) as a+ // hover-to-peek chip instead of the raw string.+ const mediaDescriptor = classifyMediaLeaf(stringValue);+ if (mediaDescriptor) {+ return {+ content: <JsonMediaTag descriptor={mediaDescriptor} />,+ needsTruncation: false,+ };+ }+const needsTruncation = stringValue.length > MAX_CELL_DISPLAY_CHARS;const displayValue =needsTruncation && !isCellExpandeddiff --git a/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsx b/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsxindex 1a8ce4ce41..8b05bb8a2d 100644--- a/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsx+++ b/web/src/components/ui/AdvancedJsonViewer/components/JsonValue.tsx@@ -17,6 +17,8 @@ import {TooltipContent,TooltipTrigger,} from "@/src/components/ui/tooltip";+import { classifyMediaLeaf } from "@/src/components/ui/media/classifyMediaLeaf";+import { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";export function JsonValue({value,@@ -109,6 +111,13 @@ export function JsonValue({adjustedCommentRanges,);+ // 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);+ if (mediaDescriptor && segments.every((segment) => segment.type === null)) {+ return <JsonMediaTag descriptor={mediaDescriptor} />;+ }+return (<spanclassName={className}diff --git a/web/src/components/ui/CodeJsonViewer.tsx b/web/src/components/ui/CodeJsonViewer.tsxindex 0e57dba61c..31ce6690e7 100644--- a/web/src/components/ui/CodeJsonViewer.tsx+++ b/web/src/components/ui/CodeJsonViewer.tsx@@ -18,6 +18,8 @@ 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 { JsonMediaTag } from "@/src/components/ui/media/JsonMediaTag";import { MarkdownJsonViewHeader } from "@/src/components/ui/MarkdownJsonView";import {renderRichPromptContent,@@ -140,6 +142,15 @@ export function JSONView(props: {}displaySize={isCollapsed ? "collapsed" : "expanded"}matchesURL={true}+ // Render previewable media (Langfuse refs, data URIs, media URLs)+ // 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);+ return descriptor ? (+ <JsonMediaTag descriptor={descriptor} />+ ) : undefined;+ }}customizeCopy={(node) => stringifyJsonNode(node)}className="w-full max-w-full min-w-0"/>diff --git a/web/src/components/ui/media/JsonMediaTag.tsx b/web/src/components/ui/media/JsonMediaTag.tsxnew file mode 100644index 0000000000..28c245e22b--- /dev/null+++ b/web/src/components/ui/media/JsonMediaTag.tsx@@ -0,0 +1,52 @@+import { useState } from "react";+import { MediaTag } from "./MediaTag";+import { useResolvedMedia } from "./useResolvedMedia";+import { type MediaLeafDescriptor } from "./classifyMediaLeaf";++type LangfuseRefDescriptor = Extract<+ MediaLeafDescriptor,+ { kind: "langfuseRef" }+>;++/**+ * Container that connects a classified media leaf 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;+}) {+ if (descriptor.kind !== "langfuseRef") {+ return (+ <MediaTag+ contentType={descriptor.contentType}+ status="ready"+ url={descriptor.src}+ />+ );+ }++ return <LangfuseRefMediaTag descriptor={descriptor} />;+}++function LangfuseRefMediaTag({+ descriptor,+}: {+ descriptor: LangfuseRefDescriptor;+}) {+ const [armed, setArmed] = useState(false);+ const { status, url } = useResolvedMedia(descriptor, { enabled: armed });++ return (+ <MediaTag+ contentType={descriptor.contentType}+ status={status}+ url={url}+ onOpenChange={(open) => {+ if (open) setArmed(true);+ }}+ />+ );+}diff --git a/web/src/components/ui/media/MediaTag.clienttest.tsx b/web/src/components/ui/media/MediaTag.clienttest.tsxnew file mode 100644index 0000000000..bfc378c1a7--- /dev/null+++ b/web/src/components/ui/media/MediaTag.clienttest.tsx@@ -0,0 +1,49 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import { MediaTag } from "./MediaTag";++describe("MediaTag", () => {+ it("opens the preview on click", async () => {+ const onOpenChange = vi.fn();++ render(+ <MediaTag+ contentType="image/png"+ status="ready"+ url="data:image/png;base64,"+ onOpenChange={onOpenChange}+ />,+ );++ fireEvent.click(screen.getByRole("button", { name: "PNG media" }));++ expect(await screen.findByText("image/png")).toBeInTheDocument();+ expect(onOpenChange).toHaveBeenCalledWith(true);+ });++ it("opens the preview on touch pointer down", async () => {+ const onOpenChange = vi.fn();++ render(+ <MediaTag+ contentType="image/png"+ status="ready"+ url="data:image/png;base64,"+ onOpenChange={onOpenChange}+ />,+ );++ const event = new Event("pointerdown", {+ bubbles: true,+ cancelable: true,+ });+ Object.defineProperty(event, "pointerType", { value: "touch" });+ fireEvent(screen.getByRole("button", { name: "PNG media" }), event);++ expect(await screen.findByText("image/png")).toBeInTheDocument();+ expect(event.defaultPrevented).toBe(true);+ expect(onOpenChange).toHaveBeenCalledWith(true);+ expect(onOpenChange).toHaveBeenCalledTimes(1);+ });+});diff --git a/web/src/components/ui/media/MediaTag.stories.tsx b/web/src/components/ui/media/MediaTag.stories.tsxnew file mode 100644index 0000000000..4114a126ef--- /dev/null+++ b/web/src/components/ui/media/MediaTag.stories.tsx@@ -0,0 +1,116 @@+import { fn } from "storybook/test";+import preview from "../../../../.storybook/preview";+import { MediaTag } from "./MediaTag";++// Inline SVG so the "ready" image preview renders without any network.+const sampleImage =+ "data:image/svg+xml;utf8," ++ encodeURIComponent(+ `<svg xmlns="http://www.w3.org/2000/svg" width="320" height="200">+ <defs>+ <linearGradient id="g" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0" stop-color="#34d399"/>+ <stop offset="1" stop-color="#0ea5e9"/>+ </linearGradient>+ </defs>+ <rect width="320" height="200" fill="url(#g)"/>+ <text x="160" y="108" font-family="sans-serif" font-size="22"+ fill="white" text-anchor="middle">sample image</text>+ </svg>`,+ );++const meta = preview.meta({+ title: "components/media/MediaTag",+ component: MediaTag,+ args: {+ contentType: "image/png",+ onOpenChange: fn(),+ },+});++// Collapsed chip; hover/focus to open the peek. Loads "ready" content so the+// popover shows the image when opened.+export const Default = meta.story({+ args: {+ status: "ready",+ url: sampleImage,+ },+});++// Peek popover forced open with a resolved image.+export const PreviewImage = meta.story({+ args: {+ open: true,+ status: "ready",+ url: sampleImage,+ },+});++// A very high-resolution image must stay bounded by the popover's caps+// (max-height + the card's max-width), not render at intrinsic size.+const largeImage =+ "data:image/svg+xml;utf8," ++ encodeURIComponent(+ `<svg xmlns="http://www.w3.org/2000/svg" width="4000" height="3000">+ <rect width="4000" height="3000" fill="#0ea5e9"/>+ <text x="2000" y="1550" font-family="sans-serif" font-size="320"+ fill="white" text-anchor="middle">4000 x 3000</text>+ </svg>`,+ );++export const PreviewLargeImage = meta.story({+ args: {+ open: true,+ status: "ready",+ url: largeImage,+ },+});++// Peek popover while the URL is still resolving (hover-triggered fetch).+export const Loading = meta.story({+ args: {+ open: true,+ status: "loading",+ },+});++// Resolved media that failed to load.+export const Error = meta.story({+ args: {+ open: true,+ status: "error",+ },+});++// Audio resolves to an inline player rather than a thumbnail.+export const PreviewAudio = meta.story({+ args: {+ contentType: "audio/mpeg",+ open: true,+ status: "ready",+ url: "data:audio/mpeg;base64,",+ },+});++// Non-previewable type: chip + open-in-new-tab only, no inline preview.+export const PreviewFile = meta.story({+ args: {+ contentType: "application/pdf",+ open: true,+ status: "ready",+ url: "data:application/pdf;base64,",+ },+});++// Design showcase: one chip per media kind, collapsed.+export const AllKinds = meta.story({+ render: () => (+ <div className="flex flex-wrap items-center gap-3">+ <MediaTag contentType="image/jpeg" />+ <MediaTag contentType="audio/mpeg" />+ <MediaTag contentType="video/mp4" />+ <MediaTag contentType="application/pdf" />+ <MediaTag contentType="image/svg+xml" />+ </div>+ ),+});diff --git a/web/src/components/ui/media/MediaTag.tsx b/web/src/components/ui/media/MediaTag.tsxnew file mode 100644index 0000000000..601f79f9ac--- /dev/null+++ b/web/src/components/ui/media/MediaTag.tsx@@ -0,0 +1,235 @@+import * as React from "react";+import {+ ExternalLink,+ File,+ Image as ImageIcon,+ ImageOff,+ Video,+ Volume2,+ type LucideIcon,+} from "lucide-react";++import { Button } from "@/src/components/ui/button";+import { Skeleton } from "@/src/components/ui/skeleton";+import {+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+} from "@/src/components/ui/hover-card";++/**+ * Resolution state of the previewable content. The collapsed chip renders the+ * same regardless of status (it only needs `contentType`); status drives the+ * peek popover body. Owned by the container that fetches the URL — `MediaTag`+ * itself never fetches, which keeps it pure and Storybook-able.+ */+export type MediaTagStatus = "idle" | "loading" | "ready" | "error";++export interface MediaTagProps {+ /**+ * Full MIME type from the media reference (e.g. "image/png"). Known before+ * any fetch, so the chip + icon + label always render without a URL.+ */+ contentType: string;+ /** Peek-content resolution state. Defaults to "idle". */+ status?: MediaTagStatus;+ /**+ * Resolved URL for the preview and the "open in new tab" action. Only+ * meaningful when `status === "ready"`.+ */+ url?: string;+ /** Overrides the chip label (defaults to the MIME subtype, e.g. "JPEG"). */+ label?: string;+ /** Controlled open state of the peek popover (used by stories/tests). */+ open?: boolean;+ /**+ * Fired when the popover opens/closes. The container arms its lazy fetch on+ * the `true` transition (VSCode-peek semantics: pull content on hover).+ */+ onOpenChange?: (open: boolean) => void;+}++type MediaKind = "image" | "audio" | "video" | "file";++function getMediaKind(contentType: string): MediaKind {+ const top = contentType.split("/")[0]?.toLowerCase();+ if (top === "image") return "image";+ if (top === "audio") return "audio";+ if (top === "video") return "video";+ return "file";+}++/** "image/svg+xml" -> "SVG", "application/pdf" -> "PDF". */+function getDefaultLabel(contentType: string): string {+ const subtype = contentType.split("/")[1]?.split("+")[0];+ return (subtype || "file").toUpperCase();+}++const MEDIA_KIND_ICON = {+ image: ImageIcon,+ audio: Volume2,+ video: Video,+ file: File,+} satisfies Record<MediaKind, LucideIcon>;++function KindIcon({+ kind,+ className,+}: {+ kind: MediaKind;+ className?: string;+}) {+ const Icon = MEDIA_KIND_ICON[kind];+ return <Icon className={className} />;+}++const MEDIA_KIND_PREVIEW = {+ image: (url: string) => (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={url}+ alt=""+ // Bounded by the max-h cap and the card's max-w-sm; object-contain+ // keeps high-resolution images from blowing out the popover.+ className="max-h-64 max-w-full rounded object-contain"+ />+ ),+ video: (url: string) => (+ <video+ src={url}+ className="max-h-64 max-w-full rounded"+ controls+ muted+ playsInline+ preload="metadata"+ />+ ),+ audio: (url: string) => (+ <audio src={url} controls className="w-64" preload="metadata" />+ ),+ file: () => (+ <div className="text-muted-foreground flex h-24 w-64 flex-col items-center justify-center gap-2">+ <File className="h-5 w-5" />+ <span className="text-xs">No inline preview</span>+ </div>+ ),+} satisfies Record<MediaKind, (url: string) => React.ReactNode>;++/** The peek body — a glance, not a full player. Images/video show a thumbnail;+ * audio gets an inline player; other types are open-in-new-tab only. */+function PeekBody({+ kind,+ status,+ url,+}: {+ kind: MediaKind;+ status: MediaTagStatus;+ url?: string;+}) {+ if (status === "error") {+ return (+ <div className="text-muted-foreground flex h-24 w-64 flex-col items-center justify-center gap-2">+ <ImageOff className="h-5 w-5" />+ <span className="text-xs">Failed to load media</span>+ </div>+ );+ }++ if (status !== "ready" || !url) {+ return <Skeleton className="h-32 w-64" />;+ }++ return MEDIA_KIND_PREVIEW[kind](url);+}++/**+ * Pure, presentational media tag for use inside JSON viewers. Renders a compact+ * inline chip (icon + MIME label) that, on hover/focus, opens a read-only peek+ * popover with a preview and an "open in new tab" action.+ *+ * It receives the resolved `url` + `status` as props and never fetches — the+ * owning container (`JsonMediaTag`) gates a lazy fetch on `onOpenChange`.+ */+export const MediaTag = React.forwardRef<HTMLButtonElement, MediaTagProps>(+ ({ contentType, status = "idle", url, label, open, onOpenChange }, ref) => {+ const kind = getMediaKind(contentType);+ const chipLabel = label ?? getDefaultLabel(contentType);+ const canOpen = status === "ready" && Boolean(url);+ const isControlled = open !== undefined;+ const [uncontrolledOpen, setUncontrolledOpen] = React.useState(false);+ const isOpen = isControlled ? open : uncontrolledOpen;++ const setOpen = React.useCallback(+ (nextOpen: boolean) => {+ if (!isControlled) setUncontrolledOpen(nextOpen);+ onOpenChange?.(nextOpen);+ },+ [isControlled, onOpenChange],+ );++ const openPeek = React.useCallback(() => setOpen(true), [setOpen]);++ return (+ <HoverCard open={isOpen} onOpenChange={setOpen}>+ <HoverCardTrigger asChild>+ <button+ ref={ref}+ type="button"+ aria-label={`${chipLabel} media`}+ aria-expanded={isOpen}+ className="hover:bg-accent focus-visible:ring-ring bg-background inline-flex h-3.5 max-w-full items-center gap-1 rounded-sm border px-1 py-0 align-middle text-xs leading-none transition-colors focus-visible:ring-2 focus-visible:outline-hidden"+ onClick={openPeek}+ onPointerDown={(event) => {+ if (event.pointerType !== "mouse") {+ event.preventDefault();+ openPeek();+ }+ }}+ >+ <KindIcon kind={kind} className="h-2.5 w-2.5 shrink-0" />+ <span className="relative top-0.25 truncate align-baseline font-mono leading-none">+ {chipLabel}+ </span>+ </button>+ </HoverCardTrigger>+ <HoverCardContent+ align="start"+ className="flex w-auto max-w-sm flex-col gap-2 p-2"+ >+ <div className="flex items-center justify-between gap-4">+ <div className="text-muted-foreground flex min-w-0 items-center gap-1.5 text-xs">+ <KindIcon kind={kind} className="h-3.5 w-3.5 shrink-0" />+ <span className="truncate font-mono leading-none">+ {contentType}+ </span>+ </div>+ {canOpen ? (+ <Button+ asChild+ variant="outline"+ size="icon-xs"+ title="Open in new tab"+ >+ <a href={url} target="_blank" rel="noopener noreferrer">+ <ExternalLink className="h-3 w-3" />+ </a>+ </Button>+ ) : (+ <Button+ variant="outline"+ size="icon-xs"+ disabled+ title="Open in new tab"+ >+ <ExternalLink className="h-3 w-3" />+ </Button>+ )}+ </div>+ <PeekBody kind={kind} status={status} url={url} />+ </HoverCardContent>+ </HoverCard>+ );+ },+);++MediaTag.displayName = "MediaTag";diff --git a/web/src/components/ui/media/classifyMediaLeaf.clienttest.ts b/web/src/components/ui/media/classifyMediaLeaf.clienttest.tsnew file mode 100644index 0000000000..094aeaa929--- /dev/null+++ b/web/src/components/ui/media/classifyMediaLeaf.clienttest.ts@@ -0,0 +1,54 @@+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/classifyMediaLeaf.ts b/web/src/components/ui/media/classifyMediaLeaf.tsnew file mode 100644index 0000000000..38e87bd79e--- /dev/null+++ b/web/src/components/ui/media/classifyMediaLeaf.ts@@ -0,0 +1,105 @@+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 DATA_URI_PREFIX = "data:";+const MAX_LANGFUSE_REFERENCE_LENGTH = 512;++// Only surface a bare http(s) URL as media when its extension is unambiguous —+// otherwise every link in a payload would become a chip.+const URL_EXTENSION_TO_MIME: Record<string, string> = {+ png: "image/png",+ jpg: "image/jpeg",+ jpeg: "image/jpeg",+ gif: "image/gif",+ webp: "image/webp",+ svg: "image/svg+xml",+ bmp: "image/bmp",+ avif: "image/avif",+ tiff: "image/tiff",+ tif: "image/tiff",+ mp3: "audio/mpeg",+ wav: "audio/wav",+ ogg: "audio/ogg",+ oga: "audio/ogg",+ m4a: "audio/mp4",+ aac: "audio/aac",+ flac: "audio/flac",+ opus: "audio/opus",+ mp4: "video/mp4",+ webm: "video/webm",+ mov: "video/quicktime",+ mpeg: "video/mpeg",+};++// 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.+const MAX_URL_LENGTH = 2048;++/**+ * Classifies a JSON string leaf 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 {+ if (typeof value !== "string" || value.length === 0) return null;++ if (value.startsWith(LANGFUSE_MEDIA_PREFIX)) {+ if (value.length > MAX_LANGFUSE_REFERENCE_LENGTH) return null;+ const parsed = MediaReferenceStringSchema.safeParse(value);+ if (!parsed.success) return null;+ return {+ kind: "langfuseRef",+ contentType: parsed.data.type,+ mediaId: parsed.data.id,+ referenceString: parsed.data.referenceString,+ };+ }++ if (value.startsWith(DATA_URI_PREFIX)) {+ // Read only the head — a base64 payload can be megabytes long.+ const match = /^data:([\w.+-]+\/[\w.+-]+)/.exec(value.slice(0, 100));+ const contentType = match?.[1];+ if (!contentType) return null;+ if (!PREVIEWABLE_TOP_LEVEL.has(contentType.split("/")[0]!)) return null;+ return { kind: "dataUri", 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 null;+}++function mimeFromUrl(url: string): string | null {+ let pathname: string;+ try {+ pathname = new URL(url).pathname;+ } catch {+ return null;+ }+ const ext = pathname.split(".").pop()?.toLowerCase();+ if (!ext || ext === pathname) return null;+ return URL_EXTENSION_TO_MIME[ext] ?? null;+}diff --git a/web/src/components/ui/media/useResolvedMedia.ts b/web/src/components/ui/media/useResolvedMedia.tsnew file mode 100644index 0000000000..50fb4d89d2--- /dev/null+++ b/web/src/components/ui/media/useResolvedMedia.ts@@ -0,0 +1,44 @@+import { api } from "@/src/utils/api";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";+import { type MediaLeafDescriptor } from "./classifyMediaLeaf";+import { type MediaTagStatus } from "./MediaTag";++type LangfuseRefDescriptor = Extract<+ MediaLeafDescriptor,+ { kind: "langfuseRef" }+>;++/**+ * Resolves the previewable URL for a media descriptor.+ *+ * - Langfuse refs fetch a presigned S3 URL via tRPC, but only once `enabled`+ * flips true (the peek opens) — this is what keeps a JSON view with N media+ * leaves from firing N `getById` requests on render. Query config mirrors+ * `LangfuseMediaView` (55-min staleTime ≈ S3 link TTL), so re-hovers are+ * served from cache.+ */+export function useResolvedMedia(+ descriptor: LangfuseRefDescriptor,+ { enabled }: { enabled: boolean },+): { status: MediaTagStatus; url?: string } {+ const projectId = useProjectIdFromURL();++ const query = api.media.getById.useQuery(+ {+ mediaId: descriptor.mediaId,+ projectId: projectId as string,+ },+ {+ enabled: enabled && Boolean(projectId),+ refetchOnWindowFocus: false,+ refetchOnMount: false,+ refetchOnReconnect: false,+ staleTime: 55 * 60 * 1000, // S3 links expire after 1 hour+ },+ );++ if (!enabled || !projectId) return { status: "idle" };+ if (query.isError) return { status: "error" };+ if (query.data?.url) return { status: "ready", url: query.data.url };+ return { status: "loading" };+}diff --git a/web/src/features/datasets/components/DatasetItemField.tsx b/web/src/features/datasets/components/DatasetItemField.tsxindex 680ad87d65..27bb5989f1 100644--- a/web/src/features/datasets/components/DatasetItemField.tsx+++ b/web/src/features/datasets/components/DatasetItemField.tsx@@ -2,6 +2,7 @@ import { useCallback, useMemo, useRef } from "react";import { type ReactCodeMirrorRef } from "@uiw/react-codemirror";import { CodeMirrorEditor } from "@/src/components/editor";+import { useMediaTagChips } from "@/src/components/editor/mediaTagWidget";import { DatasetSchemaHoverCard } from "./DatasetSchemaHoverCard";import { DatasetItemFieldSchemaErrors } from "./DatasetItemFieldSchemaErrors";import {@@ -83,20 +84,25 @@ export const DatasetItemField = ({onChangeRef.current = onChange;const handleChange = useCallback((v: string) => onChangeRef.current?.(v), []);- // Drop/paste of files mirrors the attach button: upload, then insert the- // reference string. Only wired in editable form mode so read-only/view+ // Always render media reference tags as inline chips (read-only and form).+ // Drop/paste of files mirrors the attach button (upload, then insert the+ // reference string) and is only wired in editable form mode so read-only/view// editors keep native drop/paste behavior.- const mediaEditorExtensions = useMemo(- () =>- showMediaUpload+ const { extension: mediaChipExtension, portals: mediaChipPortals } =+ useMediaTagChips();+ const editorExtensions = useMemo(+ () => [+ mediaChipExtension,+ ...(showMediaUpload? [createMediaDropPasteExtension({onUploadMedia: (file) =>onUploadMediaRef.current?.(file) ?? Promise.resolve(null),}),]- : undefined,- [showMediaUpload],+ : []),+ ],+ [mediaChipExtension, showMediaUpload],);const content = (@@ -128,7 +134,7 @@ export const DatasetItemField = ({editable={editable}editorRef={editorRef}minHeight={200}- extensions={mediaEditorExtensions}+ extensions={editorExtensions}/></FormControl>) : (@@ -137,8 +143,10 @@ export const DatasetItemField = ({value={value}editable={editable}minHeight={200}+ extensions={editorExtensions}/>)}+ {mediaChipPortals}{isFormField && <FormMessage />}{showErrors && hasSchemas && errors.length > 0 && (<DatasetItemFieldSchemaErrors errors={errors} showDatasetName={false} />diff --git a/web/src/features/datasets/components/DatasetItemMediaAttachments.clienttest.ts b/web/src/features/datasets/components/DatasetItemMediaAttachments.clienttest.tsindex c89867d40f..fc3fc9fcd9 100644--- a/web/src/features/datasets/components/DatasetItemMediaAttachments.clienttest.ts+++ b/web/src/features/datasets/components/DatasetItemMediaAttachments.clienttest.ts@@ -1,6 +1,9 @@import { describe, expect, it } from "vitest";-import { collectMediaReferenceStrings } from "./DatasetItemMediaAttachments";+import {+ collectMediaReferenceStrings,+ getMediaReferenceInsertRange,+} from "./DatasetItemMediaAttachments";const imageRef ="@@@langfuseMedia:type=image/png|id=cc48838a-3da8-4ca4-a007-2cf8df930e69|source=bytes@@@";@@ -39,3 +42,34 @@ describe("collectMediaReferenceStrings", () => {).toEqual([imageRef]);});});++describe("getMediaReferenceInsertRange", () => {+ const doc = (value: string) => ({+ length: value.length,+ sliceString: (from: number, to?: number) => value.slice(from, to),+ });++ it("replaces an empty JSON string when the cursor is between the quotes", () => {+ expect(+ getMediaReferenceInsertRange(doc('{ "image": "" }'), 12, 12),+ ).toEqual({ from: 11, to: 13 });+ });++ it("replaces a selected empty JSON string", () => {+ expect(+ getMediaReferenceInsertRange(doc('{ "image": "" }'), 11, 13),+ ).toEqual({ from: 11, to: 13 });+ });++ it("keeps normal insertion ranges unchanged", () => {+ expect(+ getMediaReferenceInsertRange(doc('{ "image": null }'), 11, 15),+ ).toEqual({ from: 11, to: 15 });+ });++ it("does not replace non-empty JSON string boundaries", () => {+ expect(+ getMediaReferenceInsertRange(doc('{ "image": "x" }'), 12, 12),+ ).toEqual({ from: 12, to: 12 });+ });+});diff --git a/web/src/features/datasets/components/DatasetItemMediaAttachments.tsx b/web/src/features/datasets/components/DatasetItemMediaAttachments.tsxindex 3dd8a156d5..6cd5158c02 100644--- a/web/src/features/datasets/components/DatasetItemMediaAttachments.tsx+++ b/web/src/features/datasets/components/DatasetItemMediaAttachments.tsx@@ -55,6 +55,33 @@ export function collectMediaReferenceStrings(return [...byMediaId.values()];}+type SliceableDoc = {+ readonly length: number;+ sliceString(from: number, to?: number): string;+};++export function getMediaReferenceInsertRange(+ doc: SliceableDoc,+ from: number,+ to: number,+) {+ if (doc.sliceString(from, to) === '""') {+ return { from, to };+ }++ if (+ from === to &&+ from > 0 &&+ from < doc.length &&+ doc.sliceString(from - 1, from) === '"' &&+ doc.sliceString(from, from + 1) === '"'+ ) {+ return { from: from - 1, to: from + 1 };+ }++ return { from, to };+}+/*** Inserts a media reference as a JSON string literal. Wrapping in quotes makes* it a valid value when inserted in a value slot; the form's JSON validation@@ -72,9 +99,10 @@ function insertMediaReferenceIntoView(anchor != null ? Math.min(anchor, view.state.doc.length) : undefined;const { from, to } =pos != null ? { from: pos, to: pos } : view.state.selection.main;+ const range = getMediaReferenceInsertRange(view.state.doc, from, to);view.dispatch({- changes: { from, to, insert },- selection: { anchor: from + insert.length },+ changes: { ...range, insert },+ selection: { anchor: range.from + insert.length },});view.focus();}diff --git a/web/src/features/datasets/components/NewDatasetItemForm.tsx b/web/src/features/datasets/components/NewDatasetItemForm.tsxindex feb7b811e4..890648eed6 100644--- a/web/src/features/datasets/components/NewDatasetItemForm.tsx+++ b/web/src/features/datasets/components/NewDatasetItemForm.tsx@@ -23,6 +23,7 @@ import {import { showErrorToast } from "@/src/features/notifications/showErrorToast";import { type ReactCodeMirrorRef } from "@uiw/react-codemirror";import { CodeMirrorEditor } from "@/src/components/editor";+import { useMediaTagChips } from "@/src/components/editor/mediaTagWidget";import { type Prisma } from "@langfuse/shared";import { cn } from "@/src/utils/tailwind";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -200,13 +201,16 @@ export const NewDatasetItemForm = (props: {// extension once and avoid reconfiguring CodeMirror on every keystroke.const uploadFileRef = useRef(uploadMedia);uploadFileRef.current = uploadMedia;+ const { extension: mediaChipExtension, portals: mediaChipPortals } =+ useMediaTagChips();const mediaDropPasteExtensions = useMemo(() => [+ mediaChipExtension,createMediaDropPasteExtension({onUploadMedia: (file) => uploadFileRef.current(file),}),],- [],+ [mediaChipExtension],);const hasInitialValues = Boolean(@@ -582,6 +586,7 @@ export const NewDatasetItemForm = (props: {) : null}</div></DialogFooter>+ {mediaChipPortals}</form></Form>);