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

attachmentUpload.ts

462 lines18.2 KB

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