Open History to see the last commit
1import {
2 isProviderSendTurnSupportedImageMimeType,
3 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
4 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
5 type UploadChatImageAttachment,
6} from "@t3tools/contracts";
7import { estimateBase64ByteSize } from "./base64";
8import { beginForegroundHandoff } from "./foreground-handoff";
9import { uuidv4 } from "./uuid";
10
11export interface DraftComposerImageAttachment extends UploadChatImageAttachment {
12 readonly id: string;
13 readonly previewUri: string;
14}
15
16/** Wire shape for startTurn: pure uploads without client draft id / previewUri. */
17export function toUploadChatImageAttachments(
18 attachments: ReadonlyArray<DraftComposerImageAttachment>,
19): ReadonlyArray<UploadChatImageAttachment> {
20 return attachments.map((attachment) => ({
21 type: attachment.type,
22 name: attachment.name,
23 mimeType: attachment.mimeType,
24 sizeBytes: attachment.sizeBytes,
25 dataUrl: attachment.dataUrl,
26 }));
27}
28
29const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
30
31async function loadImagePicker() {
32 try {
33 return await import("expo-image-picker");
34 } catch (error) {
35 throw new Error("Image attachments are unavailable right now.", { cause: error });
36 }
37}
38
39async function loadClipboard() {
40 try {
41 return await import("expo-clipboard");
42 } catch (error) {
43 throw new Error("Clipboard paste is unavailable right now.", { cause: error });
44 }
45}
46
47export async function pickComposerImages(input: { readonly existingCount: number }): Promise<{
48 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
49 readonly error: string | null;
50}> {
51 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
52 if (remainingSlots <= 0) {
53 return {
54 images: [],
55 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
56 };
57 }
58
59 let imagePicker: Awaited<ReturnType<typeof loadImagePicker>>;
60 try {
61 imagePicker = await loadImagePicker();
62 } catch (error) {
63 return {
64 images: [],
65 error:
66 error instanceof Error ? error.message : "Image attachments are unavailable right now.",
67 };
68 }
69
70 // The picker covers the Android activity, which reports the app as
71 // backgrounded; the guard keeps background-triggered restarts away mid-pick.
72 const endHandoff = beginForegroundHandoff();
73 let result: Awaited<ReturnType<typeof imagePicker.launchImageLibraryAsync>>;
74 try {
75 result = await imagePicker.launchImageLibraryAsync({
76 mediaTypes: ["images"],
77 allowsMultipleSelection: true,
78 selectionLimit: remainingSlots,
79 base64: true,
80 quality: 1,
81 });
82 } finally {
83 endHandoff();
84 }
85
86 if (result.canceled) {
87 return {
88 images: [],
89 error: null,
90 };
91 }
92
93 const nextImages: DraftComposerImageAttachment[] = [];
94 let error: string | null = null;
95
96 for (const asset of result.assets) {
97 const mimeType = asset.mimeType?.toLowerCase();
98 if (!mimeType?.startsWith("image/")) {
99 error = `Unsupported file type for '${asset.fileName ?? "image"}'.`;
100 continue;
101 }
102 if (!isProviderSendTurnSupportedImageMimeType(mimeType)) {
103 error = `'${asset.fileName ?? "image"}' is not a supported image type. Attach GIF, JPEG, PNG, or WebP images.`;
104 continue;
105 }
106
107 const base64 = asset.base64;
108 if (!base64) {
109 error = `Failed to read '${asset.fileName ?? "image"}'.`;
110 continue;
111 }
112
113 const sizeBytes = asset.fileSize ?? estimateBase64ByteSize(base64);
114 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
115 error = `'${asset.fileName ?? "image"}' exceeds the 10 MB attachment limit.`;
116 continue;
117 }
118
119 nextImages.push({
120 id: uuidv4(),
121 type: "image",
122 name: asset.fileName ?? "image",
123 mimeType,
124 sizeBytes,
125 dataUrl: `data:${mimeType};base64,${base64}`,
126 previewUri: asset.uri,
127 });
128 }
129
130 return {
131 images: nextImages,
132 error,
133 };
134}
135
136export async function pasteComposerClipboard(input: { readonly existingCount: number }): Promise<{
137 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
138 readonly text: string | null;
139 readonly error: string | null;
140}> {
141 let clipboard: Awaited<ReturnType<typeof loadClipboard>>;
142 try {
143 clipboard = await loadClipboard();
144 } catch (error) {
145 return {
146 images: [],
147 text: null,
148 error: error instanceof Error ? error.message : "Clipboard paste is unavailable right now.",
149 };
150 }
151
152 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
153
154 if (await clipboard.hasImageAsync()) {
155 if (remainingSlots <= 0) {
156 return {
157 images: [],
158 text: null,
159 error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`,
160 };
161 }
162 const image = await clipboard.getImageAsync({ format: "png" });
163 if (!image) {
164 return {
165 images: [],
166 text: null,
167 error: "Clipboard image is unavailable.",
168 };
169 }
170
171 const base64 = image.data.split(",")[1] ?? "";
172 const sizeBytes = estimateBase64ByteSize(base64);
173 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
174 return {
175 images: [],
176 text: null,
177 error: "Clipboard image exceeds the 10 MB attachment limit.",
178 };
179 }
180
181 return {
182 images: [
183 {
184 id: uuidv4(),
185 type: "image",
186 name: "pasted-image.png",
187 mimeType: "image/png",
188 sizeBytes,
189 dataUrl: image.data,
190 previewUri: image.data,
191 },
192 ],
193 text: null,
194 error: null,
195 };
196 }
197
198 if (await clipboard.hasStringAsync()) {
199 const text = await clipboard.getStringAsync();
200 return {
201 images: [],
202 text: text.length > 0 ? text : null,
203 error: text.length > 0 ? null : "Clipboard is empty.",
204 };
205 }
206
207 return {
208 images: [],
209 text: null,
210 error: "Clipboard does not contain pasteable text or image content.",
211 };
212}
213
214function mimeTypeFromUri(uri: string): string {
215 const ext = uri.split(".").pop()?.toLowerCase();
216 switch (ext) {
217 case "png":
218 return "image/png";
219 case "jpg":
220 case "jpeg":
221 return "image/jpeg";
222 case "gif":
223 return "image/gif";
224 case "webp":
225 return "image/webp";
226 case "heic":
227 return "image/heic";
228 default:
229 return "image/png";
230 }
231}
232
233export function isOwnedPastedImageUri(uri: string): boolean {
234 try {
235 const url = new URL(uri);
236 if (url.protocol !== "file:") {
237 return false;
238 }
239 const segments = url.pathname.split("/").filter(Boolean);
240 return (
241 segments.at(-2) === OWNED_PASTED_IMAGE_DIRECTORY && segments.at(-1)?.endsWith(".png") === true
242 );
243 } catch {
244 return false;
245 }
246}
247
248export async function convertPastedImagesToAttachments(input: {
249 readonly uris: ReadonlyArray<string>;
250 readonly existingCount: number;
251}): Promise<ReadonlyArray<DraftComposerImageAttachment>> {
252 const { File } = await import("expo-file-system");
253 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
254 const results: DraftComposerImageAttachment[] = [];
255
256 for (const [index, uri] of input.uris.entries()) {
257 const ownedTemporaryFile = isOwnedPastedImageUri(uri);
258 try {
259 if (index >= Math.max(0, remainingSlots)) {
260 continue;
261 }
262 const file = new File(uri);
263 const base64 = await file.base64();
264 const sizeBytes = estimateBase64ByteSize(base64);
265 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
266 continue;
267 }
268 const mimeType = mimeTypeFromUri(uri);
269 results.push({
270 id: uuidv4(),
271 type: "image",
272 name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`,
273 mimeType,
274 sizeBytes,
275 dataUrl: `data:${mimeType};base64,${base64}`,
276 previewUri: ownedTemporaryFile ? `data:${mimeType};base64,${base64}` : uri,
277 });
278 } catch (error) {
279 console.warn("Failed to read pasted image", uri, error);
280 } finally {
281 if (ownedTemporaryFile) {
282 try {
283 const file = new File(uri);
284 if (file.exists) {
285 file.delete();
286 }
287 } catch (error) {
288 console.warn("Failed to remove temporary pasted image", uri, error);
289 }
290 }
291 }
292 }
293
294 return results;
295}