Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
feat(upload): reuse the shared upload flow in Cloud
Timothy Yina9f12ed27f30
diff --git a/apps/cloud/README.md b/apps/cloud/README.mdindex 0f014d8a..1d3637c2 100644--- a/apps/cloud/README.md+++ b/apps/cloud/README.md@@ -4,6 +4,15 @@ Cloud owns its marketing, sign-in, portal and error presentation. Server authoriHost routing and tenant context remain authoritative. Cloud-only styles and componentsmust not change the Self-hosted or Site editions.+Photo uploads reuse the Console upload drawer, floating queue, scheduler and+multipart transport. The application root owns the queue so portal navigation,+including switching Sites, does not interrupt admitted uploads. Each batch keeps+its original Site, account, storage connection and album selection; signing out+or changing accounts clears the queue. Reloading/closing the browser is not+background uploading: select the same files again to resume a retained reservation.+Multipart initialization uses the same unsupported-operation fallback to signed+PUT as Self-hosted, without proxying file bodies through the edge application.+## Design languageCloud uses the shared [SaaS UI layer](../../packages/saas-ui/README.md), also thediff --git a/apps/cloud/app/app.vue b/apps/cloud/app/app.vueindex d4d629b2..07fff4a7 100644--- a/apps/cloud/app/app.vue+++ b/apps/cloud/app/app.vue@@ -1,6 +1,8 @@<script setup lang="ts">import { en, zh_cn } from '@nuxt/ui/locale'+import { provideCloudUploads } from './composables/useCloudUploads'const { locale } = useI18n()+provideCloudUploads()const componentLocale = computed(() =>locale.value === 'zh-Hans' ? zh_cn : en,)@@ -20,6 +22,7 @@ useHead(() => ({><NuxtLoadingIndicator color="var(--cf-primary)" /><NuxtLayout><NuxtPage/></NuxtLayout>+ <CloudTransferPanel /></div></UApp></template>diff --git a/apps/cloud/app/components/CloudSiteWorkspace.vue b/apps/cloud/app/components/CloudSiteWorkspace.vueindex ac645a34..d239ecb2 100644--- a/apps/cloud/app/components/CloudSiteWorkspace.vue+++ b/apps/cloud/app/components/CloudSiteWorkspace.vue@@ -50,6 +50,6 @@ const status = computed(() => (loading.value ? 'pending' : 'success')):tone="failed ? 'error' : 'info'">{{ message }}</CfAlert>- <slot /><CloudUploadDrawer /><CloudTransferPanel />+ <slot /><CloudUploadDrawer /></PhotosProvider></template>diff --git a/apps/cloud/app/components/CloudTransferPanel.vue b/apps/cloud/app/components/CloudTransferPanel.vueindex 5610ccd5..9f27423f 100644--- a/apps/cloud/app/components/CloudTransferPanel.vue+++ b/apps/cloud/app/components/CloudTransferPanel.vue@@ -1,313 +1,95 @@<script setup lang="ts">-const {- jobs,- ready,- removePhoto,- photos,- uploading,- progress,- currentFile,- uploadSession,- cancel,- admin,- busy,- action,- api,- base,-} = useCloudSiteMedia()+import { useCloudUploads } from '../composables/useCloudUploads'+const uploads = useCloudUploads()+const { uploadingFiles, remove, clearCompleted, clearAll, tracked, busy } =+ uploadsconst { t } = useI18n()-const collapsed = ref(false)-type Job = (typeof jobs.value)[number]-const tracked = ref<Record<string, Job>>({})-const dismissed = new Set<string>()-const active = (job: Job) =>- ['queued', 'running', 'retry_wait'].includes(job.state)-let initialSnapshot = true-watch(- [jobs, ready],- ([items, loaded]) => {- if (!loaded) return- if (initialSnapshot) {- // Keep historical failures reachable for cleanup without opening the panel on every visit.- collapsed.value =- !items.some(active) && items.some((job) => job.state === 'failed')- initialSnapshot = false- }- const next = { ...tracked.value }- const present = new Set(items.map((job) => job.id))- for (const job of Object.values(next)) {- if (job.state !== 'succeeded' && !present.has(job.id)) delete next[job.id]- }- for (const job of items) {- if (active(job)) dismissed.delete(job.id)- if (- next[job.id] ||- (!dismissed.has(job.id) && (active(job) || job.state === 'failed'))+async function jobAction(fileId: string, operation: 'retry' | 'delete') {+ const item = tracked.get(fileId)+ if (!item?.context.admin || !item.job || busy.value) return+ if (+ operation === 'delete' &&+ !window.confirm(+ t('cloud.messages.deleteThisPhotographAndItsManagedOriginalThumbnailAnd'),+ )+ )+ return+ busy.value = true+ try {+ await uploads.api(+ item.context,+ operation === 'retry'+ ? `/jobs/${item.jobId}/retry`+ : `/photos/${item.job.photo_id}/delete`,+ {},+ )+ if (operation === 'delete') remove(fileId)+ else {+ uploads.trackJobs(+ item.context,+ [{ ...item.job, state: 'queued', error_code: null }],+ { partial: true },)- next[job.id] = job}- tracked.value = next- },- { immediate: true },-)-const processingJobs = computed(() => Object.values(tracked.value))-const processingActive = computed(- () => processingJobs.value.filter(active).length,-)-const processingCompleted = computed(- () => processingJobs.value.filter((job) => job.state === 'succeeded').length,-)-const hasActive = computed(() => uploading.value || processingActive.value > 0)-const visible = computed(- () => uploadSession.total > 0 || processingJobs.value.length > 0,-)-const panelId = useId()-watch(uploading, (value) => {- if (value) collapsed.value = false-})-function dismiss() {- if (hasActive.value) return- for (const job of processingJobs.value) dismissed.add(job.id)- tracked.value = {}- uploadSession.total = 0- uploadSession.message = ''-}-function removeFailed(job: Job) {- if (admin.value && !busy.value && job.state === 'failed')- return removePhoto(job.photo_id)-}-function photoName(job: Job) {- return (- job.file_name ||- photos.value.find((p) => p.id === job.photo_id)?.title ||- t('cloud.messages.untitledPhotograph')- )+ uploads.revision.value+++ } catch (error) {+ const entry = uploadingFiles.value.get(fileId)+ if (entry)+ entry.error =+ error instanceof Error+ ? error.message+ : t('cloud.messages.uploadFailed')+ uploads.notify()+ } finally {+ busy.value = false+ }}</script><template><ClientOnly><Teleport to="body">- <section- v-if="visible"- class="cloud-transfer-panel"- :aria-label="t('cloud.transfer.title')"+ <UploadQueuePanel+ :uploading-files="uploadingFiles"+ @remove-file="remove"+ @clear-completed="clearCompleted"+ @clear-all="clearAll"+ @go-to-queue="navigateTo('/sites')">- <header class="flex items-center gap-2 border-b border-default p-4">- <UButton- variant="ghost"- color="neutral"- class="flex min-w-0 flex-1 items-center gap-3 text-left"- type="button"- :aria-expanded="!collapsed"- :aria-controls="panelId"- @click="collapsed = !collapsed"+ <template #file-details="{ fileId }">+ <NuxtLink+ v-if="tracked.get(fileId)"+ :to="`/sites/${tracked.get(fileId)!.context.siteId}/photos`"+ class="text-xs text-muted underline"+ >{{ tracked.get(fileId)!.context.name }}</NuxtLink>- <UIcon- :name="- hasActive ? 'i-lucide-loader-circle' : 'i-lucide-list-checks'- "- class="size-5 shrink-0"- :class="{ 'animate-spin': hasActive }"- />- <strong class="flex-1 text-sm">{{- t('cloud.transfer.title')- }}</strong>- <UIcon- :name="- collapsed ? 'i-lucide-chevron-up' : 'i-lucide-chevron-down'- "- class="size-4 shrink-0"- />- </UButton>- <UButton- v-if="!hasActive"- icon="i-lucide-x"- color="neutral"- variant="ghost"- size="sm"- :aria-label="t('cloud.transfer.dismiss')"- @click="dismiss"- />- </header>- <div- v-show="!collapsed"- :id="panelId"- class="cloud-transfer-body divide-y divide-default"- >- <div- v-if="uploadSession.total"- class="space-y-3 p-4"+ </template>+ <template #file-actions="{ fileId }">+ <template+ v-if="+ tracked.get(fileId)?.context.admin &&+ tracked.get(fileId)?.job?.state === 'failed'+ ">- <div class="flex items-center justify-between gap-3 text-sm">- <strong>{{ t('cloud.transfer.upload') }}</strong>- <span class="text-muted">{{- t('cloud.transfer.count', {- completed: uploadSession.completed,- total: uploadSession.total,- })- }}</span>- </div>- <template v-if="uploading">- <p- class="truncate text-sm"- :title="currentFile"- >- {{ currentFile }}- </p>- <UProgress :model-value="progress || undefined" />- <p- class="text-xs text-muted"- role="status"- >- {{- progress === 100- ? t('cloud.transfer.verifying')- : t(- uploadSession.storage === 'platform'- ? 'cloud.ui.uploadProgressPlatform'- : 'cloud.ui.uploadProgress',- { progress },- )- }}- </p>- <CfButton- size="sm"- variant="secondary"- @click="cancel"- >{{ t('cloud.messages.cancelUpload') }}</CfButton- >- </template>- <p- v-else- class="text-sm"- :class="uploadSession.failed ? 'text-error' : 'text-muted'"- :role="uploadSession.failed ? 'alert' : 'status'"+ <UButton+ v-if="tracked.get(fileId)!.job!.attempts <= 6"+ size="xs"+ color="neutral"+ variant="soft"+ :disabled="busy"+ @click="jobAction(fileId, 'retry')"+ >{{ t('cloud.messages.retry') }}</UButton>- {{ uploadSession.message }}- </p>- </div>- <div- v-if="processingJobs.length"- class="space-y-3 p-4"- >- <div class="flex items-center justify-between gap-3 text-sm">- <strong>{{ t('cloud.messages.processingQueue') }}</strong>- <span class="text-muted">{{- t('cloud.transfer.count', {- completed: processingCompleted,- total: processingJobs.length,- })- }}</span>- </div>- <UProgress v-if="processingActive" />- <ul class="space-y-3">- <li- v-for="job in processingJobs"- :key="job.id"- class="flex items-start gap-3"- >- <UIcon- :name="- job.state === 'failed'- ? 'i-lucide-circle-alert'- : job.state === 'succeeded'- ? 'i-lucide-circle-check'- : 'i-lucide-loader-circle'- "- class="mt-0.5 size-4 shrink-0"- :class="{- 'animate-spin': active(job),- 'text-error': job.state === 'failed',- }"- />- <div class="min-w-0 flex-1 space-y-1">- <p- class="truncate text-sm"- :title="photoName(job)"- >- {{ photoName(job) }}- </p>- <p class="text-xs text-muted">- {{- t(- [- 'queued',- 'running',- 'retry_wait',- 'failed',- 'cancelled',- 'succeeded',- ].includes(job.state)- ? 'cloud.ui.' + job.state- : 'cloud.ui.unknownJob',- )- }}- · {{ t('cloud.ui.attemptCount', { count: job.attempts }) }}- </p>- <p- v-if="job.error_code"- class="text-xs text-error"- >- {{- t('cloud.ui.processingFailure', { code: job.error_code })- }}- </p>- </div>- <CfButton- v-if="admin && job.state === 'failed' && job.attempts <= 6"- variant="secondary"- size="sm"- :disabled="busy"- @click="- action(- () =>- api(base + '/jobs/' + job.id + '/retry', {- method: 'POST',- body: {},- }),- t('cloud.messages.jobQueuedAgain'),- )- "- >{{ t('cloud.messages.retry') }}</CfButton- >- <CfButton- v-if="admin && job.state === 'failed'"- variant="destructive"- size="sm"- :disabled="busy"- @click="removeFailed(job)"- >{{ t('cloud.messages.remove') }}</CfButton- >- </li>- </ul>- </div>- </div>- </section>+ <UButton+ size="xs"+ color="error"+ variant="soft"+ :disabled="busy"+ @click="jobAction(fileId, 'delete')"+ >{{ t('cloud.messages.remove') }}</UButton+ >+ </template>+ </template>+ </UploadQueuePanel></Teleport></ClientOnly></template>-<style scoped>-.cloud-transfer-panel {- position: fixed;- z-index: 40;- right: 24px;- bottom: max(24px, env(safe-area-inset-bottom));- width: min(420px, calc(100vw - 32px));- overflow: hidden;- border: 1px solid var(--ui-border);- border-radius: 12px;- background: var(--ui-bg);- color: var(--ui-text);- box-shadow: 0 12px 36px #0003;-}-.cloud-transfer-body {- max-height: min(65dvh, 560px);- overflow-y: auto;-}-@media (max-width: 640px) {- .cloud-transfer-panel {- right: 16px;- bottom: max(16px, env(safe-area-inset-bottom));- }-}-</style>diff --git a/apps/cloud/app/components/CloudUploadDrawer.vue b/apps/cloud/app/components/CloudUploadDrawer.vueindex 704536b7..0480fc54 100644--- a/apps/cloud/app/components/CloudUploadDrawer.vue+++ b/apps/cloud/app/components/CloudUploadDrawer.vue@@ -1,9 +1,5 @@<script setup lang="ts">import { uploadQuotaGate } from '../utils/quota-gate'-import {- mergeUploadFiles,- remainingUploadFiles,-} from '../utils/upload-selection'const {uploadOpen,albums,@@ -13,15 +9,12 @@ const {connections,connectionId,upload,- uploading,preparingUpload,- usage,allowance,fileLimit,admin,} = useCloudSiteMedia()-const context = useEntryContext().value,- input = ref<HTMLInputElement>()+const context = useEntryContext().valueconst quota = useCloudQuota(context?.workspaceId)const selectedAdmission = computed(() =>uploadQuotaGate(@@ -40,267 +33,121 @@ const uploadAllowed = computed()const selectedFiles = shallowRef<File[]>([])const starting = ref(false)-const selectedPhotos = computed(- () =>- selectedFiles.value.filter(- (file) => !file.name.toLowerCase().endsWith('.mov'),- ).length,-)-const selectionLocked = computed(- () => starting.value || uploading.value || preparingUpload.value,-)-function addFiles(files: File[]) {- if (selectionLocked.value || !admin.value) return- selectedFiles.value = mergeUploadFiles(selectedFiles.value, files)-}-function selectFiles(event: Event) {- const target = event.target as HTMLInputElement- addFiles(Array.from(target.files ?? []))- target.value = ''-}-function dropFiles(event: DragEvent) {- if (!uploadAllowed.value) return- addFiles(Array.from(event.dataTransfer?.files ?? []))-}-function removeSelected(index: number) {- if (selectionLocked.value) return- selectedFiles.value = selectedFiles.value.filter(- (_, position) => position !== index,- )-}+const selectionLocked = computed(() => starting.value || preparingUpload.value)async function startUpload() {if (selectionLocked.value ||- !selectedPhotos.value ||+ !selectedFiles.value.length ||!uploadAllowed.value ||!admin.value)return- const files = [...selectedFiles.value]starting.value = truetry {- const result = await upload(files)- if (result)- selectedFiles.value = remainingUploadFiles(files, result.completed)+ const result = await upload([...selectedFiles.value])+ if (result?.queued) selectedFiles.value = []} finally {starting.value = false}}</script><template>- <USlideover+ <PhotoUploadSlideoverv-model:open="uploadOpen"- :title="$t('cloud.messages.uploadPhotographs')"- :description="- $t('cloud.messages.addPhotographsToYourLibraryJpegPngHeicAnd')- "- :ui="{ footer: 'justify-end', header: 'pe-16', body: 'min-w-0' }"- ><template #body- ><div class="min-w-0 space-y-5">- <p- v-if="message"- :role="failed ? 'alert' : 'status'"- class="cf-notice"- :class="{ 'cf-notice-error': failed }"- >- {{ message }}- </p>- <UFormField :label="$t('cloud.messages.storageConnection')"- ><USelect- v-model="connectionId"- :items="- connections- .filter(- (c) =>- c.uploads_enabled !== 0 &&- (c.pool_id || allowance?.byosLimits.byos),- )- .map((c) => ({- label: c.pool_id- ? $t('cloud.messages.platformStorage')- : c.config.bucket,- value: c.id,- disabled:- !uploadQuotaGate(quota.data.value, [c], c.id).allowed ||- !!quota.error.value,- }))- "- class="w-full"- :disabled="selectionLocked"- /></UFormField>- <i18n-t- v-if="!connections.length && allowance?.byosLimits.byos"- keypath="cloud.ui.connectStorageGuidance"- tag="p"- scope="global"- class="text-sm text-muted"- >- <template #link- ><NuxtLink- :to="`/sites/${context?.siteId}/storage`"- class="underline"- @click="uploadOpen = false"- >{{ $t('cloud.messages.storage') }}</NuxtLink- ></template- >- </i18n-t>- <p- v-if="!connections.length && !allowance?.byosLimits.byos"- class="text-sm text-muted"- >- {{ $t('cloud.storageAllowance.unavailable') }}- </p>- <CloudQuotaNotice- v-if="!selectedAdmission.allowed || quota.error.value"- :reason="selectedAdmission.reason"- :error="!!quota.error.value"- @retry="quota.refresh()"- />- <UFormField- :label="$t('cloud.transfer.albums')"- :description="$t('cloud.transfer.albumHelp')"- >- <USelectMenu- v-model="selectedAlbumIds"- multiple- value-key="value"- :items="- albums.map((album) => ({- label: album.title,- value: Number(album.id),+ v-model:files="selectedFiles"+ :max-file-size-m-b="fileLimit / 1048576"+ :disabled="selectionLocked || !uploadAllowed || !admin"+ :loading="selectionLocked"+ :can-upload="uploadAllowed && admin"+ accept="image/*,.heic,.heif,.hif,.bmp,.tif,.tiff,.mov"+ @upload="startUpload"+ >+ <template #before-files>+ <p+ v-if="message"+ :role="failed ? 'alert' : 'status'"+ class="cf-notice"+ :class="{ 'cf-notice-error': failed }"+ >+ {{ message }}+ </p>+ <UFormField :label="$t('cloud.messages.storageConnection')">+ <USelect+ v-model="connectionId"+ :items="+ connections+ .filter(+ (c) =>+ c.uploads_enabled !== 0 &&+ (c.pool_id || allowance?.byosLimits.byos),+ )+ .map((c) => ({+ label: c.pool_id+ ? $t('cloud.messages.platformStorage')+ : c.config.bucket,+ value: c.id,+ disabled:+ !uploadQuotaGate(quota.data.value, [c], c.id).allowed ||+ !!quota.error.value,}))- "- :placeholder="$t('cloud.transfer.selectAlbums')"- :disabled="selectionLocked || !admin"- class="w-full"- />- </UFormField>- <input- ref="input"- class="sr-only"- type="file"- multiple- accept="image/*,.heic,.heif,.hif,.bmp,.tif,.tiff,.mov"- :aria-label="$t('cloud.messages.choosePhotographs')"- :disabled="selectionLocked || !uploadAllowed || !admin"- @change="selectFiles"- /><UButton- variant="ghost"- color="neutral"- class="cf-upload-dropzone"- @dragover.prevent- @drop.prevent="dropFiles"- :disabled="selectionLocked || !uploadAllowed || !admin"- @click="input?.click()"- >- <UIcon- name="tabler:cloud-upload"- class="size-9"- /><strong>{{ $t('cloud.messages.selectPhotographs') }}</strong- ><span>{{- $t('cloud.messages.dropImagesHereOrChooseImagesAndMatchingMov')- }}</span- ><span>{{- $t('cloud.storageAllowance.fileLimit', {- size: (fileLimit / 1048576).toFixed(0),- })- }}</span>- </UButton>- <section- v-if="selectedFiles.length"- class="space-y-3"- :aria-label="$t('cloud.transfer.selectedFiles')"- >- <div class="flex items-center justify-between gap-3">- <strong class="text-sm">{{- $t('cloud.transfer.selectedFilesCount', {- count: selectedFiles.length,- })- }}</strong>- <UButton- color="neutral"- variant="ghost"- size="sm"- :disabled="selectionLocked"- @click="selectedFiles = []"- >{{ $t('cloud.transfer.clearSelection') }}</UButton- >- </div>- <ul- class="max-h-72 divide-y divide-default overflow-y-auto rounded-lg border border-default"- >- <li- v-for="(file, index) in selectedFiles"- :key="JSON.stringify([file.name, file.size, file.lastModified])"- class="flex items-center gap-3 px-3 py-2"- >- <UIcon- :name="- file.name.toLowerCase().endsWith('.mov')- ? 'i-lucide-film'- : 'i-lucide-image'- "- class="size-5 shrink-0 text-muted"- />- <div class="min-w-0 flex-1">- <p- class="truncate text-sm"- :title="file.name"- >- {{ file.name }}- </p>- <p class="text-xs text-muted">{{ formatBytes(file.size) }}</p>- </div>- <UButton- icon="i-lucide-x"- color="neutral"- variant="ghost"- size="sm"- :aria-label="- $t('cloud.transfer.removeSelected', { name: file.name })- "- :disabled="selectionLocked"- @click="removeSelected(index)"- />- </li>- </ul>- <p- v-if="!selectedPhotos"- class="text-xs text-muted"+ "+ class="w-full"+ :disabled="selectionLocked"+ />+ </UFormField>+ <i18n-t+ v-if="!connections.length && allowance?.byosLimits.byos"+ keypath="cloud.ui.connectStorageGuidance"+ tag="p"+ scope="global"+ class="text-sm text-muted"+ >+ <template #link>+ <NuxtLink+ :to="`/sites/${context?.siteId}/storage`"+ class="underline"+ @click="uploadOpen = false">- {{ $t('cloud.transfer.selectPhotosForVideo') }}- </p>- </section>- <p- v-if="usage"- class="text-xs text-muted"- >- {{- $t('cloud.ui.uploadUsage', {- photos: usage.photos,- bytes: (usage.bytes / 1073741824).toFixed(2),- photoLimit: allowance?.limits.photos ?? '—',- uploadLimit: (- (allowance?.limits.monthlyBytes ?? 0) / 1073741824- ).toFixed(2),- })- }}- </p>- </div></template- ><template #footer>- <CfButton- variant="secondary"- @click="uploadOpen = false"- >{{ $t('cloud.transfer.closeSelection') }}</CfButton+ {{ $t('cloud.messages.storage') }}+ </NuxtLink>+ </template>+ </i18n-t>+ <p+ v-if="!connections.length && !allowance?.byosLimits.byos"+ class="text-sm text-muted">- <CfButton- :disabled="- selectionLocked || !selectedPhotos || !uploadAllowed || !admin- "- :loading="starting"- @click="startUpload"- >{{ $t('cloud.transfer.startUpload') }}</CfButton+ {{ $t('cloud.storageAllowance.unavailable') }}+ </p>+ <CloudQuotaNotice+ v-if="!selectedAdmission.allowed || quota.error.value"+ :reason="selectedAdmission.reason"+ :error="!!quota.error.value"+ @retry="quota.refresh()"+ />+ </template>+ <UCard+ variant="soft"+ class="border border-neutral-200/80 dark:border-neutral-800/80"+ >+ <UFormField+ :label="$t('cloud.transfer.albums')"+ :description="$t('cloud.transfer.albumHelp')">- </template></USlideover- >+ <USelectMenu+ v-model="selectedAlbumIds"+ multiple+ value-key="value"+ :items="+ albums.map((album) => ({+ label: album.title,+ value: Number(album.id),+ }))+ "+ :placeholder="$t('cloud.transfer.selectAlbums')"+ :disabled="selectionLocked || !admin"+ class="w-full"+ />+ </UFormField>+ </UCard>+ </PhotoUploadSlideover></template>diff --git a/apps/cloud/app/composables/useCloudSiteMedia.ts b/apps/cloud/app/composables/useCloudSiteMedia.tsindex 138c3002..9ba38b0f 100644--- a/apps/cloud/app/composables/useCloudSiteMedia.ts+++ b/apps/cloud/app/composables/useCloudSiteMedia.ts@@ -1,10 +1,16 @@import { STORAGE_CONNECTION_MESSAGES } from '@chronoframe/contracts/storage-diagnostics'import type { Album, Photo } from '@chronoframe/contracts/resources'+import {+ cloudUploadResumeKey,+ useCloudUploads,+ type CloudUploadContext,+} from './useCloudUploads'export function useCloudMediaWorkspace(props: {siteId: numberrole?: string}) {const { t } = useI18n()+ const uploads = useCloudUploads()const entryContext = useEntryContext(),snapshot = entryContext.value?.scopeconst api = async <T = unknown>(@@ -25,6 +31,13 @@ export function useCloudMediaWorkspace(props: {}const context = useEntryContext(),base = computed(() => `/api/sites/${props.siteId}/media`)+ const uploadContext: CloudUploadContext = {+ siteId: props.siteId,+ scope: snapshot ?? '',+ userId: useState<number | null>('platform-user-id', () => null).value!,+ name: context.value?.name ?? '',+ admin: props.role === 'admin',+ }const connections = ref<{id: string@@ -71,17 +84,7 @@ export function useCloudMediaWorkspace(props: {message = ref(''),failed = ref(false),busy = ref(false),- uploading = ref(false),- preparingUpload = ref(false),- progress = ref(0),- currentFile = ref('')- const uploadSession = reactive({- total: 0,- completed: 0,- storage: 'private' as 'platform' | 'private',- message: '',- failed: false,- })+ preparingUpload = ref(false)const storage = reactive({endpoint: '',region: 'auto',@@ -97,10 +100,7 @@ export function useCloudMediaWorkspace(props: {: allowance.value?.byosLimits)?.fileBytes ?? 0,)- let timer: ReturnType<typeof setInterval> | undefined,- controller: AbortController | undefined,- activeUpload: string | undefined,- activeResumeKey: string | undefined+ let timer: ReturnType<typeof setInterval> | undefinedconst canPoll = ref(true)const ready = ref(false)const loadError = ref('')@@ -153,7 +153,7 @@ export function useCloudMediaWorkspace(props: {}loadError.value = ''canPoll.value = true- if (uploading.value || preparingUpload.value) return+ if (preparingUpload.value) returnconst uploadTargets = s.connections.filter((c) => c.uploads_enabled !== 0 && (c.pool_id || u.byosLimits?.byos),)@@ -208,6 +208,12 @@ export function useCloudMediaWorkspace(props: {canPoll.value = truevoid reload()}+ watch(jobs, (items) => {+ if (import.meta.client) uploads.trackJobs(uploadContext, items)+ })+ watch(uploads.revision, () => {+ if (!disposed) void refreshProcessing()+ })async function action(run: () => Promise<unknown>, success: string) {if (busy.value) returnbusy.value = true@@ -320,110 +326,7 @@ export function useCloudMediaWorkspace(props: {return saved}function resumeKey(file: File, albumIds: number[], connection: string) {- return (- [- 'chronoframe-upload',- context.value?.scope,- props.siteId,- file.name,- file.size,- file.lastModified,- connection,- ].join(':') + (albumIds.length ? ':albums:' + albumIds.join(',') : '')- )- }- async function sendFile(- file: File,- liveVideo: File | undefined,- albumIds: number[],- connection: string,- ) {- const cache = resumeKey(file, albumIds, connection),- id = localStorage.getItem(cache) || crypto.randomUUID()- await api(base.value + '/uploads', {- method: 'POST',- body: {- requestId: id,- connectionId: connection,- fileName: file.name,- bytes: file.size,- albumIds,- ...(liveVideo- ? { liveVideo: { fileName: liveVideo.name, bytes: liveVideo.size } }- : {}),- },- })- localStorage.setItem(cache, id)- activeResumeKey = cache- if (controller?.signal.aborted) {- await api(base.value + '/uploads/' + id + '/cancel', {- method: 'POST',- body: {},- }).catch(() => {})- localStorage.removeItem(cache)- throw new Error('cancelled')- }- activeUpload = id- const plan = await api<{- state: string- mode?: string- url?: string- contentType?: string- videoUrl?: string | null- partBytes?: number- parts?: { partNumber: number; bytes: number }[]- urls?: string[]- }>(base.value + '/uploads/' + id + '/plan', { method: 'POST', body: {} })- if (plan.state === 'completed') {- localStorage.removeItem(cache)- return- }- if (plan.state !== 'pending' || !plan.mode) {- localStorage.removeItem(cache)- activeResumeKey = undefined- activeUpload = undefined- throw new Error(t('cloud.messages.uploadUnavailable'))- }- async function put(url: string, body: Blob, type?: string) {- for (let attempt = 0; attempt < 3; attempt++) {- controller?.signal.throwIfAborted()- const response = await fetch(url, {- method: 'PUT',- body,- headers: type ? { 'Content-Type': type } : {},- signal: controller?.signal,- redirect: 'error',- })- if (response.ok) return- if (attempt === 2) throw new Error(t('cloud.messages.uploadFailed'))- await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt))- }- }- if (plan.mode === 'single') await put(plan.url!, file, plan.contentType)- else {- const partBytes = plan.partBytes!,- count = plan.urls!.length- for (let i = 0; i < count; i++) {- const start = i * partBytes,- end = Math.min(file.size, start + partBytes)- if (- !plan.parts?.some(- (p) => p.partNumber === i + 1 && p.bytes === end - start,- )- )- await put(plan.urls![i]!, file.slice(start, end))- progress.value = Math.round((end / file.size) * 100)- }- }- if (liveVideo && plan.videoUrl)- await put(plan.videoUrl, liveVideo, 'video/quicktime')- progress.value = 100- await api(base.value + '/uploads/' + id + '/complete', {- method: 'POST',- body: {},- })- localStorage.removeItem(cache)- activeUpload = undefined+ return cloudUploadResumeKey(uploadContext, file, albumIds, connection)}async function upload(event: Event | File[]) {const input = Array.isArray(event)@@ -432,16 +335,12 @@ export function useCloudMediaWorkspace(props: {files = Array.from(input.files ?? [])if (!files.length ||- uploading.value ||preparingUpload.value ||- !connectionId.value+ !connectionId.value ||+ !admin.value)returnconst batchConnection = connectionId.value- const batchStorage = connections.value.find((c) => c.id === batchConnection)- ?.pool_id- ? 'platform'- : 'private'const isVideo = (file: File) => file.name.toLowerCase().endsWith('.mov')const companionFor = (photo: File) =>files.find(@@ -470,11 +369,11 @@ export function useCloudMediaWorkspace(props: {preparingUpload.value = truetry {if (chosenAlbums.length) {- const result = await api<{ albums: typeof albums.value }>(- base.value + '/albums',+ const result = await uploads.api<{ albums: typeof albums.value }>(+ uploadContext,+ '/albums',)- if (disposed) return- albums.value = result.albums+ if (!disposed) albums.value = result.albumsconst unavailable = chosenAlbums.some((id) => !result.albums.some((album) => Number(album.id) === id),)@@ -502,69 +401,12 @@ export function useCloudMediaWorkspace(props: {} finally {preparingUpload.value = false}- const albumIds = chosenAlbums- uploadSession.total = files.filter((f) => !isVideo(f)).length- uploadSession.completed = 0- uploadSession.storage = batchStorage- uploadSession.message = ''- uploadSession.failed = false+ void uploads.enqueue(uploadContext, files, batchConnection, chosenAlbums)uploadOpen.value = false- uploading.value = truefailed.value = falsemessage.value = ''- controller = new AbortController()- try {- for (const file of files.filter(- (f) => !f.name.toLowerCase().endsWith('.mov'),- )) {- const companion = companionFor(file)- currentFile.value = file.name- progress.value = 0- await sendFile(file, companion, albumIds, batchConnection)- uploadSession.completed++- void refreshProcessing()- }- uploadSession.message = t(- 'cloud.messages.uploadVerifiedProcessingContinuesInTheBackground',- )- } catch (error) {- const albumUnavailable =- (error as { data?: { data?: { code?: string } } }).data?.data?.code ===- 'upload_albums_unavailable'- if (albumUnavailable) {- await api<{ albums: typeof albums.value }>(base.value + '/albums')- .then((result) => {- albums.value = result.albums- })- .catch(() => {})- failed.value = true- message.value = t('cloud.transfer.albumsUnavailable')- uploadOpen.value = true- }- uploadSession.failed = true- uploadSession.message = albumUnavailable- ? t('cloud.transfer.albumsUnavailable')- : controller.signal.aborted- ? t('cloud.messages.uploadCancelled')- : t('cloud.messages.uploadInterruptedSelectTheSameFileToResumeIts')- } finally {- uploading.value = false- input.value = ''- currentFile.value = ''- await reload()- }- return { completed: uploadSession.completed }- }- async function cancel() {- controller?.abort()- if (activeResumeKey) localStorage.removeItem(activeResumeKey)- activeResumeKey = undefined- if (activeUpload)- await api(base.value + '/uploads/' + activeUpload + '/cancel', {- method: 'POST',- body: {},- }).catch(() => {})- activeUpload = undefined+ input.value = ''+ return { queued: true }}async function removePhoto(id: string) {if (@@ -621,7 +463,6 @@ export function useCloudMediaWorkspace(props: {return// Idle libraries stay still; only in-flight uploads and processing need polling.if (- uploading.value ||jobs.value.some((job) =>['queued', 'running', 'retry_wait'].includes(job.state),)@@ -633,7 +474,6 @@ export function useCloudMediaWorkspace(props: {disposed = truereloadGeneration++if (timer) clearInterval(timer)- controller?.abort()})return {@@ -650,11 +490,7 @@ export function useCloudMediaWorkspace(props: {message,failed,busy,- uploading,preparingUpload,- progress,- currentFile,- uploadSession,selectedAlbumIds,storage,admin,@@ -667,7 +503,6 @@ export function useCloudMediaWorkspace(props: {loadPhoto,savePhoto,upload,- cancel,removePhoto,publish,base,diff --git a/apps/cloud/app/composables/useCloudUploads.ts b/apps/cloud/app/composables/useCloudUploads.tsnew file mode 100644index 00000000..0f5fd2c8--- /dev/null+++ b/apps/cloud/app/composables/useCloudUploads.ts@@ -0,0 +1,465 @@+import { useUpload } from '#console/composables/useUpload'+import { useUploadQueue } from '#console/composables/useUploadQueue'+import type { UploadingFile } from '@chronoframe/gallery/shared/types/uploading-file'+import {+ UploadQueueStatus,+ UploadTransportStatus,+} from '@chronoframe/gallery/shared/utils/upload-status'+import type { InjectionKey } from 'vue'++export interface CloudUploadContext {+ siteId: number+ scope: string+ userId: number+ name: string+ admin: boolean+}+export interface CloudUploadJob {+ id: string+ photo_id: string+ file_name?: string+ state: string+ attempts: number+ error_code: string | null+}+interface TrackedUpload {+ context: CloudUploadContext+ jobId: string+ job?: CloudUploadJob+}+interface CloudUploadPlan {+ state: string+ mode?: 'single' | 'multipart'+ url?: string+ contentType?: string+ videoUrl?: string | null+ partBytes?: number+ parts?: { partNumber: number; bytes: number }[]+ urls?: string[]+}++export function cloudUploadResumeKey(+ context: Pick<CloudUploadContext, 'siteId' | 'scope'>,+ file: File,+ albumIds: number[],+ connection: string,+) {+ return (+ [+ 'chronoframe-upload',+ context.scope,+ context.siteId,+ file.name,+ file.size,+ file.lastModified,+ connection,+ ].join(':') + (albumIds.length ? ':albums:' + albumIds.join(',') : '')+ )+}++function createCloudUploads() {+ const queue = useUploadQueue()+ const { t } = useI18n()+ const nuxtApp = useNuxtApp()+ const userId = useState<number | null>('platform-user-id', () => null)+ const tracked = new Map<string, TrackedUpload>()+ const activeReservations = new Set<string>()+ const revision = ref(0)+ const busy = ref(false)+ const dismissed = new Set<string>()+ let timer: ReturnType<typeof setInterval> | undefined+ let polling = false+ let disposed = false++ async function api<T>(+ context: CloudUploadContext,+ path: string,+ body?: Record<string, unknown>,+ ): Promise<T> {+ // Navigation changes the active Site, not the authority of an admitted upload.+ if (disposed || userId.value !== context.userId)+ throw new Error(t('dashboard.photos.errors.uploadUnauthorized'))+ const result = await $fetch<unknown>(+ `/api/sites/${context.siteId}/media${path}`,+ {+ method: body ? 'POST' : 'GET',+ ...(body ? { body } : {}),+ },+ )+ if (disposed || userId.value !== context.userId)+ throw new Error(t('dashboard.photos.errors.uploadUnauthorized'))+ return result as T+ }++ function updateJob(entry: UploadingFile, job: CloudUploadJob) {+ const previous = entry.status+ entry.status =+ job.state === 'succeeded'+ ? UploadQueueStatus.Completed+ : ['failed', 'cancelled'].includes(job.state)+ ? UploadQueueStatus.Error+ : UploadQueueStatus.Processing+ entry.error = job.error_code+ ? t('cloud.ui.processingFailure', { code: job.error_code })+ : entry.status === UploadQueueStatus.Error+ ? t('cloud.ui.' + job.state)+ : undefined+ entry.warning = undefined+ if (previous !== entry.status) revision.value+++ }++ function trackJobs(+ context: CloudUploadContext,+ jobs: CloudUploadJob[],+ options: { partial?: boolean } = {},+ ) {+ if (disposed || userId.value !== context.userId) return+ const present = new Set(jobs.map((job) => job.id))+ for (const [fileId, item] of tracked) {+ if (+ !options.partial &&+ item.context.scope === context.scope &&+ item.job &&+ item.job.state !== 'succeeded' &&+ !present.has(item.jobId)+ )+ remove(fileId)+ }+ for (const job of jobs) {+ const key = `${context.scope}:${job.id}`+ if (['queued', 'running', 'retry_wait'].includes(job.state))+ dismissed.delete(key)+ const existing = [...tracked].filter(+ ([, item]) =>+ item.context.scope === context.scope && item.jobId === job.id,+ )+ if (existing.length) {+ for (const [fileId, item] of existing) {+ item.job = job+ const entry = queue.uploadingFiles.value.get(fileId)+ if (+ entry &&+ (entry.status === UploadQueueStatus.Processing ||+ entry.status === UploadQueueStatus.Completed ||+ entry.status === UploadQueueStatus.Error)+ )+ updateJob(entry, job)+ }+ } else if (+ ['queued', 'running', 'retry_wait', 'failed'].includes(job.state) &&+ !dismissed.has(key)+ ) {+ const fileId = crypto.randomUUID()+ const name = job.file_name || t('cloud.messages.untitledPhotograph')+ const entry: UploadingFile = {+ fileId,+ fileName: name,+ file: new File([], name),+ status: UploadQueueStatus.Processing,+ progress: 100,+ canAbort: false,+ }+ updateJob(entry, job)+ queue.uploadingFiles.value.set(fileId, entry)+ tracked.set(fileId, { context, jobId: job.id, job })+ }+ }+ queue.notify()+ }++ async function send(+ context: CloudUploadContext,+ entry: UploadingFile,+ signal: AbortSignal,+ connection: string,+ albumIds: number[],+ liveVideo?: File,+ ) {+ const file = entry.file+ const cache = cloudUploadResumeKey(context, file, albumIds, connection)+ if (activeReservations.has(cache)) {+ entry.status = UploadQueueStatus.Blocked+ entry.error = t('cloud.transfer.alreadyQueued')+ queue.notify()+ return+ }+ const id = localStorage.getItem(cache) || crypto.randomUUID()+ activeReservations.add(cache)+ let reserved = false+ let cancellation: Promise<unknown> | undefined+ let manager: ReturnType<typeof useUpload> | undefined+ const abort = () => manager?.abortUpload()+ signal.addEventListener('abort', abort)+ tracked.set(entry.fileId, { context, jobId: id })+ const cancelSession = async () => {+ localStorage.removeItem(cache)+ if (reserved) {+ cancellation ??= api(context, `/uploads/${id}/cancel`, {})+ await cancellation+ }+ }+ entry.status = UploadQueueStatus.Preparing+ queue.notify()+ try {+ signal.throwIfAborted()+ await api(context, '/uploads', {+ requestId: id,+ connectionId: connection,+ fileName: file.name,+ bytes: file.size,+ albumIds,+ ...(liveVideo+ ? { liveVideo: { fileName: liveVideo.name, bytes: liveVideo.size } }+ : {}),+ })+ reserved = true+ localStorage.setItem(cache, id)+ signal.throwIfAborted()+ const plan = await api<CloudUploadPlan>(+ context,+ `/uploads/${id}/plan`,+ {},+ )+ signal.throwIfAborted()+ if (plan.state !== 'completed') {+ if (plan.state !== 'pending' || !plan.mode) {+ localStorage.removeItem(cache)+ throw new Error(t('cloud.messages.uploadUnavailable'))+ }+ const total = file.size + (liveVideo?.size ?? 0)+ let offset = 0+ const transfer = async (payload: File, video: boolean) => {+ signal.throwIfAborted()+ manager = await nuxtApp.runWithContext(() =>+ useUpload({+ contentType: video ? 'video/quicktime' : plan.contentType,+ multipart: {+ uploadedParts: plan.parts,+ verifyPartsOnServer: true,+ preserveOnError: true,+ abort: cancelSession,+ },+ }),+ )+ signal.throwIfAborted()+ entry.canAbort = true+ entry.status = UploadQueueStatus.Uploading+ queue.notify()+ const target = video+ ? { mode: 'single' as const, url: plan.videoUrl! }+ : plan.mode === 'multipart'+ ? {+ mode: 'multipart' as const,+ url: `/api/sites/${context.siteId}/media/uploads/${id}/complete`,+ partSize: plan.partBytes!,+ partUrls: plan.urls!,+ }+ : { mode: 'single' as const, url: plan.url! }+ if (+ !target.url ||+ (target.mode === 'multipart' &&+ (!target.partSize || !target.partUrls?.length))+ )+ throw new Error(t('cloud.messages.uploadUnavailable'))+ await manager.uploadFile(payload, target, {+ onProgress: (progress) => {+ const loaded = offset + progress.loaded+ const percentage = Math.min(+ 99,+ Math.floor((loaded / total) * 100),+ )+ entry.progress = percentage+ entry.uploadProgress = {+ ...progress,+ loaded,+ total,+ percentage,+ speedText: progress.speed+ ? `${formatBytes(progress.speed)}/s`+ : '',+ timeRemainingText:+ progress.timeRemaining !== undefined+ ? manager!.formatTime(progress.timeRemaining)+ : '',+ }+ queue.notify()+ },+ onStatusChange: (status) => {+ if (!video && status === UploadTransportStatus.Finalizing)+ entry.status = UploadQueueStatus.Finalizing+ queue.notify()+ },+ })+ offset += payload.size+ }+ // Complete publishes both objects atomically; the companion must exist first.+ if (liveVideo) await transfer(liveVideo, true)+ await transfer(file, false)+ signal.throwIfAborted()+ entry.status = UploadQueueStatus.Finalizing+ entry.canAbort = false+ queue.notify()+ if (plan.mode === 'single')+ await api(context, `/uploads/${id}/complete`, {})+ }+ localStorage.removeItem(cache)+ if (signal.aborted) return+ entry.status = UploadQueueStatus.Processing+ entry.progress = 100+ entry.canAbort = false+ tracked.set(entry.fileId, { context, jobId: id })+ revision.value+++ } catch (error) {+ entry.status = UploadQueueStatus.Error+ entry.canAbort = false+ const albumUnavailable =+ typeof error === 'object' &&+ error !== null &&+ 'data' in error &&+ (error.data as { data?: { code?: string } } | undefined)?.data?.code ===+ 'upload_albums_unavailable'+ entry.error = signal.aborted+ ? t('cloud.messages.uploadCancelled')+ : albumUnavailable+ ? t('cloud.transfer.albumsUnavailable')+ : error instanceof Error+ ? error.message+ : t('cloud.messages.uploadFailed')+ if (!signal.aborted && reserved)+ entry.warning = t(+ 'cloud.messages.uploadInterruptedSelectTheSameFileToResumeIts',+ )+ if (signal.aborted) {+ if (reserved) {+ try {+ await cancelSession()+ } catch (cancelError) {+ console.error('Failed to cancel Cloud upload:', cancelError)+ }+ }+ }+ } finally {+ activeReservations.delete(cache)+ signal.removeEventListener('abort', abort)+ queue.notify()+ }+ }++ function enqueue(+ context: CloudUploadContext,+ files: File[],+ connection: string,+ albumIds: number[],+ ) {+ if (disposed || userId.value !== context.userId)+ throw new Error(t('dashboard.photos.errors.uploadUnauthorized'))+ const photos = files.filter(+ (file) => !file.name.toLowerCase().endsWith('.mov'),+ )+ return queue.enqueue(photos, (entry, signal) =>+ send(+ context,+ entry,+ signal,+ connection,+ albumIds,+ files.find(+ (file) =>+ file.name.toLowerCase().endsWith('.mov') &&+ file.name.replace(/\.[^.]+$/, '').toLowerCase() ===+ entry.file.name.replace(/\.[^.]+$/, '').toLowerCase(),+ ),+ ),+ )+ }+ function remove(fileId: string) {+ const item = tracked.get(fileId)+ if (item) dismissed.add(`${item.context.scope}:${item.jobId}`)+ tracked.delete(fileId)+ queue.remove(fileId)+ }+ function clearCompleted() {+ const before = [...queue.uploadingFiles.value.keys()]+ queue.clearCompleted()+ for (const id of before) if (!queue.uploadingFiles.value.has(id)) remove(id)+ }+ function clearAll() {+ for (const id of queue.uploadingFiles.value.keys()) remove(id)+ }+ onMounted(() => {+ timer = setInterval(async () => {+ if (polling || disposed || document.visibilityState !== 'visible') return+ polling = true+ try {+ const contexts = new Map<string, CloudUploadContext>()+ for (const [fileId, item] of tracked)+ if (+ queue.uploadingFiles.value.get(fileId)?.status ===+ UploadQueueStatus.Processing+ )+ contexts.set(item.context.scope, item.context)+ await Promise.all(+ [...contexts.values()].map(async (context) => {+ try {+ const result = await api<{ jobs: CloudUploadJob[] }>(+ context,+ '/photos',+ )+ trackJobs(context, result.jobs)+ } catch (error) {+ console.error('Failed to refresh Cloud upload processing:', error)+ for (const [fileId, item] of tracked) {+ const entry = queue.uploadingFiles.value.get(fileId)+ if (entry && item.context.scope === context.scope)+ entry.warning = t(+ 'dashboard.photos.messages.taskStatusCheckFailed',+ )+ }+ queue.notify()+ }+ }),+ )+ } finally {+ polling = false+ }+ }, 5000)+ })+ watch(+ userId,+ () => {+ clearAll()+ dismissed.clear()+ },+ { flush: 'sync' },+ )+ onBeforeUnmount(() => {+ disposed = true+ if (timer) clearInterval(timer)+ clearAll()+ })+ return {+ ...queue,+ enqueue,+ remove,+ clearCompleted,+ clearAll,+ trackJobs,+ tracked,+ revision,+ busy,+ api,+ }+}++const cloudUploadsKey: InjectionKey<ReturnType<typeof createCloudUploads>> =+ Symbol('cloud-uploads')+export function provideCloudUploads() {+ const uploads = createCloudUploads()+ provide(cloudUploadsKey, uploads)+ return uploads+}+export function useCloudUploads() {+ const uploads = inject(cloudUploadsKey)+ if (!uploads) throw new Error('Cloud upload provider missing')+ return uploads+}diff --git a/apps/cloud/app/utils/upload-selection.ts b/apps/cloud/app/utils/upload-selection.tsdeleted file mode 100644index b766c279..00000000--- a/apps/cloud/app/utils/upload-selection.ts+++ /dev/null@@ -1,33 +0,0 @@-type UploadFile = Pick<File, 'name' | 'size' | 'lastModified'>-export function mergeUploadFiles<T extends UploadFile>(- current: T[],- incoming: T[],-): T[] {- const seen = new Set<string>()- return [...current, ...incoming].filter((file) => {- const key = JSON.stringify([file.name, file.size, file.lastModified])- if (seen.has(key)) return false- seen.add(key)- return true- })-}-/** Remove verified photos and their paired MOV files; keep interrupted and unstarted files. */-export function remainingUploadFiles<T extends UploadFile>(- files: T[],- completed: number,-): T[] {- const isVideo = (file: T) => file.name.toLowerCase().endsWith('.mov')- const photos = files.filter((file) => !isVideo(file))- const completedPhotos = photos.slice(0, completed)- const stem = (file: T) => file.name.replace(/\.[^.]+$/, '').toLowerCase()- const unfinishedStems = new Set(photos.slice(completed).map(stem))- const removed = new Set(completedPhotos)- for (const photo of completedPhotos) {- if (unfinishedStems.has(stem(photo))) continue- const companion = files.find(- (file) => isVideo(file) && stem(file) === stem(photo),- )- if (companion) removed.add(companion)- }- return files.filter((file) => !removed.has(file))-}diff --git a/apps/cloud/i18n/locales/en.json b/apps/cloud/i18n/locales/en.jsonindex 79cdbb27..891bce99 100644--- a/apps/cloud/i18n/locales/en.json+++ b/apps/cloud/i18n/locales/en.json@@ -916,6 +916,7 @@"albumHelp": "Uploaded photographs are automatically added to the selected albums. Leave empty to add only to the library.","albumsUnavailable": "A selected album is no longer available. Update your album selection and try again. Previously uploaded photographs are unaffected.","albumsCheckFailed": "Unable to verify albums. Check your connection and try again. Upload has not started.",+ "alreadyQueued": "This file is already uploading. Wait for its current upload to finish before trying again.","selectedFiles": "Files to upload","selectedFilesCount": "{count} files selected","clearSelection": "Clear",diff --git a/apps/cloud/i18n/locales/zh-Hans.json b/apps/cloud/i18n/locales/zh-Hans.jsonindex 18783182..04ea8e11 100644--- a/apps/cloud/i18n/locales/zh-Hans.json+++ b/apps/cloud/i18n/locales/zh-Hans.json@@ -916,6 +916,7 @@"albumHelp": "上传的照片将自动加入所选相簿;留空则仅加入照片库。","albumsUnavailable": "所选相簿已不可用,请更新相簿选择后重新上传。已上传的照片不受影响。","albumsCheckFailed": "无法核对相簿,请检查网络后重试。尚未开始上传。",+ "alreadyQueued": "该文件正在上传,请等待当前上传结束后再重试。","selectedFiles": "待上传文件","selectedFilesCount": "已选择 {count} 个文件","clearSelection": "清空",diff --git a/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts b/apps/cloud/server/api/sites/[siteId]/media/[...operation].tsindex ccd6faf9..fb356a61 100644--- a/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts+++ b/apps/cloud/server/api/sites/[siteId]/media/[...operation].ts@@ -20,6 +20,7 @@ import { cloudMedia, checkStorage } from '../../../../utils/cloud-media'import { siteManagementBody } from '../../../../utils/site-management'import { createResourceReader } from '@chronoframe/core'import { visitorPasswordHash } from '../../../../../../shared/platform/crypto'+import { canFallbackToSingleUpload } from '@chronoframe/storage/s3-edge'const types: Record<string, string> = {jpg: 'image/jpeg',@@ -469,18 +470,18 @@ export default definePlatformHandler(async (event) => {'video/quicktime',): null- if (upload.expected_bytes <= 10485760)- return {- state: 'pending',- mode: 'single',- videoUrl,- url: await s3.signPut(- upload.object_key,- upload.expected_bytes,- detail.content_type,- ),- contentType: detail.content_type,- }+ const single = async () => ({+ state: 'pending',+ mode: 'single',+ videoUrl,+ url: await s3.signPut(+ upload.object_key,+ upload.expected_bytes,+ detail.content_type,+ ),+ contentType: detail.content_type,+ })+ if (upload.expected_bytes <= 10485760) return single()let providerId = upload.provider_upload_idif (!providerId) {const token = crypto.randomUUID()@@ -491,21 +492,39 @@ export default definePlatformHandler(async (event) => {.bind(token, now + 30000, siteId, id, now).first()if (!lock) throw createError({ statusCode: 409 })- const recovered = await s3.recoverMultipart(upload.object_key)- providerId =- recovered[0] ??- (await s3.multipart(upload.object_key, detail.content_type))- for (const abandoned of recovered.slice(1))- await s3.abort(upload.object_key, abandoned)- const updated = await raw- .prepare(- `UPDATE cloud_uploads SET provider_upload_id=?,transport_token=NULL,transport_lease_until=NULL WHERE site_id=? AND id=? AND transport_token=? AND state='pending' RETURNING id`,- )- .bind(providerId, siteId, id, token)- .first()- if (!updated) {- await s3.abort(upload.object_key, providerId)- throw createError({ statusCode: 409 })+ try {+ const recovered = await s3.recoverMultipart(upload.object_key)+ providerId =+ recovered[0] ??+ (await s3.multipart(upload.object_key, detail.content_type))+ for (const abandoned of recovered.slice(1))+ await s3.abort(upload.object_key, abandoned)+ const updated = await raw+ .prepare(+ `UPDATE cloud_uploads SET provider_upload_id=?,transport_token=NULL,transport_lease_until=NULL WHERE site_id=? AND id=? AND transport_token=? AND state='pending' RETURNING id`,+ )+ .bind(providerId, siteId, id, token)+ .first()+ if (!updated) {+ await s3.abort(upload.object_key, providerId)+ throw createError({ statusCode: 409 })+ }+ } catch (error) {+ if (!providerId && canFallbackToSingleUpload(error)) {+ console.warn('[upload] s3.multipart.fallback.single', {+ siteId,+ uploadId: id,+ })+ return single()+ }+ throw error+ } finally {+ await raw+ .prepare(+ 'UPDATE cloud_uploads SET transport_token=NULL,transport_lease_until=NULL WHERE site_id=? AND id=? AND transport_token=?',+ )+ .bind(siteId, id, token)+ .run()}}const parts = await s3.parts(upload.object_key, providerId),diff --git a/packages/console/README.md b/packages/console/README.mdindex 4ba4f517..67971573 100644--- a/packages/console/README.md+++ b/packages/console/README.md@@ -15,3 +15,10 @@ on a Site/account switch. Authorization is always rechecked by server adapters.Self-hosted retains instance sessions, SQLite, Local/S3/OpenList, custom scripts,and unlimited quota. Cloud advertises only implemented platform capabilities;media management and plan enforcement are delivered by later SaaS phases.++Uploads share `PhotoUploadSlideover`, `UploadQueuePanel`, `useUploadQueue` and+`useUpload`. The queue owner determines its lifetime: Self-hosted owns it in the+photo page; Cloud provides it from the application root. Transport retries,+concurrency, progress and cancellation are shared. Cloud's adapter supplies+server-verified resume parts and keeps failed reservations available for retry;+its admission, tenant scope and job publication remain Cloud API concerns.diff --git a/packages/console/app/components/ui/PhotoUploadSlideover.vue b/packages/console/app/components/ui/PhotoUploadSlideover.vuenew file mode 100644index 00000000..043b4ad8--- /dev/null+++ b/packages/console/app/components/ui/PhotoUploadSlideover.vue@@ -0,0 +1,122 @@+<script setup lang="ts">+withDefaults(+ defineProps<{+ maxFileSizeMB: number+ disabled?: boolean+ loading?: boolean+ canUpload?: boolean+ accept?: string+ }>(),+ {+ canUpload: true,+ accept: 'image/jpeg,image/png,image/heic,image/heif,video/quicktime,.mov',+ },+)+const open = defineModel<boolean>('open', { required: true })+const files = defineModel<File[]>('files', { required: true })+const emit = defineEmits<{ upload: [] }>()+const summary = computed(() =>+ files.value.length+ ? $t('dashboard.photos.slideover.footer.prepared', {+ count: files.value.length,+ size: formatBytes(+ files.value.reduce((sum, file) => sum + file.size, 0),+ ),+ })+ : $t('dashboard.photos.slideover.footer.noSelection'),+)+</script>++<template>+ <USlideover+ v-model:open="open"+ :title="$t('dashboard.photos.slideover.title')"+ :description="$t('dashboard.photos.slideover.description')"+ :ui="{+ content: 'sm:max-w-xl',+ body: 'p-2',+ header: 'px-6 py-5 border-b border-neutral-200 dark:border-neutral-800',+ footer: 'px-6 py-5 border-t border-neutral-200 dark:border-neutral-800',+ }"+ >+ <template #body>+ <div class="space-y-4">+ <slot name="before-files" />+ <UFileUpload+ v-model="files"+ :label="$t('dashboard.photos.uploader.label')"+ :description="+ $t('dashboard.photos.uploader.description', {+ maxSize: maxFileSizeMB,+ })+ "+ icon="tabler:cloud-upload"+ layout="list"+ size="xl"+ :accept="accept"+ :disabled="disabled"+ multiple+ highlight+ dropzone+ :file-delete="{ variant: 'soft', color: 'neutral' }"+ :ui="{+ root: 'w-full',+ base: 'group relative flex flex-col items-center justify-center gap-3 rounded-3xl border-2 border-dashed border-neutral-200/80 bg-white/90 px-6 py-12 text-center shadow-sm transition-all duration-300 hover:border-primary-400/80 hover:bg-primary-500/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/60 dark:border-neutral-700/70 dark:bg-neutral-900/80',+ wrapper: 'flex flex-col items-center gap-2',+ label:+ 'text-base font-semibold text-neutral-800 dark:text-neutral-100',+ description: 'text-sm text-neutral-500 dark:text-neutral-400',+ files: 'mt-2 flex w-full flex-col gap-2 overflow-y-auto',+ file: 'flex items-center justify-between gap-3 rounded-2xl border border-neutral-200/80 bg-white/80 px-4 py-3 text-left shadow-sm shadow-black/5 backdrop-blur-sm dark:border-neutral-800/80 dark:bg-neutral-900/70',+ fileLeadingAvatar: 'ring-1 ring-white/80 dark:ring-neutral-800',+ fileWrapper: 'min-w-0 flex-1',+ fileName:+ 'text-sm font-medium text-neutral-700 dark:text-neutral-100 truncate',+ fileSize: 'text-xs text-neutral-500 dark:text-neutral-400',+ fileTrailingButton: 'text-neutral-400 hover:text-error-500',+ }"+ />+ <slot />+ </div>+ </template>+ <template #footer>+ <div+ class="flex w-full flex-col gap-4 sm:flex-row sm:items-center sm:justify-between"+ >+ <div+ class="flex flex-col gap-1 text-sm text-neutral-500 dark:text-neutral-400"+ >+ <span>{{ summary }}</span>+ </div>+ <div class="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">+ <UButton+ variant="soft"+ color="neutral"+ class="w-full sm:w-auto"+ :disabled="disabled || !files.length"+ @click="files = []"+ >+ {{ $t('dashboard.photos.slideover.buttons.clear') }}+ </UButton>+ <UButton+ color="primary"+ size="lg"+ class="w-full sm:w-auto"+ icon="tabler:upload"+ :loading="loading"+ :disabled="disabled || !files.length || !canUpload"+ @click="emit('upload')"+ >+ {{+ files.length+ ? $t('dashboard.photos.slideover.buttons.upload', {+ count: files.length,+ })+ : $t('dashboard.photos.buttons.upload')+ }}+ </UButton>+ </div>+ </div>+ </template>+ </USlideover>+</template>diff --git a/packages/console/app/components/ui/UploadQueueItem.vue b/packages/console/app/components/ui/UploadQueueItem.vueindex e4783730..1b2c665a 100644--- a/packages/console/app/components/ui/UploadQueueItem.vue+++ b/packages/console/app/components/ui/UploadQueueItem.vue@@ -278,6 +278,7 @@ const generateParticleStyle = (index: number) => {{{ uploadingFile.fileName }}</p></div>+ <slot name="details" /><divclass="flex items-center gap-1 text-xs text-neutral-500 dark:text-neutral-400"@@ -295,6 +296,7 @@ const generateParticleStyle = (index: number) => {<!-- 操作按钮 --><div class="flex items-center gap-2 ml-2">+ <slot name="actions" /><!-- 中止上传按钮 --><motion.divv-if="diff --git a/packages/console/app/components/ui/UploadQueuePanel.vue b/packages/console/app/components/ui/UploadQueuePanel.vueindex c9c196c1..34174c4a 100644--- a/packages/console/app/components/ui/UploadQueuePanel.vue+++ b/packages/console/app/components/ui/UploadQueuePanel.vue@@ -270,7 +270,20 @@ const clearAllFiles = () => {:uploading-file="uploadingFile":file-id="fileId"@remove-file="emit('removeFile', $event)"- />+ >+ <template #details>+ <slot+ name="file-details"+ :file-id="fileId"+ />+ </template>+ <template #actions>+ <slot+ name="file-actions"+ :file-id="fileId"+ />+ </template>+ </UploadQueueItem></AnimatePresence></div></motion.div>diff --git a/packages/console/app/composables/useUpload.ts b/packages/console/app/composables/useUpload.tsindex b244c1ee..20e524b1 100644--- a/packages/console/app/composables/useUpload.ts+++ b/packages/console/app/composables/useUpload.ts@@ -42,6 +42,13 @@ export interface UseUploadOptions {speedSampleSize?: number // 速度平均窗口(秒)maxRetries?: number // 最大重试次数retryDelay?: number // 重试延迟(毫秒)+ contentType?: string+ multipart?: {+ uploadedParts?: { partNumber: number; bytes: number }[]+ verifyPartsOnServer?: boolean+ preserveOnError?: boolean+ abort?: () => Promise<void>+ }}export function useUpload(options: UseUploadOptions = {}) {@@ -60,6 +67,8 @@ export function useUpload(options: UseUploadOptions = {}) {speedSampleSize = 5,maxRetries = 3,retryDelay = 1000,+ contentType,+ multipart,} = options// 响应式状态@@ -277,7 +286,7 @@ export function useUpload(options: UseUploadOptions = {}) {requestXHR.setRequestHeader('Content-Type',filePayload- ? file.type || 'application/octet-stream'+ ? contentType || file.type || 'application/octet-stream': 'application/json',)Object.entries({ ...headers, ...requestHeaders }).forEach(@@ -394,6 +403,18 @@ export function useUpload(options: UseUploadOptions = {}) {while (!cancelled && !stopped && nextIndex < count) {const index = nextIndex++const offset = index * partSize+ const size = Math.min(partSize, file.size - offset)+ if (+ plan.mode === 'multipart' &&+ multipart?.verifyPartsOnServer &&+ multipart.uploadedParts?.some(+ (part) =>+ part.partNumber === index + 1 && part.bytes === size,+ )+ ) {+ recordProgress(index, size)+ continue+ }const partResponse = await request('PUT',plan.mode === 'multipart'@@ -404,8 +425,9 @@ export function useUpload(options: UseUploadOptions = {}) {)if (plan.mode === 'multipart') {const etag = partResponse.getResponseHeader('ETag')- if (!etag) throw new Error(t('upload.runtimeError.missingEtag'))- parts[index] = { partNumber: index + 1, etag }+ if (!etag && !multipart?.verifyPartsOnServer)+ throw new Error(t('upload.runtimeError.missingEtag'))+ if (etag) parts[index] = { partNumber: index + 1, etag }}}} catch (error) {@@ -429,9 +451,16 @@ export function useUpload(options: UseUploadOptions = {}) {'POST',signedUrl,plan.mode === 'multipart'- ? new Blob([JSON.stringify({ parts })], {- type: 'application/json',- })+ ? new Blob(+ [+ JSON.stringify(+ multipart?.verifyPartsOnServer ? {} : { parts },+ ),+ ],+ {+ type: 'application/json',+ },+ ): undefined,0,{},@@ -466,8 +495,14 @@ export function useUpload(options: UseUploadOptions = {}) {if (cancelled) callbacks.onAbort?.()else if (failureXHR || currentXHR)callbacks.onError?.(message, (failureXHR || currentXHR)!)- if (managedSession)- void $fetch(signedUrl, { method: 'DELETE' }).catch(() => {})+ if (managedSession && (cancelled || !multipart?.preserveOnError)) {+ try {+ if (multipart?.abort) await multipart.abort()+ else await $fetch(signedUrl, { method: 'DELETE' })+ } catch (cleanupError) {+ console.error('Failed to abort upload session:', cleanupError)+ }+ }throw error} finally {clearInterval(progressTimer)@@ -544,13 +579,11 @@ export function useUpload(options: UseUploadOptions = {}) {})// 清理函数(仅在组件上下文中可用)- try {+ if (getCurrentInstance()) {onUnmounted(() => {abortUpload()currentXHR = null})- } catch {- /* empty */}return {diff --git a/packages/console/app/composables/useUploadQueue.ts b/packages/console/app/composables/useUploadQueue.tsnew file mode 100644index 00000000..b995d9af--- /dev/null+++ b/packages/console/app/composables/useUploadQueue.ts@@ -0,0 +1,98 @@+import { onScopeDispose, ref } from 'vue'+import type { UploadingFile } from '@chronoframe/gallery/shared/types/uploading-file'+import {+ UploadQueueStatus,+ isClearableUploadStatus,+} from '@chronoframe/gallery/shared/utils/upload-status'++/** The owner chooses the lifetime: a Self-hosted page or the Cloud application. */+export function useUploadQueue() {+ const uploadingFiles = ref(new Map<string, UploadingFile>())+ const pending: Array<{+ entry: UploadingFile+ run: (entry: UploadingFile, signal: AbortSignal) => Promise<void>+ controller: AbortController+ resolve: () => void+ }> = []+ const controllers = new Map<string, AbortController>()+ let active = 0+ let disposed = false++ const notify = () => {+ uploadingFiles.value = new Map(uploadingFiles.value)+ }+ function drain() {+ while (!disposed && active < 3 && pending.length) {+ const task = pending.shift()!+ if (task.controller.signal.aborted) {+ controllers.delete(task.entry.fileId)+ task.resolve()+ continue+ }+ active+++ void Promise.resolve()+ .then(() => {+ task.controller.signal.throwIfAborted()+ return task.run(task.entry, task.controller.signal)+ })+ .catch((error: unknown) => {+ task.entry.status = UploadQueueStatus.Error+ task.entry.error =+ error instanceof Error ? error.message : String(error)+ task.entry.canAbort = false+ notify()+ })+ .finally(() => {+ controllers.delete(task.entry.fileId)+ active--+ task.resolve()+ drain()+ })+ }+ }+ function enqueue(+ files: File[],+ run: (entry: UploadingFile, signal: AbortSignal) => Promise<void>,+ ) {+ if (disposed) throw new Error('Upload queue is disposed')+ const tasks = files.map((file) => {+ const controller = new AbortController()+ const entry: UploadingFile = {+ file,+ fileName: file.name,+ fileId: crypto.randomUUID(),+ status: UploadQueueStatus.Waiting,+ canAbort: false,+ abortUpload: () => controller.abort(),+ }+ controllers.set(entry.fileId, controller)+ uploadingFiles.value.set(entry.fileId, entry)+ return new Promise<void>((resolve) => {+ pending.push({ entry, run, controller, resolve })+ })+ })+ notify()+ // Let the drawer close and render all waiting entries before starting I/O.+ queueMicrotask(drain)+ return Promise.all(tasks)+ }+ function remove(fileId: string) {+ controllers.get(fileId)?.abort()+ uploadingFiles.value.get(fileId)?.abortUpload?.()+ uploadingFiles.value.delete(fileId)+ notify()+ }+ function clearCompleted() {+ for (const [id, entry] of uploadingFiles.value)+ if (isClearableUploadStatus(entry.status)) remove(id)+ }+ function clearAll() {+ for (const id of uploadingFiles.value.keys()) remove(id)+ }+ onScopeDispose(() => {+ disposed = true+ clearAll()+ for (const task of pending.splice(0)) task.resolve()+ })+ return { uploadingFiles, enqueue, remove, clearCompleted, clearAll, notify }+}diff --git a/packages/console/app/pages/dashboard/photos.vue b/packages/console/app/pages/dashboard/photos.vueindex 12d02bb3..132baf34 100644--- a/packages/console/app/pages/dashboard/photos.vue+++ b/packages/console/app/pages/dashboard/photos.vue@@ -1,11 +1,11 @@<script lang="ts" setup>import { photoLibraryPresentation } from '../../utils/photoLibraryPresentation'+import { useUploadQueue } from '../../composables/useUploadQueue'const consoleApi = useConsoleApi()import type { FormSubmitEvent, TableColumn, DropdownMenuItem } from '@nuxt/ui'import type { UploadPreparationResponse } from '@chronoframe/contracts/upload'import type { Album, Photo } from '@chronoframe/contracts/resources'-import type { UploadingFile } from '@chronoframe/gallery/shared/types/uploading-file'import {MAX_ALBUM_PHOTOS_PER_REQUEST,type AddPhotosToAlbumResult,@@ -119,7 +119,8 @@ const fetchReactions = async (photoIds: string[]) => {}}-const uploadingFiles = ref<Map<string, UploadingFile>>(new Map())+const uploadQueue = useUploadQueue()+const { uploadingFiles } = uploadQueueinterface EditFormState {title: string@@ -251,6 +252,7 @@ const uploadImage = async (existingFileId?: string,eraseLocationOnUpload?: boolean,albumId?: number,+ signal?: AbortSignal,) => {const fileName = file.nameconst fileId = existingFileId || `${Date.now()}-${fileName}`@@ -262,6 +264,8 @@ const uploadImage = async (const uploadManager = useUpload({timeout: 60 * 1000, // 单个分片一分钟超时,避免请求长时间卡住})+ const abort = () => uploadManager.abortUpload()+ signal?.addEventListener('abort', abort)// 获取或创建 uploadingFilelet uploadingFile = uploadingFiles.value.get(fileId)@@ -280,11 +284,11 @@ const uploadImage = async (uploadingFile.status = UploadQueueStatus.PreparinguploadingFile.canAbort = falseuploadingFile.warning = undefined- uploadingFile.abortUpload = () => uploadManager.abortUpload()uploadingFiles.value = new Map(uploadingFiles.value)}try {+ signal?.throwIfAborted()// 第一步:获取预签名 URLuploadingFile.status = UploadQueueStatus.Preparingconst signedUrlResponse = await consoleApi<UploadPreparationResponse>(@@ -301,6 +305,7 @@ const uploadImage = async ()uploadingFile.signedUrlResponse = signedUrlResponse+ signal?.throwIfAborted()// 检查是否为跳过模式(重复文件)if (signedUrlResponse.skipped) {@@ -399,6 +404,7 @@ const uploadImage = async (uploadingFiles.value = new Map(uploadingFiles.value)},onSuccess: async (_xhr: XMLHttpRequest) => {+ if (signal?.aborted) return// 第三步:上传完成,提交到队列任务uploadingFile.status = UploadQueueStatus.ProcessinguploadingFile.progress = 100@@ -458,7 +464,7 @@ const uploadImage = async (uploadingFiles.value = new Map(uploadingFiles.value)// 开始任务状态检查- startTaskStatusCheck(resp.taskId, fileId)+ if (!signal?.aborted) startTaskStatusCheck(resp.taskId, fileId)} else {uploadingFile.status = UploadQueueStatus.ErroruploadingFile.error = $t(@@ -537,6 +543,8 @@ const uploadImage = async (}uploadingFiles.value = new Map(uploadingFiles.value)+ } finally {+ signal?.removeEventListener('abort', abort)}}@@ -621,29 +629,6 @@ const loadUploadAlbums = async () => {}}-const hasSelectedFiles = computed(() => selectedFiles.value.length > 0)--const selectedFilesTotalSize = computed(() =>- selectedFiles.value.reduce((total, file) => total + (file?.size || 0), 0),-)--const selectedFilesTotalSizeLabel = computed(() =>- selectedFilesTotalSize.value > 0- ? formatBytes(selectedFilesTotalSize.value)- : '0 B',-)--const selectedFilesSummary = computed(() => {- if (!selectedFiles.value.length) {- return $t('dashboard.photos.slideover.footer.noSelection')- }-- return $t('dashboard.photos.slideover.footer.prepared', {- count: selectedFiles.value.length,- size: selectedFilesTotalSizeLabel.value,- })-})-const clearSelectedFiles = () => {selectedFiles.value = []}@@ -980,8 +965,7 @@ const removeUploadingFile = (fileId: string) => {}// 从列表中移除- uploadingFiles.value.delete(fileId)- uploadingFiles.value = new Map(uploadingFiles.value)+ uploadQueue.remove(fileId)}// 批量清除已完成和错误的任务@@ -1050,8 +1034,7 @@ const clearAllUploads = () => {}}- uploadingFiles.value.clear()- uploadingFiles.value = new Map(uploadingFiles.value)+ uploadQueue.clearAll()if (toRemove.length > 0) {toast.add({@@ -1165,7 +1148,6 @@ const handleUpload = async () => {// 先验证所有文件const validFiles: File[] = []- const fileIdMapping = new Map<File, string>()for (const file of fileList) {const validation = validateFile(file)@@ -1178,9 +1160,6 @@ const handleUpload = async () => {}} else {validFiles.push(file)- // 为每个有效文件生成唯一ID- const fileId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}-${file.name}`- fileIdMapping.set(file, fileId)}}@@ -1224,73 +1203,12 @@ const handleUpload = async () => {})}- // 立即为所有有效文件创建队列条目,状态为 waiting- const nextUploadingFiles = new Map(uploadingFiles.value)- for (const file of validFiles) {- const fileId = fileIdMapping.get(file)!- const uploadingFile: UploadingFile = {- file,- fileName: file.name,- fileId,- status: UploadQueueStatus.Waiting,- canAbort: false,- }- nextUploadingFiles.set(fileId, uploadingFile)- }-- // 触发队列更新- uploadingFiles.value = nextUploadingFiles-- // 本批次已经交给队列,立即释放选择器并关闭抽屉。+ const pending = uploadQueue.enqueue(validFiles, (entry, signal) =>+ uploadImage(entry.file, entry.fileId, eraseLocation, albumId, signal),+ )selectedFiles.value = []isUploadSlideoverOpen.value = false- await nextTick()- // 让浏览器先处理界面更新,再启动文件上传。- await new Promise<void>((resolve) => setTimeout(resolve, 0))-- // 动态并发上传,始终保持 CONCURRENT_LIMIT 个文件在上传- const CONCURRENT_LIMIT = 3 // 限制同时上传的文件数量-- // 创建文件队列- const fileQueue = [...validFiles]- const activeUploads = new Set<Promise<void>>()-- // 启动上传任务的函数- const startUpload = async (file: File): Promise<void> => {- const fileId = fileIdMapping.get(file)!- try {- await uploadImage(file, fileId, eraseLocation, albumId)- } catch (error: any) {- errors.push(`${file.name}: ${error.message || '上传失败'}`)- console.error('上传错误:', error)- }- }-- // 处理队列的函数- const processQueue = async (): Promise<void> => {- while (fileQueue.length > 0 || activeUploads.size > 0) {- // 如果当前活跃上传数量小于限制,且队列中还有文件,则启动新的上传- while (activeUploads.size < CONCURRENT_LIMIT && fileQueue.length > 0) {- const file = fileQueue.shift()!- const uploadPromise = startUpload(file)-- activeUploads.add(uploadPromise)-- // 当上传完成时,从活跃集合中移除- uploadPromise.finally(() => {- activeUploads.delete(uploadPromise)- })- }-- // 如果有活跃的上传,等待至少一个完成- if (activeUploads.size > 0) {- await Promise.race(activeUploads)- }- }- }-- // 开始处理队列- await processQueue()+ await pendingif (errors.length > 0) {console.error('批量上传错误详情:', errors)@@ -2145,190 +2063,98 @@ onUnmounted(() => {class="shrink-0"/>- <USlideover+ <PhotoUploadSlideoverv-model:open="isUploadSlideoverOpen"- :title="$t('dashboard.photos.slideover.title')"- :description="$t('dashboard.photos.slideover.description')"- :ui="{- content: 'sm:max-w-xl',- body: 'p-2',- header:- 'px-6 py-5 border-b border-neutral-200 dark:border-neutral-800',- footer:- 'px-6 py-5 border-t border-neutral-200 dark:border-neutral-800',- }"+ v-model:files="selectedFiles"+ :max-file-size-m-b="maxFileSizeMB"+ :can-upload="canUseSelectedUploadAlbum"+ @upload="handleUpload">- <template #body>- <div class="space-y-4">- <UFileUpload- v-model="selectedFiles"- :label="$t('dashboard.photos.uploader.label')"- :description="- $t('dashboard.photos.uploader.description', {- maxSize: maxFileSizeMB,- })- "- icon="tabler:cloud-upload"- layout="list"- size="xl"- accept="image/jpeg,image/png,image/heic,image/heif,video/quicktime,.mov"- multiple- highlight- dropzone- :file-delete="{ variant: 'soft', color: 'neutral' }"- :ui="{- root: 'w-full',- base: 'group relative flex flex-col items-center justify-center gap-3 rounded-3xl border-2 border-dashed border-neutral-200/80 bg-white/90 px-6 py-12 text-center shadow-sm transition-all duration-300 hover:border-primary-400/80 hover:bg-primary-500/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-500/60 dark:border-neutral-700/70 dark:bg-neutral-900/80',- wrapper: 'flex flex-col items-center gap-2',- label:- 'text-base font-semibold text-neutral-800 dark:text-neutral-100',- description: 'text-sm text-neutral-500 dark:text-neutral-400',- files: 'mt-2 flex w-full flex-col gap-2 overflow-y-auto',- file: 'flex items-center justify-between gap-3 rounded-2xl border border-neutral-200/80 bg-white/80 px-4 py-3 text-left shadow-sm shadow-black/5 backdrop-blur-sm dark:border-neutral-800/80 dark:bg-neutral-900/70',- fileLeadingAvatar:- 'ring-1 ring-white/80 dark:ring-neutral-800',- fileWrapper: 'min-w-0 flex-1',- fileName:- 'text-sm font-medium text-neutral-700 dark:text-neutral-100 truncate',- fileSize: 'text-xs text-neutral-500 dark:text-neutral-400',- fileTrailingButton: 'text-neutral-400 hover:text-error-500',- }"+ <UCard+ variant="soft"+ class="border border-neutral-200/80 dark:border-neutral-800/80"+ >+ <UFormField+ :label="$t('dashboard.photos.slideover.album.label')"+ :description="$t('dashboard.photos.slideover.album.description')"+ >+ <USelectMenu+ v-model="selectedUploadAlbumId"+ :items="uploadAlbumItems"+ value-key="value"+ label-key="label"+ :loading="isLoadingUploadAlbums"+ :disabled="isLoadingUploadAlbums"+ :aria-label="$t('dashboard.photos.slideover.album.label')"+ class="w-full"/>-- <UCard+ </UFormField>+ <p+ v-if="+ !isLoadingUploadAlbums &&+ !uploadAlbumsLoadFailed &&+ uploadAlbums.length === 0+ "+ class="mt-2 text-xs text-neutral-500 dark:text-neutral-400"+ >+ {{ $t('dashboard.photos.slideover.album.empty') }}+ </p>+ <p+ v-if="selectedUploadAlbumUnavailable"+ role="alert"+ class="mt-2 text-sm text-error-600 dark:text-error-400"+ >+ {{+ $t(+ requestedUploadAlbumId === selectedUploadAlbumId+ ? 'dashboard.photos.slideover.album.requestedUnavailable'+ : 'dashboard.photos.slideover.album.unavailable',+ )+ }}+ </p>+ <div+ v-if="uploadAlbumsLoadFailed"+ role="alert"+ class="mt-2 flex items-center justify-between gap-2 text-sm text-error-600 dark:text-error-400"+ >+ <span>{{+ $t('dashboard.photos.slideover.album.loadFailedUpload')+ }}</span>+ <UButton+ size="xs"variant="soft"- class="border border-neutral-200/80 dark:border-neutral-800/80"+ @click="loadUploadAlbums">- <UFormField- :label="$t('dashboard.photos.slideover.album.label')"- :description="- $t('dashboard.photos.slideover.album.description')- "- >- <USelectMenu- v-model="selectedUploadAlbumId"- :items="uploadAlbumItems"- value-key="value"- label-key="label"- :loading="isLoadingUploadAlbums"- :disabled="isLoadingUploadAlbums"- :aria-label="$t('dashboard.photos.slideover.album.label')"- class="w-full"- />- </UFormField>+ {{ $t('dashboard.photos.slideover.album.retry') }}+ </UButton>+ </div>+ </UCard>++ <UCard+ variant="soft"+ class="border border-neutral-200/80 dark:border-neutral-800/80"+ >+ <div class="flex items-start justify-between gap-4">+ <div class="space-y-1"><p- v-if="- !isLoadingUploadAlbums &&- !uploadAlbumsLoadFailed &&- uploadAlbums.length === 0- "- class="mt-2 text-xs text-neutral-500 dark:text-neutral-400"+ class="text-sm font-medium text-neutral-800 dark:text-neutral-100">- {{ $t('dashboard.photos.slideover.album.empty') }}+ {{+ $t('dashboard.photos.slideover.options.eraseLocation.label')+ }}</p>- <p- v-if="selectedUploadAlbumUnavailable"- role="alert"- class="mt-2 text-sm text-error-600 dark:text-error-400"- >+ <p class="text-xs text-neutral-500 dark:text-neutral-400">{{$t(- requestedUploadAlbumId === selectedUploadAlbumId- ? 'dashboard.photos.slideover.album.requestedUnavailable'- : 'dashboard.photos.slideover.album.unavailable',+ 'dashboard.photos.slideover.options.eraseLocation.description',)}}</p>- <div- v-if="uploadAlbumsLoadFailed"- role="alert"- class="mt-2 flex items-center justify-between gap-2 text-sm text-error-600 dark:text-error-400"- >- <span>{{- $t('dashboard.photos.slideover.album.loadFailedUpload')- }}</span>- <UButton- size="xs"- variant="soft"- @click="loadUploadAlbums"- >- {{ $t('dashboard.photos.slideover.album.retry') }}- </UButton>- </div>- </UCard>-- <UCard- variant="soft"- class="border border-neutral-200/80 dark:border-neutral-800/80"- >- <div class="flex items-start justify-between gap-4">- <div class="space-y-1">- <p- class="text-sm font-medium text-neutral-800 dark:text-neutral-100"- >- {{- $t(- 'dashboard.photos.slideover.options.eraseLocation.label',- )- }}- </p>- <p class="text-xs text-neutral-500 dark:text-neutral-400">- {{- $t(- 'dashboard.photos.slideover.options.eraseLocation.description',- )- }}- </p>- </div>- <USwitch v-model="uploadEraseLocationEnabled" />- </div>- </UCard>- </div>- </template>-- <template #footer>- <div- class="flex w-full flex-col gap-4 sm:flex-row sm:items-center sm:justify-between"- >- <div- class="flex flex-col gap-1 text-sm text-neutral-500 dark:text-neutral-400"- >- <span>{{- hasSelectedFiles- ? selectedFilesSummary- : $t('dashboard.photos.slideover.footer.noSelection')- }}</span>- </div>- <div class="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">- <UButton- variant="soft"- color="neutral"- class="w-full sm:w-auto"- :disabled="!hasSelectedFiles"- @click="clearSelectedFiles"- >- {{ $t('dashboard.photos.slideover.buttons.clear') }}- </UButton>- <UButton- color="primary"- size="lg"- class="w-full sm:w-auto"- icon="tabler:upload"- :disabled="!hasSelectedFiles || !canUseSelectedUploadAlbum"- @click="handleUpload"- >- {{- hasSelectedFiles- ? $t('dashboard.photos.slideover.buttons.upload', {- count: selectedFiles.length,- })- : $t('dashboard.photos.buttons.upload')- }}- </UButton></div>+ <USwitch v-model="uploadEraseLocationEnabled" /></div>- </template>- </USlideover>+ </UCard>+ </PhotoUploadSlideover><!-- 统合容器:工具栏 + 照片列表 --><div :class="photoLibraryPresentation.panel">diff --git a/packages/gallery/shared/types/uploading-file.ts b/packages/gallery/shared/types/uploading-file.tsindex 0a6b626e..3e7e78e7 100644--- a/packages/gallery/shared/types/uploading-file.ts+++ b/packages/gallery/shared/types/uploading-file.ts@@ -1,5 +1,5 @@import type { UploadPreparationResponse } from '@chronoframe/contracts/upload'-import type { UploadQueueStatus } from '~~/shared/utils/upload-status'+import type { UploadQueueStatus } from '../utils/upload-status'export interface UploadingFile {file: Filediff --git a/packages/storage/README.md b/packages/storage/README.mdindex a87ea02a..06338180 100644--- a/packages/storage/README.md+++ b/packages/storage/README.md@@ -10,4 +10,9 @@ Configuration and errors may contain sensitive information: only trusted servercode should instantiate providers or access configuration. Upload lifecycle logskeep the existing sanitized metadata policy.+Self-hosted S3 and the Cloud upload adapter share `canFallbackToSingleUpload`+(also exported by `s3-edge`). Only unsupported or denied multipart initialization+may fall back to signed PUT; transient, authentication and signing failures must+remain errors. Existing multipart sessions keep their original part sizing.+Run `pnpm check:packages` and `pnpm test` from the workspace root.diff --git a/packages/storage/src/multipart-fallback.ts b/packages/storage/src/multipart-fallback.tsnew file mode 100644index 00000000..42c4fef1--- /dev/null+++ b/packages/storage/src/multipart-fallback.ts@@ -0,0 +1,18 @@+/** Only unsupported/denied multipart operations may downgrade to signed PUT. */+export function canFallbackToSingleUpload(error: unknown): boolean {+ if (!error || typeof error !== 'object') return false+ const failure = error as {+ name?: string+ Code?: string+ $metadata?: { httpStatusCode?: number }+ }+ return (+ [405, 501].includes(failure.$metadata?.httpStatusCode ?? 0) ||+ [+ 'NotImplemented',+ 'NotSupported',+ 'UnsupportedOperation',+ 'AccessDenied',+ ].includes(failure.name || failure.Code || '')+ )+}diff --git a/packages/storage/src/providers/s3.ts b/packages/storage/src/providers/s3.tsindex f486914c..af76eedb 100644--- a/packages/storage/src/providers/s3.ts+++ b/packages/storage/src/providers/s3.ts@@ -25,6 +25,7 @@ import type {} from '../interfaces.ts'import { UPLOAD_CHUNK_SIZE } from '@chronoframe/contracts/upload'import { logUpload } from '../upload-log.ts'+import { canFallbackToSingleUpload } from '../multipart-fallback.ts'const createClient = (config: S3StorageConfig): S3Client => {if (config.provider !== 's3') {@@ -284,15 +285,7 @@ export class S3StorageProvider implements StorageProvider {Code?: string$metadata?: { httpStatusCode?: number }}- if (- [405, 501].includes(unsupported.$metadata?.httpStatusCode ?? 0) ||- [- 'NotImplemented',- 'NotSupported',- 'UnsupportedOperation',- 'AccessDenied',- ].includes(unsupported.name || unsupported.Code || '')- ) {+ if (canFallbackToSingleUpload(error)) {// A provider can allow ordinary PUT uploads while denying multipart// initiation. Keep the file on the direct path in that case.logUpload(this.logger, 's3.multipart.fallback.single', {diff --git a/packages/storage/src/s3-edge.ts b/packages/storage/src/s3-edge.tsindex 5bfbe0cf..8bddd3ef 100644--- a/packages/storage/src/s3-edge.ts+++ b/packages/storage/src/s3-edge.ts@@ -18,6 +18,7 @@ import {} from '@aws-sdk/client-s3'import { getSignedUrl } from '@aws-sdk/s3-request-presigner'import { FetchHttpHandler } from '@smithy/fetch-http-handler'+export { canFallbackToSingleUpload } from './multipart-fallback.ts'export interface CloudS3Config {endpoint: stringdiff --git a/tests/helpers/upload-runtime.ts b/tests/helpers/upload-runtime.tsnew file mode 100644index 00000000..d9319fc6--- /dev/null+++ b/tests/helpers/upload-runtime.ts@@ -0,0 +1,130 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import vm from 'node:vm'+import ts from 'typescript'+import * as vue from 'vue'+import * as statuses from '../../packages/gallery/shared/utils/upload-status.ts'+import { UPLOAD_CHUNK_SIZE } from '../../packages/contracts/src/upload.ts'++export function loadUploadCode(+ file: string,+ globals: Record<string, unknown> = {},+ imports: Record<string, unknown> = {},+ suffix = '',+) {+ const exports: Record<string, any> = {}+ const source = readFileSync(file, 'utf8')+ const script = file.endsWith('.vue')+ ? source.split('<script setup lang="ts">')[1]!.split('</script>')[0]!+ : source+ vm.runInNewContext(+ ts+ .transpileModule(script + suffix, {+ compilerOptions: {+ module: ts.ModuleKind.CommonJS,+ target: ts.ScriptTarget.ES2022,+ },+ })+ .outputText.replaceAll('import.meta.client', 'true'),+ {+ exports,+ ...vue,+ File,+ Blob,+ AbortController,+ crypto,+ performance,+ console,+ setTimeout,+ clearTimeout,+ setInterval,+ clearInterval,+ queueMicrotask,+ ...globals,+ require: (name: string) => {+ if (name === 'vue') return vue+ if (name === '@chronoframe/gallery/shared/utils/upload-status')+ return statuses+ if (name === '@chronoframe/gallery/shared/utils/upload')+ return { UPLOAD_CHUNK_SIZE }+ assert.ok(name in imports, `Missing test import: ${name}`)+ return imports[name]+ },+ },+ )+ return exports+}++export function createCloudUploadHarness(globals: Record<string, any> = {}) {+ const scope = vue.effectScope()+ const user = globals.user ?? vue.ref<number | null>(1)+ const storage = new Map<string, string>()+ const mounts: (() => void)[] = []+ const unmounts: (() => void)[] = []+ const intervals: (() => Promise<void>)[] = []+ const base = {+ useState: () => user,+ useI18n: () => ({ t: (key: string) => key }),+ useNuxtApp: () => ({+ $i18n: { t: (key: string) => key },+ runWithContext: (fn: () => unknown) => fn(),+ }),+ localStorage: {+ getItem: (key: string) => storage.get(key),+ setItem: (key: string, value: string) => storage.set(key, value),+ removeItem: (key: string) => storage.delete(key),+ },+ document: { visibilityState: 'visible' },+ ...globals,+ onMounted: (fn: () => void) => mounts.push(fn),+ onBeforeUnmount: (fn: () => void) => unmounts.push(fn),+ setInterval: (fn: () => Promise<void>) => {+ intervals.push(fn)+ return intervals.length+ },+ clearInterval: () => {},+ }+ const transport = loadUploadCode(+ 'packages/console/app/composables/useUpload.ts',+ {+ ...base,+ setInterval,+ clearInterval,+ },+ )+ const queue = loadUploadCode(+ 'packages/console/app/composables/useUploadQueue.ts',+ )+ const module = loadUploadCode(+ 'apps/cloud/app/composables/useCloudUploads.ts',+ base,+ {+ '#console/composables/useUpload': transport,+ '#console/composables/useUploadQueue': queue,+ },+ '\nexport { createCloudUploads }',+ )+ const uploads = scope.run(() => module.createCloudUploads())!+ const pending: Promise<unknown>[] = []+ const enqueue = uploads.enqueue+ uploads.enqueue = (...args: unknown[]) => {+ const result = enqueue(...args)+ pending.push(result)+ return result+ }+ return {+ uploads,+ module,+ user,+ storage,+ scope,+ transport,+ flush: () => Promise.all(pending),+ mount: () => mounts.forEach((fn) => fn()),+ poll: () => Promise.all(intervals.map((fn) => fn())),+ dispose: () => {+ unmounts.forEach((fn) => fn())+ scope.stop()+ },+ }+}diff --git a/tests/portal-review-regressions.test.ts b/tests/portal-review-regressions.test.tsindex 5a461c33..60b5c666 100644--- a/tests/portal-review-regressions.test.ts+++ b/tests/portal-review-regressions.test.ts@@ -5,10 +5,7 @@ import vm from 'node:vm'import { createServer } from 'node:http'import { createRequire } from 'node:module'import ts from 'typescript'-import {- mergeUploadFiles,- remainingUploadFiles,-} from '../apps/cloud/app/utils/upload-selection.ts'+import { createCloudUploadHarness } from './helpers/upload-runtime.ts'import { isAlbumPagePath } from '../packages/gallery/shared/utils/albumPath.ts'import {ref,@@ -29,9 +26,32 @@ function load(source?: string,) {const exports: Record<string, any> = {}- const code = ts.transpileModule(source ?? readFileSync(file, 'utf8'), {- compilerOptions: { module: ts.ModuleKind.CommonJS },- }).outputText+ if (file === 'apps/cloud/app/composables/useCloudSiteMedia.ts') {+ const harness = createCloudUploadHarness(globals)+ globals = {+ useState: () => harness.user,+ useCloudUploads: () => harness.uploads,+ ...globals,+ }+ imports = {+ './useCloudUploads': {+ ...harness.module,+ useCloudUploads: () => harness.uploads,+ },+ ...imports,+ }+ exports.uploads = harness.uploads+ exports.flushUploads = harness.flush+ }+ const code = ts.transpileModule(+ (source ?? readFileSync(file, 'utf8')).replaceAll(+ 'import.meta.client',+ 'false',+ ),+ {+ compilerOptions: { module: ts.ModuleKind.CommonJS },+ },+ ).outputTextvm.runInNewContext(code, {exports,ref,@@ -118,7 +138,7 @@ test('Live Photo validation rejects the combined size before reserving any uploaassert.equal(input.value, '')assert.equal(requests.length, 0)}- await media.upload({+ const result = await media.upload({target: {files: [{ name: 'IMG.HEIC', size: 60 * mib },@@ -127,12 +147,17 @@ test('Live Photo validation rejects the combined size before reserving any uploavalue: 'chosen',},})+ assert.equal(result.queued, true)+ await module.flushUploads()assert.equal(media.failed.value, false)const reservation = requests.find((r) => r.path.endsWith('/uploads'))!assert.equal(reservation.body.bytes, 60 * mib)assert.deepEqual(Array.from(reservation.body.albumIds), [])assert.equal(reservation.body.liveVideo.bytes, 40 * mib)- assert.match(media.uploadSession.message, /Upload verified/)+ assert.equal(+ [...module.uploads.uploadingFiles.value.values()][0].status,+ 'processing',+ )})test('subscription retains edits through network/503 failures and invalidates only authoritative denials', async () => {@@ -747,7 +772,7 @@ test('explicit subscription-change checks refresh the plan without confusing the}})-test('upload sessions capture their actual storage type and move progress out of the selection drawer', async () => {+test('upload batches capture storage and albums before leaving the selection drawer', async () => {for (const platform of [true, false]) {let release!: () => voidconst gate = new Promise<void>((resolve) => {@@ -821,15 +846,14 @@ test('upload sessions capture their actual storage type and move progress out ofmedia.connectionId.value = 'changed-during-preflight'assert.equal(media.preparingUpload.value, true)await new Promise((resolve) => setImmediate(resolve))- assert.equal(media.uploading.value, true)assert.equal(media.uploadOpen.value, false)- assert.equal(media.uploadSession.storage, platform ? 'platform' : 'private')+ assert.equal(module.uploads.uploadingFiles.value.size, 2)media.connectionId.value = 'changed-during-upload'media.selectedAlbumIds.value = [7]media.connections.value = []- assert.equal(media.uploadSession.storage, platform ? 'platform' : 'private')release()await pending+ await module.flushUploads()assert.deepEqual(reservations.map((body) => body.connectionId),['chosen', 'chosen'],@@ -838,10 +862,12 @@ test('upload sessions capture their actual storage type and move progress out ofcacheKeys.length > 0 &&cacheKeys.every((key) => key.includes(':chosen:albums:')),)- assert.equal(media.uploadSession.total, 2)- assert.equal(media.uploadSession.completed, 2)- assert.equal(media.uploadSession.failed, false)- assert.match(media.uploadSession.message, /Upload verified/)+ assert.deepEqual(+ [...module.uploads.uploadingFiles.value.values()].map(+ (item) => item.status,+ ),+ ['processing', 'processing'],+ )assert.deepEqual(reservations.map((body) => Array.from(body.albumIds)),[@@ -852,92 +878,7 @@ test('upload sessions capture their actual storage type and move progress out of}})-test('floating queue follows task completion and retry without showing historical successful jobs', async () => {- const removed: string[] = []- const media = {- jobs: ref<any[]>([{ id: 'old', state: 'succeeded' }]),- ready: ref(true),- removePhoto: (id: string) => {- removed.push(id)- },- photos: ref([]),- uploading: ref(false),- progress: ref(0),- currentFile: ref(''),- uploadSession: reactive({ total: 0, message: '' }),- admin: ref(true),- busy: ref(false),- action: () => {},- api: () => {},- base: ref(''),- }- const file = 'apps/cloud/app/components/CloudTransferPanel.vue'- const script = readFileSync(file, 'utf8')- .split('<script setup lang="ts">')[1]!- .split('</script>')[0]!- const state = load(- file,- { useCloudSiteMedia: () => media, useId: () => 'queue' },- {},- script +- '\nexport { visible, collapsed, processingJobs, processingActive, processingCompleted, dismiss, removeFailed }',- )- assert.equal(state.visible.value, false)- media.jobs.value = [{ id: 'j', state: 'queued', attempts: 0 }]- await nextTick()- assert.equal(state.processingActive.value, 1)- state.dismiss()- assert.equal(state.visible.value, true)- media.jobs.value = [{ id: 'j', state: 'succeeded', attempts: 1 }]- await nextTick()- assert.equal(state.processingCompleted.value, 1)- state.dismiss()- assert.equal(state.visible.value, false)- media.jobs.value = [{ id: 'j', state: 'failed', attempts: 2 }]- await nextTick()- assert.equal(state.visible.value, false)- media.jobs.value = [{ id: 'j', state: 'retry_wait', attempts: 2 }]- await nextTick()- assert.equal(state.processingActive.value, 1)- media.jobs.value = [{ id: 'j', state: 'failed', attempts: 3 }]- await nextTick()- assert.equal(state.processingJobs.value[0].state, 'failed')- const failedJob = {- id: 'failed',- photo_id: 'never-ready',- state: 'failed',- attempts: 7,- }- media.admin.value = false- state.removeFailed(failedJob)- assert.deepEqual(removed, [])- media.admin.value = true- media.busy.value = true- state.removeFailed(failedJob)- assert.deepEqual(removed, [])- media.busy.value = false- state.removeFailed(failedJob)- assert.deepEqual(removed, ['never-ready'])- media.jobs.value = [] // The server omits tombstoned photos after deletion.- await nextTick()- assert.equal(state.processingJobs.value.length, 0)- // A new visit keeps historical failures accessible, but starts collapsed.- media.ready.value = false- media.jobs.value = [failedJob]- const history = load(- file,- { useCloudSiteMedia: () => media, useId: () => 'history' },- {},- script + '\nexport { visible, collapsed }',- )- assert.equal(history.visible.value, false)- media.ready.value = true- await nextTick()- assert.equal(history.visible.value, true)- assert.equal(history.collapsed.value, true)-})--test('upload album preflight fails closed for new uploads, refreshes reservation races and preserves resumable choices', async () => {+test('upload album preflight fails closed for new uploads and preserves resumable choices', async () => {for (const scenario of ['removed', 'offline', 'race', 'resume']) {let reservations = 0,albumReads = 0@@ -1000,14 +941,23 @@ test('upload album preflight fails closed for new uploads, refreshes reservationawait media.upload({target: { files: [{ name: 'one.jpg', size: 10 }], value: 'chosen' },})+ await module.flushUploads()assert.deepEqual(Array.from(media.selectedAlbumIds.value), [1])assert.equal(media.preparingUpload.value, false)assert.equal(reservations,['removed', 'offline'].includes(scenario) ? 0 : 1,)- if (scenario === 'resume') assert.equal(media.uploadSession.completed, 1)- else {+ if (scenario === 'resume')+ assert.equal(+ [...module.uploads.uploadingFiles.value.values()][0].status,+ 'processing',+ )+ else if (scenario === 'race') {+ const item = [...module.uploads.uploadingFiles.value.values()][0]+ assert.equal(item.status, 'error')+ assert.equal(item.error, 'cloud.transfer.albumsUnavailable')+ } else {assert.equal(media.failed.value, true)assert.match(media.message.value,@@ -1017,17 +967,16 @@ test('upload album preflight fails closed for new uploads, refreshes reservation)assert.equal(media.uploadOpen.value, true)}- if (scenario === 'race') assert(albumReads >= 2)}})-test('file selection and dropping only stage files; explicit start uploads once and retains unfinished photos', async () => {+test('shared upload drawer stages files and consumes them only after queue admission', async () => {const batches: File[][] = []let release!: () => voidlet gate = new Promise<void>((resolve) => {release = resolve})- let completed: number | undefined = 1+ let admitted = trueconst media = {uploadOpen: ref(true),albums: ref([]),@@ -1036,7 +985,6 @@ test('file selection and dropping only stage files; explicit start uploads oncefailed: ref(false),connections: ref([]),connectionId: ref('storage'),- uploading: ref(false),preparingUpload: ref(false),usage: ref(null),allowance: ref(null),@@ -1045,7 +993,7 @@ test('file selection and dropping only stage files; explicit start uploads onceupload: async (files: File[]) => {batches.push(files)await gate- return completed === undefined ? undefined : { completed }+ return admitted ? { queued: true } : undefined},}const file = 'apps/cloud/app/components/CloudUploadDrawer.vue'@@ -1061,21 +1009,14 @@ test('file selection and dropping only stage files; explicit start uploads once},{'../utils/quota-gate': { uploadQuotaGate: () => ({ allowed: true }) },- '../utils/upload-selection': { mergeUploadFiles, remainingUploadFiles },},- script +- '\nexport { selectedFiles, selectFiles, dropFiles, removeSelected, startUpload }',+ script + '\nexport { selectedFiles, startUpload }',)const photo = new File(['photo'], 'one.HEIC', { lastModified: 1 })const video = new File(['video'], 'one.MOV', { lastModified: 1 })const other = new File(['other'], 'two.jpg', { lastModified: 1 })- const input = { files: [photo, video], value: 'chosen' }- state.selectFiles({ target: input })- assert.equal(input.value, '')- state.dropFiles({ dataTransfer: { files: [photo, other] } })- assert.equal(state.selectedFiles.value.length, 3)+ state.selectedFiles.value = [photo, video]assert.equal(batches.length, 0)- state.removeSelected(2)const pending = state.startUpload()await state.startUpload()assert.equal(batches.length, 1)@@ -1087,15 +1028,8 @@ test('file selection and dropping only stage files; explicit start uploads onceawait pendingassert.equal(state.selectedFiles.value.length, 0)gate = Promise.resolve()- state.selectFiles({- target: { files: [photo, video, other], value: 'chosen' },- })- await state.startUpload()- assert.deepEqual(- Array.from(state.selectedFiles.value as File[]).map((f) => f.name),- ['two.jpg'],- )- completed = undefined // Admission/preflight rejection must not consume staged files.+ state.selectedFiles.value = [other]+ admitted = false // Admission/preflight rejection must not consume staged files.await state.startUpload()assert.equal(state.selectedFiles.value[0].name, 'two.jpg')media.admin.value = false@@ -1103,20 +1037,3 @@ test('file selection and dropping only stage files; explicit start uploads onceawait state.startUpload()assert.equal(batches.length, count)})--test('partial upload cleanup retains shared MOV companions until every matching photo completes', () => {- const heic = new File(['heic'], 'One.HEIC', { lastModified: 1 })- const video = new File(['video'], 'one.MOV', { lastModified: 1 })- const jpeg = new File(['jpeg'], 'ONE.jpg', { lastModified: 1 })- const orphan = new File(['orphan'], 'other.MOV', { lastModified: 1 })- const selected = [heic, video, jpeg, orphan]- assert.deepEqual(remainingUploadFiles(selected, 0), selected)- const remaining = remainingUploadFiles(selected, 1)- assert.deepEqual(remaining, [video, jpeg, orphan])- assert.equal(- remaining.find((file) => file.name.toLowerCase().endsWith('.mov')),- video,- )- assert.deepEqual(remainingUploadFiles(remaining, 1), [orphan])- assert.deepEqual(remainingUploadFiles(selected, 2), [orphan])-})diff --git a/tests/shared-upload.test.ts b/tests/shared-upload.test.tsnew file mode 100644index 00000000..83dfacdb--- /dev/null+++ b/tests/shared-upload.test.ts@@ -0,0 +1,762 @@+import assert from 'node:assert/strict'+import { readFileSync } from 'node:fs'+import test from 'node:test'+import { effectScope, ref } from 'vue'+import {+ createCloudUploadHarness,+ loadUploadCode,+} from './helpers/upload-runtime.ts'+import { canFallbackToSingleUpload } from '../packages/storage/src/multipart-fallback.ts'++const tick = () => new Promise<void>((resolve) => setImmediate(resolve))+const context = {+ siteId: 7,+ scope: 'site:7:user:1',+ userId: 1,+ name: 'Gallery',+ admin: true,+}++function xhrFixture(respond?: (xhr: FakeXHR) => void) {+ const requests: FakeXHR[] = []+ class FakeXHR {+ method = ''+ url = ''+ status = 0+ timeout = 0+ body?: Blob+ headers: Record<string, string> = {}+ etag: string | null = '"fixture"'+ aborted = false+ listeners: Record<string, ((event?: unknown) => void)[]> = {}+ progress?: (event: unknown) => void+ upload = {+ addEventListener: (_: string, callback: (event: unknown) => void) => {+ this.progress = callback+ },+ }+ open(method: string, url: string) {+ this.method = method+ this.url = url+ }+ setRequestHeader(key: string, value: string) {+ this.headers[key] = value+ }+ getResponseHeader() {+ return this.etag+ }+ addEventListener(event: string, callback: () => void) {+ ;(this.listeners[event] ??= []).push(callback)+ }+ emit(event: string) {+ for (const callback of this.listeners[event] ?? []) callback()+ }+ send(body?: Blob) {+ this.body = body+ requests.push(this)+ queueMicrotask(() => (respond ? respond(this) : this.succeed()))+ }+ succeed() {+ if (this.aborted) return+ this.progress?.({ lengthComputable: true, loaded: this.body?.size ?? 0 })+ this.status = 200+ this.emit('load')+ }+ abort() {+ this.aborted = true+ this.emit('abort')+ }+ }+ return { XMLHttpRequest: FakeXHR, requests }+}+type FakeXHR = ReturnType<typeof xhrFixture>['requests'][number]++function transport(globals: Record<string, unknown> = {}) {+ return loadUploadCode('packages/console/app/composables/useUpload.ts', {+ useNuxtApp: () => ({ $i18n: { t: (key: string) => key } }),+ $fetch: async () => {},+ ...globals,+ }).useUpload+}++test('both editions render the same upload controls and Cloud mounts its queue outside routed layouts', () => {+ for (const path of [+ 'packages/console/app/pages/dashboard/photos.vue',+ 'apps/cloud/app/components/CloudUploadDrawer.vue',+ ]) {+ const source = readFileSync(path, 'utf8')+ assert.match(source, /<PhotoUploadSlideover/)+ assert.doesNotMatch(source, /<UFileUpload|type="file"/)+ }+ const cloud = readFileSync('apps/cloud/app/app.vue', 'utf8')+ assert.match(cloud, /provideCloudUploads\(\)/)+ assert.match(cloud, /<\/NuxtLayout>\s*<CloudTransferPanel/)+ assert.doesNotMatch(+ readFileSync('apps/cloud/app/components/CloudSiteWorkspace.vue', 'utf8'),+ /CloudTransferPanel/,+ )+ assert.match(+ readFileSync('apps/cloud/app/components/CloudTransferPanel.vue', 'utf8'),+ /<UploadQueuePanel/,+ )+})++test('shared scheduler limits all batches to three files and discards cancelled waiting entries', async () => {+ const scope = effectScope()+ const module = loadUploadCode(+ 'packages/console/app/composables/useUploadQueue.ts',+ )+ const queue = scope.run(() => module.useUploadQueue())!+ const started: string[] = []+ const releases: (() => void)[] = []+ const run = async (entry: { fileName: string }) => {+ started.push(entry.fileName)+ await new Promise<void>((resolve) => releases.push(resolve))+ }+ try {+ const first = queue.enqueue(+ [1, 2, 3, 4].map((n) => new File(['x'], `${n}.jpg`)),+ run,+ )+ const second = queue.enqueue([new File(['x'], '5.jpg')], run)+ await tick()+ assert.deepEqual(started, ['1.jpg', '2.jpg', '3.jpg'])+ const waiting = [...queue.uploadingFiles.value.values()].find(+ (item: any) => item.fileName === '4.jpg',+ ) as any+ queue.remove(waiting.fileId)+ releases.shift()!()+ await tick()+ assert.deepEqual(started, ['1.jpg', '2.jpg', '3.jpg', '5.jpg'])+ releases.forEach((release) => release())+ await Promise.all([first, second])+ assert.equal(queue.uploadingFiles.value.size, 4)+ } finally {+ scope.stop()+ }+})++test('shared multipart transport uploads concurrent parts, retries transient failures and finalizes ordered ETags', async () => {+ let failed = false+ const xhr = xhrFixture((request) => {+ if (request.url === 'part-2' && !failed) {+ failed = true+ request.status = 503+ request.emit('load')+ } else request.succeed()+ })+ const upload = transport(xhr)({ retryDelay: 0 })+ const states: string[] = []+ await upload.uploadFile(+ new File(['abcdefg'], 'photo.jpg'),+ {+ mode: 'multipart',+ url: '/complete',+ partSize: 2,+ partUrls: ['part-1', 'part-2', 'part-3', 'part-4'],+ },+ { onStatusChange: (status: string) => states.push(status) },+ )+ assert.deepEqual(+ xhr.requests.slice(0, 3).map((r) => r.url),+ ['part-1', 'part-2', 'part-3'],+ )+ assert.equal(xhr.requests.filter((r) => r.url === 'part-2').length, 2)+ const completion = xhr.requests.at(-1)!+ assert.equal(completion.method, 'POST')+ assert.deepEqual(+ JSON.parse(await completion.body!.text()).parts,+ [1, 2, 3, 4].map((partNumber) => ({ partNumber, etag: '"fixture"' })),+ )+ assert(states.includes('finalizing'))+ assert.equal(upload.uploadStatus.value.status, 'success')+ assert.equal(upload.uploadStatus.value.progress.percentage, 100)+})++test('server-verified resume skips only exact-size parts, accepts hidden ETags and preserves failed sessions', async () => {+ const xhr = xhrFixture((request) => {+ request.etag = null+ request.succeed()+ })+ const upload = transport(xhr)({+ multipart: {+ verifyPartsOnServer: true,+ uploadedParts: [+ { partNumber: 1, bytes: 2 },+ { partNumber: 2, bytes: 1 },+ ],+ preserveOnError: true,+ },+ })+ await upload.uploadFile(new File(['abcdef'], 'photo.jpg'), {+ mode: 'multipart',+ url: '/complete',+ partSize: 2,+ partUrls: ['part-1', 'part-2', 'part-3'],+ })+ assert.deepEqual(+ xhr.requests.map((r) => r.url),+ ['part-2', 'part-3', '/complete'],+ )+ assert.deepEqual(JSON.parse(await xhr.requests.at(-1)!.body!.text()), {})+ const failedXHR = xhrFixture((request) => {+ request.status = 403+ request.emit('load')+ })+ let cleanup = 0+ const failed = transport({+ ...failedXHR,+ $fetch: async () => {+ cleanup+++ },+ })({+ multipart: { verifyPartsOnServer: true, preserveOnError: true },+ })+ await assert.rejects(+ failed.uploadFile(new File(['xx'], 'photo.jpg'), {+ mode: 'multipart',+ url: '/complete',+ partSize: 2,+ partUrls: ['part'],+ }),+ )+ assert.equal(+ failedXHR.requests.length,+ 1,+ 'authorization errors are not retried',+ )+ assert.equal(cleanup, 0)+})++test('legacy chunks and sequential range plans retain their original completion protocols', async () => {+ for (const mode of ['chunks', 'range'] as const) {+ const xhr = xhrFixture()+ const upload = transport(xhr)()+ await upload.uploadFile(+ new File(['abcdef'], 'photo.jpg'),+ mode === 'chunks'+ ? { mode, url: '/chunks' }+ : { mode, url: '/range', partSize: 2 },+ )+ if (mode === 'chunks') {+ assert.deepEqual(+ xhr.requests.map((r) => [r.method, r.url]),+ [+ ['PUT', '/chunks?index=0'],+ ['POST', '/chunks'],+ ],+ )+ } else {+ assert.deepEqual(+ xhr.requests.map((r) => r.headers['Content-Range']),+ ['bytes 0-1/6', 'bytes 2-3/6', 'bytes 4-5/6'],+ )+ assert(xhr.requests.every((r) => r.method === 'PUT'))+ }+ }+})++test('Cloud upload continues after page disposal and Site navigation, then polls the original Site', async () => {+ let release!: () => void+ const reservation = new Promise<void>((resolve) => {+ release = resolve+ })+ const paths: string[] = []+ const xhr = xhrFixture()+ const currentSite = ref(7)+ const runtime = createCloudUploadHarness({+ ...xhr,+ formatBytes: (value: number) => String(value),+ $fetch: async (path: string) => {+ paths.push(path)+ if (path.endsWith('/uploads')) await reservation+ if (path.endsWith('/plan'))+ return {+ state: 'pending',+ mode: 'single',+ url: 'https://storage/photo',+ contentType: 'image/jpeg',+ }+ if (path.endsWith('/photos'))+ return {+ jobs: [...runtime.uploads.tracked.values()].map((item: any) => ({+ id: item.jobId,+ state: 'succeeded',+ photo_id: item.jobId,+ attempts: 1,+ error_code: null,+ })),+ }+ return {}+ },+ })+ try {+ runtime.mount()+ const page = effectScope()+ page.run(() =>+ runtime.uploads.enqueue(+ { ...context, siteId: currentSite.value },+ [new File(['photo'], 'one.jpg')],+ 'original-storage',+ [3],+ ),+ )+ await tick()+ currentSite.value = 99+ page.stop()+ release()+ await runtime.flush()+ assert(paths.every((path) => path.startsWith('/api/sites/7/media/')))+ assert.equal(xhr.requests.length, 1)+ assert.equal(xhr.requests[0]!.aborted, false)+ const entry = [...runtime.uploads.uploadingFiles.value.values()][0] as any+ assert.equal(entry.status, 'processing')+ await runtime.poll()+ assert.equal(entry.status, 'completed')+ } finally {+ runtime.dispose()+ }+})++test('Live Photo companion and multipart photo share the transport and publish only after both finish', async () => {+ const xhr = xhrFixture()+ const runtime = createCloudUploadHarness({+ ...xhr,+ formatBytes: String,+ $fetch: async (path: string) =>+ path.endsWith('/plan')+ ? {+ state: 'pending',+ mode: 'multipart',+ partBytes: 2,+ urls: ['photo-1', 'photo-2'],+ videoUrl: 'video',+ }+ : {},+ })+ try {+ await runtime.uploads.enqueue(+ context,+ [new File(['abcd'], 'one.HEIC'), new File(['video'], 'ONE.MOV')],+ 'storage',+ [],+ )+ assert.equal(xhr.requests[0]!.url, 'video')+ assert.deepEqual(+ xhr.requests.slice(1, 3).map((r) => r.url),+ ['photo-1', 'photo-2'],+ )+ assert.match(xhr.requests.at(-1)!.url, /\/complete$/)+ assert.equal(runtime.storage.size, 0)+ assert.equal(+ [...runtime.uploads.uploadingFiles.value.values()][0].status,+ 'processing',+ )+ } finally {+ runtime.dispose()+ }+})++test('clearing an in-flight queue aborts requests, releases reservations and never starts waiting files', async () => {+ const xhr = xhrFixture(() => {})+ const cancellations: string[] = []+ const runtime = createCloudUploadHarness({+ ...xhr,+ formatBytes: String,+ $fetch: async (path: string) => {+ if (path.endsWith('/cancel')) cancellations.push(path)+ if (path.endsWith('/plan'))+ return { state: 'pending', mode: 'single', url: 'storage' }+ return {}+ },+ })+ try {+ runtime.uploads.enqueue(+ context,+ [1, 2, 3, 4].map((n) => new File(['x'], `${n}.jpg`)),+ 'storage',+ [],+ )+ await tick()+ assert.equal(xhr.requests.length, 3)+ runtime.uploads.clearAll()+ await runtime.flush()+ assert(xhr.requests.every((request) => request.aborted))+ assert.equal(xhr.requests.length, 3)+ assert.equal(cancellations.length, 3)+ assert.equal(runtime.storage.size, 0)+ assert.equal(runtime.uploads.uploadingFiles.value.size, 0)+ } finally {+ runtime.dispose()+ }+})++test('account changes clear and abort upload state instead of exposing it to another user', async () => {+ const xhr = xhrFixture(() => {})+ const runtime = createCloudUploadHarness({+ ...xhr,+ formatBytes: String,+ console: { error: () => {} },+ $fetch: async (path: string) =>+ path.endsWith('/plan')+ ? { state: 'pending', mode: 'single', url: 'storage' }+ : {},+ })+ try {+ runtime.uploads.enqueue(+ context,+ [new File(['x'], 'one.jpg')],+ 'storage',+ [],+ )+ await tick()+ runtime.user.value = 2+ await runtime.flush()+ assert.equal(xhr.requests[0]!.aborted, true)+ assert.equal(runtime.uploads.uploadingFiles.value.size, 0)+ assert.equal(runtime.storage.size, 0)+ } finally {+ runtime.dispose()+ }+})++test('shared floating queue tracks processing, retry and deletion without resurrecting dismissed successes', () => {+ const runtime = createCloudUploadHarness()+ const queue = runtime.uploads+ try {+ const job = {+ id: 'j',+ photo_id: 'photo',+ file_name: 'one.jpg',+ state: 'succeeded',+ attempts: 1,+ error_code: null,+ }+ queue.trackJobs(context, [job])+ assert.equal(queue.uploadingFiles.value.size, 0)+ queue.trackJobs(context, [{ ...job, state: 'queued' }])+ const entry = [...queue.uploadingFiles.value.values()][0]+ assert.equal(entry.status, 'processing')+ queue.trackJobs(context, [job])+ assert.equal(entry.status, 'completed')+ queue.clearCompleted()+ queue.trackJobs(context, [job])+ assert.equal(queue.uploadingFiles.value.size, 0)+ queue.trackJobs(context, [{ ...job, state: 'retry_wait' }])+ assert.equal(queue.uploadingFiles.value.size, 1)+ queue.trackJobs(context, [+ { ...job, state: 'failed', error_code: 'processing_failed' },+ ])+ assert.equal([...queue.uploadingFiles.value.values()][0].status, 'error')+ queue.trackJobs(context, [])+ assert.equal(queue.uploadingFiles.value.size, 0)+ } finally {+ runtime.dispose()+ }+})++test('Self-hosted and edge use the same narrow multipart fallback policy', () => {+ for (const name of [+ 'NotImplemented',+ 'NotSupported',+ 'UnsupportedOperation',+ 'AccessDenied',+ ])+ assert.equal(canFallbackToSingleUpload({ name }), true)+ for (const status of [405, 501])+ assert.equal(+ canFallbackToSingleUpload({ $metadata: { httpStatusCode: status } }),+ true,+ )+ for (const error of [+ null,+ new Error('offline'),+ { name: 'SignatureDoesNotMatch' },+ { name: 'SlowDown' },+ { $metadata: { httpStatusCode: 503 } },+ ])+ assert.equal(canFallbackToSingleUpload(error), false)+ for (const path of [+ 'packages/storage/src/providers/s3.ts',+ 'apps/cloud/server/api/sites/[siteId]/media/[...operation].ts',+ ])+ assert.match(+ readFileSync(path, 'utf8'),+ /canFallbackToSingleUpload\(error\)/,+ )+})++test('Cloud plan falls back only before a multipart session exists and always releases its initialization lease', async () => {+ for (const failure of [+ { name: 'AccessDenied' },+ { name: 'NotImplemented' },+ { name: 'ServiceUnavailable', $metadata: { httpStatusCode: 503 } },+ ]) {+ let released = 0+ let signed = 0+ const raw = {+ prepare: () => ({+ bind: () => ({+ first: async () => ({ id: 'upload' }),+ run: async () => {+ released+++ },+ }),+ }),+ }+ const module = loadUploadCode(+ 'apps/cloud/server/api/sites/[siteId]/media/[...operation].ts',+ {+ console: { warn: () => {} },+ },+ {+ '../../../../utils/cloud-upload-albums': {},+ '../../../../utils/cloud-live-attachment': {},+ '../../../../utils/cloud-photo-processing': {},+ '@chronoframe/platform/entitlements': {},+ '@chronoframe/platform/domains': {},+ '@chronoframe/contracts/domains': {},+ '@chronoframe/database/cloud-album-slugs': {},+ '../../../../utils/cloud-photo-delete': {},+ '../../../../utils/cloud-album-editor': {},+ h3: {+ getRouterParam: () => 'uploads/upload/plan',+ createError: (value: unknown) => value,+ },+ '../../../../../../shared/platform/runtime': {+ definePlatformHandler: (handler: unknown) => handler,+ },+ '../../../../utils/site-management': {+ siteManagementBody: async () => ({}),+ },+ '@chronoframe/core': {},+ '../../../../../../shared/platform/crypto': {},+ '@chronoframe/storage/s3-edge': { canFallbackToSingleUpload },+ '../../../../utils/cloud-media': {+ cloudMedia: async () => ({+ siteId: 7,+ userId: 1,+ raw,+ repository: {+ upload: async () => ({+ state: 'pending',+ expires_at: Date.now() + 60000,+ expected_bytes: 20 * 1048576,+ object_key: 'source.jpg',+ connection_id: 'storage',+ provider_upload_id: null,+ }),+ },+ sql: async () => [+ { content_type: 'image/jpeg', connection_revision: 1 },+ ],+ storage: async () => ({+ s3: {+ recoverMultipart: async () => [],+ multipart: async () => {+ throw failure+ },+ signPut: async () => {+ signed+++ return 'https://storage/put'+ },+ },+ }),+ }),+ },+ },+ )++ if (failure.name === 'ServiceUnavailable') {+ await assert.rejects(module.default({ method: 'POST' }))+ assert.equal(signed, 0)+ } else {+ const plan = await module.default({ method: 'POST' })+ assert.equal(plan.mode, 'single')+ assert.equal(plan.contentType, 'image/jpeg')+ assert.equal(signed, 1)+ }+ assert.equal(released, 1)+ }+})++test('navigation during album preflight still hands the selected batch to the original Site queue', async () => {+ let release!: () => void+ const gate = new Promise<void>((resolve) => {+ release = resolve+ })+ const requests: string[] = []+ const fetcher = async (path: string) => {+ requests.push(path)+ if (path.endsWith('/albums')) {+ await gate+ return { albums: [{ id: 3 }] }+ }+ if (path.endsWith('/plan')) return { state: 'completed' }+ return {}+ }+ const runtime = createCloudUploadHarness({ $fetch: fetcher })+ const entry = ref({ ...context, audience: 'portal' })+ let unmount = () => {}+ const pageScope = effectScope()+ const module = loadUploadCode(+ 'apps/cloud/app/composables/useCloudSiteMedia.ts',+ {+ useI18n: () => ({ t: (key: string) => key }),+ useEntryContext: () => entry,+ useState: () => runtime.user,+ onMounted: () => {},+ onBeforeUnmount: (fn: () => void) => {+ unmount = fn+ },+ $fetch: fetcher,+ localStorage: { getItem: () => null },+ },+ {+ '@chronoframe/contracts/storage-diagnostics': {+ STORAGE_CONNECTION_MESSAGES: {},+ },+ './useCloudUploads': {+ ...runtime.module,+ useCloudUploads: () => runtime.uploads,+ },+ },+ )+ try {+ const media = pageScope.run(() =>+ module.useCloudMediaWorkspace({ siteId: 7, role: 'admin' }),+ )!+ media.connectionId.value = 'original'+ media.allowance.value = {+ byosLimits: { byos: 1, fileBytes: 100 },+ limits: { fileBytes: 100 },+ }+ media.selectedAlbumIds.value = [3]+ const pending = media.upload([new File(['photo'], 'one.jpg')])+ entry.value = { ...entry.value, siteId: 99, scope: 'different-site' }+ unmount()+ pageScope.stop()+ release()+ assert.equal((await pending).queued, true)+ await runtime.flush()+ assert(requests.every((path) => path.startsWith('/api/sites/7/media/')))+ assert.equal(+ [...runtime.uploads.uploadingFiles.value.values()][0].status,+ 'processing',+ )+ } finally {+ pageScope.stop()+ runtime.dispose()+ }+})++test('concurrent duplicate selections do not race the same Cloud reservation', async () => {+ let release!: () => void+ const gate = new Promise<void>((resolve) => {+ release = resolve+ })+ let reservations = 0+ const runtime = createCloudUploadHarness({+ $fetch: async (path: string) => {+ if (path.endsWith('/uploads')) {+ reservations+++ await gate+ }+ return path.endsWith('/plan') ? { state: 'completed' } : {}+ },+ })+ try {+ const file = new File(['x'], 'same.jpg')+ runtime.uploads.enqueue(context, [file, file], 'storage', [])+ await tick()+ assert.equal(reservations, 1)+ assert(+ [...runtime.uploads.uploadingFiles.value.values()].some(+ (item) => item.status === 'blocked',+ ),+ )+ release()+ await runtime.flush()+ } finally {+ runtime.dispose()+ }+})++test('retrying one processing job keeps other jobs in the same Site queue', () => {+ const runtime = createCloudUploadHarness()+ try {+ const failed = {+ id: 'failed-job',+ photo_id: 'photo-1',+ state: 'failed',+ attempts: 1,+ error_code: 'processing_failed',+ }+ runtime.uploads.trackJobs(context, [+ failed,+ { ...failed, id: 'other-job', photo_id: 'photo-2', state: 'running' },+ ])+ runtime.uploads.trackJobs(+ context,+ [{ ...failed, state: 'queued', error_code: null }],+ { partial: true },+ )+ assert.equal(runtime.uploads.uploadingFiles.value.size, 2)+ assert(+ [...runtime.uploads.uploadingFiles.value.values()].every(+ (item) => item.status === 'processing',+ ),+ )+ } finally {+ runtime.dispose()+ }+})++test('reselecting an interrupted upload resumes its reservation and every matching queue row reaches completion', async () => {+ let fail = true+ const xhr = xhrFixture((request) => {+ if (fail) {+ request.status = 403+ request.emit('load')+ } else request.succeed()+ })+ const ids: string[] = []+ const runtime = createCloudUploadHarness({+ ...xhr,+ formatBytes: String,+ $fetch: async (+ path: string,+ options?: { body?: { requestId?: string } },+ ) => {+ if (options?.body?.requestId) ids.push(options.body.requestId)+ return path.endsWith('/plan')+ ? { state: 'pending', mode: 'multipart', partBytes: 2, urls: ['part'] }+ : {}+ },+ })+ try {+ const file = new File(['xx'], 'resume.jpg')+ await runtime.uploads.enqueue(context, [file], 'storage', [])+ assert.equal(runtime.storage.size, 1)+ fail = false+ await runtime.uploads.enqueue(context, [file], 'storage', [])+ assert.equal(ids.length, 2)+ assert.equal(ids[0], ids[1])+ runtime.uploads.trackJobs(context, [+ {+ id: ids[0],+ photo_id: ids[0],+ state: 'succeeded',+ attempts: 1,+ error_code: null,+ },+ ])+ assert(+ [...runtime.uploads.uploadingFiles.value.values()].every(+ (item) => item.status === 'completed',+ ),+ )+ } finally {+ runtime.dispose()+ }+})