Open History to see the last commit
1import {
2 PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
3 type ChatAttachment,
4 type EnvironmentId,
5} from "@t3tools/contracts";
6import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets";
7import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
8import { create } from "zustand";
9
10import type { ComposerImageAttachment } from "../composerDraftStore";
11import { appAtomRegistry } from "../rpc/atomRegistry";
12import { attachmentEnvironment } from "../state/attachments";
13import { readPreparedConnection } from "../state/session";
14import type { AttachmentUploadState, ReadyAttachmentUpload } from "./attachmentUploadState";
15
16const MAX_UPLOADS_PER_ENVIRONMENT = 3;
17const UPLOAD_TIMEOUT_MS = 5 * 60_000;
18
19interface AttachmentUploadStore {
20 readonly uploadsByImageId: Readonly<Record<string, AttachmentUploadState>>;
21}
22
23export const useAttachmentUploadStore = create<AttachmentUploadStore>(() => ({
24 uploadsByImageId: {},
25}));
26
27interface UploadJob {
28 readonly image: ComposerImageAttachment;
29 readonly environmentId: EnvironmentId;
30 readonly previous?: ReadyAttachmentUpload;
31 readonly settled: Promise<void>;
32 resolveSettled: () => void;
33 attachmentId: string | null;
34 cancelled: boolean;
35 abort: (() => void) | null;
36}
37
38const jobsByImageId = new Map<string, UploadJob>();
39const queue: UploadJob[] = [];
40const activeUploadsByEnvironment = new Map<EnvironmentId, number>();
41
42function setUploadState(imageId: string, upload: AttachmentUploadState): void {
43 useAttachmentUploadStore.setState((state) => ({
44 uploadsByImageId: { ...state.uploadsByImageId, [imageId]: upload },
45 }));
46}
47
48function clearUploadState(imageId: string): void {
49 useAttachmentUploadStore.setState((state) => {
50 if (!(imageId in state.uploadsByImageId)) {
51 return state;
52 }
53 const uploadsByImageId = { ...state.uploadsByImageId };
54 delete uploadsByImageId[imageId];
55 return { uploadsByImageId };
56 });
57}
58
59export function readAttachmentUpload(imageId: string): AttachmentUploadState | undefined {
60 return useAttachmentUploadStore.getState().uploadsByImageId[imageId];
61}
62
63function deletePendingUpload(environmentId: EnvironmentId, attachmentId: string): void {
64 void runAtomCommand(
65 appAtomRegistry,
66 attachmentEnvironment.remove,
67 { environmentId, input: { attachmentId } },
68 { reportFailure: false, reportDefect: false },
69 );
70}
71
72function uploadBytes(input: {
73 readonly url: string;
74 readonly file: File;
75 readonly onProgress: (progress: number) => void;
76}): { readonly done: Promise<void>; readonly abort: () => void } {
77 const xhr = new XMLHttpRequest();
78 const done = new Promise<void>((resolve, reject) => {
79 xhr.open("POST", input.url, true);
80 xhr.timeout = UPLOAD_TIMEOUT_MS;
81 xhr.setRequestHeader("Content-Type", input.file.type);
82 xhr.upload.addEventListener("progress", (event) => {
83 if (event.lengthComputable && event.total > 0) {
84 input.onProgress(event.loaded / event.total);
85 }
86 });
87 xhr.addEventListener("load", () => {
88 if (xhr.status >= 200 && xhr.status < 300) {
89 resolve();
90 } else {
91 reject(new Error(`Upload rejected (${xhr.status})`));
92 }
93 });
94 xhr.addEventListener("error", () => reject(new Error("Upload failed")));
95 xhr.addEventListener("timeout", () => reject(new Error("Upload timed out")));
96 xhr.addEventListener("abort", () => reject(new Error("Upload cancelled")));
97 xhr.send(input.file);
98 });
99
100 return { done, abort: () => xhr.abort() };
101}
102
103async function runUpload(job: UploadJob): Promise<void> {
104 const mimeType = PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.find(
105 (supportedMimeType) => supportedMimeType === job.image.mimeType.toLowerCase(),
106 );
107 if (!mimeType) {
108 setUploadState(job.image.id, {
109 status: "failed",
110 environmentId: job.environmentId,
111 reason: "Unsupported image type",
112 ...(job.previous ? { previous: job.previous } : {}),
113 });
114 return;
115 }
116
117 const minted = await runAtomCommand(
118 appAtomRegistry,
119 attachmentEnvironment.createUploadUrl,
120 {
121 environmentId: job.environmentId,
122 input: {
123 name: job.image.name,
124 mimeType,
125 sizeBytes: job.image.file.size,
126 },
127 },
128 { reportFailure: false },
129 );
130 if (job.cancelled) {
131 if (minted._tag === "Success") {
132 deletePendingUpload(job.environmentId, minted.value.attachmentId);
133 }
134 return;
135 }
136 if (minted._tag !== "Success") {
137 setUploadState(job.image.id, {
138 status: "failed",
139 environmentId: job.environmentId,
140 reason: "Upload could not start",
141 ...(job.previous ? { previous: job.previous } : {}),
142 });
143 return;
144 }
145 job.attachmentId = minted.value.attachmentId;
146
147 const connection = readPreparedConnection(job.environmentId);
148 const url = connection ? resolveAssetUrl(connection.httpBaseUrl, minted.value.relativeUrl) : null;
149 if (!url) {
150 setUploadState(job.image.id, {
151 status: "failed",
152 environmentId: job.environmentId,
153 reason: "Not connected",
154 attachmentId: minted.value.attachmentId,
155 ...(job.previous ? { previous: job.previous } : {}),
156 });
157 return;
158 }
159
160 let lastStep = -1;
161 const upload = uploadBytes({
162 url,
163 file: job.image.file,
164 onProgress: (progress) => {
165 const step = Math.floor(progress * 20);
166 if (step === lastStep || job.cancelled) {
167 return;
168 }
169 lastStep = step;
170 setUploadState(job.image.id, {
171 status: "uploading",
172 environmentId: job.environmentId,
173 progress,
174 ...(job.previous ? { previous: job.previous } : {}),
175 });
176 },
177 });
178 job.abort = upload.abort;
179
180 try {
181 await upload.done;
182 if (job.cancelled) {
183 return;
184 }
185 setUploadState(job.image.id, {
186 status: "ready",
187 environmentId: job.environmentId,
188 attachmentId: minted.value.attachmentId,
189 });
190 if (job.previous) {
191 deletePendingUpload(job.previous.environmentId, job.previous.attachmentId);
192 }
193 } catch (error) {
194 if (job.cancelled) {
195 return;
196 }
197 setUploadState(job.image.id, {
198 status: "failed",
199 environmentId: job.environmentId,
200 reason: error instanceof Error ? error.message : "Upload failed",
201 attachmentId: minted.value.attachmentId,
202 ...(job.previous ? { previous: job.previous } : {}),
203 });
204 } finally {
205 job.abort = null;
206 }
207}
208
209function pumpUploads(): void {
210 for (let index = 0; index < queue.length; ) {
211 const job = queue[index]!;
212 const active = activeUploadsByEnvironment.get(job.environmentId) ?? 0;
213 if (active >= MAX_UPLOADS_PER_ENVIRONMENT) {
214 index += 1;
215 continue;
216 }
217
218 queue.splice(index, 1);
219 if (job.cancelled) {
220 continue;
221 }
222 activeUploadsByEnvironment.set(job.environmentId, active + 1);
223 void runUpload(job)
224 .catch(() => {
225 if (!job.cancelled) {
226 setUploadState(job.image.id, {
227 status: "failed",
228 environmentId: job.environmentId,
229 reason: "Upload failed",
230 ...(job.previous ? { previous: job.previous } : {}),
231 });
232 }
233 })
234 .finally(() => {
235 if (jobsByImageId.get(job.image.id) === job) {
236 jobsByImageId.delete(job.image.id);
237 }
238 const remaining = (activeUploadsByEnvironment.get(job.environmentId) ?? 1) - 1;
239 if (remaining > 0) {
240 activeUploadsByEnvironment.set(job.environmentId, remaining);
241 } else {
242 activeUploadsByEnvironment.delete(job.environmentId);
243 }
244 job.resolveSettled();
245 pumpUploads();
246 });
247 }
248}
249
250export function startAttachmentUpload(input: {
251 readonly environmentId: EnvironmentId;
252 readonly image: ComposerImageAttachment;
253}): void {
254 const existingJob = jobsByImageId.get(input.image.id);
255 if (existingJob?.environmentId === input.environmentId) {
256 return;
257 }
258
259 const existing = readAttachmentUpload(input.image.id);
260 if (existing?.status === "ready" && existing.environmentId === input.environmentId) {
261 return;
262 }
263 if (existing?.status === "failed" && existing.environmentId === input.environmentId) {
264 return;
265 }
266 if (
267 existing &&
268 "previous" in existing &&
269 existing.previous?.environmentId === input.environmentId
270 ) {
271 cancelAttachmentUpload(input.image.id);
272 if (existing.status === "failed" && existing.attachmentId) {
273 deletePendingUpload(existing.environmentId, existing.attachmentId);
274 }
275 setUploadState(input.image.id, existing.previous);
276 return;
277 }
278
279 if (existingJob) {
280 cancelAttachmentUpload(input.image.id);
281 }
282 const previous = existing?.status === "ready" ? existing : existing?.previous;
283 let resolveSettled: () => void = () => {};
284 const settled = new Promise<void>((resolve) => {
285 resolveSettled = resolve;
286 });
287 const job: UploadJob = {
288 image: input.image,
289 environmentId: input.environmentId,
290 ...(previous ? { previous } : {}),
291 settled,
292 resolveSettled,
293 attachmentId: null,
294 cancelled: false,
295 abort: null,
296 };
297
298 jobsByImageId.set(input.image.id, job);
299 queue.push(job);
300 setUploadState(input.image.id, {
301 status: "uploading",
302 environmentId: input.environmentId,
303 progress: 0,
304 ...(previous ? { previous } : {}),
305 });
306 pumpUploads();
307}
308
309export function cancelAttachmentUpload(imageId: string): void {
310 const job = jobsByImageId.get(imageId);
311 if (!job) {
312 return;
313 }
314 job.cancelled = true;
315 jobsByImageId.delete(imageId);
316 const queuedIndex = queue.indexOf(job);
317 if (queuedIndex !== -1) {
318 queue.splice(queuedIndex, 1);
319 }
320 job.abort?.();
321 if (job.attachmentId) {
322 deletePendingUpload(job.environmentId, job.attachmentId);
323 }
324 job.resolveSettled();
325}
326
327export function releaseAttachmentUpload(imageId: string): void {
328 const upload = readAttachmentUpload(imageId);
329 cancelAttachmentUpload(imageId);
330 if (upload?.status === "ready") {
331 deletePendingUpload(upload.environmentId, upload.attachmentId);
332 } else if (upload) {
333 if (upload.status === "failed" && upload.attachmentId) {
334 deletePendingUpload(upload.environmentId, upload.attachmentId);
335 }
336 if (upload.previous) {
337 deletePendingUpload(upload.previous.environmentId, upload.previous.attachmentId);
338 }
339 }
340 clearUploadState(imageId);
341}
342
343export function retryAttachmentUpload(input: {
344 readonly environmentId: EnvironmentId;
345 readonly image: ComposerImageAttachment;
346}): void {
347 const previous = readAttachmentUpload(input.image.id);
348 cancelAttachmentUpload(input.image.id);
349 if (previous?.status === "failed" && previous.attachmentId) {
350 deletePendingUpload(previous.environmentId, previous.attachmentId);
351 }
352 if (previous && "previous" in previous && previous.previous) {
353 setUploadState(input.image.id, previous.previous);
354 } else {
355 clearUploadState(input.image.id);
356 }
357 startAttachmentUpload(input);
358}
359
360export async function awaitAttachmentUploads(imageIds: ReadonlyArray<string>): Promise<void> {
361 await Promise.all(imageIds.map((imageId) => jobsByImageId.get(imageId)?.settled));
362}
363
364export function getUploadedAttachments(input: {
365 readonly environmentId: EnvironmentId;
366 readonly images: ReadonlyArray<ComposerImageAttachment>;
367}): ChatAttachment[] | null {
368 const attachments: ChatAttachment[] = [];
369 for (const image of input.images) {
370 const upload = readAttachmentUpload(image.id);
371 if (upload?.status !== "ready" || upload.environmentId !== input.environmentId) {
372 return null;
373 }
374 attachments.push({
375 type: "image",
376 id: upload.attachmentId,
377 name: image.name,
378 mimeType: image.mimeType,
379 sizeBytes: image.sizeBytes,
380 });
381 }
382 return attachments;
383}
384
385export function releaseAttachmentUploads(images: ReadonlyArray<ComposerImageAttachment>): void {
386 for (const image of images) {
387 releaseAttachmentUpload(image.id);
388 }
389}