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