Open History to see the last commit
1import { msg, type Msg } from "gt-react";
2import {
3 AuthOrchestrationOperateScope,
4 AuthOrchestrationReadScope,
5 PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
6 type ChatAttachment,
7 type EnvironmentId,
8} from "@t3tools/contracts";
9import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
10import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
11import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
12import {
13 attachmentUploadError,
14 createAttachmentUploadRegistry,
15} from "@t3tools/client-runtime/state/attachment-uploads";
16import {
17 deletePendingAttachmentUpload,
18 runAttachmentUploadCycle,
19 verifyPersistedAttachmentUpload,
20 type PersistedAttachmentVerification,
21} from "@t3tools/client-runtime/state/attachments";
22import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
23import { create } from "zustand";
24import * as Effect from "effect/Effect";
25import * as Fiber from "effect/Fiber";
26import * as Option from "effect/Option";
27import { AsyncResult } from "effect/reactivity";
28
29import {
30 DraftId,
31 useComposerDraftStore,
32 type ComposerFileAttachment,
33 type ComposerImageAttachment,
34 type ComposerThreadTarget,
35} from "../composerDraftStore";
36import { appAtomRegistry } from "../rpc/atomRegistry";
37import { environmentCatalog } from "../connection/catalog";
38import { assetEnvironment } from "../state/assets";
39import { attachmentEnvironment } from "../state/attachments";
40import { readEnvironmentScope, readPreparedConnection } from "../state/session";
41import type { AttachmentUploadState, ReadyAttachmentUpload } from "./attachmentUploadState";
42import { m } from "../i18n/messages";
43
44const MAX_UPLOADS_PER_ENVIRONMENT = 3;
45const UPLOAD_TIMEOUT_MS = 5 * 60_000;
46
47interface AttachmentUploadStore {
48 readonly uploadsByImageId: Readonly<Record<string, AttachmentUploadState>>;
49}
50
51export const useAttachmentUploadStore = create<AttachmentUploadStore>(() => ({
52 uploadsByImageId: {},
53}));
54
55interface UploadJob {
56 readonly image: ComposerImageAttachment | ComposerFileAttachment;
57 readonly environmentId: EnvironmentId;
58 /** Original owner; completion resolves the current owner because uploads can outlive draft moves. */
59 readonly draftTarget?: ComposerThreadTarget;
60 readonly previous?: ReadyAttachmentUpload;
61 /** Draft-owned; delete only through releasePersistedAttachmentUpload, never queue cancel/retry. */
62 readonly persistedAttachmentId?: string;
63}
64
65type DraftFileOwner = Pick<UploadJob, "image" | "environmentId" | "draftTarget">;
66
67/** The upload each image holds; a failed one stays held for its retry. */
68interface HeldUpload {
69 readonly job: UploadJob;
70 readonly release: () => void;
71 readonly stopWatchingConnection: () => void;
72}
73
74const heldUploads = new Map<string, HeldUpload>();
75const jobKey = (job: UploadJob) => `${job.environmentId}:${job.image.id}`;
76
77function setUploadState(imageId: string, upload: AttachmentUploadState): void {
78 useAttachmentUploadStore.setState((state) => ({
79 uploadsByImageId: { ...state.uploadsByImageId, [imageId]: upload },
80 }));
81}
82
83function clearUploadState(imageId: string): void {
84 useAttachmentUploadStore.setState((state) => {
85 if (!(imageId in state.uploadsByImageId)) {
86 return state;
87 }
88 const uploadsByImageId = { ...state.uploadsByImageId };
89 delete uploadsByImageId[imageId];
90 return { uploadsByImageId };
91 });
92}
93
94export function readAttachmentUpload(imageId: string): AttachmentUploadState | undefined {
95 return useAttachmentUploadStore.getState().uploadsByImageId[imageId];
96}
97
98function resolveCurrentFileDraftTarget(job: DraftFileOwner): ComposerThreadTarget | undefined {
99 if (job.draftTarget === undefined || job.image.type !== "file") {
100 return undefined;
101 }
102 const store = useComposerDraftStore.getState();
103 for (const [key, draft] of Object.entries(store.draftsByThreadKey)) {
104 if (!draft.files.some((file) => file.id === job.image.id)) {
105 continue;
106 }
107 const draftSession = store.draftThreadsByThreadKey[key];
108 if (draftSession !== undefined) {
109 if (draftSession.environmentId === job.environmentId) {
110 return DraftId.make(key);
111 }
112 continue;
113 }
114 if (typeof job.draftTarget === "string" && job.draftTarget === key) {
115 return DraftId.make(key);
116 }
117 const threadRef = parseScopedThreadKey(key);
118 if (threadRef?.environmentId === job.environmentId) {
119 return threadRef;
120 }
121 }
122 return undefined;
123}
124
125/** Persist background completions even when no composer is mounted. */
126function stampDraftFileUpload(job: DraftFileOwner, attachmentId: string): void {
127 const draftTarget = resolveCurrentFileDraftTarget(job);
128 if (draftTarget === undefined) {
129 return;
130 }
131 useComposerDraftStore
132 .getState()
133 .setFileUpload(draftTarget, job.image.id, job.environmentId, attachmentId);
134}
135
136function deletePendingUpload(environmentId: EnvironmentId, attachmentId: string): void {
137 if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return;
138 deletePendingAttachmentUpload({
139 registry: appAtomRegistry,
140 remove: attachmentEnvironment.remove,
141 environmentId,
142 attachmentId,
143 });
144}
145
146function uploadBytes(input: {
147 readonly url: string;
148 readonly file: File;
149 readonly mimeType: string;
150 readonly signal: AbortSignal;
151 readonly onProgress: (progress: number) => void;
152 readonly onTransportFailure: () => void;
153}): Promise<void> {
154 const xhr = new XMLHttpRequest();
155 return new Promise<void>((resolve, reject) => {
156 xhr.open("POST", input.url, true);
157 xhr.timeout = UPLOAD_TIMEOUT_MS;
158 xhr.setRequestHeader("Content-Type", input.mimeType);
159 xhr.upload.addEventListener("progress", (event) => {
160 if (event.lengthComputable && event.total > 0) {
161 input.onProgress(event.loaded / event.total);
162 }
163 });
164 xhr.addEventListener("load", () => {
165 if (xhr.status >= 200 && xhr.status < 300) {
166 resolve();
167 } else {
168 reject(new Error(m(msg`Upload rejected (${{ status: xhr.status }})`)));
169 }
170 });
171 xhr.addEventListener("error", () => {
172 input.onTransportFailure();
173 reject(new Error(m(msg("Upload failed"))));
174 });
175 xhr.addEventListener("timeout", () => {
176 input.onTransportFailure();
177 reject(new Error(m(msg("Upload timed out"))));
178 });
179 xhr.addEventListener("abort", () => reject(new Error(m(msg("Upload cancelled")))));
180 input.signal.addEventListener("abort", () => xhr.abort(), { once: true });
181 xhr.send(input.file);
182 });
183}
184
185const canOperate = (environmentId: EnvironmentId) =>
186 readEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
187
188const uploadFailureReason = (reasonMessage: string) => ({
189 reason: m(reasonMessage),
190 reasonMessage,
191});
192
193/** Records the failure the composer shows, then fails the upload with it. */
194const failUpload = (job: UploadJob, reasonMessage: string | Msg, attachmentId?: string) =>
195 Effect.sync(() =>
196 setUploadState(job.image.id, {
197 status: "failed",
198 environmentId: job.environmentId,
199 reason: m(reasonMessage),
200 reasonMessage,
201 ...(attachmentId ? { attachmentId } : {}),
202 ...(job.previous ? { previous: job.previous } : {}),
203 }),
204 ).pipe(Effect.andThen(Effect.fail(attachmentUploadError(new Error(m(reasonMessage))))));
205
206/** Uploads one composer attachment, writing the state its composer shows as it goes. */
207const uploadJob = Effect.fn("WebAttachmentUploads.upload")(function* (job: UploadJob) {
208 if (!canOperate(job.environmentId)) {
209 return yield* failUpload(job, msg("This connection cannot upload attachments."));
210 }
211 if (job.persistedAttachmentId) {
212 const verification = yield* verifyPersistedAttachmentUpload({
213 registry: appAtomRegistry,
214 createAssetUrl: assetEnvironment.createUrl,
215 environmentId: job.environmentId,
216 attachmentId: job.persistedAttachmentId,
217 });
218 if (verification.status === "verified") {
219 setUploadState(job.image.id, {
220 status: "ready",
221 environmentId: job.environmentId,
222 attachmentId: job.persistedAttachmentId,
223 });
224 stampDraftFileUpload(job, job.persistedAttachmentId);
225 return job.persistedAttachmentId;
226 }
227 if (verification.status === "missing" && !job.image.file && job.image.type === "file") {
228 const draftTarget = resolveCurrentFileDraftTarget(job);
229 if (
230 draftTarget !== undefined &&
231 useComposerDraftStore
232 .getState()
233 .markFileUploadMissing(
234 draftTarget,
235 job.image.id,
236 job.environmentId,
237 job.persistedAttachmentId,
238 )
239 ) {
240 // The draft now shows the file as missing, so the composer has no upload to show.
241 clearUploadState(job.image.id);
242 return yield* attachmentUploadError(new Error(m(msg("Uploaded file expired."))));
243 }
244 }
245 if (verification.status === "failed" || !job.image.file) {
246 // Failed-state ids get deleted on retry/release; exclude persisted ids after transient verification failure.
247 return yield* failUpload(
248 job,
249 verification.status === "missing"
250 ? msg("Uploaded file expired. Remove it and attach it again.")
251 : msg("Uploaded file could not be verified. Retry when the server reconnects."),
252 );
253 }
254 }
255
256 const mimeType =
257 job.image.type === "file"
258 ? job.image.mimeType.toLowerCase()
259 : PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.find(
260 (supportedMimeType) => supportedMimeType === job.image.mimeType.toLowerCase(),
261 );
262 if (!mimeType) return yield* failUpload(job, msg("Unsupported image type"));
263 const file = job.image.file;
264 if (!file) return yield* failUpload(job, msg("Original file is no longer available"));
265 if (!canOperate(job.environmentId)) {
266 return yield* failUpload(job, msg("This connection cannot upload attachments."));
267 }
268
269 let lastStep = -1;
270 let transportFailed = false;
271 const result = yield* runAttachmentUploadCycle({
272 registry: appAtomRegistry,
273 createUploadUrl: attachmentEnvironment.createUploadUrl,
274 remove: attachmentEnvironment.remove,
275 environmentId: job.environmentId,
276 upload: {
277 ...(job.image.type === "file" ? { type: "file" as const } : {}),
278 name: job.image.name,
279 mimeType,
280 sizeBytes: file.size,
281 },
282 resolveUploadUrl: (relativeUrl) => {
283 if (!canOperate(job.environmentId)) return null;
284 const connection = readPreparedConnection(job.environmentId);
285 return connection ? resolveAssetUrl(connection.httpBaseUrl, relativeUrl) : null;
286 },
287 transport: (url) =>
288 Effect.tryPromise({
289 try: (signal) =>
290 uploadBytes({
291 url,
292 file,
293 mimeType,
294 signal,
295 onTransportFailure: () => {
296 transportFailed = true;
297 },
298 onProgress: (progress) => {
299 const step = Math.floor(progress * 20);
300 if (step === lastStep || signal.aborted) return;
301 lastStep = step;
302 setUploadState(job.image.id, {
303 status: "uploading",
304 environmentId: job.environmentId,
305 progress,
306 ...(job.previous ? { previous: job.previous } : {}),
307 });
308 },
309 }),
310 catch: attachmentUploadError,
311 }),
312 });
313 if (result.status === "uploaded") {
314 setUploadState(job.image.id, {
315 status: "ready",
316 environmentId: job.environmentId,
317 attachmentId: result.attachmentId,
318 });
319 stampDraftFileUpload(job, result.attachmentId);
320 if (job.previous) {
321 deletePendingUpload(job.previous.environmentId, job.previous.attachmentId);
322 }
323 return result.attachmentId;
324 }
325 return yield* failUpload(
326 job,
327 result.step === "mint"
328 ? msg("Upload could not start")
329 : result.step === "resolve-url"
330 ? canOperate(job.environmentId)
331 ? msg("Not connected")
332 : msg("This connection cannot upload attachments.")
333 : result.error instanceof Error
334 ? msg`${{ reason: errorDisplayMessage(result.error, m) ?? result.error.message }}`
335 : msg("Upload failed"),
336 result.attachmentId ?? undefined,
337 ).pipe(
338 Effect.tapError(() =>
339 transportFailed
340 ? Effect.sync(() => {
341 void runAtomCommand(
342 appAtomRegistry,
343 environmentCatalog.checkHttpOrigin,
344 job.environmentId,
345 { reportFailure: false, reportDefect: false },
346 );
347 })
348 : Effect.void,
349 ),
350 );
351});
352
353const uploads = createAttachmentUploadRegistry<UploadJob>({
354 key: jobKey,
355 environmentId: (job) => job.environmentId,
356 concurrencyPerEnvironment: MAX_UPLOADS_PER_ENVIRONMENT,
357 upload: (job) =>
358 uploadJob(job).pipe(
359 Effect.catchDefect((defect) =>
360 failUpload(job, msg("Upload failed")).pipe(
361 Effect.ensuring(Effect.logWarning("Composer attachment upload threw", defect)),
362 ),
363 ),
364 ),
365});
366
367/** Waits for an image's held upload to finish, without keeping it running. */
368function awaitHeldUpload(imageId: string): Effect.Effect<void> {
369 const held = heldUploads.get(imageId);
370 const fiber = held === undefined ? undefined : uploads.current(jobKey(held.job));
371 return fiber === undefined ? Effect.void : Effect.asVoid(Fiber.await(fiber));
372}
373
374export function startAttachmentUpload(input: {
375 readonly environmentId: EnvironmentId;
376 readonly image: ComposerImageAttachment | ComposerFileAttachment;
377 readonly draftTarget?: ComposerThreadTarget;
378 readonly force?: boolean;
379}): void {
380 if (!canOperate(input.environmentId)) return;
381 const existingHold = heldUploads.get(input.image.id);
382 if (existingHold?.job.environmentId === input.environmentId) {
383 return;
384 }
385
386 const existing = readAttachmentUpload(input.image.id);
387 if (
388 !input.force &&
389 existing?.status === "ready" &&
390 existing.environmentId === input.environmentId
391 ) {
392 // A file restored into a draft after its upload finished (stash, failed send) missed the
393 // completion stamp; stamping here keeps it from re-uploading after a reload.
394 stampDraftFileUpload(input, existing.attachmentId);
395 return;
396 }
397 if (existing?.status === "failed" && existing.environmentId === input.environmentId) {
398 return;
399 }
400 if (
401 existing &&
402 "previous" in existing &&
403 existing.previous?.environmentId === input.environmentId
404 ) {
405 cancelAttachmentUpload(input.image.id);
406 if (existing.status === "failed" && existing.attachmentId) {
407 deletePendingUpload(existing.environmentId, existing.attachmentId);
408 }
409 setUploadState(input.image.id, existing.previous);
410 // Retargeting a scratch draft cleared the file's upload stamp; restore it for reloads.
411 stampDraftFileUpload(input, existing.previous.attachmentId);
412 return;
413 }
414
415 if (existingHold) {
416 cancelAttachmentUpload(input.image.id);
417 }
418 const previous = existing?.status === "ready" ? existing : existing?.previous;
419 const job: UploadJob = {
420 image: input.image,
421 environmentId: input.environmentId,
422 ...(input.draftTarget !== undefined ? { draftTarget: input.draftTarget } : {}),
423 ...(previous ? { previous } : {}),
424 ...(!input.force &&
425 input.image.type === "file" &&
426 input.image.uploadEnvironmentId === input.environmentId &&
427 input.image.uploadedAttachmentId
428 ? { persistedAttachmentId: input.image.uploadedAttachmentId }
429 : {}),
430 };
431
432 setUploadState(input.image.id, {
433 status: "uploading",
434 environmentId: input.environmentId,
435 progress: 0,
436 ...(previous ? { previous } : {}),
437 });
438 const connectionAtom = environmentCatalog.stateAtom(job.environmentId);
439 const isConnected = () =>
440 Option.exists(
441 AsyncResult.value(appAtomRegistry.get(connectionAtom)),
442 (state) => state.phase === "connected",
443 );
444 const ownsImage = () => heldUploads.get(input.image.id)?.job === job;
445 let wasConnected = isConnected();
446 const stopWatchingConnection = appAtomRegistry.subscribe(connectionAtom, () => {
447 const connected = isConnected();
448 const reconnected = connected && !wasConnected;
449 wasConnected = connected;
450 if (!reconnected) return;
451 // HTTP failures can follow reconnection; await the attempt and retry only if this job still owns the file.
452 Effect.runFork(
453 awaitHeldUpload(input.image.id).pipe(
454 Effect.andThen(
455 Effect.sync(() => {
456 if (
457 ownsImage() &&
458 readAttachmentUpload(input.image.id)?.status === "failed" &&
459 isConnected()
460 ) {
461 retryAttachmentUpload(input);
462 }
463 }),
464 ),
465 ),
466 );
467 });
468 heldUploads.set(input.image.id, {
469 job,
470 release: uploads.hold(job),
471 stopWatchingConnection,
472 });
473 // A finished upload lets go of its image; a failed one stays held for its retry.
474 uploads.current(jobKey(job))?.addObserver((exit) => {
475 if (exit._tag !== "Success" || !ownsImage()) return;
476 const held = heldUploads.get(input.image.id)!;
477 heldUploads.delete(input.image.id);
478 held.stopWatchingConnection();
479 held.release();
480 });
481}
482
483function cancelAttachmentUpload(imageId: string): void {
484 const held = heldUploads.get(imageId);
485 if (!held) {
486 return;
487 }
488 heldUploads.delete(imageId);
489 held.stopWatchingConnection();
490 // Releasing interrupts a running upload, which aborts its transfer and deletes its mint.
491 held.release();
492}
493
494export function releaseAttachmentUpload(imageId: string): void {
495 const upload = readAttachmentUpload(imageId);
496 cancelAttachmentUpload(imageId);
497 if (upload?.status === "ready") {
498 deletePendingUpload(upload.environmentId, upload.attachmentId);
499 } else if (upload) {
500 if (upload.status === "failed" && upload.attachmentId) {
501 deletePendingUpload(upload.environmentId, upload.attachmentId);
502 }
503 if (upload.previous) {
504 deletePendingUpload(upload.previous.environmentId, upload.previous.attachmentId);
505 }
506 }
507 clearUploadState(imageId);
508}
509
510export function releasePersistedAttachmentUpload(input: {
511 readonly id: string;
512 readonly environmentId: EnvironmentId;
513 readonly attachmentId: string;
514}): void {
515 const upload = readAttachmentUpload(input.id);
516 if (
517 upload?.status === "ready" &&
518 upload.environmentId === input.environmentId &&
519 upload.attachmentId === input.attachmentId
520 ) {
521 releaseAttachmentUpload(input.id);
522 return;
523 }
524 const held = heldUploads.get(input.id);
525 if (
526 held?.job.environmentId === input.environmentId &&
527 held.job.persistedAttachmentId === input.attachmentId
528 ) {
529 releaseAttachmentUpload(input.id);
530 }
531 deletePendingUpload(input.environmentId, input.attachmentId);
532}
533
534export function retryAttachmentUpload(input: {
535 readonly environmentId: EnvironmentId;
536 readonly image: ComposerImageAttachment | ComposerFileAttachment;
537 readonly draftTarget?: ComposerThreadTarget;
538}): void {
539 if (!canOperate(input.environmentId)) return;
540 const previous = readAttachmentUpload(input.image.id);
541 const held = heldUploads.get(input.image.id);
542 cancelAttachmentUpload(input.image.id);
543 // The failed upload stays cached until dropped, and the retry must start a fresh one.
544 if (held) uploads.invalidate(jobKey(held.job));
545 if (previous?.status === "failed" && previous.attachmentId) {
546 deletePendingUpload(previous.environmentId, previous.attachmentId);
547 }
548 if (previous && "previous" in previous && previous.previous) {
549 setUploadState(input.image.id, previous.previous);
550 } else {
551 clearUploadState(input.image.id);
552 }
553 startAttachmentUpload(input);
554}
555
556/** Verifies uploads before stash restore; pending uploads expire after 24 hours. */
557export function verifyStashedAttachmentUpload(input: {
558 readonly environmentId: EnvironmentId;
559 readonly attachmentId: string;
560}): Promise<PersistedAttachmentVerification> {
561 return Effect.runPromise(
562 verifyPersistedAttachmentUpload({
563 registry: appAtomRegistry,
564 createAssetUrl: assetEnvironment.createUrl,
565 environmentId: input.environmentId,
566 attachmentId: input.attachmentId,
567 }),
568 );
569}
570
571/** Resolves once these images' uploads finish, fail or are cancelled. */
572export function awaitAttachmentUploads(imageIds: ReadonlyArray<string>): Promise<void> {
573 return Effect.runPromise(
574 Effect.forEach(imageIds, awaitHeldUpload, { concurrency: "unbounded", discard: true }),
575 );
576}
577
578/** Revalidate ready uploads at send time; a long-lived draft can outlive server cleanup. */
579export async function refreshExpiredAttachmentUploads(input: {
580 readonly environmentId: EnvironmentId;
581 readonly images: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>;
582 readonly draftTarget?: ComposerThreadTarget;
583}): Promise<void> {
584 const canVerify = readEnvironmentScope(input.environmentId, AuthOrchestrationReadScope);
585 await Promise.all(
586 input.images.map(async (image) => {
587 const upload = readAttachmentUpload(image.id);
588 if (upload?.status !== "ready" || upload.environmentId !== input.environmentId) return;
589 if (!canVerify) {
590 if (image.file) {
591 startAttachmentUpload({
592 environmentId: input.environmentId,
593 image,
594 force: true,
595 ...(input.draftTarget !== undefined ? { draftTarget: input.draftTarget } : {}),
596 });
597 } else {
598 setUploadState(image.id, {
599 status: "failed",
600 environmentId: input.environmentId,
601 previous: upload,
602 ...uploadFailureReason(
603 msg("Uploaded attachment could not be verified. Attach the file again."),
604 ),
605 });
606 }
607 return;
608 }
609 const verification = await verifyStashedAttachmentUpload({
610 environmentId: input.environmentId,
611 attachmentId: upload.attachmentId,
612 }).catch((error: unknown): PersistedAttachmentVerification => ({ status: "failed", error }));
613 // The user may have removed or replaced the attachment while verification was in flight.
614 if (readAttachmentUpload(image.id) !== upload) return;
615 if (verification.status === "verified") return;
616 if (verification.status === "missing" && image.file) {
617 clearUploadState(image.id);
618 startAttachmentUpload({
619 environmentId: input.environmentId,
620 image,
621 force: true,
622 ...(input.draftTarget !== undefined ? { draftTarget: input.draftTarget } : {}),
623 });
624 return;
625 }
626 setUploadState(image.id, {
627 status: "failed",
628 environmentId: input.environmentId,
629 previous: upload,
630 ...uploadFailureReason(
631 verification.status === "missing"
632 ? msg("Uploaded attachment expired. Remove it and attach it again.")
633 : msg("Uploaded attachment could not be verified. Retry when the server reconnects."),
634 ),
635 });
636 }),
637 );
638 await awaitAttachmentUploads(input.images.map((image) => image.id));
639}
640
641export function getUploadedAttachments(input: {
642 readonly environmentId: EnvironmentId;
643 readonly images: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>;
644}): ChatAttachment[] | null {
645 const attachments: ChatAttachment[] = [];
646 for (const image of input.images) {
647 const upload = readAttachmentUpload(image.id);
648 if (upload?.status !== "ready" || upload.environmentId !== input.environmentId) {
649 return null;
650 }
651 attachments.push({
652 type: image.type,
653 id: upload.attachmentId,
654 name: image.name,
655 mimeType: image.mimeType,
656 sizeBytes: image.sizeBytes,
657 ...(image.source ? { source: image.source } : {}),
658 });
659 }
660 return attachments;
661}
662
663/** In-memory queue releases miss uploads after reload; every draft discard must use this path. */
664export function releaseDraftAttachment(
665 attachment: ComposerImageAttachment | ComposerFileAttachment,
666): void {
667 if (
668 attachment.type === "file" &&
669 attachment.uploadedAttachmentId !== undefined &&
670 attachment.uploadEnvironmentId !== undefined
671 ) {
672 releasePersistedAttachmentUpload({
673 id: attachment.id,
674 environmentId: attachment.uploadEnvironmentId,
675 attachmentId: attachment.uploadedAttachmentId,
676 });
677 if (heldUploads.has(attachment.id) || readAttachmentUpload(attachment.id)) {
678 releaseAttachmentUpload(attachment.id);
679 }
680 return;
681 }
682 releaseAttachmentUpload(attachment.id);
683}
684
685export function releaseDraftAttachments(
686 attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>,
687): void {
688 for (const attachment of attachments) {
689 releaseDraftAttachment(attachment);
690 }
691}