Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composerImages.ts

623 lines20.3 KB

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