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