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

composerImages.ts

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