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 * An unavailable file has no dimensions, so its `aspect-video w-full` frame
89 * would fill the row and `max-height` would squash it. Bound the width so the
90 * frame stays 16:9 at the height cap.
91 */
92function unavailableImageSizeStyle(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 readonly imageProps?:
198 | Omit<ComponentProps<"img">, "src" | "alt" | "className" | "style">
199 | undefined;
200 readonly actionsSource: MediaActionSource;
201 readonly originalUrl?: string | undefined;
202 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
203}) {
204 const gt = useGT();
205 const m = useMessages();
206 const [loadedSrc, setLoadedSrc] = useState<string | null>(null);
207 const [failedSrc, setFailedSrc] = useState<string | null>(null);
208 const src = props.src ?? loadedSrc;
209 const failed = props.sourceFailed === true || (src !== null && failedSrc === src);
210 const settled = src !== null && !failed && (!props.standalone || loadedSrc !== null);
211 // Cached images are complete before `onLoad` can fire.
212 const markLoadedIfComplete = (image: HTMLImageElement | null) => {
213 if (!image) return;
214 if (image.complete && image.naturalWidth > 0) setLoadedSrc(image.currentSrc || image.src);
215 markdownImageItems.set(image, {
216 src,
217 name: props.alt.trim() || "image",
218 actionsSource: props.actionsSource,
219 ...(props.originalUrl ? { originalUrl: props.originalUrl } : {}),
220 });
221 };
222 const imageEvents = (loadingSrc: string) => ({
223 onLoad: () => {
224 setLoadedSrc(loadingSrc);
225 setFailedSrc(null);
226 },
227 onError: () => {
228 setFailedSrc(loadingSrc);
229 setLoadedSrc(null);
230 },
231 });
232
233 if (settled) {
234 return (
235 <MediaActions source={props.actionsSource}>
236 <img
237 {...props.imageProps}
238 ref={markLoadedIfComplete}
239 src={src}
240 alt={props.alt}
241 data-markdown-copy={props.copyMarkdown}
242 decoding="async"
243 loading="lazy"
244 draggable={false}
245 className={cn(
246 CHAT_MARKDOWN_IMAGE_SIZE_CLASS_NAME,
247 props.className,
248 props.onImageExpand && "cursor-zoom-in",
249 )}
250 style={props.style}
251 {...expandableMarkdownImageProps(props.onImageExpand, props.alt, m)}
252 {...imageEvents(src)}
253 />
254 </MediaActions>
255 );
256 }
257 if (!props.standalone) {
258 return failed ? (
259 <ChatMarkdownImageFallback
260 alt={props.alt}
261 copyMarkdown={props.copyMarkdown}
262 actionsSource={props.actionsSource}
263 detail={props.unavailableDetail}
264 />
265 ) : (
266 <span
267 id={props.imageProps?.id}
268 data-markdown-copy={props.copyMarkdown}
269 role="status"
270 aria-label={gt("Loading image")}
271 className={CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME}
272 />
273 );
274 }
275 return (
276 <MediaActions source={props.actionsSource}>
277 <span
278 id={props.imageProps?.id}
279 data-markdown-copy={props.copyMarkdown}
280 className={cn(
281 CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
282 CHAT_MARKDOWN_IMAGE_FRAME_CLASS_NAME,
283 "relative",
284 )}
285 style={props.style}
286 {...(failed
287 ? { role: "alert" as const }
288 : { role: "status" as const, "aria-label": gt("Loading image") })}
289 >
290 {failed ? (
291 <span className="flex size-full items-center justify-center p-2 text-center text-xs text-muted-foreground">
292 <ChatMarkdownMediaUnavailableLabel alt={props.alt} detail={props.unavailableDetail} />
293 </span>
294 ) : src !== null ? (
295 <img
296 ref={markLoadedIfComplete}
297 src={src}
298 alt={props.alt}
299 decoding="async"
300 loading="lazy"
301 draggable={false}
302 className="invisible absolute inset-0 size-full"
303 {...imageEvents(src)}
304 />
305 ) : null}
306 </span>
307 </MediaActions>
308 );
309}
310
311export function ChatMarkdownVideo(props: {
312 readonly src: string | null;
313 readonly alt: string;
314 readonly copyMarkdown: string | undefined;
315 readonly originalUrl?: string | undefined;
316 readonly sourceFailed?: boolean | undefined;
317 readonly unavailableDetail?: string | undefined;
318 readonly style?: CSSProperties | undefined;
319 readonly mediaIdentity?: string | undefined;
320 readonly actionsSource?: MediaActionSource | undefined;
321 readonly onRetry?: (() => Promise<unknown>) | undefined;
322}) {
323 return (
324 <MediaVideoPlayer
325 key={props.mediaIdentity ?? props.copyMarkdown ?? props.src}
326 src={props.src}
327 sourceFailed={props.sourceFailed}
328 unavailableDetail={props.unavailableDetail}
329 label={props.alt}
330 originalUrl={props.originalUrl}
331 style={props.style}
332 copyMarkdown={props.copyMarkdown}
333 className={cn(
334 CHAT_MARKDOWN_MEDIA_LAYOUT_CLASS_NAME,
335 CHAT_MARKDOWN_MEDIA_MAX_WIDTH_CLASS_NAME,
336 "w-full",
337 )}
338 videoClassName={cn(
339 CHAT_MARKDOWN_MEDIA_BOUNDS_CLASS_NAME,
340 CHAT_MARKDOWN_MEDIA_FRAME_CLASS_NAME,
341 )}
342 onRetry={props.onRetry}
343 actionsSource={props.actionsSource}
344 />
345 );
346}
347
348type ChatMarkdownAssetResource = Extract<
349 AssetResource,
350 {
351 readonly _tag:
352 | "attachment"
353 | "workspace-file"
354 | "media-file"
355 | typeof SOURCE_CONTROL_MEDIA_ASSET
356 | "tool-output-image";
357 }
358>;
359
360export function assetMediaActionsSource(input: {
361 readonly environmentId: EnvironmentId;
362 readonly resource: ChatMarkdownAssetResource;
363 readonly kind: "image" | "video";
364 readonly name: string;
365 readonly src: string | null;
366 readonly workspaceRoot?: string | undefined;
367 readonly originalUrl?: string | undefined;
368 readonly downloadable?: boolean | undefined;
369}): MediaActionSource {
370 const { environmentId, resource } = input;
371 const path =
372 resource._tag === "media-file"
373 ? resource.path
374 : resource._tag === "workspace-file" && input.workspaceRoot
375 ? `${input.workspaceRoot.replace(/[\\/]+$/, "")}/${resource.path}`
376 : undefined;
377 const reference = path
378 ? mediaFileReference(path, input.workspaceRoot)
379 : input.originalUrl
380 ? mediaUrlReference(input.originalUrl)
381 : undefined;
382 const relativePath = reference?.kind === "file" ? reference.relativePath : undefined;
383 return {
384 kind: input.kind,
385 name: input.name,
386 src: input.src,
387 ...(input.downloadable === false ? {} : { asset: { environmentId, resource } }),
388 ...(reference ? { reference } : {}),
389 ...(relativePath && (resource._tag === "media-file" || resource._tag === "workspace-file")
390 ? {
391 onOpenFile: () =>
392 useRightPanelStore
393 .getState()
394 .openFile({ environmentId, threadId: resource.threadId }, relativePath),
395 }
396 : {}),
397 };
398}
399
400export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props: {
401 readonly environmentId: EnvironmentId;
402 readonly resource: ChatMarkdownAssetResource;
403 readonly kind?: "image" | "video";
404 readonly alt: string;
405 readonly copyMarkdown?: string;
406 readonly srcFragment?: string;
407 readonly standalone?: boolean | undefined;
408 readonly maxHeightRem?: number | undefined;
409 readonly style?: CSSProperties | undefined;
410 readonly className?: string | undefined;
411 readonly imageProps?:
412 | Omit<ComponentProps<"img">, "src" | "alt" | "className" | "style">
413 | undefined;
414 readonly originalUrl?: string | undefined;
415 readonly framed?: boolean | undefined;
416 readonly fallbackSrc?: string | undefined;
417 readonly workspaceRoot?: string | undefined;
418 readonly workspaceMutationId?: string | null | undefined;
419 readonly onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
420}) {
421 const gt = useGT();
422 const resource = props.resource;
423 const threadWorkspaceMutationId = use(WorkspaceMutationIdContext);
424 const workspaceMutationId = props.workspaceMutationId ?? threadWorkspaceMutationId;
425 const assetUrl = useAssetUrlState(
426 props.environmentId,
427 resource,
428 workspaceMutationId !== undefined &&
429 props.kind !== "video" &&
430 (resource._tag === "media-file" || resource._tag === "workspace-file")
431 ? workspaceMutationId
432 : undefined,
433 );
434 const refreshAssetUrl = useAssetUrlRefresh(props.environmentId, resource);
435 const fallbackSrc = assetUrl._tag === "Failure" ? props.fallbackSrc : undefined;
436 const missingFileAccess =
437 assetUrl._tag === "Failure" &&
438 assetUrl.reason === "missing-file-access" &&
439 fallbackSrc === undefined;
440 const unavailableDetail = missingFileAccess
441 ? gt("This connection cannot read host files. Pair again with a new link to view it.")
442 : undefined;
443 const src =
444 assetUrl._tag === "Success"
445 ? assetUrl.url + (props.srcFragment ?? "")
446 : fallbackSrc === undefined
447 ? null
448 : fallbackSrc + (props.srcFragment ?? "");
449 const knownSize = assetUrl._tag === "Success" ? assetUrl.imageDimensions : undefined;
450 const maxHeightRem = props.maxHeightRem ?? 30;
451 const unavailable = assetUrl._tag === "Failure" && fallbackSrc === undefined;
452 const style =
453 props.style ??
454 (knownSize
455 ? authoredImageSizeStyle(knownSize.width, knownSize.height, maxHeightRem)
456 : unavailable
457 ? unavailableImageSizeStyle(maxHeightRem)
458 : maxHeightRem !== 30
459 ? { maxHeight: `${maxHeightRem}rem` }
460 : undefined);
461 const actionsSource = assetMediaActionsSource({
462 environmentId: props.environmentId,
463 resource,
464 kind: props.kind ?? "image",
465 name: props.alt || (props.kind ?? "image"),
466 src,
467 workspaceRoot: props.workspaceRoot,
468 originalUrl: props.originalUrl,
469 downloadable: fallbackSrc === undefined,
470 });
471
472 if (props.kind === "video") {
473 return (
474 <ChatMarkdownVideo
475 src={src}
476 sourceFailed={unavailable}
477 unavailableDetail={unavailableDetail}
478 alt={props.alt}
479 copyMarkdown={props.copyMarkdown}
480 originalUrl={props.originalUrl}
481 style={props.style}
482 mediaIdentity={JSON.stringify([props.environmentId, props.resource, props.srcFragment])}
483 // Re-signing cannot grant the file access this connection lacks.
484 onRetry={missingFileAccess ? undefined : refreshAssetUrl}
485 actionsSource={actionsSource}
486 />
487 );
488 }
489
490 return (
491 <ChatMarkdownImage
492 key={JSON.stringify([props.environmentId, props.resource, props.srcFragment])}
493 src={src}
494 sourceFailed={unavailable}
495 unavailableDetail={unavailableDetail}
496 alt={props.alt}
497 copyMarkdown={props.copyMarkdown}
498 standalone={props.standalone ?? true}
499 className={cn(
500 props.framed === false ? undefined : CHAT_MARKDOWN_WORKSPACE_IMAGE_CLASS_NAME,
501 props.className,
502 )}
503 style={style}
504 imageProps={props.imageProps}
505 actionsSource={actionsSource}
506 originalUrl={props.originalUrl}
507 onImageExpand={props.onImageExpand}
508 />
509 );
510});