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