Open History to see the last commit
1import {
2 clampFileAttachmentUploadBytes,
3 fileAttachmentTooLargeMessage,
4} from "@t3tools/client-runtime/state/attachments";
5import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
6import {
7 isProviderSendTurnSupportedImageMimeType,
8 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
9 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
10 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
11 type EnvironmentId,
12 type PastedTextAttachmentSource,
13 type UploadChatImageAttachment,
14} from "@t3tools/contracts";
15import type { AttachmentUploadStatus } from "@t3tools/client-runtime/state/attachment-uploads";
16import type { DocumentPickerResult } from "expo-document-picker";
17import { msg } from "gt-react-native";
18import { m } from "../i18n/messages";
19import { estimateBase64ByteSize } from "./base64";
20import {
21 COMPOSER_ATTACHMENT_DIRECTORY,
22 isComposerAttachmentFileRetained,
23 resolveOwnedComposerAttachmentFileUri,
24} from "./composerAttachmentFiles";
25import { imageMimeType } from "@t3tools/shared/image";
26import { videoMimeType } from "@t3tools/shared/video";
27import { fitComposerImage, renderPhoto } from "./composerImageFit";
28import { beginForegroundHandoff } from "./foreground-handoff";
29import { uuidv4 } from "./uuid";
30import { writeFileAtomically } from "./atomic-file";
31
32export interface DraftComposerImageAttachment extends Omit<UploadChatImageAttachment, "dataUrl"> {
33 readonly id: string;
34 readonly previewUri: string;
35 readonly fileUri?: string;
36 readonly dataUrl?: string;
37 readonly uploadedAttachmentId?: string;
38 readonly uploadEnvironmentId?: EnvironmentId;
39}
40
41export interface DraftComposerFileAttachment {
42 readonly id: string;
43 readonly type: "file";
44 readonly name: string;
45 readonly mimeType: string;
46 readonly sizeBytes: number;
47 readonly fileUri: string;
48 readonly source?: PastedTextAttachmentSource;
49 readonly uploadedAttachmentId?: string;
50 readonly uploadEnvironmentId?: EnvironmentId;
51}
52
53export async function createPastedTextComposerAttachment(input: {
54 readonly text: string;
55 readonly name: string;
56 readonly maxBytes: number;
57}): Promise<DraftComposerFileAttachment> {
58 const bytes = new TextEncoder().encode(input.text).byteLength;
59 if (bytes <= 0) {
60 throw new Error(m(msg("Clipboard is empty.")));
61 }
62 if (bytes > input.maxBytes) {
63 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes, m));
64 }
65
66 const { Directory, File, Paths } = await import("expo-file-system");
67 const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY);
68 directory.create({ idempotent: true, intermediates: true });
69 const file = new File(directory, `${uuidv4()}-${input.name}`);
70 await writeFileAtomically(file, input.text);
71 return {
72 id: uuidv4(),
73 type: "file",
74 name: input.name,
75 mimeType: "text/plain;charset=utf-8",
76 sizeBytes: bytes,
77 fileUri: file.uri,
78 source: { _tag: "pasted-text" },
79 };
80}
81
82export type DraftComposerAttachment = DraftComposerImageAttachment | DraftComposerFileAttachment;
83
84/**
85 * Non-media attachments require chip references; missing references mean lost draft files.
86 * A chip cannot retry an upload or show its progress, so a document whose upload failed joins
87 * the strip until its retry finishes.
88 */
89export function composerStripAttachments(
90 attachments: ReadonlyArray<DraftComposerAttachment>,
91 uploadStatus: (attachment: DraftComposerAttachment) => AttachmentUploadStatus | undefined,
92): ReadonlyArray<DraftComposerAttachment> {
93 return attachments.filter((attachment) => {
94 if (
95 attachment.type === "image" ||
96 imageMimeType(attachment) !== null ||
97 videoMimeType(attachment) !== null
98 ) {
99 return true;
100 }
101 const upload = uploadStatus(attachment);
102 return (
103 upload?.status === "failed" || (upload?.status === "uploading" && upload.retrying === true)
104 );
105 });
106}
107
108/** Promote legacy document-picked images only when their originals fit the image contract. */
109export function isComposerImageAttachment(
110 attachment: DraftComposerAttachment,
111): attachment is DraftComposerImageAttachment {
112 return (
113 attachment.type === "image" ||
114 (attachment.sizeBytes <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES &&
115 imageMimeType(attachment) !== null)
116 );
117}
118
119export type FileBackedComposerAttachment = DraftComposerAttachment & { readonly fileUri: string };
120
121export function isFileBackedComposerAttachment(
122 attachment: DraftComposerAttachment,
123): attachment is FileBackedComposerAttachment {
124 return attachment.fileUri !== undefined;
125}
126
127/** Legacy inline images have only a local draft id, so a remote asset lookup cannot load them. */
128export function composerAttachmentInlineUri(
129 attachment: DraftComposerAttachment | undefined,
130): string | undefined {
131 if (attachment === undefined || isFileBackedComposerAttachment(attachment)) return undefined;
132 return attachment.type === "image" ? (attachment.dataUrl ?? attachment.previewUri) : undefined;
133}
134
135const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
136const ATTACHMENT_COPY_CHUNK_BYTES = 64 * 1024;
137
138// Android's java.net.URI rejects characters expo-file-system leaves unencoded, such as `[` and `]`.
139function safeComposerAttachmentName(name: string): string {
140 return name.replace(/[^\w. -]/g, "-") || "file";
141}
142
143export async function persistComposerAttachmentFile(
144 uri: string,
145 name: string,
146 maxBytes?: number,
147): Promise<string> {
148 const { Directory, File, FileMode, Paths } = await import("expo-file-system");
149 const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY);
150 directory.create({ idempotent: true, intermediates: true });
151 const prefix = `${uuidv4()}-`;
152 // The basename is ASCII. Keep its tail for the extension within the 255-byte filesystem limit.
153 const nameBudget = 255 - prefix.length;
154 const destination = new File(
155 directory,
156 prefix + safeComposerAttachmentName(name).slice(-nameBudget),
157 );
158 const source = new File(uri);
159 const sourceSize = source.size;
160 if (
161 maxBytes !== undefined &&
162 (sourceSize === null || (sourceSize === 0 && uri.startsWith("content:")))
163 ) {
164 destination.create();
165 try {
166 const reader = source.open(FileMode.ReadOnly);
167 try {
168 const writer = destination.open(FileMode.WriteOnly);
169 try {
170 let copiedBytes = 0;
171 while (true) {
172 const chunk = await reader.readBytes(
173 Math.min(ATTACHMENT_COPY_CHUNK_BYTES, maxBytes - copiedBytes + 1),
174 );
175 if (chunk.byteLength === 0) {
176 break;
177 }
178 copiedBytes += chunk.byteLength;
179 if (copiedBytes > maxBytes) {
180 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes, m));
181 }
182 await writer.writeBytes(chunk);
183 }
184 } finally {
185 writer.close();
186 }
187 } finally {
188 reader.close();
189 }
190 } catch (error) {
191 if (destination.exists) {
192 destination.delete();
193 }
194 throw error;
195 }
196 return destination.uri;
197 }
198
199 if (maxBytes !== undefined && sourceSize !== null && sourceSize > maxBytes) {
200 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes, m));
201 }
202 try {
203 await source.copy(destination);
204 } catch (error) {
205 // Failed copies may leave untracked partial files; delete before surfacing failure.
206 try {
207 if (destination.exists) {
208 destination.delete();
209 }
210 } catch (cleanupError) {
211 console.warn("[composer-attachments] could not remove a partial copy", cleanupError);
212 }
213 throw error;
214 }
215 // Android content streams may exceed reported size; validate the persisted copy.
216 const copiedSize = destination.size;
217 if (maxBytes !== undefined && copiedSize !== null && copiedSize > maxBytes) {
218 try {
219 if (destination.exists) {
220 destination.delete();
221 }
222 } catch (cleanupError) {
223 console.warn("[composer-attachments] could not remove an oversized copy", cleanupError);
224 }
225 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes, m));
226 }
227 return destination.uri;
228}
229
230async function ownedComposerImageAttachment(input: {
231 readonly fileUri: string;
232 readonly name: string;
233 readonly mimeType: string;
234}): Promise<DraftComposerImageAttachment> {
235 try {
236 const { File } = await import("expo-file-system");
237 const sizeBytes = new File(input.fileUri).size;
238 if (sizeBytes === null || sizeBytes <= 0) {
239 throw new Error(m(msg("''{name}'' is empty or could not be read.", { name: input.name })));
240 }
241 if (sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
242 throw new Error(
243 fileAttachmentTooLargeMessage(input.name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, m),
244 );
245 }
246 return {
247 ...input,
248 id: uuidv4(),
249 type: "image",
250 sizeBytes,
251 previewUri: input.fileUri,
252 };
253 } catch (error) {
254 await removePersistedComposerAttachmentFile(input.fileUri);
255 throw error;
256 }
257}
258
259export async function removePersistedComposerAttachmentFile(uri: string): Promise<void> {
260 try {
261 const { File, Paths } = await import("expo-file-system");
262 const ownedUri = resolveOwnedComposerAttachmentFileUri(uri, Paths.document.uri);
263 if (ownedUri === null || isComposerAttachmentFileRetained(ownedUri)) {
264 return;
265 }
266 const file = new File(ownedUri);
267 if (file.exists) {
268 file.delete();
269 }
270 } catch (error) {
271 console.warn("[composer-attachments] could not remove local file", error);
272 }
273}
274
275export async function createComposerFileAttachment(input: {
276 readonly uri: string;
277 readonly name: string;
278 readonly mimeType: string;
279 readonly sizeBytes: number | null;
280 readonly maxBytes: number;
281}): Promise<DraftComposerFileAttachment> {
282 if (input.sizeBytes !== null && input.sizeBytes > input.maxBytes) {
283 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes, m));
284 }
285 const { File } = await import("expo-file-system");
286 const fileUri = await persistComposerAttachmentFile(input.uri, input.name, input.maxBytes);
287 try {
288 const sizeBytes = new File(fileUri).size ?? input.sizeBytes ?? 0;
289 if (sizeBytes <= 0) {
290 throw new Error(m(msg("''{name}'' is empty or could not be read.", { name: input.name })));
291 }
292 if (sizeBytes > input.maxBytes) {
293 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes, m));
294 }
295 return {
296 id: uuidv4(),
297 type: "file",
298 name: input.name,
299 mimeType: input.mimeType,
300 sizeBytes,
301 fileUri,
302 };
303 } catch (error) {
304 await removePersistedComposerAttachmentFile(fileUri);
305 throw error;
306 }
307}
308
309export async function pickComposerFiles(input: {
310 readonly existingCount: number;
311 readonly maxBytes?: number;
312 readonly acceptSelection?: () => boolean;
313}): Promise<{
314 readonly files: ReadonlyArray<DraftComposerAttachment>;
315 readonly error: string | null;
316}> {
317 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
318 if (remainingSlots <= 0) {
319 return {
320 files: [],
321 error: m(
322 msg("You can attach up to {max} files per message.", {
323 max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
324 }),
325 ),
326 };
327 }
328
329 const { getDocumentAsync } = await import("expo-document-picker");
330 const endHandoff = beginForegroundHandoff();
331 let result: DocumentPickerResult;
332 try {
333 // Import a readable cache copy because FileSystem may not read provider URIs directly.
334 result = await getDocumentAsync({ multiple: true, copyToCacheDirectory: true });
335 } catch (cause) {
336 return {
337 files: [],
338 error: errorDisplayMessage(cause, m) ?? m(msg("Could not open the file picker.")),
339 };
340 } finally {
341 endHandoff();
342 }
343 if (result.canceled || input.acceptSelection?.() === false) {
344 return { files: [], error: null };
345 }
346
347 const maxBytes = clampFileAttachmentUploadBytes(
348 input.maxBytes ?? PROVIDER_SEND_TURN_MAX_FILE_BYTES,
349 );
350 const attachments: DraftComposerAttachment[] = [];
351 let error: string | null = null;
352 let exceededAttachmentLimit = false;
353 for (const file of result.assets) {
354 if (attachments.length >= remainingSlots) {
355 exceededAttachmentLimit = true;
356 break;
357 }
358 // SAF can return blank display names, but the wire contract rejects them; fill before persisting.
359 const name = file.name.trim().length > 0 ? file.name : "file";
360 try {
361 const mimeType = imageMimeType({ name, mimeType: file.mimeType ?? "" });
362 const attachment = await createComposerFileAttachment({
363 uri: file.uri,
364 name,
365 mimeType: file.mimeType || "application/octet-stream",
366 sizeBytes: file.size ?? null,
367 maxBytes:
368 mimeType === null ? maxBytes : Math.max(maxBytes, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES),
369 });
370 if (mimeType === null || attachment.sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
371 attachments.push(attachment);
372 continue;
373 }
374 const { File } = await import("expo-file-system");
375 let fileUri = attachment.fileUri;
376 try {
377 const original = await new File(fileUri).base64();
378 const candidate = await fitComposerImage({ uri: fileUri, mimeType, base64: original });
379 const fitted =
380 candidate !== null &&
381 estimateBase64ByteSize(candidate.base64) <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
382 ? candidate
383 : null;
384 if (fitted !== null) {
385 fileUri = await persistComposerAttachmentFile(
386 fitted.uri,
387 name,
388 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
389 );
390 await removePersistedComposerAttachmentFile(attachment.fileUri);
391 }
392 } catch (cause) {
393 await removePersistedComposerAttachmentFile(attachment.fileUri);
394 throw cause;
395 }
396 attachments.push(await ownedComposerImageAttachment({ fileUri, name, mimeType }));
397 } catch (cause) {
398 error = errorDisplayMessage(cause, m) ?? m(msg("Could not read ''{name}''.", { name }));
399 }
400 }
401 if (exceededAttachmentLimit) {
402 error = m(
403 msg("You can attach up to {max} files per message.", {
404 max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
405 }),
406 );
407 }
408 return { files: attachments, error };
409}
410
411async function loadImagePicker() {
412 try {
413 return await import("expo-image-picker");
414 } catch (error) {
415 throw new Error(m(msg("The photo library is unavailable right now.")), { cause: error });
416 }
417}
418
419export async function pickComposerImages(input: { readonly existingCount: number }): Promise<{
420 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
421 readonly error: string | null;
422}> {
423 const result = await pickComposerMedia(input);
424 return {
425 images: result.attachments.filter((attachment) => attachment.type === "image"),
426 error: result.error,
427 };
428}
429
430export async function pickComposerMedia(input: {
431 readonly existingCount: number;
432 readonly maxVideoBytes?: number;
433 readonly acceptSelection?: () => boolean;
434}): Promise<{
435 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
436 readonly error: string | null;
437}> {
438 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
439 if (remainingSlots <= 0) {
440 return {
441 attachments: [],
442 error: m(
443 msg("You can attach up to {max} attachments per message.", {
444 max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
445 }),
446 ),
447 };
448 }
449
450 let imagePicker: Awaited<ReturnType<typeof loadImagePicker>>;
451 try {
452 imagePicker = await loadImagePicker();
453 } catch (error) {
454 return {
455 attachments: [],
456 error: errorDisplayMessage(error, m) ?? m(msg("The photo library is unavailable right now.")),
457 };
458 }
459
460 // Android pickers report background state; guard against deferred restarts mid-pick.
461 const endHandoff = beginForegroundHandoff();
462 let result: Awaited<ReturnType<typeof imagePicker.launchImageLibraryAsync>>;
463 try {
464 result = await imagePicker.launchImageLibraryAsync({
465 mediaTypes: input.maxVideoBytes === undefined ? ["images"] : ["images", "videos"],
466 allowsMultipleSelection: true,
467 selectionLimit: remainingSlots,
468 // Base64 makes iOS decode all full-size photos and stalls JS with large strings; read bytes only as needed.
469 base64: false,
470 quality: 1,
471 shouldDownloadFromNetwork: true,
472 });
473 } catch (error) {
474 return {
475 attachments: [],
476 error: errorDisplayMessage(error, m) ?? m(msg("Could not open the photo library.")),
477 };
478 } finally {
479 endHandoff();
480 }
481
482 if (result.canceled || input.acceptSelection?.() === false) {
483 return {
484 attachments: [],
485 error: null,
486 };
487 }
488
489 const attachments: DraftComposerAttachment[] = [];
490 let error: string | null = null;
491
492 for (const asset of result.assets) {
493 if (attachments.length >= remainingSlots) {
494 error = m(
495 msg("You can attach up to {max} attachments per message.", {
496 max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
497 }),
498 );
499 break;
500 }
501 const mimeType = asset.mimeType?.toLowerCase();
502 if (asset.type === "video" || mimeType?.startsWith("video/")) {
503 if (input.maxVideoBytes === undefined) {
504 error = m(msg("Video attachments are unavailable here."));
505 continue;
506 }
507 try {
508 const { File } = await import("expo-file-system");
509 const file = new File(asset.uri);
510 attachments.push(
511 await createComposerFileAttachment({
512 uri: asset.uri,
513 name: asset.fileName?.trim() || file.name || "video",
514 mimeType: mimeType || file.type || "application/octet-stream",
515 sizeBytes: asset.fileSize ?? null,
516 maxBytes: clampFileAttachmentUploadBytes(input.maxVideoBytes),
517 }),
518 );
519 } catch (cause) {
520 error =
521 errorDisplayMessage(cause, m) ??
522 m(msg("Could not read ''{name}''.", { name: asset.fileName ?? "video" }));
523 }
524 continue;
525 }
526 if (asset.type !== "image" && !mimeType?.startsWith("image/")) {
527 error = m(msg("Unsupported file type for ''{name}''.", { name: asset.fileName ?? "image" }));
528 continue;
529 }
530
531 const name = asset.fileName?.trim() || "image";
532 // Android content streams can exceed their reported size; measure the file before loading bytes into JS.
533 let sourceBytes: number | null = null;
534 try {
535 const { File } = await import("expo-file-system");
536 sourceBytes = new File(asset.uri).size;
537 } catch {
538 sourceBytes = null;
539 }
540 // Pass through supported, under-cap originals unchanged to preserve transparency and animation.
541 const originalMimeType =
542 mimeType !== undefined &&
543 isProviderSendTurnSupportedImageMimeType(mimeType) &&
544 sourceBytes !== null &&
545 sourceBytes > 0 &&
546 sourceBytes <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
547 ? mimeType
548 : null;
549
550 let image: { base64: string; mimeType: string; name: string; uri: string };
551 try {
552 if (originalMimeType !== null) {
553 const { File } = await import("expo-file-system");
554 const base64 = await new File(asset.uri).base64();
555 const fitted = await fitComposerImage({
556 uri: asset.uri,
557 mimeType: originalMimeType,
558 base64,
559 });
560 image = {
561 base64: fitted?.base64 ?? base64,
562 mimeType: originalMimeType,
563 name,
564 uri: fitted?.uri ?? asset.uri,
565 };
566 } else {
567 const rendered = await renderPhoto(asset.uri);
568 image = {
569 base64: rendered.base64,
570 mimeType: "image/jpeg",
571 name: /\.jpe?g$/i.test(name) ? name : `${name.replace(/\.[^.]+$/, "")}.jpg`,
572 uri: rendered.uri,
573 };
574 }
575 } catch {
576 error = m(msg("Failed to read ''{name}''.", { name }));
577 continue;
578 }
579
580 const sizeBytes = estimateBase64ByteSize(image.base64);
581 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
582 error = m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name }));
583 continue;
584 }
585
586 try {
587 const fileUri = await persistComposerAttachmentFile(
588 image.uri,
589 image.name,
590 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
591 );
592 attachments.push(
593 await ownedComposerImageAttachment({ fileUri, name: image.name, mimeType: image.mimeType }),
594 );
595 } catch (cause) {
596 error = errorDisplayMessage(cause, m) ?? m(msg("Failed to read ''{name}''.", { name }));
597 }
598 }
599
600 return {
601 attachments,
602 error,
603 };
604}
605
606function mimeTypeFromUri(uri: string): string {
607 const ext = uri.split(".").pop()?.toLowerCase();
608 switch (ext) {
609 case "png":
610 return "image/png";
611 case "jpg":
612 case "jpeg":
613 return "image/jpeg";
614 case "gif":
615 return "image/gif";
616 case "webp":
617 return "image/webp";
618 case "heic":
619 return "image/heic";
620 default:
621 return "image/png";
622 }
623}
624
625function isOwnedPastedImageUri(uri: string): boolean {
626 try {
627 const url = new URL(uri);
628 if (url.protocol !== "file:") {
629 return false;
630 }
631 const segments = url.pathname.split("/").filter(Boolean);
632 return segments.at(-2) === OWNED_PASTED_IMAGE_DIRECTORY;
633 } catch {
634 return false;
635 }
636}
637
638/** Leave out existingCount when the draft store caps after its duplicate check. */
639export async function convertPastedImagesToAttachments(input: {
640 readonly uris: ReadonlyArray<string>;
641 readonly existingCount?: number;
642}): Promise<{
643 readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
644 readonly error: string | null;
645}> {
646 const { File } = await import("expo-file-system");
647 const remainingSlots =
648 input.existingCount === undefined
649 ? Number.POSITIVE_INFINITY
650 : PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
651 const attachments: DraftComposerImageAttachment[] = [];
652 let error: string | null = null;
653
654 for (const [index, uri] of input.uris.entries()) {
655 const temporaryUris = isOwnedPastedImageUri(uri) ? [uri] : [];
656 try {
657 if (index >= Math.max(0, remainingSlots)) {
658 continue;
659 }
660 const file = new File(uri);
661 const reportedMimeType = file.type;
662 const sourceMimeType = reportedMimeType?.startsWith("image/")
663 ? reportedMimeType
664 : mimeTypeFromUri(uri);
665 let mimeType = isProviderSendTurnSupportedImageMimeType(sourceMimeType)
666 ? sourceMimeType
667 : "image/jpeg";
668 const rendered = mimeType === sourceMimeType ? null : await renderPhoto(uri);
669 const pastedBase64 = rendered?.base64 ?? (await file.base64());
670 const fitted = rendered ?? (await fitComposerImage({ uri, mimeType, base64: pastedBase64 }));
671 if (fitted !== null) {
672 temporaryUris.push(fitted.uri);
673 }
674 let base64 = fitted?.base64 ?? pastedBase64;
675 let sourceUri = fitted?.uri ?? uri;
676 if (
677 rendered === null &&
678 estimateBase64ByteSize(base64) > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
679 ) {
680 const jpeg = await renderPhoto(uri);
681 temporaryUris.push(jpeg.uri);
682 mimeType = "image/jpeg";
683 base64 = jpeg.base64;
684 sourceUri = jpeg.uri;
685 }
686 const sizeBytes = estimateBase64ByteSize(base64);
687 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
688 error =
689 sizeBytes > 0
690 ? m(msg("A pasted image exceeds the 10 MB attachment limit."))
691 : m(msg("Could not read a pasted image."));
692 continue;
693 }
694 const name = `pasted-image.${mimeType.split("/")[1] ?? "png"}`;
695 const fileUri = await persistComposerAttachmentFile(
696 sourceUri,
697 name,
698 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
699 );
700 attachments.push(await ownedComposerImageAttachment({ fileUri, name, mimeType }));
701 } catch (cause) {
702 console.warn("Failed to read pasted image", uri, cause);
703 error = m(msg("Could not read a pasted image."));
704 } finally {
705 for (const temporaryUri of temporaryUris) {
706 try {
707 const file = new File(temporaryUri);
708 if (file.exists) {
709 file.delete();
710 }
711 } catch (error) {
712 console.warn("Failed to remove temporary pasted image", temporaryUri, error);
713 }
714 }
715 }
716 }
717
718 return { attachments, error };
719}