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