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