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