import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets"; import { mediaFileReference, mediaUrlReference } from "@t3tools/client-runtime/media-reference"; import type { AssetResource, EnvironmentId, SOURCE_CONTROL_MEDIA_ASSET } from "@t3tools/contracts"; import { TriangleAlertIcon } from "lucide-react"; import { createContext, memo, use, useState, type ComponentProps, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, } from "react"; import { useAssetUrlRefresh, useAssetUrlState } from "../../assets/assetUrls"; import { cn } from "../../lib/utils"; import { useRightPanelStore } from "../../rightPanelStore"; import { MediaActions, type MediaActionSource } from "../media/MediaActions"; import { MediaVideoPlayer } from "../media/MediaVideoPlayer"; import type { ExpandedImagePreview } from "./ExpandedImagePreview"; import { markdownImageGallery, markdownImageItems } from "./markdownImageGallery"; const CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME = "max-w-[min(100%,30rem)]"; const CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME = cn( "max-h-[30rem]", CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME, ); const CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME = "inline-block!"; const CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME = "rounded-lg border border-border/40"; const CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME = cn( "h-auto w-auto object-contain", CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME, ); export function markdownImageCopy(alt: string, src: string, title: string | undefined): string { const escapedAlt = alt.replaceAll("\\", "\\\\").replaceAll("[", "\\[").replaceAll("]", "\\]"); const titleSuffix = title === undefined ? "" : ` "${title.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`; return `![${escapedAlt}](${src}${titleSuffix})`; } /** * `maxHeightRem` folds a height cap into the width bound: `max-height` alone * would not feed back through `aspect-ratio` once `width` is definite, so a * tall image would keep a box wider than the picture it draws. */ export function authoredImageSizeStyle( width: string | number | undefined, height: string | number | undefined, maxHeightRem = 30, ): CSSProperties | undefined { const parsedWidth = Number(width); const parsedHeight = Number(height); const hasWidth = Number.isFinite(parsedWidth) && parsedWidth > 0; const hasHeight = Number.isFinite(parsedHeight) && parsedHeight > 0; if (hasWidth && hasHeight) { return { width: parsedWidth, height: "auto", aspectRatio: `${parsedWidth} / ${parsedHeight}`, maxWidth: `min(100%, 30rem, ${(maxHeightRem * parsedWidth) / parsedHeight}rem)`, }; } if (hasWidth) return { maxWidth: `min(100%, 30rem, ${parsedWidth}px)` }; if (hasHeight) return { maxHeight: `min(30rem, ${parsedHeight}px)` }; return undefined; } const CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME = cn( CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME, CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME, ); export const MarkdownLinkContext = createContext(false); /** The thread's workspace mutation id, so a host image the agent rewrites gets a fresh URL. */ export const WorkspaceMutationIdContext = createContext(undefined); function expandableMarkdownImageProps( onImageExpand: ((preview: ExpandedImagePreview) => void) | undefined, alt: string, ) { if (!onImageExpand) return {}; const previewName = alt.trim() || "image"; const expand = (event: ReactMouseEvent | ReactKeyboardEvent) => { if (event.currentTarget.closest("a")) return; event.preventDefault(); event.stopPropagation(); const item = markdownImageItems.get(event.currentTarget); if (item) onImageExpand(markdownImageGallery(event.currentTarget, item)); }; return { role: "button" as const, tabIndex: 0, "aria-label": `Preview ${previewName}`, onClick: expand, onKeyDown: (event: ReactKeyboardEvent) => { if (event.key === "Enter" || event.key === " ") expand(event); }, }; } function ChatMarkdownMediaUnavailableLabel(props: { readonly alt: string; readonly kind?: "image" | "video" | "audio" | undefined; readonly detail?: string | undefined; }) { const label = props.kind === "audio" ? "Audio unavailable" : props.kind === "video" ? "Video unavailable" : "Image unavailable"; return ( {[label, props.alt, props.detail].filter(Boolean).join(" ยท ")} ); } export function ChatMarkdownImageFallback(props: { readonly alt: string; readonly copyMarkdown?: string | undefined; readonly kind?: "image" | "video" | "audio"; readonly actionsSource?: MediaActionSource | undefined; readonly detail?: string | undefined; }) { const content = ( ); return props.actionsSource ? ( {content} ) : ( content ); } const CHAT_MARKDOWN_IMAGE_FRAME_CLASS_NAME = cn( "aspect-video w-full overflow-hidden bg-muted/60", CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME, CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME, ); /** * Callers key this on the file's identity, not its URL: a re-signed URL for * the same file keeps the decoded image on screen while the new bytes arrive, * and a different file starts from the slot again. */ export function ChatMarkdownImage(props: { readonly src: string | null; readonly sourceFailed?: boolean | undefined; readonly unavailableDetail?: string | undefined; readonly alt: string; readonly copyMarkdown: string | undefined; readonly standalone: boolean; readonly className?: string | undefined; readonly style?: CSSProperties | undefined; readonly imageProps?: | Omit, "src" | "alt" | "className" | "style"> | undefined; readonly actionsSource: MediaActionSource; readonly originalUrl?: string | undefined; readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined; }) { const [loadedSrc, setLoadedSrc] = useState(null); const [failedSrc, setFailedSrc] = useState(null); const src = props.src ?? loadedSrc; const failed = props.sourceFailed === true || (src !== null && failedSrc === src); const settled = src !== null && !failed && (!props.standalone || loadedSrc !== null); // Cached images are complete before `onLoad` can fire. const markLoadedIfComplete = (image: HTMLImageElement | null) => { if (!image) return; if (image.complete && image.naturalWidth > 0) setLoadedSrc(image.currentSrc || image.src); markdownImageItems.set(image, { src, name: props.alt.trim() || "image", actionsSource: props.actionsSource, ...(props.originalUrl ? { originalUrl: props.originalUrl } : {}), }); }; const imageEvents = (loadingSrc: string) => ({ onLoad: () => { setLoadedSrc(loadingSrc); setFailedSrc(null); }, onError: () => { setFailedSrc(loadingSrc); setLoadedSrc(null); }, }); if (settled) { return ( {props.alt} ); } if (!props.standalone) { return failed ? ( ) : ( ); } return ( {failed ? ( ) : src !== null ? ( {props.alt} ) : null} ); } export function ChatMarkdownVideo(props: { readonly src: string | null; readonly alt: string; readonly copyMarkdown: string | undefined; readonly originalUrl?: string | undefined; readonly sourceFailed?: boolean | undefined; readonly style?: CSSProperties | undefined; readonly mediaIdentity?: string | undefined; readonly actionsSource?: MediaActionSource | undefined; readonly onRetry?: (() => Promise) | undefined; }) { return ( ); } export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props: { readonly environmentId: EnvironmentId; readonly resource: Extract< AssetResource, { readonly _tag: | "attachment" | "workspace-file" | "media-file" | typeof SOURCE_CONTROL_MEDIA_ASSET | "tool-output-image"; } >; readonly kind?: "image" | "video"; readonly alt: string; readonly copyMarkdown?: string; readonly srcFragment?: string; readonly standalone?: boolean | undefined; readonly maxHeightRem?: number | undefined; readonly style?: CSSProperties | undefined; readonly className?: string | undefined; readonly imageProps?: | Omit, "src" | "alt" | "className" | "style"> | undefined; readonly originalUrl?: string | undefined; readonly framed?: boolean | undefined; readonly fallbackSrc?: string | undefined; readonly workspaceRoot?: string | undefined; readonly workspaceMutationId?: string | null | undefined; readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined; }) { const resource = props.resource; const threadWorkspaceMutationId = use(WorkspaceMutationIdContext); const workspaceMutationId = props.workspaceMutationId ?? threadWorkspaceMutationId; const assetUrl = useAssetUrlState( props.environmentId, resource, workspaceMutationId !== undefined && props.kind !== "video" && (resource._tag === "media-file" || resource._tag === "workspace-file") ? workspaceMutationId : undefined, ); const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource); const path = resource._tag === "media-file" ? resource.path : resource._tag === "workspace-file" && props.workspaceRoot ? `${props.workspaceRoot.replace(/[\\/]+$/, "")}/${resource.path}` : undefined; const reference = path ? mediaFileReference(path, props.workspaceRoot) : props.originalUrl ? mediaUrlReference(props.originalUrl) : undefined; const relativePath = reference?.kind === "file" ? reference.relativePath : undefined; const fallbackSrc = assetUrl._tag === "Failure" ? props.fallbackSrc : undefined; const src = assetUrl._tag === "Success" ? assetUrl.url + (props.srcFragment ?? "") : fallbackSrc === undefined ? null : fallbackSrc + (props.srcFragment ?? ""); const knownSize = assetUrl._tag === "Success" ? assetUrl.imageDimensions : undefined; const maxHeightRem = props.maxHeightRem ?? 30; const style = props.style ?? (knownSize ? authoredImageSizeStyle(knownSize.width, knownSize.height, maxHeightRem) : maxHeightRem !== 30 ? { maxHeight: `${maxHeightRem}rem` } : undefined); const actionsSource: MediaActionSource = { kind: props.kind ?? "image", name: props.alt || (props.kind ?? "image"), src, ...(fallbackSrc === undefined ? { asset: { environmentId: props.environmentId, resource } } : {}), ...(reference ? { reference } : {}), ...(relativePath && (resource._tag === "media-file" || resource._tag === "workspace-file") ? { onOpenFile: () => useRightPanelStore .getState() .openFile( { environmentId: props.environmentId, threadId: resource.threadId }, relativePath, ), } : {}), }; if (props.kind === "video") { return ( ); } return ( ); });