Open History to see the last commit
1import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
2import {
3 clampFileAttachmentUploadBytes,
4 fileAttachmentTooLargeMessage,
5 isAssetAttachmentNotFoundFailure,
6 runAttachmentUploadCycle,
7 verifyPersistedAttachmentUpload,
8} from "@t3tools/client-runtime/state/attachments";
9import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
10import type {
11 ChatFileAttachment,
12 ChatImageAttachment,
13 EnvironmentId,
14 UploadChatImageAttachment,
15} from "@t3tools/contracts";
16import {
17 AuthOrchestrationOperateScope,
18 PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
19} from "@t3tools/contracts";
20import * as Option from "effect/Option";
21
22import { appAtomRegistry } from "../state/atom-registry";
23import { assetEnvironment } from "../state/assets";
24import { attachmentEnvironment } from "../state/attachments";
25import { environmentSession, readEnvironmentScope } from "../state/session";
26import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
27import { retainComposerAttachmentFileForPreview } from "./composerAttachmentPreviewRetention";
28import {
29 isComposerImageAttachment,
30 isFileBackedComposerAttachment,
31 type DraftComposerAttachment,
32 type DraftComposerImageAttachment,
33} from "./composerImages";
34import { imageMimeType } from "@t3tools/shared/image";
35import { uuidv4 } from "./uuid";
36
37export type UploadedMobileAttachment =
38 | UploadChatImageAttachment
39 | ChatImageAttachment
40 | ChatFileAttachment;
41
42export function validateDraftFileAttachments(input: {
43 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
44 readonly serverConfig: {
45 readonly environment: {
46 readonly capabilities: {
47 readonly attachmentUploads?: boolean;
48 readonly fileAttachments?: { readonly maxUploadBytes: number };
49 };
50 };
51 } | null;
52}): string | null {
53 const files = input.attachments.filter((attachment) => attachment.type === "file");
54 if (files.length === 0) return null;
55 if (input.serverConfig === null) return "Server attachment support is still loading.";
56 const capabilities = input.serverConfig.environment.capabilities;
57 if (capabilities.attachmentUploads !== true || capabilities.fileAttachments === undefined) {
58 return "This server does not support file attachments.";
59 }
60 const maxBytes = clampFileAttachmentUploadBytes(capabilities.fileAttachments.maxUploadBytes);
61 const oversized = files.find((attachment) => attachment.sizeBytes > maxBytes);
62 return oversized ? fileAttachmentTooLargeMessage(oversized.name, maxBytes) : null;
63}
64
65export function withUploadedMobileAttachmentReferences(input: {
66 readonly environmentId: EnvironmentId;
67 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
68 readonly uploadedAttachments: ReadonlyArray<UploadedMobileAttachment>;
69}): ReadonlyArray<DraftComposerAttachment> {
70 return input.attachments.map((attachment, index) => {
71 const uploaded = input.uploadedAttachments[index];
72 // Files-picked images upload as images; compare wire types to retain uploaded ids and avoid re-uploading.
73 const uploadedAs = isComposerImageAttachment(attachment) ? "image" : attachment.type;
74 if (
75 !uploaded ||
76 !("id" in uploaded) ||
77 uploadedAs !== uploaded.type ||
78 (attachment.uploadedAttachmentId === uploaded.id &&
79 attachment.uploadEnvironmentId === input.environmentId)
80 ) {
81 return attachment;
82 }
83 return {
84 ...attachment,
85 uploadedAttachmentId: uploaded.id,
86 uploadEnvironmentId: input.environmentId,
87 };
88 });
89}
90
91export async function releasePendingAttachmentUploads(
92 environmentId: EnvironmentId,
93 attachmentIds: ReadonlyArray<string>,
94): Promise<void> {
95 const deleteOnce = async (attachmentId: string): Promise<boolean> => {
96 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
97 throw new Error("This connection cannot delete pending attachments.");
98 }
99 const result = await runAtomCommand(
100 appAtomRegistry,
101 attachmentEnvironment.remove,
102 { environmentId, input: { attachmentId } },
103 { reportFailure: false, reportDefect: false },
104 );
105 return (
106 result._tag === "Success" ||
107 isAssetAttachmentNotFoundFailure(squashAtomCommandFailure(result))
108 );
109 };
110
111 const failedAttachmentIds: string[] = [];
112 for (const attachmentId of attachmentIds) {
113 if (!(await deleteOnce(attachmentId)) && !(await deleteOnce(attachmentId))) {
114 failedAttachmentIds.push(attachmentId);
115 }
116 }
117 if (failedAttachmentIds.length > 0) {
118 throw new Error(
119 `Could not delete ${failedAttachmentIds.length} pending attachment upload(s): ${failedAttachmentIds.join(", ")}.`,
120 );
121 }
122}
123
124async function releaseCreatedUploadsQuietly(
125 environmentId: EnvironmentId,
126 attachmentIds: ReadonlyArray<string>,
127): Promise<void> {
128 try {
129 await releasePendingAttachmentUploads(environmentId, attachmentIds);
130 } catch (error) {
131 console.warn("[attachments] could not delete abandoned pending uploads", error);
132 }
133}
134
135export interface PreparedTurnAttachments {
136 readonly status: "ready";
137 readonly attachments: ReadonlyArray<UploadedMobileAttachment>;
138 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
139 readonly pendingAttachmentIds: ReadonlyArray<string>;
140}
141
142export type PrepareTurnAttachmentsResult =
143 | PreparedTurnAttachments
144 | { readonly status: "abandoned" };
145
146/** Promote Files-picked images consistently in headers, payloads and references or ChatImageAttachment rejects them. */
147export function composerAttachmentWireMimeType(attachment: DraftComposerAttachment): string {
148 if (!isComposerImageAttachment(attachment)) return attachment.mimeType;
149 return supportedImageWireMimeType(attachment);
150}
151
152function supportedImageWireMimeType(
153 attachment: DraftComposerAttachment,
154): (typeof PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES)[number] {
155 const inferred = imageMimeType(attachment);
156 const mimeType = PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.find(
157 (type) => type === attachment.mimeType.toLowerCase() || type === inferred,
158 );
159 if (!mimeType) throw new Error(`Unsupported image type for '${attachment.name}'.`);
160 return mimeType;
161}
162
163function uploadedReference(
164 attachment: DraftComposerAttachment,
165 id: string,
166): ChatImageAttachment | ChatFileAttachment {
167 const fields = {
168 id,
169 name: attachment.name,
170 mimeType: composerAttachmentWireMimeType(attachment),
171 sizeBytes: attachment.sizeBytes,
172 };
173 return isComposerImageAttachment(attachment)
174 ? { type: "image", ...fields }
175 : {
176 type: "file",
177 ...fields,
178 ...(attachment.source ? { source: attachment.source } : {}),
179 };
180}
181
182function attachmentUploadInput(attachment: DraftComposerAttachment) {
183 const fields = { name: attachment.name, sizeBytes: attachment.sizeBytes };
184 return isComposerImageAttachment(attachment)
185 ? { ...fields, mimeType: supportedImageWireMimeType(attachment) }
186 : { type: "file" as const, ...fields, mimeType: attachment.mimeType };
187}
188
189async function toUploadChatImageAttachments(
190 attachments: ReadonlyArray<DraftComposerImageAttachment>,
191): Promise<ReadonlyArray<UploadChatImageAttachment>> {
192 return Promise.all(
193 attachments.map(async (attachment) => ({
194 type: attachment.type,
195 name: attachment.name,
196 mimeType: attachment.mimeType,
197 sizeBytes: attachment.sizeBytes,
198 dataUrl: await composerImageAttachmentDataUrl(attachment),
199 })),
200 );
201}
202
203async function composerImageAttachmentDataUrl(
204 attachment: DraftComposerImageAttachment,
205): Promise<string> {
206 if (attachment.dataUrl !== undefined) {
207 return attachment.dataUrl;
208 }
209 if (!isFileBackedComposerAttachment(attachment)) {
210 throw new Error(`'${attachment.name}' is no longer available. Attach the image again.`);
211 }
212 const release = retainComposerAttachmentFileForPreview(attachment);
213 try {
214 const { File, Paths } = await import("expo-file-system");
215 const uri =
216 resolveOwnedComposerAttachmentFileUri(attachment.fileUri, Paths.document.uri) ??
217 attachment.fileUri;
218 const base64 = await new File(uri).base64();
219 return `data:${attachment.mimeType};base64,${base64}`;
220 } finally {
221 release();
222 }
223}
224
225async function uploadFileBytes(
226 environmentId: EnvironmentId,
227 attachment: DraftComposerAttachment,
228 url: string,
229 signal: AbortSignal,
230 onProgress?: (progress: number) => void,
231): Promise<void> {
232 const { File, Paths, UploadType } = await import("expo-file-system");
233 if (signal.aborted) throw new Error("Upload cancelled.");
234 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
235 throw new Error("This connection cannot upload attachments.");
236 }
237 const fileUri = attachment.fileUri;
238 const inlineDataUrl = attachment.type === "image" ? attachment.dataUrl : undefined;
239 if (fileUri === undefined && inlineDataUrl === undefined) {
240 throw new Error(`'${attachment.name}' is no longer available. Attach the image again.`);
241 }
242 const file =
243 fileUri === undefined
244 ? new File(Paths.cache, `t3-upload-${uuidv4()}`)
245 : new File(resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri) ?? fileUri);
246 try {
247 if (fileUri === undefined && inlineDataUrl !== undefined) {
248 file.create();
249 await file.write(inlineDataUrl.slice(inlineDataUrl.indexOf(",") + 1), {
250 encoding: "base64",
251 });
252 }
253 const result = await file.upload(url, {
254 httpMethod: "POST",
255 uploadType: UploadType.BINARY_CONTENT,
256 headers: { "Content-Type": composerAttachmentWireMimeType(attachment) },
257 signal,
258 ...(onProgress
259 ? {
260 onProgress: ({ bytesSent, totalBytes }) => {
261 if (totalBytes > 0) onProgress(bytesSent / totalBytes);
262 },
263 }
264 : {}),
265 });
266 if (result.status < 200 || result.status >= 300) {
267 throw new Error(`Upload failed for '${attachment.name}' (${result.status}).`);
268 }
269 } finally {
270 if (fileUri === undefined && file.exists) file.delete();
271 }
272}
273
274/** persistUploadedReferences runs only for new uploaded ids; save them to their owner so crash retries reuse bytes. */
275export async function prepareTurnAttachments(input: {
276 readonly environmentId: EnvironmentId;
277 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
278 readonly supportsImageUploads?: boolean;
279 readonly signal?: AbortSignal;
280 readonly onUploadProgress?: (attachmentId: string, progress: number) => void;
281 readonly persistUploadedReferences?: (
282 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
283 ) => Promise<"persisted" | "abandon">;
284}): Promise<PrepareTurnAttachmentsResult> {
285 const { environmentId } = input;
286 if (input.signal?.aborted) return { status: "abandoned" };
287 const files = input.attachments.filter((attachment) => attachment.type === "file");
288 const ready = (
289 attachments: ReadonlyArray<UploadedMobileAttachment>,
290 pendingAttachmentIds: ReadonlyArray<string>,
291 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
292 ): PreparedTurnAttachments => ({
293 status: "ready",
294 attachments,
295 draftAttachments,
296 pendingAttachmentIds,
297 });
298
299 if (input.attachments.length === 0 || (files.length === 0 && !input.supportsImageUploads)) {
300 try {
301 const imageAttachments = await toUploadChatImageAttachments(
302 input.attachments.filter((attachment) => attachment.type === "image"),
303 );
304 if (input.signal?.aborted) return { status: "abandoned" };
305 return ready(imageAttachments, [], input.attachments);
306 } catch (error) {
307 if (input.signal?.aborted) return { status: "abandoned" };
308 throw error;
309 }
310 }
311
312 const requireUploadAccess = () => {
313 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) {
314 throw new Error("This connection cannot upload attachments.");
315 }
316 };
317 requireUploadAccess();
318
319 const connection = appAtomRegistry.get(
320 environmentSession.preparedConnectionValueAtom(environmentId),
321 );
322 if (Option.isNone(connection)) {
323 throw new Error("The environment is not connected.");
324 }
325
326 const uploadedAttachments: UploadedMobileAttachment[] = [];
327 const pendingAttachmentIds: string[] = [];
328 const createdAttachmentIds: string[] = [];
329 const controller = new AbortController();
330 const abort = () => controller.abort();
331 input.signal?.addEventListener("abort", abort, { once: true });
332 try {
333 for (const attachment of input.attachments) {
334 if (controller.signal.aborted) throw new Error("Upload cancelled.");
335 requireUploadAccess();
336 if (attachment.type === "image" && !input.supportsImageUploads) {
337 uploadedAttachments.push(...(await toUploadChatImageAttachments([attachment])));
338 continue;
339 }
340
341 if (
342 attachment.uploadEnvironmentId === environmentId &&
343 attachment.uploadedAttachmentId !== undefined
344 ) {
345 const verification = await verifyPersistedAttachmentUpload({
346 registry: appAtomRegistry,
347 createAssetUrl: assetEnvironment.createUrl,
348 environmentId,
349 attachmentId: attachment.uploadedAttachmentId,
350 });
351 if (verification.status === "failed") {
352 throw verification.error;
353 }
354 if (verification.status === "verified") {
355 pendingAttachmentIds.push(attachment.uploadedAttachmentId);
356 uploadedAttachments.push(uploadedReference(attachment, attachment.uploadedAttachmentId));
357 continue;
358 }
359 }
360
361 requireUploadAccess();
362 const result = await runAttachmentUploadCycle({
363 registry: appAtomRegistry,
364 createUploadUrl: attachmentEnvironment.createUploadUrl,
365 remove: attachmentEnvironment.remove,
366 environmentId,
367 upload: attachmentUploadInput(attachment),
368 // Resolve at transfer time; reconnects may change the base URL.
369 resolveUploadUrl: (relativeUrl) => {
370 requireUploadAccess();
371 const currentConnection = appAtomRegistry.get(
372 environmentSession.preparedConnectionValueAtom(environmentId),
373 );
374 return Option.isNone(currentConnection)
375 ? null
376 : resolveAssetUrl(currentConnection.value.httpBaseUrl, relativeUrl);
377 },
378 transport: (url) => ({
379 done: uploadFileBytes(
380 environmentId,
381 attachment,
382 url,
383 controller.signal,
384 input.onUploadProgress
385 ? (progress) => input.onUploadProgress?.(attachment.id, progress)
386 : undefined,
387 ),
388 abort,
389 }),
390 onMinted: (attachmentId) => {
391 if (controller.signal.aborted) return "cancel";
392 pendingAttachmentIds.push(attachmentId);
393 createdAttachmentIds.push(attachmentId);
394 return "continue";
395 },
396 });
397 if (result.status !== "uploaded") {
398 throw result.status === "failed" && result.error !== undefined
399 ? result.error
400 : new Error(`Upload failed for '${attachment.name}'.`);
401 }
402 uploadedAttachments.push(uploadedReference(attachment, result.attachmentId));
403 }
404
405 if (controller.signal.aborted) throw new Error("Upload cancelled.");
406
407 const draftAttachments = withUploadedMobileAttachmentReferences({
408 environmentId,
409 attachments: input.attachments,
410 uploadedAttachments,
411 });
412 const referencesChanged = draftAttachments.some(
413 (attachment, index) => attachment !== input.attachments[index],
414 );
415 if (referencesChanged && input.persistUploadedReferences) {
416 if ((await input.persistUploadedReferences(draftAttachments)) === "abandon") {
417 await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
418 return { status: "abandoned" };
419 }
420 }
421 return ready(uploadedAttachments, pendingAttachmentIds, draftAttachments);
422 } catch (error) {
423 await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
424 if (controller.signal.aborted) return { status: "abandoned" };
425 throw error;
426 } finally {
427 input.signal?.removeEventListener("abort", abort);
428 }
429}