Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composerImages.ts

742 lines24.4 KB

1import {
2 clampFileAttachmentUploadBytes,
3 fileAttachmentTooLargeMessage,
4} from "@t3tools/client-runtime/state/attachments";
5import {
6 isProviderSendTurnSupportedImageMimeType,
7 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
8 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
9 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
10 type EnvironmentId,
11 type PastedTextAttachmentSource,
12 type UploadChatImageAttachment,
13} from "@t3tools/contracts";
14import type { DocumentPickerResult } from "expo-document-picker";
15import { estimateBase64ByteSize } from "./base64";
16import {
17 COMPOSER_ATTACHMENT_DIRECTORY,
18 isComposerAttachmentFileRetained,
19 resolveOwnedComposerAttachmentFileUri,
20} from "./composerAttachmentFiles";
21import { imageMimeType } from "@t3tools/shared/image";
22import { videoMimeType } from "@t3tools/shared/video";
23import { beginForegroundHandoff } from "./foreground-handoff";
24import { uuidv4 } from "./uuid";
25import { writeFileAtomically } from "./atomic-file";
26​
27export interface DraftComposerImageAttachment extends Omit<UploadChatImageAttachment, "dataUrl"> {
28 readonly id: string;
29 readonly previewUri: string;
30 /** Owned image bytes from a file-backed draft. Current writers still use inline bytes. */
31 readonly fileUri?: string;
32 /** Inline bytes from current writers and older drafts. */
33 readonly dataUrl?: string;
34 readonly uploadedAttachmentId?: string;
35 readonly uploadEnvironmentId?: EnvironmentId;
37​
38export interface DraftComposerFileAttachment {
39 readonly id: string;
40 readonly type: "file";
41 readonly name: string;
42 readonly mimeType: string;
43 readonly sizeBytes: number;
44 readonly fileUri: string;
45 readonly source?: PastedTextAttachmentSource;
46 readonly uploadedAttachmentId?: string;
47 readonly uploadEnvironmentId?: EnvironmentId;
49​
50export async function createPastedTextComposerAttachment(input: {
51 readonly text: string;
52 readonly name: string;
53 readonly maxBytes: number;
54}): Promise<DraftComposerFileAttachment> {
55 const bytes = new TextEncoder().encode(input.text).byteLength;
56 if (bytes <= 0) {
57 throw new Error("Clipboard is empty.");
58 }
59 if (bytes > input.maxBytes) {
60 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes));
61 }
62​
63 const { Directory, File, Paths } = await import("expo-file-system");
64 const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY);
65 directory.create({ idempotent: true, intermediates: true });
66 const file = new File(directory, `${uuidv4()}-${input.name}`);
67 await writeFileAtomically(file, input.text);
68 return {
69 id: uuidv4(),
70 type: "file",
71 name: input.name,
72 mimeType: "text/plain;charset=utf-8",
73 sizeBytes: bytes,
74 fileUri: file.uri,
75 source: { _tag: "pasted-text" },
76 };
78​
79export type DraftComposerAttachment = DraftComposerImageAttachment | DraftComposerFileAttachment;
80​
81/**
82 * What the strip above the composer shows: media, and nothing else. A thumbnail is the only
83 * way to see a picture or a video, so those always preview there. Everything else reads as
84 * its inline chip, which carries the name, the type and the size in the line of prose the
85 * file belongs to — a square tile showing a generic document glyph says strictly less.
86 *
87 * The chip is not optional for a non-media file. Every path that attaches one also writes
88 * its reference, so a file with no chip means the draft lost it rather than that the strip
89 * should stand in. Which attachments carry a chip is therefore not consulted at all; surfaces
90 * whose attachments never get chips (a question answer) pass them to the strip directly
91 * instead of through this filter.
92 */
93export function composerStripAttachments(
94 attachments: ReadonlyArray<DraftComposerAttachment>,
95): ReadonlyArray<DraftComposerAttachment> {
96 return attachments.filter(
97 (attachment) => isComposerImageAttachment(attachment) || videoMimeType(attachment) !== null,
98 );
100​
101/**
102 * Whether a draft attachment is a picture. The document picker types every pick as a plain
103 * file, so the answer comes from the attachment itself rather than from which picker made it.
104 */
105export function isComposerImageAttachment(
106 attachment: DraftComposerAttachment,
107): attachment is DraftComposerImageAttachment {
108 return attachment.type === "image" || imageMimeType(attachment) !== null;
110​
111/** Any composer attachment whose bytes live in the app-owned attachment directory. */
112export type FileBackedComposerAttachment = DraftComposerAttachment & { readonly fileUri: string };
113​
114/** Files have a local copy. Images can have one after a file-backed draft is restored. */
115export function isFileBackedComposerAttachment(
116 attachment: DraftComposerAttachment,
117): attachment is FileBackedComposerAttachment {
118 return attachment.fileUri !== undefined;
120​
121/**
122 * The bytes a draft attachment can be previewed from without the server. A picture taken from
123 * the photo library or the clipboard owns no file and carries its bytes inline, and its
124 * `attachmentId` is a local draft id the server has never seen — so falling back to a remote
125 * asset for one only ever fails. Returns undefined when the attachment really is remote-only.
126 */
127export function composerAttachmentInlineUri(
128 attachment: DraftComposerAttachment | undefined,
129): string | undefined {
130 if (attachment === undefined || isFileBackedComposerAttachment(attachment)) return undefined;
131 return attachment.type === "image" ? (attachment.dataUrl ?? attachment.previewUri) : undefined;
133​
134const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
135const ATTACHMENT_COPY_CHUNK_BYTES = 64 * 1024;
136​
137export async function persistComposerAttachmentFile(
138 uri: string,
139 name: string,
140 maxBytes?: number,
141): Promise<string> {
142 const { Directory, File, FileMode, Paths } = await import("expo-file-system");
143 const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY);
144 directory.create({ idempotent: true, intermediates: true });
145 const safeName =
146 Array.from(name, (character) =>
147 character === "/" || character === "\\" || character.charCodeAt(0) < 32 ? "-" : character,
148 ).join("") || "file";
149 const destination = new File(directory, `${uuidv4()}-${safeName}`);
150 const source = new File(uri);
151 const sourceSize = source.size;
152 if (
153 maxBytes !== undefined &&
154 (sourceSize === null || (sourceSize === 0 && uri.startsWith("content:")))
155 ) {
156 destination.create();
157 try {
158 const reader = source.open(FileMode.ReadOnly);
159 try {
160 const writer = destination.open(FileMode.WriteOnly);
161 try {
162 let copiedBytes = 0;
163 while (true) {
164 const chunk = await reader.readBytes(
165 Math.min(ATTACHMENT_COPY_CHUNK_BYTES, maxBytes - copiedBytes + 1),
166 );
167 if (chunk.byteLength === 0) {
168 break;
169 }
170 copiedBytes += chunk.byteLength;
171 if (copiedBytes > maxBytes) {
172 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes));
173 }
174 await writer.writeBytes(chunk);
175 }
176 } finally {
177 writer.close();
178 }
179 } finally {
180 reader.close();
181 }
182 } catch (error) {
183 if (destination.exists) {
184 destination.delete();
185 }
186 throw error;
187 }
188 return destination.uri;
189 }
190​
191 if (maxBytes !== undefined && sourceSize !== null && sourceSize > maxBytes) {
192 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes));
193 }
194 try {
195 await source.copy(destination);
196 } catch (error) {
197 // A failed copy can leave a partial destination file behind with no URI
198 // returned to release it later; delete it before surfacing the failure.
199 try {
200 if (destination.exists) {
201 destination.delete();
202 }
203 } catch (cleanupError) {
204 console.warn("[composer-attachments] could not remove a partial copy", cleanupError);
205 }
206 throw error;
207 }
208 // An Android content: stream can deliver more bytes than the size it
209 // reported before the copy. Validate the persisted copy so an oversized
210 // file is never retained under a stale recorded size.
211 const copiedSize = destination.size;
212 if (maxBytes !== undefined && copiedSize !== null && copiedSize > maxBytes) {
213 try {
214 if (destination.exists) {
215 destination.delete();
216 }
217 } catch (cleanupError) {
218 console.warn("[composer-attachments] could not remove an oversized copy", cleanupError);
219 }
220 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes));
221 }
222 return destination.uri;
224​
225export async function removePersistedComposerAttachmentFile(uri: string): Promise<void> {
226 try {
227 const { File, Paths } = await import("expo-file-system");
228 const ownedUri = resolveOwnedComposerAttachmentFileUri(uri, Paths.document.uri);
229 if (ownedUri === null || isComposerAttachmentFileRetained(ownedUri)) {
230 return;
231 }
232 const file = new File(ownedUri);
233 if (file.exists) {
234 file.delete();
235 }
236 } catch (error) {
237 console.warn("[composer-attachments] could not remove local file", error);
238 }
240​
241async function createComposerFileAttachment(input: {
242 readonly uri: string;
243 readonly name: string;
244 readonly mimeType: string;
245 readonly sizeBytes: number | null;
246 readonly maxBytes: number;
247}): Promise<DraftComposerFileAttachment> {
248 if (input.sizeBytes !== null && input.sizeBytes > input.maxBytes) {
249 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes));
250 }
251 const { File } = await import("expo-file-system");
252 const fileUri = await persistComposerAttachmentFile(input.uri, input.name, input.maxBytes);
253 try {
254 const sizeBytes = new File(fileUri).size ?? input.sizeBytes ?? 0;
255 if (sizeBytes <= 0) {
256 throw new Error(`'${input.name}' is empty or could not be read.`);
257 }
258 if (sizeBytes > input.maxBytes) {
259 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes));
260 }
261 return {
262 id: uuidv4(),
263 type: "file",
264 name: input.name,
265 mimeType: input.mimeType,
266 sizeBytes,
267 fileUri,
268 };
269 } catch (error) {
270 await removePersistedComposerAttachmentFile(fileUri);
271 throw error;
272 }
274​
275export async function pickComposerFiles(input: {
276 readonly existingCount: number;
277 readonly maxBytes?: number;
278}): Promise<{
279 readonly files: ReadonlyArray<DraftComposerFileAttachment>;
280 readonly error: string | null;
281}> {
282 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
283 if (remainingSlots <= 0) {
284 return {
285 files: [],
286 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
287 };
288 }
289​
290 const { getDocumentAsync } = await import("expo-document-picker");
291 const endHandoff = beginForegroundHandoff();
292 let result: DocumentPickerResult;
293 try {
294 // File providers may expose a URI that FileSystem cannot read directly.
295 // Import a readable cache copy before persisting the draft's owned file.
296 result = await getDocumentAsync({ multiple: true, copyToCacheDirectory: true });
297 } catch (cause) {
298 return {
299 files: [],
300 error: cause instanceof Error ? cause.message : "Could not open the file picker.",
301 };
302 } finally {
303 endHandoff();
304 }
305 if (result.canceled) {
306 return { files: [], error: null };
307 }
308​
309 const maxBytes = clampFileAttachmentUploadBytes(
310 input.maxBytes ?? PROVIDER_SEND_TURN_MAX_FILE_BYTES,
311 );
312 const attachments: DraftComposerFileAttachment[] = [];
313 let error: string | null = null;
314 let exceededAttachmentLimit = false;
315 for (const file of result.assets) {
316 if (attachments.length >= remainingSlots) {
317 exceededAttachmentLimit = true;
318 break;
319 }
320 // A SAF/document picker can hand back a blank display name; the wire
321 // contract rejects empty names at send time, so fall back before the name
322 // reaches storage, errors, or the attachment itself.
323 const name = file.name.trim().length > 0 ? file.name : "file";
324 try {
325 attachments.push(
326 await createComposerFileAttachment({
327 uri: file.uri,
328 name,
329 mimeType: file.mimeType || "application/octet-stream",
330 sizeBytes: file.size ?? null,
331 maxBytes,
332 }),
333 );
334 } catch (cause) {
335 error = cause instanceof Error ? cause.message : `Could not read '${name}'.`;
336 }
337 }
338 if (exceededAttachmentLimit) {
339 error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`;
340 }
341 return { files: attachments, error };
343​
344/**
345 * Longest edge kept when a photo has to be re-encoded. Matches the web composer's
346 * MAX_DIMENSION so every client hands providers the same resolution.
347 */
348const PHOTO_MAX_EDGE = 2048;
349const PHOTO_JPEG_QUALITY = 0.85;
350​
351/**
352 * Renders a photo-library pick to a provider-readable JPEG. Decode, downscale, and encode run
353 * natively; only the bounded result crosses the bridge. Camera photos are 12-48 MP HEIC files,
354 * so a full-size conversion is both slow to transfer and far more than a model can use.
355 */
356async function renderPhotoAsJpeg(uri: string): Promise<{ base64: string; uri: string }> {
357 const { ImageManipulator, SaveFormat } = await import("expo-image-manipulator");
358 let image = await ImageManipulator.manipulate(uri).renderAsync();
359 try {
360 const longestEdge = Math.max(image.width, image.height);
361 if (longestEdge > PHOTO_MAX_EDGE) {
362 const resized = await ImageManipulator.manipulate(image)
363 .resize(
364 image.width >= image.height ? { width: PHOTO_MAX_EDGE } : { height: PHOTO_MAX_EDGE },
365 )
366 .renderAsync();
367 image.release();
368 image = resized;
369 }
370 const saved = await image.saveAsync({
371 format: SaveFormat.JPEG,
372 compress: PHOTO_JPEG_QUALITY,
373 base64: true,
374 });
375 if (!saved.base64) {
376 throw new Error("The rendered photo has no bytes.");
377 }
378 return { base64: saved.base64, uri: saved.uri };
379 } finally {
380 image.release();
381 }
383​
384async function loadImagePicker() {
385 try {
386 return await import("expo-image-picker");
387 } catch (error) {
388 throw new Error("The photo library is unavailable right now.", { cause: error });
389 }
391​
392async function loadClipboard() {
393 try {
394 return await import("expo-clipboard");
395 } catch (error) {
396 throw new Error("Clipboard paste is unavailable right now.", { cause: error });
397 }
399​
400export async function pickComposerImages(input: { readonly existingCount: number }): Promise<{
401 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
402 readonly error: string | null;
403}> {
404 const result = await pickComposerMedia(input);
405 return {
406 images: result.attachments.filter((attachment) => attachment.type === "image"),
407 error: result.error,
408 };
410​
411/** Videos use file uploads; omit maxVideoBytes for image-only destinations. */
412export async function pickComposerMedia(input: {
413 readonly existingCount: number;
414 readonly maxVideoBytes?: number;
415}): Promise<{
416 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
417 readonly error: string | null;
418}> {
419 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
420 if (remainingSlots <= 0) {
421 return {
422 attachments: [],
423 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`,
424 };
425 }
426​
427 let imagePicker: Awaited<ReturnType<typeof loadImagePicker>>;
428 try {
429 imagePicker = await loadImagePicker();
430 } catch (error) {
431 return {
432 attachments: [],
433 error: error instanceof Error ? error.message : "The photo library is unavailable right now.",
434 };
435 }
436​
437 // The picker covers the Android activity, which reports the app as
438 // backgrounded; the guard keeps background-triggered restarts away mid-pick.
439 const endHandoff = beginForegroundHandoff();
440 let result: Awaited<ReturnType<typeof imagePicker.launchImageLibraryAsync>>;
441 try {
442 result = await imagePicker.launchImageLibraryAsync({
443 mediaTypes: input.maxVideoBytes === undefined ? ["images"] : ["images", "videos"],
444 allowsMultipleSelection: true,
445 selectionLimit: remainingSlots,
446 // Bytes stay in the picker's file until we know how much of them we need. Asking for
447 // base64 here made iOS decode and re-encode every camera photo at full resolution and
448 // hand JS a 10 MB+ string, which stalled the composer for seconds.
449 base64: false,
450 quality: 1,
451 shouldDownloadFromNetwork: true,
452 });
453 } catch (error) {
454 return {
455 attachments: [],
456 error: error instanceof Error ? error.message : "Could not open the photo library.",
457 };
458 } finally {
459 endHandoff();
460 }
461​
462 if (result.canceled) {
463 return {
464 attachments: [],
465 error: null,
466 };
467 }
468​
469 const attachments: DraftComposerAttachment[] = [];
470 let error: string | null = null;
471​
472 for (const asset of result.assets) {
473 if (attachments.length >= remainingSlots) {
474 error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`;
475 break;
476 }
477 const mimeType = asset.mimeType?.toLowerCase();
478 if (asset.type === "video" || mimeType?.startsWith("video/")) {
479 if (input.maxVideoBytes === undefined) {
480 error = "Video attachments are unavailable here.";
481 continue;
482 }
483 try {
484 const { File } = await import("expo-file-system");
485 const file = new File(asset.uri);
486 attachments.push(
487 await createComposerFileAttachment({
488 uri: asset.uri,
489 name: asset.fileName?.trim() || file.name || "video",
490 mimeType: mimeType || file.type || "application/octet-stream",
491 sizeBytes: asset.fileSize ?? null,
492 maxBytes: clampFileAttachmentUploadBytes(input.maxVideoBytes),
493 }),
494 );
495 } catch (cause) {
496 error =
497 cause instanceof Error ? cause.message : `Could not read '${asset.fileName ?? "video"}'.`;
498 }
499 continue;
500 }
501 if (asset.type !== "image" && !mimeType?.startsWith("image/")) {
502 error = `Unsupported file type for '${asset.fileName ?? "image"}'.`;
503 continue;
504 }
505​
506 const name = asset.fileName?.trim() || "image";
507 // The picker's reported size is a hint, not a measurement: Android content streams can
508 // deliver more bytes than they advertise. Only a size read from the file itself decides
509 // whether the original bytes are safe to load into JS.
510 let sourceBytes: number | null = null;
511 try {
512 const { File } = await import("expo-file-system");
513 sourceBytes = new File(asset.uri).size;
514 } catch {
515 sourceBytes = null;
516 }
517 // Originals the provider can read and that fit the cap pass through byte for byte so
518 // transparency and animation survive. Everything else (HEIC/HEIF, oversized JPEGs,
519 // unmeasurable sources) is rendered to a bounded JPEG off the JS thread.
520 const originalMimeType =
521 mimeType !== undefined &&
522 isProviderSendTurnSupportedImageMimeType(mimeType) &&
523 sourceBytes !== null &&
524 sourceBytes > 0 &&
525 sourceBytes <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
526 ? mimeType
527 : null;
528​
529 let image: { base64: string; mimeType: string; name: string; previewUri: string };
530 try {
531 if (originalMimeType !== null) {
532 const { File } = await import("expo-file-system");
533 image = {
534 base64: await new File(asset.uri).base64(),
535 mimeType: originalMimeType,
536 name,
537 previewUri: asset.uri,
538 };
539 } else {
540 const rendered = await renderPhotoAsJpeg(asset.uri);
541 image = {
542 base64: rendered.base64,
543 mimeType: "image/jpeg",
544 name: /\.jpe?g$/i.test(name) ? name : `${name.replace(/\.[^.]+$/, "")}.jpg`,
545 previewUri: rendered.uri,
546 };
547 }
548 } catch {
549 error = `Failed to read '${name}'.`;
550 continue;
551 }
552​
553 const sizeBytes = estimateBase64ByteSize(image.base64);
554 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
555 error = `'${name}' exceeds the 10 MB attachment limit.`;
556 continue;
557 }
558​
559 attachments.push({
560 id: uuidv4(),
561 type: "image",
562 name: image.name,
563 mimeType: image.mimeType,
564 sizeBytes,
565 dataUrl: `data:${image.mimeType};base64,${image.base64}`,
566 previewUri: image.previewUri,
567 });
568 }
569​
570 return {
571 attachments,
572 error,
573 };
575​
576/** Clipboard images take priority over their alternate text representation. */
577export async function pasteComposerClipboard(input: { readonly existingCount: number }): Promise<
578 | {
579 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
580 readonly text: null;
581 readonly error: string | null;
582 }
583 | {
584 readonly images: readonly [];
585 readonly text: string;
586 readonly error: null;
587 }
588> {
589 let clipboard: Awaited<ReturnType<typeof loadClipboard>>;
590 try {
591 clipboard = await loadClipboard();
592 } catch (error) {
593 return {
594 images: [],
595 text: null,
596 error: error instanceof Error ? error.message : "Clipboard paste is unavailable right now.",
597 };
598 }
599​
600 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
601​
602 if (await clipboard.hasImageAsync()) {
603 if (remainingSlots <= 0) {
604 return {
605 images: [],
606 text: null,
607 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
608 };
609 }
610 const image = await clipboard.getImageAsync({ format: "png" });
611 if (!image) {
612 return {
613 images: [],
614 text: null,
615 error: "Clipboard image is unavailable.",
616 };
617 }
618​
619 const base64 = image.data.split(",")[1] ?? "";
620 const sizeBytes = estimateBase64ByteSize(base64);
621 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
622 return {
623 images: [],
624 text: null,
625 error: "Clipboard image exceeds the 10 MB attachment limit.",
626 };
627 }
628​
629 return {
630 images: [
631 {
632 id: uuidv4(),
633 type: "image",
634 name: "pasted-image.png",
635 mimeType: "image/png",
636 sizeBytes,
637 dataUrl: image.data,
638 previewUri: image.data,
639 },
640 ],
641 text: null,
642 error: null,
643 };
644 }
645​
646 if (await clipboard.hasStringAsync()) {
647 const text = await clipboard.getStringAsync();
648 return {
649 images: [],
650 ...(text.length > 0 ? { text, error: null } : { text: null, error: "Clipboard is empty." }),
651 };
652 }
653​
654 return {
655 images: [],
656 text: null,
657 error: "Clipboard does not contain pasteable text or image content.",
658 };
660​
661function mimeTypeFromUri(uri: string): string {
662 const ext = uri.split(".").pop()?.toLowerCase();
663 switch (ext) {
664 case "png":
665 return "image/png";
666 case "jpg":
667 case "jpeg":
668 return "image/jpeg";
669 case "gif":
670 return "image/gif";
671 case "webp":
672 return "image/webp";
673 case "heic":
674 return "image/heic";
675 default:
676 return "image/png";
677 }
679​
680export function isOwnedPastedImageUri(uri: string): boolean {
681 try {
682 const url = new URL(uri);
683 if (url.protocol !== "file:") {
684 return false;
685 }
686 const segments = url.pathname.split("/").filter(Boolean);
687 return (
688 segments.at(-2) === OWNED_PASTED_IMAGE_DIRECTORY && segments.at(-1)?.endsWith(".png") === true
689 );
690 } catch {
691 return false;
692 }
694​
695export async function convertPastedImagesToAttachments(input: {
696 readonly uris: ReadonlyArray<string>;
697 readonly existingCount: number;
698}): Promise<ReadonlyArray<DraftComposerImageAttachment>> {
699 const { File } = await import("expo-file-system");
700 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
701 const results: DraftComposerImageAttachment[] = [];
702​
703 for (const [index, uri] of input.uris.entries()) {
704 const ownedTemporaryFile = isOwnedPastedImageUri(uri);
705 try {
706 if (index >= Math.max(0, remainingSlots)) {
707 continue;
708 }
709 const file = new File(uri);
710 const base64 = await file.base64();
711 const sizeBytes = estimateBase64ByteSize(base64);
712 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
713 continue;
714 }
715 const mimeType = mimeTypeFromUri(uri);
716 results.push({
717 id: uuidv4(),
718 type: "image",
719 name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`,
720 mimeType,
721 sizeBytes,
722 dataUrl: `data:${mimeType};base64,${base64}`,
723 previewUri: ownedTemporaryFile ? `data:${mimeType};base64,${base64}` : uri,
724 });
725 } catch (error) {
726 console.warn("Failed to read pasted image", uri, error);
727 } finally {
728 if (ownedTemporaryFile) {
729 try {
730 const file = new File(uri);
731 if (file.exists) {
732 file.delete();
733 }
734 } catch (error) {
735 console.warn("Failed to remove temporary pasted image", uri, error);
736 }
737 }
738 }
739 }
740​
741 return results;