Skip to content

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

fix(web): prevent media tags from appearing squished (#18524)

Tobias Wochinger95816be3ae81
diff --git a/packages/shared/src/server/services/StorageService.ts b/packages/shared/src/server/services/StorageService.ts
index 425037dc0f..4c591fc431 100644
--- a/packages/shared/src/server/services/StorageService.ts
+++ b/packages/shared/src/server/services/StorageService.ts
@@ -3,6 +3,7 @@ import { pipeline } from "stream/promises";
import {
DeleteObjectsCommand,
GetObjectCommand,
+ HeadObjectCommand,
ListObjectsV2Command,
PutObjectCommand,
PutObjectCommandInput,
@@ -319,6 +320,8 @@ export interface StorageService {
asAttachment?: boolean,
): Promise<string>;
+ getObjectContentLength(path: string): Promise<number | undefined>;
+
getSignedUploadUrl(params: {
path: string;
ttlSeconds: number;
@@ -706,6 +709,19 @@ class AzureBlobStorageService implements StorageService {
}
}
+ public async getObjectContentLength(
+ path: string,
+ ): Promise<number | undefined> {
+ try {
+ await this.createContainerIfNotExists();
+ const properties = await this.client.getBlobClient(path).getProperties();
+ return properties.contentLength;
+ } catch (err) {
+ logger.error(`Failed to read Azure Blob Storage metadata ${path}`, err);
+ handleStorageError(err, "read Azure Blob Storage metadata");
+ }
+ }
+
public async getSignedUploadUrl(params: {
path: string;
ttlSeconds: number;
@@ -1064,6 +1080,23 @@ class S3StorageService implements StorageService {
}
}
+ public async getObjectContentLength(
+ path: string,
+ ): Promise<number | undefined> {
+ try {
+ const response = await this.client.send(
+ new HeadObjectCommand({
+ Bucket: this.bucketName,
+ Key: path,
+ }),
+ );
+ return response.ContentLength;
+ } catch (err) {
+ this.logClientFailure(`Failed to read S3 object metadata ${path}`, err);
+ handleStorageError(err, "read S3 object metadata");
+ }
+ }
+
public async deleteFiles(paths: string[]): Promise<void> {
await backOff(() => this.deleteFilesNonRetrying(paths), {
numOfAttempts: 3,
@@ -1346,6 +1379,19 @@ class GoogleCloudStorageService implements StorageService {
}
}
+ public async getObjectContentLength(
+ path: string,
+ ): Promise<number | undefined> {
+ try {
+ const [metadata] = await this.bucket.file(path).getMetadata();
+ const contentLength = Number(metadata.size);
+ return Number.isFinite(contentLength) ? contentLength : undefined;
+ } catch (err) {
+ logger.error(`Failed to read Google Cloud Storage metadata ${path}`, err);
+ handleStorageError(err, "read Google Cloud Storage metadata");
+ }
+ }
+
public async getSignedUploadUrl(params: {
path: string;
ttlSeconds: number;
@@ -1863,6 +1909,23 @@ class OCIObjectStorageService implements StorageService {
}
}
+ public async getObjectContentLength(
+ path: string,
+ ): Promise<number | undefined> {
+ try {
+ const { client, namespaceName } = await this.getClientAndNamespace();
+ const response = await client.headObject({
+ namespaceName,
+ bucketName: this.bucketName,
+ objectName: path,
+ });
+ return response.contentLength;
+ } catch (err) {
+ logger.error(`Failed to read OCI Object Storage metadata ${path}`, err);
+ handleStorageError(err, "read OCI Object Storage metadata");
+ }
+ }
+
public async deleteFiles(paths: string[]): Promise<void> {
try {
const { client, namespaceName } = await this.getClientAndNamespace();
diff --git a/web/src/__tests__/server/external-media-storage-service.servertest.ts b/web/src/__tests__/server/external-media-storage-service.servertest.ts
index 1848a05c23..c74c92e543 100644
--- a/web/src/__tests__/server/external-media-storage-service.servertest.ts
+++ b/web/src/__tests__/server/external-media-storage-service.servertest.ts
@@ -131,6 +131,7 @@ describe("external media storage service", () => {
const getSignedUrl = vi.fn().mockResolvedValue("https://signed.example");
(StorageServiceFactory.getInstance as Mock).mockReturnValue({
getSignedUrl,
+ getObjectContentLength: vi.fn().mockResolvedValue(42),
});
const project = await prepareIntegration({ prefix: "customer/" });
@@ -147,6 +148,7 @@ describe("external media storage service", () => {
const getSignedUrl = vi.fn().mockResolvedValue("https://signed.example");
(StorageServiceFactory.getInstance as Mock).mockReturnValue({
getSignedUrl,
+ getObjectContentLength: vi.fn().mockResolvedValue(42),
});
const project = await prepareIntegration({ prefix: null });
diff --git a/web/src/components/MediaTag/MediaTag.stories.tsx b/web/src/components/MediaTag/MediaTag.stories.tsx
index 3b9fb2eded..144229681c 100644
--- a/web/src/components/MediaTag/MediaTag.stories.tsx
+++ b/web/src/components/MediaTag/MediaTag.stories.tsx
@@ -158,6 +158,23 @@ export const InlineWithText = meta.story({
),
});
+export const FormattedView = meta.story({
+ render: () => (
+ <div className="grid w-full font-mono text-xs/5">
+ <MediaTag contentType="image/png" />
+ </div>
+ ),
+});
+
+export const CompactJsonRow = meta.story({
+ render: () => (
+ <span className="flex items-start font-mono text-[0.7rem] leading-[14px]">
+ <span>media: </span>
+ <MediaTag contentType="image/png" size="sm" />
+ </span>
+ ),
+});
+
export const OfficeFormats = meta.story({
render: () => (
<div className="flex flex-wrap items-center gap-3">
diff --git a/web/src/components/MediaTag/MediaTag.tsx b/web/src/components/MediaTag/MediaTag.tsx
index c4e869fb91..28e824ed48 100644
--- a/web/src/components/MediaTag/MediaTag.tsx
+++ b/web/src/components/MediaTag/MediaTag.tsx
@@ -27,6 +27,7 @@ import { getMappedMediaLabel } from "@/src/fns/getMappedMediaLabel";
*/
export type MediaTagStatus = "idle" | "loading" | "ready" | "error";
type MediaTagIntent = "default" | "attachment";
+type MediaTagSize = "sm" | "md";
export interface MediaTagProps {
/**
@@ -53,6 +54,8 @@ export interface MediaTagProps {
openActionLabel?: string;
/** Visual framing for the collapsed chip. */
intent?: MediaTagIntent;
+ /** Height of the collapsed chip. */
+ size?: MediaTagSize;
/** Controlled open state of the peek popover (used by stories/tests). */
open?: boolean;
/**
@@ -99,7 +102,7 @@ const MEDIA_KIND_ICON = {
} satisfies Record<MediaKind, LucideIcon>;
const mediaTagVariants = cva(
- "focus-visible:ring-ring inline-flex h-3.5 max-w-full items-center gap-1 rounded-sm border px-1 py-0 align-middle text-xs leading-4 transition-colors focus-visible:ring-2 focus-visible:outline-hidden",
+ "focus-visible:ring-ring inline-flex w-fit max-w-full items-center gap-1 rounded-sm border px-1 py-0 align-middle text-xs leading-4 transition-colors focus-visible:ring-2 focus-visible:outline-hidden",
{
variants: {
intent: {
@@ -107,9 +110,14 @@ const mediaTagVariants = cva(
attachment:
"border-blue-500/40 bg-blue-50 text-blue-800 hover:bg-blue-100 dark:bg-blue-950/30 dark:text-blue-200 dark:hover:bg-blue-950/50",
},
+ size: {
+ sm: "h-3.5",
+ md: "h-5",
+ },
},
defaultVariants: {
intent: "default",
+ size: "md",
},
},
);
@@ -226,6 +234,7 @@ export const MediaTag = React.forwardRef<HTMLButtonElement, MediaTagProps>(
errorDetail,
openActionLabel,
intent,
+ size,
open,
onOpenChange,
},
@@ -327,7 +336,7 @@ export const MediaTag = React.forwardRef<HTMLButtonElement, MediaTagProps>(
// Containers detect chip hover via event delegation to suppress their own previews.
data-media-tag=""
aria-label={`${chipLabel} media`}
- className={mediaTagVariants({ intent })}
+ className={mediaTagVariants({ intent, size })}
{...getTriggerProps({
ref,
onClick: openPeek,
diff --git a/web/src/components/ui/LangfuseMediaView.clienttest.tsx b/web/src/components/ui/LangfuseMediaView.clienttest.tsx
index e72898e3f0..cc6a7d70dc 100644
--- a/web/src/components/ui/LangfuseMediaView.clienttest.tsx
+++ b/web/src/components/ui/LangfuseMediaView.clienttest.tsx
@@ -4,7 +4,7 @@ import { describe, expect, it, vi } from "vitest";
import { LangfuseMediaView } from "./LangfuseMediaView";
vi.mock("@/src/hooks/useProjectIdFromURL", () => ({
- default: () => "project-id",
+ default: () => "project-1",
}));
vi.mock("@/src/utils/api", () => ({
diff --git a/web/src/components/ui/LangfuseMediaView.tsx b/web/src/components/ui/LangfuseMediaView.tsx
index 771c8c3c08..a9b4e88b07 100644
--- a/web/src/components/ui/LangfuseMediaView.tsx
+++ b/web/src/components/ui/LangfuseMediaView.tsx
@@ -1,26 +1,21 @@
/* eslint-disable @repo/no-null-render */
import { api } from "@/src/utils/api";
-import { cn } from "@/src/utils/tailwind";
-import { useMemo, useState } from "react";
-import { Button } from "@/src/components/ui/button";
+import { useMemo } from "react";
-import { ImageOff, ExternalLink } from "lucide-react";
+import { ImageOff } from "lucide-react";
import {
MediaReferenceStringSchema,
OBSERVATION_FIELD_SIZE_LIMIT_MEDIA_SOURCE,
type ParsedMediaReferenceType,
} from "@langfuse/shared";
-import {
- COMPACT_IMAGE_MAX_HEIGHT_REM,
- ResizableImage,
-} from "@/src/components/ui/resizable-image";
+import { ResizableImage } from "@/src/components/ui/resizable-image";
import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
import {
type MediaContentType,
type MediaReturnType,
} from "@/src/features/media";
import { MediaReferenceTag } from "@/src/components/ui/media/MediaReferenceTag";
-import { MediaFileCard } from "@/src/components/MediaFileCard/MediaFileCard";
+import { MediaFileView } from "@/src/components/ui/media/MediaFileView";
// Above this, "preview" media falls back to the click-to-open icon instead of
// rendering inline, so a large file isn't fetched/decoded just by opening a view.
@@ -135,7 +130,7 @@ export const LangfuseMediaView = ({
variant === "preview" &&
(data?.contentLength ?? 0) <= PREVIEW_AUTO_EXPAND_MAX_BYTES;
return (
- <FileViewer
+ <MediaFileView
src={mediaUrl}
contentType={mediaData.type}
defaultExpanded={autoExpand}
@@ -156,118 +151,9 @@ export const LangfuseMediaView = ({
} else if (mediaData.type.startsWith("video")) {
return <VideoPlayer src={mediaUrl} />;
}
- return <FileViewer src={mediaUrl} contentType={mediaData.type} />;
+ return <MediaFileView src={mediaUrl} contentType={mediaData.type} />;
};
-function FileViewer({
- src,
- contentType,
- defaultExpanded = false,
-}: {
- src?: string;
- contentType: MediaContentType;
- defaultExpanded?: boolean;
-}) {
- const mimeType = String(contentType);
- const fileType = mimeType.split("/")[0];
- const isImage = fileType === "image";
- const isAudio = fileType === "audio";
- const isVideo = fileType === "video";
- const isPreviewable = isImage || isAudio || isVideo;
-
- const [isExpanded, setIsExpanded] = useState(
- defaultExpanded && isPreviewable,
- );
- const [compactImageWidth, setCompactImageWidth] = useState<string>();
-
- if (!src) return null;
-
- const fileName = src.split("/").pop()?.split("?")[0] || "";
- const openInNewTab = () => {
- window.open(src, "_blank", "noopener,noreferrer");
- };
-
- const expandPreview = () => {
- if (!isImage || compactImageWidth) {
- setIsExpanded(true);
- return;
- }
-
- const image = new window.Image();
- image.onload = () => {
- const { naturalWidth, naturalHeight } = image;
- if (naturalWidth && naturalHeight) {
- setCompactImageWidth(
- `${COMPACT_IMAGE_MAX_HEIGHT_REM * (naturalWidth / naturalHeight)}rem`,
- );
- }
- setIsExpanded(true);
- };
- image.onerror = () => setIsExpanded(true);
- image.src = src;
- };
-
- const previewContent = (() => {
- if (isImage) {
- return (
- <ResizableImage
- src={src}
- alt={fileName}
- isDefaultVisible={true}
- shouldValidateImageSource={false}
- fitContent
- compactWidth={compactImageWidth}
- />
- );
- }
- if (isAudio) {
- return <AudioPlayer src={src} />;
- }
- if (isVideo) {
- return <VideoPlayer src={src} />;
- }
- return null;
- })();
-
- return (
- <div
- className={cn(
- "flex flex-col gap-2",
- isPreviewable && isExpanded ? "basis-full" : "shrink-0",
- )}
- >
- {isPreviewable && isExpanded ? (
- <div className="flex max-w-3xl items-start gap-2">
- <div className={cn(isImage ? "contents" : "min-w-0 flex-1")}>
- {isAudio ? (
- <div className="max-w-xl min-w-72">{previewContent}</div>
- ) : (
- previewContent
- )}
- </div>
- <Button
- type="button"
- variant="outline"
- size="icon"
- onClick={openInNewTab}
- aria-label={`Open ${fileName} in new tab`}
- title={`Open ${fileName} in new tab`}
- className="shrink-0"
- >
- <ExternalLink className="icon-base text-icon-foreground" />
- </Button>
- </div>
- ) : (
- <MediaFileCard
- contentType={contentType}
- fileName={fileName}
- onClick={() => (isPreviewable ? expandPreview() : openInNewTab())}
- />
- )}
- </div>
- );
-}
-
function AudioPlayer({ src }: { src?: string }) {
if (!src) return null;
diff --git a/web/src/components/ui/media/ExternalMediaView.tsx b/web/src/components/ui/media/ExternalMediaView.tsx
new file mode 100644
index 0000000000..cc47e88081
--- /dev/null
+++ b/web/src/components/ui/media/ExternalMediaView.tsx
@@ -0,0 +1,66 @@
+import { Skeleton } from "@/src/components/ui/skeleton";
+import { useIsFeatureEnabled } from "@/src/features/feature-flags";
+import { type MediaContentType } from "@/src/features/media";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import { MediaFileView } from "./MediaFileView";
+import { type MediaDescriptor } from "./mediaUtils";
+import { useResolvedExternalMedia } from "./useResolvedExternalMedia";
+
+const PREVIEW_AUTO_EXPAND_MAX_BYTES = 50 * 1024 * 1024;
+
+export type ExternalMediaViewProps = {
+ descriptor: S3MediaDescriptor;
+};
+
+export function ExternalMediaView({ descriptor }: ExternalMediaViewProps) {
+ const projectId = useProjectIdFromURL();
+ const isFeatureEnabled = useIsFeatureEnabled("externalMediaStorage", {
+ enableForAdmins: false,
+ projectId,
+ });
+ if (!isFeatureEnabled) return <ExternalMediaFallback uri={descriptor.uri} />;
+
+ return <EnabledExternalMediaView descriptor={descriptor} />;
+}
+
+function EnabledExternalMediaView({ descriptor }: ExternalMediaViewProps) {
+ const { status, url, contentLength } = useResolvedExternalMedia(descriptor, {
+ enabled: true,
+ });
+
+ if (status === "idle" || status === "error") {
+ return <ExternalMediaFallback uri={descriptor.uri} />;
+ }
+
+ if (status === "loading" || !url) {
+ return <Skeleton className="h-24 w-24 max-w-full" />;
+ }
+
+ return (
+ <MediaFileView
+ src={url}
+ contentType={descriptor.contentType as MediaContentType}
+ defaultExpanded={
+ contentLength !== undefined &&
+ contentLength <= PREVIEW_AUTO_EXPAND_MAX_BYTES
+ }
+ />
+ );
+}
+
+function ExternalMediaFallback({ uri }: ExternalMediaFallbackProps) {
+ return (
+ <span
+ className="text-muted-foreground block max-w-full min-w-0 truncate text-xs"
+ title={uri}
+ >
+ {uri}
+ </span>
+ );
+}
+
+type S3MediaDescriptor = Extract<MediaDescriptor, { kind: "s3" }>;
+
+type ExternalMediaFallbackProps = {
+ uri: string;
+};
diff --git a/web/src/components/ui/media/MediaFileView.tsx b/web/src/components/ui/media/MediaFileView.tsx
new file mode 100644
index 0000000000..17af38b5a2
--- /dev/null
+++ b/web/src/components/ui/media/MediaFileView.tsx
@@ -0,0 +1,159 @@
+import { useState } from "react";
+import { ExternalLink } from "lucide-react";
+
+import { MediaFileCard } from "@/src/components/MediaFileCard/MediaFileCard";
+import { Button } from "@/src/components/ui/button";
+import {
+ COMPACT_IMAGE_MAX_HEIGHT_REM,
+ ResizableImage,
+} from "@/src/components/ui/resizable-image";
+import { type MediaContentType } from "@/src/features/media";
+import { cn } from "@/src/utils/tailwind";
+
+export type MediaFileViewProps = {
+ src: string;
+ contentType: MediaContentType;
+ defaultExpanded?: boolean;
+};
+
+export function MediaFileView({
+ src,
+ contentType,
+ defaultExpanded = false,
+}: MediaFileViewProps) {
+ const mimeType = String(contentType);
+ const fileType = mimeType.split("/")[0];
+ const isImage = fileType === "image";
+ const isAudio = fileType === "audio";
+ const isVideo = fileType === "video";
+ const isPreviewable = isImage || isAudio || isVideo;
+ const [isExpanded, setIsExpanded] = useState(
+ defaultExpanded && isPreviewable,
+ );
+ const [compactImageWidth, setCompactImageWidth] = useState<string>();
+ const fileName = src.split("/").pop()?.split("?")[0] || "";
+
+ const openInNewTab = () => {
+ window.open(src, "_blank", "noopener,noreferrer");
+ };
+ const expandPreview = () => {
+ if (!isImage || compactImageWidth) {
+ setIsExpanded(true);
+ return;
+ }
+
+ const image = new window.Image();
+ image.onload = () => {
+ const { naturalWidth, naturalHeight } = image;
+ if (naturalWidth && naturalHeight) {
+ setCompactImageWidth(
+ `${COMPACT_IMAGE_MAX_HEIGHT_REM * (naturalWidth / naturalHeight)}rem`,
+ );
+ }
+ setIsExpanded(true);
+ };
+ image.onerror = () => setIsExpanded(true);
+ image.src = src;
+ };
+ const handleFileCardClick = () => {
+ if (isPreviewable) {
+ expandPreview();
+ return;
+ }
+ openInNewTab();
+ };
+
+ return (
+ <div
+ className={cn(
+ "flex flex-col gap-2",
+ isPreviewable && isExpanded ? "basis-full" : "shrink-0",
+ )}
+ >
+ {isPreviewable && isExpanded ? (
+ <div className="flex max-w-3xl items-start gap-2">
+ <div className={cn(isImage ? "contents" : "min-w-0 flex-1")}>
+ <MediaFilePreview
+ src={src}
+ fileName={fileName}
+ fileType={fileType as MediaFilePreviewProps["fileType"]}
+ compactImageWidth={compactImageWidth}
+ />
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ size="icon"
+ onClick={openInNewTab}
+ aria-label={`Open ${fileName} in new tab`}
+ title={`Open ${fileName} in new tab`}
+ className="shrink-0"
+ >
+ <ExternalLink className="icon-base text-icon-foreground" />
+ </Button>
+ </div>
+ ) : (
+ <MediaFileCard
+ contentType={contentType}
+ fileName={fileName}
+ onClick={handleFileCardClick}
+ />
+ )}
+ </div>
+ );
+}
+
+function MediaFilePreview({
+ src,
+ fileName,
+ fileType,
+ compactImageWidth,
+}: MediaFilePreviewProps) {
+ if (fileType === "image") {
+ return (
+ <ResizableImage
+ src={src}
+ alt={fileName}
+ isDefaultVisible={true}
+ shouldValidateImageSource={false}
+ fitContent
+ compactWidth={compactImageWidth}
+ />
+ );
+ }
+
+ if (fileType === "audio") {
+ return (
+ <div className="max-w-xl min-w-72">
+ <AudioPlayer src={src} />
+ </div>
+ );
+ }
+
+ return <VideoPlayer src={src} />;
+}
+
+function AudioPlayer({ src }: { src: string }) {
+ return (
+ <audio controls className="w-full" preload="metadata">
+ <source src={src} />
+ Your browser does not support the audio element.
+ </audio>
+ );
+}
+
+function VideoPlayer({ src }: { src: string }) {
+ return (
+ <video controls className="w-full" preload="metadata" playsInline>
+ <source src={src} />
+ Your browser does not support the video element.
+ </video>
+ );
+}
+
+type MediaFilePreviewProps = {
+ src: string;
+ fileName: string;
+ fileType: "image" | "audio" | "video";
+ compactImageWidth?: string;
+};
diff --git a/web/src/components/ui/media/MediaReferenceTag.tsx b/web/src/components/ui/media/MediaReferenceTag.tsx
index 7cee646469..50faf7ad45 100644
--- a/web/src/components/ui/media/MediaReferenceTag.tsx
+++ b/web/src/components/ui/media/MediaReferenceTag.tsx
@@ -1,30 +1,15 @@
import { useState } from "react";
-import { MediaTag, type MediaTagStatus } from "../../MediaTag/MediaTag";
+import { MediaTag, type MediaTagProps } from "../../MediaTag/MediaTag";
import { useResolvedMedia } from "./useResolvedMedia";
+import { useResolvedExternalMedia } from "./useResolvedExternalMedia";
import { type MediaDescriptor } from "./mediaUtils";
import { OBSERVATION_FIELD_SIZE_LIMIT_MEDIA_SOURCE } from "@langfuse/shared";
-import { api } from "@/src/utils/api";
-import { useRouter } from "next/router";
import { useIsFeatureEnabled } from "@/src/features/feature-flags";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
type LangfuseRefDescriptor = Extract<MediaDescriptor, { kind: "langfuseRef" }>;
type S3Descriptor = Extract<MediaDescriptor, { kind: "s3" }>;
-function getS3MediaStatus({
- armed,
- isError,
- hasData,
-}: {
- armed: boolean;
- isError: boolean;
- hasData: boolean;
-}): MediaTagStatus {
- if (!armed) return "idle";
- if (isError) return "error";
- if (hasData) return "ready";
- return "loading";
-}
-
/**
* 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
@@ -33,12 +18,14 @@ function getS3MediaStatus({
export function MediaReferenceTag({
descriptor,
label,
+ size,
}: {
descriptor: MediaDescriptor;
label?: string;
+ size?: MediaTagProps["size"];
}) {
if (descriptor.kind === "s3") {
- return <S3MediaTag descriptor={descriptor} label={label} />;
+ return <S3MediaTag descriptor={descriptor} label={label} size={size} />;
}
if (descriptor.kind !== "langfuseRef") {
@@ -47,76 +34,77 @@ export function MediaReferenceTag({
contentType={descriptor.contentType}
status="ready"
url={descriptor.src}
+ size={size}
/>
);
}
- return <LangfuseRefMediaTag descriptor={descriptor} />;
+ return <LangfuseRefMediaTag descriptor={descriptor} size={size} />;
}
function S3MediaTag({
descriptor,
label,
+ size,
}: {
descriptor: S3Descriptor;
label?: string;
+ size?: MediaTagProps["size"];
}) {
- const router = useRouter();
- const projectId =
- typeof router.query.projectId === "string"
- ? router.query.projectId
- : undefined;
+ const projectId = useProjectIdFromURL();
const isFeatureEnabled = useIsFeatureEnabled("externalMediaStorage", {
enableForAdmins: false,
projectId,
});
const [armed, setArmed] = useState(false);
const [open, setOpen] = useState(false);
- const resolved = api.media.resolveExternalMedia.useQuery(
- { projectId: projectId ?? "", uri: descriptor.uri },
+ const { status, url, refreshIfNeeded } = useResolvedExternalMedia(
+ descriptor,
{
- enabled: armed && isFeatureEnabled && Boolean(projectId),
- staleTime: 4 * 60 * 1000,
- refetchInterval: open ? 4 * 60 * 1000 : false,
- retry: false,
- meta: { silentHttpCodes: [404] },
+ enabled: isFeatureEnabled && armed,
},
);
+ const handleOpenChange = (nextOpen: boolean) => {
+ setOpen(nextOpen);
+ if (!nextOpen) return;
- if (!isFeatureEnabled) return descriptor.uri;
+ if (armed) {
+ refreshIfNeeded().catch(() => undefined);
+ }
+ setArmed(true);
+ };
- const isSignedUrlExpired =
- resolved.data?.expiresAt !== undefined &&
- resolved.data.expiresAt.getTime() <= Date.now();
- const status = getS3MediaStatus({
- armed,
- isError: resolved.isError,
- hasData: Boolean(resolved.data) && !isSignedUrlExpired,
- });
+ if (!isFeatureEnabled) {
+ return (
+ <span
+ className="inline-block max-w-full min-w-0 truncate align-middle"
+ title={descriptor.uri}
+ >
+ {descriptor.uri}
+ </span>
+ );
+ }
return (
<MediaTag
contentType={descriptor.contentType}
label={label}
+ size={size}
status={status}
- url={isSignedUrlExpired ? undefined : resolved.data?.url}
+ url={url}
errorDetail={descriptor.uri}
open={open}
- onOpenChange={(nextOpen) => {
- setOpen(nextOpen);
- if (nextOpen) {
- if (armed && isSignedUrlExpired) resolved.refetch();
- setArmed(true);
- }
- }}
+ onOpenChange={handleOpenChange}
/>
);
}
function LangfuseRefMediaTag({
descriptor,
+ size,
}: {
descriptor: LangfuseRefDescriptor;
+ size?: MediaTagProps["size"];
}) {
const [armed, setArmed] = useState(false);
const [open, setOpen] = useState(false);
@@ -133,6 +121,7 @@ function LangfuseRefMediaTag({
return (
<MediaTag
contentType={descriptor.contentType}
+ size={size}
status={status}
url={url}
contentLength={contentLength}
diff --git a/web/src/components/ui/media/useResolvedExternalMedia.clienttest.ts b/web/src/components/ui/media/useResolvedExternalMedia.clienttest.ts
new file mode 100644
index 0000000000..be36cf389d
--- /dev/null
+++ b/web/src/components/ui/media/useResolvedExternalMedia.clienttest.ts
@@ -0,0 +1,60 @@
+import { act, renderHook } from "@testing-library/react";
+
+import { useResolvedExternalMedia } from "./useResolvedExternalMedia";
+
+const { queryState, refetchMock } = vi.hoisted(() => ({
+ queryState: {
+ data: {
+ url: "https://signed.example.com/photo.jpeg",
+ expiresAt: new Date("2026-10-09T14:05:00.000Z"),
+ },
+ isError: false,
+ isFetching: false,
+ },
+ refetchMock: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock("@/src/hooks/useProjectIdFromURL", () => ({
+ default: () => "project-1",
+}));
+
+vi.mock("@/src/utils/api", () => ({
+ api: {
+ media: {
+ resolveExternalMedia: {
+ useQuery: () => ({ ...queryState, refetch: refetchMock }),
+ },
+ },
+ },
+}));
+
+const descriptor = {
+ kind: "s3",
+ contentType: "image/jpeg",
+ uri: "s3://customer-bucket/media/photo.jpeg",
+} as const;
+
+describe("useResolvedExternalMedia", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-10-09T14:04:00.000Z"));
+ refetchMock.mockClear();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("refreshes a cached signed URL when it expires before the next open", async () => {
+ const { result } = renderHook(() =>
+ useResolvedExternalMedia(descriptor, { enabled: true }),
+ );
+
+ expect(result.current.status).toBe("ready");
+
+ vi.setSystemTime(new Date("2026-10-09T14:06:00.000Z"));
+ await act(result.current.refreshIfNeeded);
+
+ expect(refetchMock).toHaveBeenCalledOnce();
+ });
+});
diff --git a/web/src/components/ui/media/useResolvedExternalMedia.ts b/web/src/components/ui/media/useResolvedExternalMedia.ts
new file mode 100644
index 0000000000..f53041ec34
--- /dev/null
+++ b/web/src/components/ui/media/useResolvedExternalMedia.ts
@@ -0,0 +1,60 @@
+import { api } from "@/src/utils/api";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import { type MediaTagStatus } from "../../MediaTag/MediaTag";
+import { type MediaDescriptor } from "./mediaUtils";
+
+export function useResolvedExternalMedia(
+ descriptor: S3MediaDescriptor,
+ { enabled }: { enabled: boolean },
+): {
+ status: MediaTagStatus;
+ url?: string;
+ contentLength?: number;
+ refreshIfNeeded: () => Promise<void>;
+} {
+ const projectId = useProjectIdFromURL();
+ const query = api.media.resolveExternalMedia.useQuery(
+ { projectId: projectId ?? "", uri: descriptor.uri },
+ {
+ enabled: enabled && Boolean(projectId),
+ retry: false,
+ meta: { silentHttpCodes: [404] },
+ refetchOnWindowFocus: false,
+ refetchOnMount: true,
+ refetchOnReconnect: false,
+ staleTime: 4 * 60 * 1000,
+ },
+ );
+ const refreshIfNeeded = async () => {
+ if (!query.isError && !isExpired(query.data?.expiresAt)) return;
+ await query.refetch();
+ };
+
+ if (!enabled || !projectId) {
+ return { status: "idle", refreshIfNeeded };
+ }
+ if (query.isError) {
+ return { status: "error", refreshIfNeeded };
+ }
+ if (isExpired(query.data?.expiresAt)) {
+ return {
+ status: query.isFetching ? "loading" : "error",
+ refreshIfNeeded,
+ };
+ }
+ if (query.data?.url) {
+ return {
+ status: "ready",
+ url: query.data.url,
+ contentLength: query.data.contentLength,
+ refreshIfNeeded,
+ };
+ }
+ return { status: "loading", refreshIfNeeded };
+}
+
+function isExpired(expiresAt?: Date) {
+ return expiresAt !== undefined && expiresAt.getTime() <= Date.now();
+}
+
+type S3MediaDescriptor = Extract<MediaDescriptor, { kind: "s3" }>;
diff --git a/web/src/features/external-media-storage/server/service.ts b/web/src/features/external-media-storage/server/service.ts
index da9a95d578..726fd9c12d 100644
--- a/web/src/features/external-media-storage/server/service.ts
+++ b/web/src/features/external-media-storage/server/service.ts
@@ -215,14 +215,21 @@ export function createExternalMediaStorageService(prisma: PrismaClient) {
await validateExternalMediaStorageEndpoint(integration.endpoint);
}
- const url = await createStorageService(integration).getSignedUrl(
- parsed.key,
- EXTERNAL_MEDIA_URL_TTL_SECONDS,
- false,
- );
+ const storageService = createStorageService(integration);
+ const [url, contentLength] = await Promise.all([
+ storageService.getSignedUrl(
+ parsed.key,
+ EXTERNAL_MEDIA_URL_TTL_SECONDS,
+ false,
+ ),
+ storageService
+ .getObjectContentLength(parsed.key)
+ .catch(() => undefined),
+ ]);
return {
url,
+ contentLength,
expiresAt: new Date(Date.now() + EXTERNAL_MEDIA_URL_TTL_SECONDS * 1000),
};
},
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsx
index 522dfd0efa..66a7ad086d 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.stories.tsx
@@ -427,3 +427,44 @@ export const RejectUnsafeFileUrl = meta.story({
await expect(canvasElement).toHaveTextContent("javascript:alert(1)");
},
});
+
+const s3ImageUri = "s3://customer-bucket/media/photo.jpeg";
+
+export const S3ImageFile = meta.story({
+ name: "S3 image file",
+ parameters: { a11y: { test: "off" } },
+ args: {
+ role: "user",
+ parts: [
+ { type: "text", text: "Show this S3 image." },
+ {
+ type: "file",
+ mediaType: "image/jpeg",
+ content: { kind: "url", url: s3ImageUri },
+ },
+ ],
+ },
+});
+
+export const NarrowUnresolvedImageLayout = meta.story({
+ name: "Narrow unresolved image layout",
+ parameters: { a11y: { test: "off" } },
+ args: {
+ role: "user",
+ parts: [
+ { type: "text", text: "Show this unresolved image." },
+ {
+ type: "file",
+ mediaType: "image/*",
+ content: { kind: "base64", data: "A".repeat(800) },
+ },
+ ],
+ timestamp: new Date("2026-10-09T11:45:47.000Z"),
+ onOpenObservation: fn(),
+ },
+ render: (args) => (
+ <div className="w-[241px]">
+ <SessionTimelineContentMessage {...args} />
+ </div>
+ ),
+});
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/SessionTimelinePart.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/SessionTimelinePart.tsx
index f053d6b47e..c4212bcad4 100644
--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/SessionTimelinePart.tsx
+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/SessionTimelinePart.tsx
@@ -1,4 +1,3 @@
-/* eslint-disable no-nested-ternary */
import { FileIcon, Wrench } from "lucide-react";
import { useState, type ReactNode } from "react";
import { SessionTimelineCollapsibleRow } from "../SessionTimelineCollapsibleRow/SessionTimelineCollapsibleRow";
@@ -10,11 +9,87 @@ import {
} from "@langfuse/shared/src/utils/normalized-io";
import { SessionTimelineCollapsiblePart } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelinePart/components/SessionTimelineCollapsiblePart/SessionTimelineCollapsiblePart";
import { LangfuseMediaView } from "@/src/components/ui/LangfuseMediaView";
+import { ExternalMediaView } from "@/src/components/ui/media/ExternalMediaView";
import { MarkdownView } from "@/src/components/ui/MarkdownViewer";
import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";
+import {
+ classifyMediaValue,
+ type MediaDescriptor,
+} from "@/src/components/ui/media/mediaUtils";
import { getSafeImageUrl, getSafeLinkUrl } from "@/src/components/ui/safe-url";
+import { cn } from "@/src/utils/tailwind";
import { decodeUnicodeEscapesOnly } from "@/src/utils/unicode";
+export function SessionTimelinePart({
+ part,
+ trailingContent,
+}: {
+ part: NormalizedMessage["parts"][number];
+ trailingContent?: ReactNode;
+}) {
+ if (part.type === "text") {
+ return (
+ <div className="flex flex-col gap-1">
+ {part.refusal ? (
+ <span className="text-dark-red text-[11px] font-bold">Refusal</span>
+ ) : null}
+ <div data-session-search-content>
+ <MarkdownView
+ markdown={decodeUnicodeEscapesOnly(part.text, true)}
+ className="px-0 py-0"
+ />
+ </div>
+ </div>
+ );
+ }
+
+ if (part.type === "reasoning") {
+ return (
+ <SessionTimelineReasoning part={part} trailingContent={trailingContent} />
+ );
+ }
+
+ if (part.type === "file") {
+ return <SessionTimelineFile part={part} />;
+ }
+
+ if (part.type === "tool-call" || part.type === "tool-result") {
+ const isCall = part.type === "tool-call";
+ return (
+ <SessionTimelineCollapsiblePart
+ label={`${part.toolName ?? "Tool"} · ${isCall ? "Call" : "Result"}`}
+ icon={Wrench}
+ status={
+ part.type === "tool-result" && part.isError ? "error" : undefined
+ }
+ variant="plain"
+ alignment="row"
+ >
+ <PrettyJsonView
+ json={part.type === "tool-call" ? part.input : part.output}
+ currentView="pretty"
+ />
+ </SessionTimelineCollapsiblePart>
+ );
+ }
+
+ if (part.type === "data") {
+ return <PrettyJsonView json={part.value} currentView="pretty" />;
+ }
+
+ if (part.type === "custom") {
+ return (
+ <PrettyJsonView
+ title={part.kind}
+ json={part.value}
+ currentView="pretty"
+ />
+ );
+ }
+
+ return assertUnreachable(part);
+}
+
function SessionTimelineReasoning({
part,
trailingContent,
@@ -82,120 +157,121 @@ function SessionTimelineReasoning({
}
function SessionTimelineFile({ part }: { part: FilePart }) {
- const source = part.providerMetadata?.source;
- const safeUrl =
- part.content.kind === "url" ? getSafeLinkUrl(part.content.url) : null;
- const safeImageUrl =
- part.content.kind === "url" && part.mediaType?.startsWith("image/")
- ? getSafeImageUrl(part.content.url)
- : null;
- const reference =
- part.content.kind === "reference" &&
- part.mediaType &&
- typeof source === "string"
- ? `@@@langfuseMedia:type=${part.mediaType}|id=${part.content.id}|source=${source}@@@`
- : undefined;
+ const content = getSessionTimelineFileContent(part);
return (
- <div className="border-border/70 bg-background flex w-fit max-w-full flex-col gap-2 rounded-md border p-3">
+ <div
+ className={cn(
+ "border-border/70 bg-background flex max-w-full flex-col gap-2 rounded-md border p-3",
+ content.kind === "fallback" ? "w-full" : "w-fit",
+ )}
+ >
<div className="text-muted-foreground flex items-center gap-2 text-xs font-bold">
<FileIcon className="icon-base" />
{part.filename ?? part.mediaType ?? "File"}
</div>
- {reference ? (
- <LangfuseMediaView mediaReferenceString={reference} variant="preview" />
- ) : safeImageUrl ? (
- <a href={safeImageUrl} target="_blank" rel="noreferrer">
- {/* eslint-disable-next-line @next/next/no-img-element */}
- <img
- src={safeImageUrl}
- alt={part.filename ?? "Embedded image"}
- className="max-h-64 max-w-full rounded-md object-contain"
- />
- </a>
- ) : safeUrl ? (
- <a
- href={safeUrl}
- target="_blank"
- rel="noreferrer"
- className="text-primary min-w-0 truncate text-xs underline underline-offset-2"
- title={part.content.kind === "url" ? part.content.url : undefined}
- >
- {safeUrl}
- </a>
- ) : (
- <PrettyJsonView json={part} currentView="pretty" />
- )}
+ <SessionTimelineFileBody
+ content={content}
+ filename={part.filename ?? "Embedded image"}
+ />
</div>
);
}
-export function SessionTimelinePart({
- part,
- trailingContent,
-}: {
- part: NormalizedMessage["parts"][number];
- trailingContent?: ReactNode;
-}) {
- if (part.type === "text") {
+function SessionTimelineFileBody({
+ content,
+ filename,
+}: SessionTimelineFileBodyProps) {
+ if (content.kind === "langfuse") {
return (
- <div className="flex flex-col gap-1">
- {part.refusal ? (
- <span className="text-dark-red text-[11px] font-bold">Refusal</span>
- ) : null}
- <div data-session-search-content>
- <MarkdownView
- markdown={decodeUnicodeEscapesOnly(part.text, true)}
- className="px-0 py-0"
- />
- </div>
- </div>
+ <LangfuseMediaView
+ mediaReferenceString={content.reference}
+ variant="preview"
+ />
);
}
- if (part.type === "reasoning") {
- return (
- <SessionTimelineReasoning part={part} trailingContent={trailingContent} />
- );
+ if (content.kind === "s3") {
+ return <ExternalMediaView descriptor={content.descriptor} />;
}
- if (part.type === "file") {
- return <SessionTimelineFile part={part} />;
+ if (content.kind === "image") {
+ return (
+ <a href={content.url} target="_blank" rel="noreferrer">
+ {/* eslint-disable-next-line @next/next/no-img-element */}
+ <img
+ src={content.url}
+ alt={filename}
+ className="max-h-64 max-w-full rounded-md object-contain"
+ />
+ </a>
+ );
}
- if (part.type === "tool-call" || part.type === "tool-result") {
- const isCall = part.type === "tool-call";
+ if (content.kind === "link") {
return (
- <SessionTimelineCollapsiblePart
- label={`${part.toolName ?? "Tool"} · ${isCall ? "Call" : "Result"}`}
- icon={Wrench}
- status={
- part.type === "tool-result" && part.isError ? "error" : undefined
- }
- variant="plain"
- alignment="row"
+ <a
+ href={content.url}
+ target="_blank"
+ rel="noreferrer"
+ className="text-primary min-w-0 truncate text-xs underline underline-offset-2"
+ title={content.sourceUrl}
>
- <PrettyJsonView
- json={part.type === "tool-call" ? part.input : part.output}
- currentView="pretty"
- />
- </SessionTimelineCollapsiblePart>
+ {content.url}
+ </a>
);
}
- if (part.type === "data") {
- return <PrettyJsonView json={part.value} currentView="pretty" />;
+ return (
+ <div className="min-w-0 overflow-x-auto">
+ <PrettyJsonView json={content.part} currentView="pretty" />
+ </div>
+ );
+}
+
+function getSessionTimelineFileContent(
+ part: FilePart,
+): SessionTimelineFileContent {
+ const source = part.providerMetadata?.source;
+ const reference =
+ part.content.kind === "reference" &&
+ part.mediaType &&
+ typeof source === "string"
+ ? `@@@langfuseMedia:type=${part.mediaType}|id=${part.content.id}|source=${source}@@@`
+ : undefined;
+
+ if (reference) return { kind: "langfuse", reference };
+ if (part.content.kind !== "url") return { kind: "fallback", part };
+
+ const classifiedMedia = classifyMediaValue(part.content.url);
+ if (classifiedMedia?.kind === "s3") {
+ return { kind: "s3", descriptor: classifiedMedia };
}
- if (part.type === "custom") {
- return (
- <PrettyJsonView
- title={part.kind}
- json={part.value}
- currentView="pretty"
- />
- );
+ const safeImageUrl = part.mediaType?.startsWith("image/")
+ ? getSafeImageUrl(part.content.url)
+ : null;
+ if (safeImageUrl) return { kind: "image", url: safeImageUrl };
+
+ const safeUrl = getSafeLinkUrl(part.content.url);
+ if (safeUrl) {
+ return { kind: "link", url: safeUrl, sourceUrl: part.content.url };
}
- return assertUnreachable(part);
+ return { kind: "fallback", part };
}
+
+type SessionTimelineFileContent =
+ | { kind: "langfuse"; reference: string }
+ | {
+ kind: "s3";
+ descriptor: Extract<MediaDescriptor, { kind: "s3" }>;
+ }
+ | { kind: "image"; url: string }
+ | { kind: "link"; url: string; sourceUrl: string }
+ | { kind: "fallback"; part: FilePart };
+
+type SessionTimelineFileBodyProps = {
+ content: SessionTimelineFileContent;
+ filename: string;
+};
diff --git a/web/src/features/traces/components/AdvancedJsonViewer/components/JsonValue.tsx b/web/src/features/traces/components/AdvancedJsonViewer/components/JsonValue.tsx
index dc0b8d8736..d6871fa660 100644
--- a/web/src/features/traces/components/AdvancedJsonViewer/components/JsonValue.tsx
+++ b/web/src/features/traces/components/AdvancedJsonViewer/components/JsonValue.tsx
@@ -116,7 +116,7 @@ export function JsonValue({
// text highlighter found no search/comment overlays to preserve.
const mediaDescriptor = classifyMediaValue(str);
if (mediaDescriptor && segments.every((segment) => segment.type === null)) {
- return <MediaReferenceTag descriptor={mediaDescriptor} />;
+ return <MediaReferenceTag descriptor={mediaDescriptor} size="sm" />;
}
return (