Open History to see the last commit
1import { MISSING_FILE_ACCESS_MESSAGE } from "@t3tools/client-runtime/state/assets";
2import { mediaFileReference, mediaUrlReference } from "@t3tools/client-runtime/media-reference";
3import type { AssetResource, EnvironmentId, SOURCE_CONTROL_MEDIA_ASSET } from "@t3tools/contracts";
4import { TriangleAlertIcon } from "lucide-react";
5import {
6 createContext,
7 memo,
8 use,
9 useState,
10 type ComponentProps,
11 type CSSProperties,
12 type KeyboardEvent as ReactKeyboardEvent,
13 type MouseEvent as ReactMouseEvent,
14} from "react";
15
16import { useAssetUrlRefresh, useAssetUrlState } from "../../assets/assetUrls";
17import { cn } from "../../lib/utils";
18import { useRightPanelStore } from "../../rightPanelStore";
19import { MediaActions, type MediaActionSource } from "../media/MediaActions";
20import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
21import type { ExpandedImagePreview } from "./ExpandedImagePreview";
22import { markdownImageGallery, markdownImageItems } from "./markdownImageGallery";
23
24const CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME = "max-w-[min(100%,30rem)]";
25const CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME = cn(
26 "max-h-[30rem]",
27 CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME,
28);
29const CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME = "inline-block!";
30const CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME = "rounded-lg border border-border/40";
31const CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME = cn(
32 "h-auto w-auto object-contain",
33 CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME,
34);
35
36export function markdownImageCopy(alt: string, src: string, title: string | undefined): string {
37 const escapedAlt = alt.replaceAll("\\", "\\\\").replaceAll("[", "\\[").replaceAll("]", "\\]");
38 const titleSuffix =
39 title === undefined ? "" : ` "${title.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
40 return ``;
41}
42
43/**
44 * `maxHeightRem` folds a height cap into the width bound: `max-height` alone
45 * would not feed back through `aspect-ratio` once `width` is definite, so a
46 * tall image would keep a box wider than the picture it draws.
47 */
48export function authoredImageSizeStyle(
49 width: string | number | undefined,
50 height: string | number | undefined,
51 maxHeightRem = 30,
52): CSSProperties | undefined {
53 const parsedWidth = Number(width);
54 const parsedHeight = Number(height);
55 const hasWidth = Number.isFinite(parsedWidth) && parsedWidth > 0;
56 const hasHeight = Number.isFinite(parsedHeight) && parsedHeight > 0;
57 if (hasWidth && hasHeight) {
58 return {
59 width: parsedWidth,
60 height: "auto",
61 aspectRatio: `${parsedWidth} / ${parsedHeight}`,
62 maxWidth: `min(100%, 30rem, ${(maxHeightRem * parsedWidth) / parsedHeight}rem)`,
63 };
64 }
65 if (hasWidth) return { maxWidth: `min(100%, 30rem, ${parsedWidth}px)` };
66 if (hasHeight) return { maxHeight: `min(30rem, ${parsedHeight}px)` };
67 return undefined;
68}
69
70const CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME = cn(
71 CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
72 CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME,
73);
74export const MarkdownLinkContext = createContext(false);
75/** The thread's workspace mutation id, so a host image the agent rewrites gets a fresh URL. */
76export const WorkspaceMutationIdContext = createContext<string | null | undefined>(undefined);
77
78function expandableMarkdownImageProps(
79 onImageExpand: ((preview: ExpandedImagePreview) => void) | undefined,
80 alt: string,
81) {
82 if (!onImageExpand) return {};
83 const previewName = alt.trim() || "image";
84 const expand = (event: ReactMouseEvent | ReactKeyboardEvent) => {
85 if (event.currentTarget.closest("a")) return;
86 event.preventDefault();
87 event.stopPropagation();
88 const item = markdownImageItems.get(event.currentTarget);
89 if (item) onImageExpand(markdownImageGallery(event.currentTarget, item));
90 };
91 return {
92 role: "button" as const,
93 tabIndex: 0,
94 "aria-label": `Preview ${previewName}`,
95 onClick: expand,
96 onKeyDown: (event: ReactKeyboardEvent) => {
97 if (event.key === "Enter" || event.key === " ") expand(event);
98 },
99 };
100}
101
102function ChatMarkdownMediaUnavailableLabel(props: {
103 readonly alt: string;
104 readonly kind?: "image" | "video" | "audio" | undefined;
105 readonly detail?: string | undefined;
106}) {
107 const label =
108 props.kind === "audio"
109 ? "Audio unavailable"
110 : props.kind === "video"
111 ? "Video unavailable"
112 : "Image unavailable";
113 return (
114 <span data-thread-find-ignore className="inline-flex items-center gap-1.5">
115 <TriangleAlertIcon aria-hidden className="size-3.5 shrink-0" />
116 {[label, props.alt, props.detail].filter(Boolean).join(" · ")}
117 </span>
118 );
119}
120
121export function ChatMarkdownImageFallback(props: {
122 readonly alt: string;
123 readonly copyMarkdown?: string | undefined;
124 readonly kind?: "image" | "video" | "audio";
125 readonly actionsSource?: MediaActionSource | undefined;
126 readonly detail?: string | undefined;
127}) {
128 const content = (
129 <span
130 data-markdown-copy={props.copyMarkdown}
131 className={cn(
132 CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
133 "rounded-md border border-border/40 bg-muted/40 px-2 py-1 text-xs text-muted-foreground",
134 )}
135 >
136 <ChatMarkdownMediaUnavailableLabel alt={props.alt} kind={props.kind} detail={props.detail} />
137 </span>
138 );
139 return props.actionsSource ? (
140 <MediaActions source={props.actionsSource}>{content}</MediaActions>
141 ) : (
142 content
143 );
144}
145
146const CHAT_MARKDOWN_IMAGE_FRAME_CLASS_NAME = cn(
147 "aspect-video w-full overflow-hidden bg-muted/60",
148 CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME,
149 CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME,
150);
151
152/**
153 * Callers key this on the file's identity, not its URL: a re-signed URL for
154 * the same file keeps the decoded image on screen while the new bytes arrive,
155 * and a different file starts from the slot again.
156 */
157export function ChatMarkdownImage(props: {
158 readonly src: string | null;
159 readonly sourceFailed?: boolean | undefined;
160 readonly unavailableDetail?: string | undefined;
161 readonly alt: string;
162 readonly copyMarkdown: string | undefined;
163 readonly standalone: boolean;
164 readonly className?: string | undefined;
165 readonly style?: CSSProperties | undefined;
166 readonly imageProps?:
167 | Omit<ComponentProps<"img">, "src" | "alt" | "className" | "style">
168 | undefined;
169 readonly actionsSource: MediaActionSource;
170 readonly originalUrl?: string | undefined;
171 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
172}) {
173 const [loadedSrc, setLoadedSrc] = useState<string | null>(null);
174 const [failedSrc, setFailedSrc] = useState<string | null>(null);
175 const src = props.src ?? loadedSrc;
176 const failed = props.sourceFailed === true || (src !== null && failedSrc === src);
177 const settled = src !== null && !failed && (!props.standalone || loadedSrc !== null);
178 // Cached images are complete before `onLoad` can fire.
179 const markLoadedIfComplete = (image: HTMLImageElement | null) => {
180 if (!image) return;
181 if (image.complete && image.naturalWidth > 0) setLoadedSrc(image.currentSrc || image.src);
182 markdownImageItems.set(image, {
183 src,
184 name: props.alt.trim() || "image",
185 actionsSource: props.actionsSource,
186 ...(props.originalUrl ? { originalUrl: props.originalUrl } : {}),
187 });
188 };
189 const imageEvents = (loadingSrc: string) => ({
190 onLoad: () => {
191 setLoadedSrc(loadingSrc);
192 setFailedSrc(null);
193 },
194 onError: () => {
195 setFailedSrc(loadingSrc);
196 setLoadedSrc(null);
197 },
198 });
199
200 if (settled) {
201 return (
202 <MediaActions source={props.actionsSource}>
203 <img
204 {...props.imageProps}
205 ref={markLoadedIfComplete}
206 src={src}
207 alt={props.alt}
208 data-markdown-copy={props.copyMarkdown}
209 decoding="async"
210 loading="lazy"
211 draggable={false}
212 className={cn(
213 CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME,
214 props.className,
215 props.onImageExpand && "cursor-zoom-in",
216 )}
217 style={props.style}
218 {...expandableMarkdownImageProps(props.onImageExpand, props.alt)}
219 {...imageEvents(src)}
220 />
221 </MediaActions>
222 );
223 }
224 if (!props.standalone) {
225 return failed ? (
226 <ChatMarkdownImageFallback
227 alt={props.alt}
228 copyMarkdown={props.copyMarkdown}
229 actionsSource={props.actionsSource}
230 detail={props.unavailableDetail}
231 />
232 ) : (
233 <span
234 id={props.imageProps?.id}
235 data-markdown-copy={props.copyMarkdown}
236 role="status"
237 aria-label="Loading image"
238 className={CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME}
239 />
240 );
241 }
242 return (
243 <MediaActions source={props.actionsSource}>
244 <span
245 id={props.imageProps?.id}
246 data-markdown-copy={props.copyMarkdown}
247 className={cn(
248 CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
249 CHAT_MARKDOWN_IMAGE_FRAME_CLASS_NAME,
250 "relative",
251 )}
252 style={props.style}
253 {...(failed
254 ? { role: "alert" as const }
255 : { role: "status" as const, "aria-label": "Loading image" })}
256 >
257 {failed ? (
258 <span className="flex size-full items-center justify-center p-2 text-center text-xs text-muted-foreground">
259 <ChatMarkdownMediaUnavailableLabel alt={props.alt} detail={props.unavailableDetail} />
260 </span>
261 ) : src !== null ? (
262 <img
263 ref={markLoadedIfComplete}
264 src={src}
265 alt={props.alt}
266 decoding="async"
267 loading="lazy"
268 draggable={false}
269 className="invisible absolute inset-0 size-full"
270 {...imageEvents(src)}
271 />
272 ) : null}
273 </span>
274 </MediaActions>
275 );
276}
277
278export function ChatMarkdownVideo(props: {
279 readonly src: string | null;
280 readonly alt: string;
281 readonly copyMarkdown: string | undefined;
282 readonly originalUrl?: string | undefined;
283 readonly sourceFailed?: boolean | undefined;
284 readonly style?: CSSProperties | undefined;
285 readonly mediaIdentity?: string | undefined;
286 readonly actionsSource?: MediaActionSource | undefined;
287 readonly onRetry?: (() => Promise<unknown>) | undefined;
288}) {
289 return (
290 <MediaVideoPlayer
291 key={props.mediaIdentity ?? props.copyMarkdown ?? props.src}
292 src={props.src}
293 sourceFailed={props.sourceFailed}
294 label={props.alt}
295 originalUrl={props.originalUrl}
296 style={props.style}
297 copyMarkdown={props.copyMarkdown}
298 className={cn(
299 CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
300 CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME,
301 "w-full",
302 )}
303 videoClassName={cn(
304 CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME,
305 CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME,
306 )}
307 onRetry={props.onRetry}
308 actionsSource={props.actionsSource}
309 />
310 );
311}
312
313export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props: {
314 readonly environmentId: EnvironmentId;
315 readonly resource: Extract<
316 AssetResource,
317 {
318 readonly _tag:
319 | "attachment"
320 | "workspace-file"
321 | "media-file"
322 | typeof SOURCE_CONTROL_MEDIA_ASSET
323 | "tool-output-image";
324 }
325 >;
326 readonly kind?: "image" | "video";
327 readonly alt: string;
328 readonly copyMarkdown?: string;
329 readonly srcFragment?: string;
330 readonly standalone?: boolean | undefined;
331 readonly maxHeightRem?: number | undefined;
332 readonly style?: CSSProperties | undefined;
333 readonly className?: string | undefined;
334 readonly imageProps?:
335 | Omit<ComponentProps<"img">, "src" | "alt" | "className" | "style">
336 | undefined;
337 readonly originalUrl?: string | undefined;
338 readonly framed?: boolean | undefined;
339 readonly fallbackSrc?: string | undefined;
340 readonly workspaceRoot?: string | undefined;
341 readonly workspaceMutationId?: string | null | undefined;
342 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
343}) {
344 const resource = props.resource;
345 const threadWorkspaceMutationId = use(WorkspaceMutationIdContext);
346 const workspaceMutationId = props.workspaceMutationId ?? threadWorkspaceMutationId;
347 const assetUrl = useAssetUrlState(
348 props.environmentId,
349 resource,
350 workspaceMutationId !== undefined &&
351 props.kind !== "video" &&
352 (resource._tag === "media-file" || resource._tag === "workspace-file")
353 ? workspaceMutationId
354 : undefined,
355 );
356 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
357 const path =
358 resource._tag === "media-file"
359 ? resource.path
360 : resource._tag === "workspace-file" && props.workspaceRoot
361 ? `${props.workspaceRoot.replace(/[\\/]+$/, "")}/${resource.path}`
362 : undefined;
363 const reference = path
364 ? mediaFileReference(path, props.workspaceRoot)
365 : props.originalUrl
366 ? mediaUrlReference(props.originalUrl)
367 : undefined;
368 const relativePath = reference?.kind === "file" ? reference.relativePath : undefined;
369 const fallbackSrc = assetUrl._tag === "Failure" ? props.fallbackSrc : undefined;
370 const src =
371 assetUrl._tag === "Success"
372 ? assetUrl.url + (props.srcFragment ?? "")
373 : fallbackSrc === undefined
374 ? null
375 : fallbackSrc + (props.srcFragment ?? "");
376 const knownSize = assetUrl._tag === "Success" ? assetUrl.imageDimensions : undefined;
377 const maxHeightRem = props.maxHeightRem ?? 30;
378 const style =
379 props.style ??
380 (knownSize
381 ? authoredImageSizeStyle(knownSize.width, knownSize.height, maxHeightRem)
382 : maxHeightRem !== 30
383 ? { maxHeight: `${maxHeightRem}rem` }
384 : undefined);
385 const actionsSource: MediaActionSource = {
386 kind: props.kind ?? "image",
387 name: props.alt || (props.kind ?? "image"),
388 src,
389 ...(fallbackSrc === undefined
390 ? { asset: { environmentId: props.environmentId, resource } }
391 : {}),
392 ...(reference ? { reference } : {}),
393 ...(relativePath && (resource._tag === "media-file" || resource._tag === "workspace-file")
394 ? {
395 onOpenFile: () =>
396 useRightPanelStore
397 .getState()
398 .openFile(
399 { environmentId: props.environmentId, threadId: resource.threadId },
400 relativePath,
401 ),
402 }
403 : {}),
404 };
405
406 if (props.kind === "video") {
407 return (
408 <ChatMarkdownVideo
409 src={src}
410 sourceFailed={assetUrl._tag === "Failure" && fallbackSrc === undefined}
411 alt={props.alt}
412 copyMarkdown={props.copyMarkdown}
413 originalUrl={props.originalUrl}
414 style={props.style}
415 mediaIdentity={JSON.stringify([props.environmentId, props.resource, props.srcFragment])}
416 onRetry={refreshAssetUrl}
417 actionsSource={actionsSource}
418 />
419 );
420 }
421
422 return (
423 <ChatMarkdownImage
424 key={JSON.stringify([props.environmentId, props.resource, props.srcFragment])}
425 src={src}
426 sourceFailed={assetUrl._tag === "Failure" && fallbackSrc === undefined}
427 unavailableDetail={
428 assetUrl._tag === "Failure" &&
429 assetUrl.reason === "missing-file-access" &&
430 fallbackSrc === undefined
431 ? MISSING_FILE_ACCESS_MESSAGE
432 : undefined
433 }
434 alt={props.alt}
435 copyMarkdown={props.copyMarkdown}
436 standalone={props.standalone ?? true}
437 className={cn(
438 props.framed === false ? undefined : CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME,
439 props.className,
440 )}
441 style={style}
442 imageProps={props.imageProps}
443 actionsSource={actionsSource}
444 originalUrl={props.originalUrl}
445 onImageExpand={props.onImageExpand}
446 />
447 );
448});