Open History to see the last commit
1import { filePreviewDelimiter } from "@t3tools/shared/delimitedPreview";
2import type { EnvironmentId } from "@t3tools/contracts";
3import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
4import { readFilePreviewResponse } from "@t3tools/client-runtime/file-preview";
5import { filePreviewKind, FILE_TEXT_PREVIEW_MAX_BYTES } from "@t3tools/shared/filePreview";
6import { ChevronRightIcon, DownloadIcon, Trash2Icon, WrapTextIcon, XIcon } from "lucide-react";
7import { Check, Code2, Copy, Eye, Table2 } from "lucide";
8import { lazy, Suspense, useEffect, useMemo, useRef, useState } from "react";
9
10import { useAssetUrlRefresh } from "~/assets/assetUrls";
11import ChatMarkdown from "~/components/ChatMarkdown";
12import { MorphIcon } from "~/components/MorphIcon";
13import { ScrollArea } from "~/components/ui/scroll-area";
14import { toastManager } from "~/components/ui/toast";
15import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
16import { useClientSettings, useUpdateClientSettings } from "~/hooks/useSettings";
17import { cn } from "~/lib/utils";
18
19import { AudioPreview } from "./AudioPreview";
20import { BrowserDocumentFrame } from "./BrowserDocumentFrame";
21import { DelimitedTablePreview } from "./DelimitedTablePreview";
22import {
23 FILE_SURFACE_SUBHEADER_CLASS,
24 FileSurfaceAction,
25 FileSurfaceFailure,
26 FileSurfaceLoading,
27 FileSurfaceNotice,
28} from "./fileSurfaceChrome";
29
30const SourcePreview = lazy(() => import("./ReadOnlySourcePreview"));
31
32/** Signed asset URLs live for an hour; treat anything older than this as worth re-minting. */
33const STALE_URL_MS = 5 * 60_000;
34
35/** Highlighted read-only source, loaded on demand so message rendering never waits on the highlighter. */
36export function ReadOnlySourcePreview(props: { name: string; text: string }) {
37 return (
38 <Suspense fallback={<FileSurfaceLoading className="p-4" />}>
39 <SourcePreview {...props} />
40 </Suspense>
41 );
42}
43
44function renderedToggleLabel(mode: "markdown" | "html" | "table", rendered: boolean): string {
45 if (mode === "markdown") return rendered ? "Show markdown source" : "Show rendered markdown";
46 if (mode === "table") return rendered ? "Show source" : "Show table";
47 return rendered ? "Show HTML source" : "Show rendered page";
48}
49
50/**
51 * A captured attachment shown with the same chrome as a workspace file: one
52 * header row with crumbs and icon actions, then the document. Captured bytes
53 * are viewed independently of similarly named files in the workspace.
54 */
55export function AttachmentFilePreview(props: {
56 name: string;
57 mimeType: string;
58 /** Zero when unknown. */
59 sizeBytes: number;
60 file?: Blob | null;
61 asset?: { environmentId: EnvironmentId; attachmentId: string };
62 /** An agent's HTML render, shown in the app theme. */
63 htmlRender?: boolean;
64 /** First crumb: where the file comes from. */
65 origin?: string;
66 onRemove?: () => void;
67 onClose?: () => void;
68}) {
69 const kind = filePreviewKind(props);
70 const delimiter = filePreviewDelimiter(props);
71 const renderedMode =
72 kind === "markdown" ? "markdown" : kind === "html" ? "html" : delimiter ? "table" : null;
73 const attachmentId = props.asset?.attachmentId;
74 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: props.name });
75 const resource = useMemo(
76 () =>
77 attachmentId
78 ? {
79 _tag: "attachment" as const,
80 attachmentId,
81 fileName: props.name,
82 mimeType: props.mimeType,
83 disposition: "inline" as const,
84 }
85 : null,
86 [attachmentId, props.name, props.mimeType],
87 );
88 const refresh = useAssetUrlRefresh(
89 props.file ? null : (props.asset?.environmentId ?? null),
90 props.file ? null : resource,
91 );
92 const downloadResource = useMemo(
93 () => (resource ? { ...resource, disposition: "attachment" as const } : null),
94 [resource],
95 );
96 const prepareDownload = useAssetUrlRefresh(props.asset?.environmentId ?? null, downloadResource);
97 const [saving, setSaving] = useState(false);
98 const [localUrl, setLocalUrl] = useState<string | null>(null);
99 const [remoteUrl, setRemoteUrl] = useState<string | null>(null);
100 const [rendered, setRendered] = useState(true);
101 const [revision, setRevision] = useState(0);
102 const [content, setContent] = useState<{ text: string; truncated: boolean } | null>(null);
103 const [error, setError] = useState<string | null>(null);
104 // Reading source is a separate failure from loading the file: a rendered HTML page can be
105 // fine while its bytes are not UTF-8, and switching back to the page must not stay stuck.
106 const [contentError, setContentError] = useState<string | null>(null);
107 const authorizedAt = useRef(0);
108 useEffect(() => {
109 if (!props.file) return;
110 const url = URL.createObjectURL(props.file);
111 // oxlint-disable-next-line react/set-state-in-effect -- Publish an object URL only after its cleanup is registered for this Blob.
112 setLocalUrl(url);
113 return () => URL.revokeObjectURL(url);
114 }, [props.file]);
115 useEffect(() => {
116 if (props.file) return;
117 let cancelled = false;
118 // Await a fresh signed URL: cached links can expire while the client is suspended.
119 // oxlint-disable-next-line react/set-state-in-effect -- A new preview request clears its previous URL and error.
120 setRemoteUrl(null);
121 setError(null);
122 void refresh()
123 .then((url) => {
124 if (cancelled) return;
125 if (!url) throw new Error("Reconnect to the environment and try again.");
126 authorizedAt.current = Date.now();
127 setRemoteUrl(url);
128 })
129 .catch((cause: unknown) => {
130 if (!cancelled)
131 setError(cause instanceof Error ? cause.message : "The attachment is unavailable.");
132 });
133 return () => {
134 cancelled = true;
135 };
136 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retry must reauthorize the remote file.
137 }, [props.file, refresh, revision]);
138 const url = props.file ? localUrl : remoteUrl;
139 const needsText = kind === "text" || kind === "markdown" || (kind === "html" && !rendered);
140 useEffect(() => {
141 if (!needsText || !url) return;
142 const controller = new AbortController();
143 // oxlint-disable-next-line react/set-state-in-effect -- A new external resource must clear the previous response before loading.
144 setContent(null);
145 setContentError(null);
146 const file = props.file;
147 void (async () => {
148 // A signed URL minted when the file opened may have expired by the time the user
149 // switches to source. Publish its replacement so later mode switches use it too.
150 if (!file && Date.now() - authorizedAt.current > STALE_URL_MS) {
151 const target = await refresh();
152 if (controller.signal.aborted) return;
153 if (!target) throw new Error("Reconnect to the environment and try again.");
154 authorizedAt.current = Date.now();
155 if (target !== url) {
156 setRemoteUrl(target);
157 // The URL change restarts this effect; fetch once with the new authorization.
158 return;
159 }
160 }
161 const response = file
162 ? { ok: true, body: file.stream() }
163 : await fetch(url, {
164 signal: controller.signal,
165 ...(props.sizeBytes > 0
166 ? { headers: { Range: `bytes=0-${FILE_TEXT_PREVIEW_MAX_BYTES}` } }
167 : {}),
168 cache: revision === 0 ? "default" : "reload",
169 });
170 const result = await readFilePreviewResponse(response, controller.signal);
171 if (!controller.signal.aborted) setContent(result);
172 })().catch((cause: unknown) => {
173 if (!controller.signal.aborted)
174 setContentError(cause instanceof Error ? cause.message : "Could not load this file.");
175 });
176 return () => controller.abort();
177 }, [url, needsText, revision, props.sizeBytes, props.file, refresh]);
178 const failure = error ?? (needsText ? contentError : null);
179 const wordWrap = useClientSettings((settings) => settings.wordWrap);
180 const updateClientSettings = useUpdateClientSettings();
181 // Only the raw-text body honours word wrap. A rendered table or Markdown lays itself out,
182 // so offering the toggle there would be a control that visibly does nothing.
183 const showsRawText =
184 failure === null &&
185 needsText &&
186 content !== null &&
187 !(delimiter && rendered) &&
188 !(kind === "markdown" && rendered);
189
190 const save = () => {
191 setSaving(true);
192 void (async () => {
193 try {
194 let file = props.file;
195 if (!file) {
196 const target = await prepareDownload();
197 if (!target) throw new Error("Reconnect to the environment and try again.");
198 const response = await fetch(target);
199 if (!response.ok) throw new Error("The file could not be loaded. Try again.");
200 file = await response.blob();
201 }
202 // A Blob keeps cross-origin downloads inside the desktop client instead of
203 // navigating its custom app scheme to an external browser.
204 const downloadUrl = URL.createObjectURL(file);
205 try {
206 const anchor = document.createElement("a");
207 anchor.href = downloadUrl;
208 anchor.download = props.name;
209 anchor.click();
210 } finally {
211 setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000);
212 }
213 } catch (cause) {
214 toastManager.add({
215 type: "error",
216 title: "Could not save file",
217 description: cause instanceof Error ? cause.message : "Please try again.",
218 });
219 } finally {
220 setSaving(false);
221 }
222 })();
223 };
224
225 const body = failure ? (
226 <FileSurfaceFailure
227 message={failure}
228 onRetry={() => {
229 // Clearing first lets a local Blob preview remount: its URL never changes, so the
230 // revision bump alone would re-render the same failed element.
231 setError(null);
232 setRevision((value) => value + 1);
233 }}
234 />
235 ) : !url || (needsText && !content) ? (
236 <FileSurfaceLoading />
237 ) : needsText && content ? (
238 delimiter && rendered ? (
239 <DelimitedTablePreview name={props.name} text={content.text} delimiter={delimiter} />
240 ) : kind === "markdown" && rendered ? (
241 <ScrollArea className="min-h-0 flex-1">
242 <ChatMarkdown text={content.text} cwd={undefined} className="mx-auto max-w-4xl px-6 py-5" />
243 </ScrollArea>
244 ) : (
245 <ReadOnlySourcePreview name={props.name} text={content.text} />
246 )
247 ) : kind === "pdf" || kind === "html" ? (
248 <BrowserDocumentFrame
249 src={url}
250 title={props.name}
251 pdf={kind === "pdf"}
252 htmlRender={props.htmlRender === true}
253 />
254 ) : kind === "audio" ? (
255 <AudioPreview src={url} name={props.name} onError={() => setError("Unable to load audio.")} />
256 ) : kind === "video" ? (
257 <div className="flex min-h-0 flex-1 items-center justify-center bg-black">
258 <video
259 controls
260 playsInline
261 src={url}
262 aria-label={props.name}
263 className="max-h-full max-w-full"
264 onError={() => setError("Unable to load video.")}
265 />
266 </div>
267 ) : kind === "image" ? (
268 <div className="flex min-h-0 flex-1 items-center justify-center overflow-auto p-4">
269 <img
270 src={url}
271 alt={props.name}
272 className="max-h-full max-w-full object-contain"
273 onError={() => setError("Unable to load image.")}
274 />
275 </div>
276 ) : (
277 <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-1 px-6 text-center">
278 <p className="text-sm font-medium">No preview for this file</p>
279 <p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
280 Save it to open in an app that supports {props.name.split(".").at(-1) || "this format"}{" "}
281 files.
282 </p>
283 </div>
284 );
285
286 return (
287 <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-background">
288 <div className={cn(FILE_SURFACE_SUBHEADER_CLASS)} data-surface-subheader>
289 <div className="flex min-w-0 flex-1 items-center text-xs">
290 <span className="shrink-0 px-0.5 text-muted-foreground">
291 {props.origin ?? "Attachment"}
292 </span>
293 <ChevronRightIcon className="mx-1 size-3.5 shrink-0 text-muted-foreground/60" />
294 <span aria-current="page" className="min-w-0 truncate px-0.5 font-medium text-foreground">
295 {props.name}
296 </span>
297 {props.sizeBytes > 0 ? (
298 <span className="ml-2 shrink-0 text-muted-foreground">
299 {formatAttachmentSize(props.sizeBytes)}
300 </span>
301 ) : null}
302 </div>
303 {renderedMode ? (
304 <FileSurfaceAction
305 label={renderedToggleLabel(renderedMode, rendered)}
306 pressed={rendered}
307 onPress={() => setRendered((value) => !value)}
308 >
309 <MorphIcon
310 className="size-3.5"
311 icon={rendered ? Code2 : renderedMode === "table" ? Table2 : Eye}
312 />
313 </FileSurfaceAction>
314 ) : null}
315 {showsRawText ? (
316 <FileSurfaceAction
317 label={wordWrap ? "Disable word wrap" : "Enable word wrap"}
318 pressed={wordWrap}
319 onPress={() => updateClientSettings({ wordWrap: !wordWrap })}
320 >
321 <WrapTextIcon className="size-3.5" />
322 </FileSurfaceAction>
323 ) : null}
324 {content ? (
325 <FileSurfaceAction
326 label={isCopied ? "Copied" : content.truncated ? "Copy preview" : "Copy contents"}
327 onPress={() => copyToClipboard(content.text, undefined)}
328 >
329 <MorphIcon className="size-3.5" icon={isCopied ? Check : Copy} />
330 </FileSurfaceAction>
331 ) : null}
332 {url ? (
333 <FileSurfaceAction
334 label={saving ? "Preparing file…" : "Save file"}
335 disabled={saving}
336 onPress={save}
337 >
338 <DownloadIcon className="size-3.5" />
339 </FileSurfaceAction>
340 ) : null}
341 {props.onRemove ? (
342 <FileSurfaceAction label="Remove from draft" onPress={props.onRemove}>
343 <Trash2Icon className="size-3.5" />
344 </FileSurfaceAction>
345 ) : null}
346 {props.onClose ? (
347 <FileSurfaceAction label="Close" onPress={props.onClose}>
348 <XIcon className="size-3.5" />
349 </FileSurfaceAction>
350 ) : null}
351 </div>
352 {content?.truncated ? (
353 <FileSurfaceNotice>
354 Preview limited to the first 1 MB
355 {props.sizeBytes > 0 ? ` of a ${props.sizeBytes.toLocaleString()} byte file` : ""}. Save
356 the file to read it in full.
357 </FileSurfaceNotice>
358 ) : null}
359 {body}
360 </div>
361 );
362}