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 { PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES } from "@t3tools/contracts";
17import * as Option from "effect/Option";
18
19import { appAtomRegistry } from "../state/atom-registry";
20import { assetEnvironment } from "../state/assets";
21import { attachmentEnvironment } from "../state/attachments";
22import { environmentSession } from "../state/session";
23import { retainComposerAttachmentFileForPreview } from "../state/use-composer-drafts";
24import { resolveOwnedComposerAttachmentFileUri } from "./composerAttachmentFiles";
25import {
26 isFileBackedComposerAttachment,
27 type DraftComposerAttachment,
28 type DraftComposerImageAttachment,
29} from "./composerImages";
30import { uuidv4 } from "./uuid";
31
32/**
33 * This module owns the server side of a composer attachment's lifecycle.
34 * `prepareTurnAttachments` acquires pending uploads (verifying and reusing
35 * persisted ones), hands the uploaded ids back to the attachment's durable
36 * owner (queued outbox message or composer draft), and returns a release
37 * handle for after the turn consumed the bytes. Nothing outside this module
38 * mints or deletes pending uploads. The local-file side of the lifecycle is
39 * owned by `removeThreadOutboxMessage` / the composer draft mutators, which
40 * release files through `releaseUnusedComposerAttachmentFiles`.
41 */
42export type UploadedMobileAttachment =
43 | UploadChatImageAttachment
44 | ChatImageAttachment
45 | ChatFileAttachment;
46
47export function validateDraftFileAttachments(input: {
48 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
49 readonly serverConfig: {
50 readonly environment: {
51 readonly capabilities: {
52 readonly attachmentUploads?: boolean;
53 readonly fileAttachments?: { readonly maxUploadBytes: number };
54 };
55 };
56 } | null;
57}): string | null {
58 const files = input.attachments.filter((attachment) => attachment.type === "file");
59 if (files.length === 0) return null;
60 if (input.serverConfig === null) return "Server attachment support is still loading.";
61 const capabilities = input.serverConfig.environment.capabilities;
62 if (capabilities.attachmentUploads !== true || capabilities.fileAttachments === undefined) {
63 return "This server does not support file attachments.";
64 }
65 const maxBytes = clampFileAttachmentUploadBytes(capabilities.fileAttachments.maxUploadBytes);
66 const oversized = files.find((attachment) => attachment.sizeBytes > maxBytes);
67 return oversized ? fileAttachmentTooLargeMessage(oversized.name, maxBytes) : null;
68}
69
70/** Keep uploaded ids alongside the local bytes so a later send can reuse them. */
71export function withUploadedMobileAttachmentReferences(input: {
72 readonly environmentId: EnvironmentId;
73 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
74 readonly uploadedAttachments: ReadonlyArray<UploadedMobileAttachment>;
75}): ReadonlyArray<DraftComposerAttachment> {
76 return input.attachments.map((attachment, index) => {
77 const uploaded = input.uploadedAttachments[index];
78 if (
79 !uploaded ||
80 !("id" in uploaded) ||
81 attachment.type !== uploaded.type ||
82 (attachment.uploadedAttachmentId === uploaded.id &&
83 attachment.uploadEnvironmentId === input.environmentId)
84 ) {
85 return attachment;
86 }
87 return {
88 ...attachment,
89 uploadedAttachmentId: uploaded.id,
90 uploadEnvironmentId: input.environmentId,
91 };
92 });
93}
94
95/**
96 * Deletes pending uploads the client no longer references. Every delete result
97 * is inspected; failed deletes are retried once and a persistent failure
98 * throws, so a caller can never silently leak the outcome. (The server also
99 * expires pending uploads, so a leaked id self-heals eventually.)
100 */
101export async function releasePendingAttachmentUploads(
102 environmentId: EnvironmentId,
103 attachmentIds: ReadonlyArray<string>,
104): Promise<void> {
105 const deleteOnce = async (attachmentId: string): Promise<boolean> => {
106 const result = await runAtomCommand(
107 appAtomRegistry,
108 attachmentEnvironment.remove,
109 { environmentId, input: { attachmentId } },
110 { reportFailure: false, reportDefect: false },
111 );
112 return (
113 result._tag === "Success" ||
114 isAssetAttachmentNotFoundFailure(squashAtomCommandFailure(result))
115 );
116 };
117
118 const failedAttachmentIds: string[] = [];
119 for (const attachmentId of attachmentIds) {
120 if (!(await deleteOnce(attachmentId)) && !(await deleteOnce(attachmentId))) {
121 failedAttachmentIds.push(attachmentId);
122 }
123 }
124 if (failedAttachmentIds.length > 0) {
125 throw new Error(
126 `Could not delete ${failedAttachmentIds.length} pending attachment upload(s): ${failedAttachmentIds.join(", ")}.`,
127 );
128 }
129}
130
131async function releaseCreatedUploadsQuietly(
132 environmentId: EnvironmentId,
133 attachmentIds: ReadonlyArray<string>,
134): Promise<void> {
135 try {
136 await releasePendingAttachmentUploads(environmentId, attachmentIds);
137 } catch (error) {
138 // The original failure must propagate; the leaked pending uploads expire
139 // on the server.
140 console.warn("[attachments] could not delete abandoned pending uploads", error);
141 }
142}
143
144export interface PreparedTurnAttachments {
145 readonly status: "ready";
146 /** Wire attachments for `startTurn`, in the original composer order. */
147 readonly attachments: ReadonlyArray<UploadedMobileAttachment>;
148 /** Composer attachments annotated with the uploaded pending ids. */
149 readonly draftAttachments: ReadonlyArray<DraftComposerAttachment>;
150 /** Every pending upload backing this turn (reused and newly minted). */
151 readonly pendingAttachmentIds: ReadonlyArray<string>;
152 /** Deletes all pending uploads once the delivered turn holds the bytes. */
153 readonly releaseUploads: () => Promise<void>;
154}
155
156export type PrepareTurnAttachmentsResult =
157 | PreparedTurnAttachments
158 | { readonly status: "abandoned" };
159
160function uploadedReference(
161 attachment: DraftComposerAttachment,
162 id: string,
163): ChatImageAttachment | ChatFileAttachment {
164 const fields = {
165 id,
166 name: attachment.name,
167 mimeType: attachment.mimeType,
168 sizeBytes: attachment.sizeBytes,
169 };
170 return attachment.type === "image" ? { type: "image", ...fields } : { type: "file", ...fields };
171}
172
173function attachmentUploadInput(attachment: DraftComposerAttachment) {
174 const fields = {
175 name: attachment.name,
176 mimeType: attachment.mimeType,
177 sizeBytes: attachment.sizeBytes,
178 };
179 if (attachment.type === "file") return { type: "file" as const, ...fields };
180 const mimeType = PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.find(
181 (type) => type === attachment.mimeType.toLowerCase(),
182 );
183 if (!mimeType) throw new Error(`Unsupported image type for '${attachment.name}'.`);
184 return { ...fields, mimeType };
185}
186
187/**
188 * Wire shape for startTurn on servers without attachment uploads: pure inline
189 * uploads without client draft id / previewUri. File-backed images read their
190 * base64 from disk lazily, only when this legacy path is actually taken.
191 */
192async function toUploadChatImageAttachments(
193 attachments: ReadonlyArray<DraftComposerImageAttachment>,
194): Promise<ReadonlyArray<UploadChatImageAttachment>> {
195 return Promise.all(
196 attachments.map(async (attachment) => ({
197 type: attachment.type,
198 name: attachment.name,
199 mimeType: attachment.mimeType,
200 sizeBytes: attachment.sizeBytes,
201 dataUrl: await composerImageAttachmentDataUrl(attachment),
202 })),
203 );
204}
205
206/** Inline bytes for one image: legacy drafts carry them, file-backed ones read them from disk. */
207async function composerImageAttachmentDataUrl(
208 attachment: DraftComposerImageAttachment,
209): Promise<string> {
210 if (attachment.dataUrl !== undefined) {
211 return attachment.dataUrl;
212 }
213 if (!isFileBackedComposerAttachment(attachment)) {
214 throw new Error(`'${attachment.name}' is no longer available. Attach the image again.`);
215 }
216 const release = retainComposerAttachmentFileForPreview(attachment);
217 try {
218 const { File, Paths } = await import("expo-file-system");
219 const uri =
220 resolveOwnedComposerAttachmentFileUri(attachment.fileUri, Paths.document.uri) ??
221 attachment.fileUri;
222 const base64 = await new File(uri).base64();
223 return `data:${attachment.mimeType};base64,${base64}`;
224 } finally {
225 release();
226 }
227}
228
229async function uploadFileBytes(
230 attachment: DraftComposerAttachment,
231 url: string,
232 signal: AbortSignal,
233 onProgress?: (progress: number) => void,
234): Promise<void> {
235 const { File, Paths, UploadType } = await import("expo-file-system");
236 if (signal.aborted) throw new Error("Upload cancelled.");
237 // Legacy image drafts persisted inline bytes and stage them in a temp cache
238 // file for the native uploader. Everything else uploads its owned copy.
239 const fileUri = attachment.fileUri;
240 const inlineDataUrl = attachment.type === "image" ? attachment.dataUrl : undefined;
241 if (fileUri === undefined && inlineDataUrl === undefined) {
242 throw new Error(`'${attachment.name}' is no longer available. Attach the image again.`);
243 }
244 const file =
245 fileUri === undefined
246 ? new File(Paths.cache, `t3-upload-${uuidv4()}`)
247 : new File(resolveOwnedComposerAttachmentFileUri(fileUri, Paths.document.uri) ?? fileUri);
248 try {
249 if (fileUri === undefined && inlineDataUrl !== undefined) {
250 file.create();
251 file.write(inlineDataUrl.slice(inlineDataUrl.indexOf(",") + 1), {
252 encoding: "base64",
253 });
254 }
255 const result = await file.upload(url, {
256 httpMethod: "POST",
257 uploadType: UploadType.BINARY_CONTENT,
258 headers: { "Content-Type": attachment.mimeType },
259 signal,
260 ...(onProgress
261 ? {
262 onProgress: ({ bytesSent, totalBytes }) => {
263 if (totalBytes > 0) onProgress(bytesSent / totalBytes);
264 },
265 }
266 : {}),
267 });
268 if (result.status < 200 || result.status >= 300) {
269 throw new Error(`Upload failed for '${attachment.name}' (${result.status}).`);
270 }
271 } finally {
272 if (fileUri === undefined && file.exists) file.delete();
273 }
274}
275
276/**
277 * Acquires server-side uploads for one turn's attachments and persists the
278 * uploaded ids into the attachments' durable owner.
279 *
280 * `persistUploadedReferences` runs once the bytes are on the server and only
281 * when new ids appeared. It must write the annotated attachments into the
282 * owner (queued message or draft) so a retry after a crash reuses the bytes.
283 * Returning `"abandon"` (owner no longer wants the send) or throwing deletes
284 * the pending uploads this call minted, so the owner cannot leak them.
285 */
286export async function prepareTurnAttachments(input: {
287 readonly environmentId: EnvironmentId;
288 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
289 /** Older environments continue to receive inline images. */
290 readonly supportsImageUploads?: boolean;
291 readonly signal?: AbortSignal;
292 readonly onUploadProgress?: (attachmentId: string, progress: number) => void;
293 readonly persistUploadedReferences?: (
294 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
295 ) => Promise<"persisted" | "abandon">;
296}): Promise<PrepareTurnAttachmentsResult> {
297 const { environmentId } = input;
298 if (input.signal?.aborted) return { status: "abandoned" };
299 const files = input.attachments.filter((attachment) => attachment.type === "file");
300 const ready = (
301 attachments: ReadonlyArray<UploadedMobileAttachment>,
302 pendingAttachmentIds: ReadonlyArray<string>,
303 draftAttachments: ReadonlyArray<DraftComposerAttachment>,
304 ): PreparedTurnAttachments => ({
305 status: "ready",
306 attachments,
307 draftAttachments,
308 pendingAttachmentIds,
309 releaseUploads: () => releasePendingAttachmentUploads(environmentId, pendingAttachmentIds),
310 });
311
312 if (input.attachments.length === 0 || (files.length === 0 && !input.supportsImageUploads)) {
313 try {
314 const imageAttachments = await toUploadChatImageAttachments(
315 input.attachments.filter((attachment) => attachment.type === "image"),
316 );
317 if (input.signal?.aborted) return { status: "abandoned" };
318 return ready(imageAttachments, [], input.attachments);
319 } catch (error) {
320 if (input.signal?.aborted) return { status: "abandoned" };
321 throw error;
322 }
323 }
324
325 const connection = appAtomRegistry.get(
326 environmentSession.preparedConnectionValueAtom(environmentId),
327 );
328 if (Option.isNone(connection)) {
329 throw new Error("The environment is not connected.");
330 }
331
332 const uploadedAttachments: UploadedMobileAttachment[] = [];
333 const pendingAttachmentIds: string[] = [];
334 const createdAttachmentIds: string[] = [];
335 const controller = new AbortController();
336 const abort = () => controller.abort();
337 input.signal?.addEventListener("abort", abort, { once: true });
338 try {
339 for (const attachment of input.attachments) {
340 if (controller.signal.aborted) throw new Error("Upload cancelled.");
341 if (attachment.type === "image" && !input.supportsImageUploads) {
342 uploadedAttachments.push(...(await toUploadChatImageAttachments([attachment])));
343 continue;
344 }
345
346 // Reuse the bytes from a previous attempt when their pending upload is
347 // still alive on this environment.
348 if (
349 attachment.uploadEnvironmentId === environmentId &&
350 attachment.uploadedAttachmentId !== undefined
351 ) {
352 const verification = await verifyPersistedAttachmentUpload({
353 registry: appAtomRegistry,
354 createAssetUrl: assetEnvironment.createUrl,
355 environmentId,
356 attachmentId: attachment.uploadedAttachmentId,
357 });
358 if (verification.status === "failed") {
359 throw verification.error;
360 }
361 if (verification.status === "verified") {
362 pendingAttachmentIds.push(attachment.uploadedAttachmentId);
363 uploadedAttachments.push(uploadedReference(attachment, attachment.uploadedAttachmentId));
364 continue;
365 }
366 // "missing": the pending upload expired, upload the bytes again.
367 }
368
369 const result = await runAttachmentUploadCycle({
370 registry: appAtomRegistry,
371 createUploadUrl: attachmentEnvironment.createUploadUrl,
372 remove: attachmentEnvironment.remove,
373 environmentId,
374 upload: attachmentUploadInput(attachment),
375 // Read the connection at transfer time: the environment may have
376 // reconnected on a new base URL since this cycle started.
377 resolveUploadUrl: (relativeUrl) => {
378 const currentConnection = appAtomRegistry.get(
379 environmentSession.preparedConnectionValueAtom(environmentId),
380 );
381 return Option.isNone(currentConnection)
382 ? null
383 : resolveAssetUrl(currentConnection.value.httpBaseUrl, relativeUrl);
384 },
385 transport: (url) => ({
386 done: uploadFileBytes(
387 attachment,
388 url,
389 controller.signal,
390 input.onUploadProgress
391 ? (progress) => input.onUploadProgress?.(attachment.id, progress)
392 : undefined,
393 ),
394 abort,
395 }),
396 onMinted: (attachmentId) => {
397 if (controller.signal.aborted) return "cancel";
398 pendingAttachmentIds.push(attachmentId);
399 createdAttachmentIds.push(attachmentId);
400 return "continue";
401 },
402 });
403 if (result.status !== "uploaded") {
404 throw result.status === "failed" && result.error !== undefined
405 ? result.error
406 : new Error(`Upload failed for '${attachment.name}'.`);
407 }
408 uploadedAttachments.push(uploadedReference(attachment, result.attachmentId));
409 }
410
411 if (controller.signal.aborted) throw new Error("Upload cancelled.");
412
413 const draftAttachments = withUploadedMobileAttachmentReferences({
414 environmentId,
415 attachments: input.attachments,
416 uploadedAttachments,
417 });
418 const referencesChanged = draftAttachments.some(
419 (attachment, index) => attachment !== input.attachments[index],
420 );
421 if (referencesChanged && input.persistUploadedReferences) {
422 if ((await input.persistUploadedReferences(draftAttachments)) === "abandon") {
423 await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
424 return { status: "abandoned" };
425 }
426 }
427 return ready(uploadedAttachments, pendingAttachmentIds, draftAttachments);
428 } catch (error) {
429 await releaseCreatedUploadsQuietly(environmentId, createdAttachmentIds);
430 if (controller.signal.aborted) return { status: "abandoned" };
431 throw error;
432 } finally {
433 input.signal?.removeEventListener("abort", abort);
434 }
435}