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