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 UploadChatImageAttachment,
12} from "@t3tools/contracts";
13import type { DocumentPickerResult } from "expo-document-picker";
14import { estimateBase64ByteSize } from "./base64";
15import {
16 COMPOSER_ATTACHMENT_DIRECTORY,
17 isComposerAttachmentFileRetained,
18 resolveOwnedComposerAttachmentFileUri,
19} from "./composerAttachmentFiles";
20import { beginForegroundHandoff } from "./foreground-handoff";
21import { uuidv4 } from "./uuid";
22
23export interface DraftComposerImageAttachment extends Omit<UploadChatImageAttachment, "dataUrl"> {
24 readonly id: string;
25 readonly previewUri: string;
26 /** Owned image bytes from a file-backed draft. Current writers still use inline bytes. */
27 readonly fileUri?: string;
28 /** Inline bytes from current writers and older drafts. */
29 readonly dataUrl?: string;
30 readonly uploadedAttachmentId?: string;
31 readonly uploadEnvironmentId?: EnvironmentId;
32}
33
34export interface DraftComposerFileAttachment {
35 readonly id: string;
36 readonly type: "file";
37 readonly name: string;
38 readonly mimeType: string;
39 readonly sizeBytes: number;
40 readonly fileUri: string;
41 readonly uploadedAttachmentId?: string;
42 readonly uploadEnvironmentId?: EnvironmentId;
43}
44
45export type DraftComposerAttachment = DraftComposerImageAttachment | DraftComposerFileAttachment;
46
47/** Any composer attachment whose bytes live in the app-owned attachment directory. */
48export type FileBackedComposerAttachment = DraftComposerAttachment & { readonly fileUri: string };
49
50/** Files have a local copy. Images can have one after a file-backed draft is restored. */
51export function isFileBackedComposerAttachment(
52 attachment: DraftComposerAttachment,
53): attachment is FileBackedComposerAttachment {
54 return attachment.fileUri !== undefined;
55}
56
57const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
58const ATTACHMENT_COPY_CHUNK_BYTES = 64 * 1024;
59
60export async function persistComposerAttachmentFile(
61 uri: string,
62 name: string,
63 maxBytes?: number,
64): Promise<string> {
65 const { Directory, File, FileMode, Paths } = await import("expo-file-system");
66 const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY);
67 directory.create({ idempotent: true, intermediates: true });
68 const safeName =
69 Array.from(name, (character) =>
70 character === "/" || character === "\\" || character.charCodeAt(0) < 32 ? "-" : character,
71 ).join("") || "file";
72 const destination = new File(directory, `${uuidv4()}-${safeName}`);
73 const source = new File(uri);
74 const sourceSize = source.size;
75 if (
76 maxBytes !== undefined &&
77 (sourceSize === null || (sourceSize === 0 && uri.startsWith("content:")))
78 ) {
79 destination.create();
80 try {
81 const reader = source.open(FileMode.ReadOnly);
82 try {
83 const writer = destination.open(FileMode.WriteOnly);
84 try {
85 let copiedBytes = 0;
86 while (true) {
87 const chunk = reader.readBytes(
88 Math.min(ATTACHMENT_COPY_CHUNK_BYTES, maxBytes - copiedBytes + 1),
89 );
90 if (chunk.byteLength === 0) {
91 break;
92 }
93 copiedBytes += chunk.byteLength;
94 if (copiedBytes > maxBytes) {
95 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes));
96 }
97 writer.writeBytes(chunk);
98 }
99 } finally {
100 writer.close();
101 }
102 } finally {
103 reader.close();
104 }
105 } catch (error) {
106 if (destination.exists) {
107 destination.delete();
108 }
109 throw error;
110 }
111 return destination.uri;
112 }
113
114 if (maxBytes !== undefined && sourceSize !== null && sourceSize > maxBytes) {
115 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes));
116 }
117 try {
118 await source.copy(destination);
119 } catch (error) {
120 // A failed copy can leave a partial destination file behind with no URI
121 // returned to release it later; delete it before surfacing the failure.
122 try {
123 if (destination.exists) {
124 destination.delete();
125 }
126 } catch (cleanupError) {
127 console.warn("[composer-attachments] could not remove a partial copy", cleanupError);
128 }
129 throw error;
130 }
131 // An Android content: stream can deliver more bytes than the size it
132 // reported before the copy. Validate the persisted copy so an oversized
133 // file is never retained under a stale recorded size.
134 const copiedSize = destination.size;
135 if (maxBytes !== undefined && copiedSize !== null && copiedSize > maxBytes) {
136 try {
137 if (destination.exists) {
138 destination.delete();
139 }
140 } catch (cleanupError) {
141 console.warn("[composer-attachments] could not remove an oversized copy", cleanupError);
142 }
143 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes));
144 }
145 return destination.uri;
146}
147
148export async function removePersistedComposerAttachmentFile(uri: string): Promise<void> {
149 try {
150 const { File, Paths } = await import("expo-file-system");
151 const ownedUri = resolveOwnedComposerAttachmentFileUri(uri, Paths.document.uri);
152 if (ownedUri === null || isComposerAttachmentFileRetained(ownedUri)) {
153 return;
154 }
155 const file = new File(ownedUri);
156 if (file.exists) {
157 file.delete();
158 }
159 } catch (error) {
160 console.warn("[composer-attachments] could not remove local file", error);
161 }
162}
163
164async function createComposerFileAttachment(input: {
165 readonly uri: string;
166 readonly name: string;
167 readonly mimeType: string;
168 readonly sizeBytes: number | null;
169 readonly maxBytes: number;
170}): Promise<DraftComposerFileAttachment> {
171 if (input.sizeBytes !== null && input.sizeBytes > input.maxBytes) {
172 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes));
173 }
174 const { File } = await import("expo-file-system");
175 const fileUri = await persistComposerAttachmentFile(input.uri, input.name, input.maxBytes);
176 try {
177 const sizeBytes = new File(fileUri).size ?? input.sizeBytes ?? 0;
178 if (sizeBytes <= 0) {
179 throw new Error(`'${input.name}' is empty or could not be read.`);
180 }
181 if (sizeBytes > input.maxBytes) {
182 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes));
183 }
184 return {
185 id: uuidv4(),
186 type: "file",
187 name: input.name,
188 mimeType: input.mimeType,
189 sizeBytes,
190 fileUri,
191 };
192 } catch (error) {
193 await removePersistedComposerAttachmentFile(fileUri);
194 throw error;
195 }
196}
197
198export async function pickComposerFiles(input: {
199 readonly existingCount: number;
200 readonly maxBytes?: number;
201}): Promise<{
202 readonly files: ReadonlyArray<DraftComposerFileAttachment>;
203 readonly error: string | null;
204}> {
205 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
206 if (remainingSlots <= 0) {
207 return {
208 files: [],
209 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`,
210 };
211 }
212
213 const { getDocumentAsync } = await import("expo-document-picker");
214 const endHandoff = beginForegroundHandoff();
215 let result: DocumentPickerResult;
216 try {
217 // File providers may expose a URI that FileSystem cannot read directly.
218 // Import a readable cache copy before persisting the draft's owned file.
219 result = await getDocumentAsync({ multiple: true, copyToCacheDirectory: true });
220 } catch (cause) {
221 return {
222 files: [],
223 error: cause instanceof Error ? cause.message : "Could not open the file picker.",
224 };
225 } finally {
226 endHandoff();
227 }
228 if (result.canceled) {
229 return { files: [], error: null };
230 }
231
232 const maxBytes = clampFileAttachmentUploadBytes(
233 input.maxBytes ?? PROVIDER_SEND_TURN_MAX_FILE_BYTES,
234 );
235 const attachments: DraftComposerFileAttachment[] = [];
236 let error: string | null = null;
237 let exceededAttachmentLimit = false;
238 for (const file of result.assets) {
239 if (attachments.length >= remainingSlots) {
240 exceededAttachmentLimit = true;
241 break;
242 }
243 // A SAF/document picker can hand back a blank display name; the wire
244 // contract rejects empty names at send time, so fall back before the name
245 // reaches storage, errors, or the attachment itself.
246 const name = file.name.trim().length > 0 ? file.name : "file";
247 try {
248 attachments.push(
249 await createComposerFileAttachment({
250 uri: file.uri,
251 name,
252 mimeType: file.mimeType || "application/octet-stream",
253 sizeBytes: file.size ?? null,
254 maxBytes,
255 }),
256 );
257 } catch (cause) {
258 error = cause instanceof Error ? cause.message : `Could not read '${name}'.`;
259 }
260 }
261 if (exceededAttachmentLimit) {
262 error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`;
263 }
264 return { files: attachments, error };
265}
266
267async function loadImagePicker() {
268 try {
269 return await import("expo-image-picker");
270 } catch (error) {
271 throw new Error("The photo library is unavailable right now.", { cause: error });
272 }
273}
274
275async function loadClipboard() {
276 try {
277 return await import("expo-clipboard");
278 } catch (error) {
279 throw new Error("Clipboard paste is unavailable right now.", { cause: error });
280 }
281}
282
283export async function pickComposerImages(input: { readonly existingCount: number }): Promise<{
284 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
285 readonly error: string | null;
286}> {
287 const result = await pickComposerMedia(input);
288 return {
289 images: result.attachments.filter((attachment) => attachment.type === "image"),
290 error: result.error,
291 };
292}
293
294/** Videos use file uploads; omit maxVideoBytes for image-only destinations. */
295export async function pickComposerMedia(input: {
296 readonly existingCount: number;
297 readonly maxVideoBytes?: number;
298}): Promise<{
299 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
300 readonly error: string | null;
301}> {
302 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
303 if (remainingSlots <= 0) {
304 return {
305 attachments: [],
306 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`,
307 };
308 }
309
310 let imagePicker: Awaited<ReturnType<typeof loadImagePicker>>;
311 try {
312 imagePicker = await loadImagePicker();
313 } catch (error) {
314 return {
315 attachments: [],
316 error: error instanceof Error ? error.message : "The photo library is unavailable right now.",
317 };
318 }
319
320 // The picker covers the Android activity, which reports the app as
321 // backgrounded; the guard keeps background-triggered restarts away mid-pick.
322 const endHandoff = beginForegroundHandoff();
323 let result: Awaited<ReturnType<typeof imagePicker.launchImageLibraryAsync>>;
324 try {
325 result = await imagePicker.launchImageLibraryAsync({
326 mediaTypes: input.maxVideoBytes === undefined ? ["images"] : ["images", "videos"],
327 allowsMultipleSelection: true,
328 selectionLimit: remainingSlots,
329 base64: true,
330 quality: 1,
331 shouldDownloadFromNetwork: true,
332 });
333 } catch (error) {
334 return {
335 attachments: [],
336 error: error instanceof Error ? error.message : "Could not open the photo library.",
337 };
338 } finally {
339 endHandoff();
340 }
341
342 if (result.canceled) {
343 return {
344 attachments: [],
345 error: null,
346 };
347 }
348
349 const attachments: DraftComposerAttachment[] = [];
350 let error: string | null = null;
351
352 for (const asset of result.assets) {
353 if (attachments.length >= remainingSlots) {
354 error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`;
355 break;
356 }
357 let mimeType = asset.mimeType?.toLowerCase();
358 if (asset.type === "video" || mimeType?.startsWith("video/")) {
359 if (input.maxVideoBytes === undefined) {
360 error = "Video attachments are unavailable here.";
361 continue;
362 }
363 try {
364 const { File } = await import("expo-file-system");
365 const file = new File(asset.uri);
366 attachments.push(
367 await createComposerFileAttachment({
368 uri: asset.uri,
369 name: asset.fileName?.trim() || file.name || "video",
370 mimeType: mimeType || file.type || "application/octet-stream",
371 sizeBytes: asset.fileSize ?? null,
372 maxBytes: clampFileAttachmentUploadBytes(input.maxVideoBytes),
373 }),
374 );
375 } catch (cause) {
376 error =
377 cause instanceof Error ? cause.message : `Could not read '${asset.fileName ?? "video"}'.`;
378 }
379 continue;
380 }
381 if (asset.type !== "image" && !mimeType?.startsWith("image/")) {
382 error = `Unsupported file type for '${asset.fileName ?? "image"}'.`;
383 continue;
384 }
385
386 let base64 = asset.base64;
387 if (!base64) {
388 error = `Failed to read '${asset.fileName ?? "image"}'.`;
389 continue;
390 }
391
392 let name = asset.fileName?.trim() || "image";
393 // The iOS picker returns JPEG base64 even when its metadata describes HEIC,
394 // PNG, or GIF. Keep supported originals so transparency and animation survive;
395 // use the native JPEG conversion for formats providers cannot accept.
396 if (base64.startsWith("/9j/")) {
397 if (
398 mimeType &&
399 mimeType !== "image/jpeg" &&
400 isProviderSendTurnSupportedImageMimeType(mimeType)
401 ) {
402 try {
403 const { File } = await import("expo-file-system");
404 base64 = await new File(asset.uri).base64();
405 } catch {
406 error = `Failed to read '${name}'.`;
407 continue;
408 }
409 } else {
410 mimeType = "image/jpeg";
411 if (!/\.jpe?g$/i.test(name)) {
412 name = `${name.replace(/\.[^.]+$/, "")}.jpg`;
413 }
414 }
415 }
416 if (!mimeType || !isProviderSendTurnSupportedImageMimeType(mimeType)) {
417 error = `'${name}' is not a supported image type. Attach GIF, JPEG, PNG, or WebP images.`;
418 continue;
419 }
420
421 const sizeBytes = estimateBase64ByteSize(base64);
422 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
423 error = `'${asset.fileName ?? "image"}' exceeds the 10 MB attachment limit.`;
424 continue;
425 }
426
427 const dataUrl = `data:${mimeType};base64,${base64}`;
428 attachments.push({
429 id: uuidv4(),
430 type: "image",
431 name,
432 mimeType,
433 sizeBytes,
434 dataUrl,
435 previewUri: mimeType === asset.mimeType?.toLowerCase() ? asset.uri : dataUrl,
436 });
437 }
438
439 return {
440 attachments,
441 error,
442 };
443}
444
445export async function pasteComposerClipboard(input: { readonly existingCount: number }): Promise<{
446 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
447 readonly text: string | null;
448 readonly error: string | null;
449}> {
450 let clipboard: Awaited<ReturnType<typeof loadClipboard>>;
451 try {
452 clipboard = await loadClipboard();
453 } catch (error) {
454 return {
455 images: [],
456 text: null,
457 error: error instanceof Error ? error.message : "Clipboard paste is unavailable right now.",
458 };
459 }
460
461 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
462
463 if (await clipboard.hasImageAsync()) {
464 if (remainingSlots <= 0) {
465 return {
466 images: [],
467 text: null,
468 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
469 };
470 }
471 const image = await clipboard.getImageAsync({ format: "png" });
472 if (!image) {
473 return {
474 images: [],
475 text: null,
476 error: "Clipboard image is unavailable.",
477 };
478 }
479
480 const base64 = image.data.split(",")[1] ?? "";
481 const sizeBytes = estimateBase64ByteSize(base64);
482 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
483 return {
484 images: [],
485 text: null,
486 error: "Clipboard image exceeds the 10 MB attachment limit.",
487 };
488 }
489
490 return {
491 images: [
492 {
493 id: uuidv4(),
494 type: "image",
495 name: "pasted-image.png",
496 mimeType: "image/png",
497 sizeBytes,
498 dataUrl: image.data,
499 previewUri: image.data,
500 },
501 ],
502 text: null,
503 error: null,
504 };
505 }
506
507 if (await clipboard.hasStringAsync()) {
508 const text = await clipboard.getStringAsync();
509 return {
510 images: [],
511 text: text.length > 0 ? text : null,
512 error: text.length > 0 ? null : "Clipboard is empty.",
513 };
514 }
515
516 return {
517 images: [],
518 text: null,
519 error: "Clipboard does not contain pasteable text or image content.",
520 };
521}
522
523function mimeTypeFromUri(uri: string): string {
524 const ext = uri.split(".").pop()?.toLowerCase();
525 switch (ext) {
526 case "png":
527 return "image/png";
528 case "jpg":
529 case "jpeg":
530 return "image/jpeg";
531 case "gif":
532 return "image/gif";
533 case "webp":
534 return "image/webp";
535 case "heic":
536 return "image/heic";
537 default:
538 return "image/png";
539 }
540}
541
542export function isOwnedPastedImageUri(uri: string): boolean {
543 try {
544 const url = new URL(uri);
545 if (url.protocol !== "file:") {
546 return false;
547 }
548 const segments = url.pathname.split("/").filter(Boolean);
549 return (
550 segments.at(-2) === OWNED_PASTED_IMAGE_DIRECTORY && segments.at(-1)?.endsWith(".png") === true
551 );
552 } catch {
553 return false;
554 }
555}
556
557export async function convertPastedImagesToAttachments(input: {
558 readonly uris: ReadonlyArray<string>;
559 readonly existingCount: number;
560}): Promise<ReadonlyArray<DraftComposerImageAttachment>> {
561 const { File } = await import("expo-file-system");
562 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
563 const results: DraftComposerImageAttachment[] = [];
564
565 for (const [index, uri] of input.uris.entries()) {
566 const ownedTemporaryFile = isOwnedPastedImageUri(uri);
567 try {
568 if (index >= Math.max(0, remainingSlots)) {
569 continue;
570 }
571 const file = new File(uri);
572 const base64 = await file.base64();
573 const sizeBytes = estimateBase64ByteSize(base64);
574 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
575 continue;
576 }
577 const mimeType = mimeTypeFromUri(uri);
578 results.push({
579 id: uuidv4(),
580 type: "image",
581 name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`,
582 mimeType,
583 sizeBytes,
584 dataUrl: `data:${mimeType};base64,${base64}`,
585 previewUri: ownedTemporaryFile ? `data:${mimeType};base64,${base64}` : uri,
586 });
587 } catch (error) {
588 console.warn("Failed to read pasted image", uri, error);
589 } finally {
590 if (ownedTemporaryFile) {
591 try {
592 const file = new File(uri);
593 if (file.exists) {
594 file.delete();
595 }
596 } catch (error) {
597 console.warn("Failed to remove temporary pasted image", uri, error);
598 }
599 }
600 }
601 }
602
603 return results;
604}