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