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