diff --git a/src/features/production/components/KeyframeDialog.vue b/src/features/production/components/KeyframeDialog.vue index b3cb7b4..8be37d1 100644 --- a/src/features/production/components/KeyframeDialog.vue +++ b/src/features/production/components/KeyframeDialog.vue @@ -33,6 +33,8 @@ const props = defineProps<{ direction?: ShotDirection | null /** 当前镜头的正式画面即时状态。 */ visualState?: ShotVisualState | null + /** 提交前已有候选,用于区分下载恢复与历史候选。 */ + previousCandidateIds?: readonly string[] /** 仅发送已经确认的当前快照。 */ submitGeneration: (input: GenerateKeyframeInput) => Promise }>() @@ -73,6 +75,7 @@ const { } = useImageGenerationPreview({ open, recoveryTarget: () => (props.shotId ? 'keyframe:' + props.shotId : ''), + previousCandidateIds: () => props.previousCandidateIds, target: () => JSON.stringify([props.shotId, props.direction, props.visualState]), input: () => generationInput.value, disabled: () => props.disabled || !imageProvider.value, diff --git a/src/features/production/components/ShotProductionAssets.vue b/src/features/production/components/ShotProductionAssets.vue index 4e9f9fb..7c38630 100644 --- a/src/features/production/components/ShotProductionAssets.vue +++ b/src/features/production/components/ShotProductionAssets.vue @@ -13,6 +13,7 @@ import { ImagePlus, RefreshCw } from '@lucide/vue' import { AssetImage } from '../../../components/ui' import { usePolling } from '../../../composables/usePolling' import { useQuery } from '../../../composables/useQuery' +import { releaseRecoveredImageRequest } from '../../subject-images/image-request-guard' import { ApiError, errorMessage } from '../../../lib/http' import { candidateDialogWidth } from '../../../lib/candidate-layout' import type { DesignedShot } from '../../storyboard/types' @@ -175,6 +176,21 @@ const currentVideoInput = computed(() => videoInputQuery.data.value?.shotId === key.value ? videoInputQuery.data.value : null ) const keyframes = computed(() => query.data.value?.keyframes ?? []) +/** 下载回执丢失或刷新后,只用列表明确保存的恢复结果解除同镜头的保护。 */ +watch(keyframes, rows => { + const shotId = props.shot.shotId + for (const item of rows) { + if ( + item.shotId === shotId && + item.status === 'completed' && + item.imageUrl && + item.recoveryRequired === false && + item.canRecoverSavedResult === false && + item.recoveryReason === 'provider_result_recovered' + ) + releaseRecoveredImageRequest('keyframe:' + shotId, item.id, item.providerInputFingerprint) + } +}) const videos = computed(() => query.data.value?.videos ?? []) /** 当前镜头尚未结束的首帧任务数量,包含等待提交和生成中。 */ const activeKeyframeCount = computed( @@ -328,6 +344,8 @@ const canGeneratePrompt = computed( const canGenerateKeyframe = computed( () => !assetBlocked.value && + !query.loading.value && + !!query.data.value && !keyframes.value.some(item => item.recoveryRequired || ['pending', 'generating'].includes(item.status)) && !!props.keyframeReadiness && props.keyframeReadiness.issues.length === 0 @@ -453,7 +471,15 @@ async function generateKeyframe(input: GenerateKeyframeInput) { const projectId = props.projectId const accepted = await runOperation(projectId, `生成镜头 ${props.shot.shotNo} 首帧`, async () => { const result = await productionApi.generateKeyframe(shotId, input) - if (!result || result.shotId !== shotId) throw new ApiError('首帧生成结果待核对。', 200) + if ( + !result?.id || + result.shotId !== shotId || + result.status !== 'completed' || + !result.imageUrl || + result.recoveryRequired !== false || + result.providerInputFingerprint !== input.expectedPreviewFingerprint + ) + throw new ApiError('首帧生成结果待核对。', 200) }) const cause = getOperation(projectId).cause if (props.projectId === projectId && props.shot.shotId === shotId) await refreshAll() @@ -470,8 +496,18 @@ async function recoverSavedKeyframe(item: ShotKeyframe) { const shotId = props.shot.shotId await runOperation(projectId, `恢复已生成首帧 ${item.id}`, async () => { const result = await productionApi.recoverSavedKeyframe(shotId, item.id) - if (result.id !== item.id || result.shotId !== shotId || result.status !== 'completed') + if ( + !result || + result.id !== item.id || + result.shotId !== shotId || + result.status !== 'completed' || + !result.imageUrl || + result.recoveryRequired !== false || + result.canRecoverSavedResult !== false || + result.providerInputFingerprint !== item.providerInputFingerprint + ) throw new Error('下载结果待核对,请刷新候选。') + releaseRecoveredImageRequest('keyframe:' + shotId, result.id, result.providerInputFingerprint) }) if (projectId === props.projectId && shotId === props.shot.shotId) await refreshAll() } @@ -1082,6 +1118,7 @@ defineExpose({ inspectSpecs, inspecting }) :direction="shot.direction" :visual-state="shot.visualState" :disabled="!canGenerateKeyframe" + :previous-candidate-ids="keyframes.map(item => item.id)" :submit-generation="generateKeyframe" /> diff --git a/src/features/subject-images/components/ImageGalleryDialog.vue b/src/features/subject-images/components/ImageGalleryDialog.vue index 2be86ea..28f911c 100644 --- a/src/features/subject-images/components/ImageGalleryDialog.vue +++ b/src/features/subject-images/components/ImageGalleryDialog.vue @@ -16,6 +16,7 @@ import { referenceImageUrl } from '../../../lib/assets' import { formatDate } from '../../../lib/format' import { getOperation, runOperation } from '../../workflows/operations' import { subjectImagesApi } from '../api' +import { imageRequestNotice, runGuardedImageRequest } from '../image-request-guard' import { hasRunningImages, primaryImage, currentIdentityAnchorId, isIdentityAnchorReuse } from '../model' import type { SubjectFormAsset, FormImageQualityResult } from '../types' @@ -77,6 +78,20 @@ const sourceCurrent = computed( source.data.value?.sourceCurrent === true && source.data.value?.canValidate === true ) +/** 同一候选的审核、修复和可能收费的主图确认共用一个保护范围。 */ +const reviewTarget = computed(() => + key.value && selected.value ? JSON.stringify(['form-review', key.value, selected.value.id]) : '' +) +/** 回执未知时保留原候选和只读刷新入口。 */ +const reviewNotice = computed(() => imageRequestNotice(reviewTarget.value)) + +/** 刷新图片及其来源。候选变更时由预检查询自动读取新的目标。 */ +async function refreshImages() { + const target = key.value + const previousSource = sourceKey.value + await query.refresh() + if (target === key.value && previousSource && previousSource === sourceKey.value) await source.refresh() +} /** 项目内的真实活动锁。 */ const operation = computed(() => getOperation(props.projectId)) /** 历史复用图失去当前母版或基础形态条件时只供查看,不能重新设为主图。 */ @@ -93,6 +108,7 @@ const canSetPrimary = computed( !props.disabled && !operation.value.pending && !pending.value && + !reviewNotice.value && !query.loading.value && !query.error.value && !hasRunningImages(images.value) && @@ -114,6 +130,7 @@ const canValidate = computed( !props.disabled && !operation.value.pending && !pending.value && + !reviewNotice.value && !query.loading.value && !query.error.value && !hasRunningImages(images.value) && @@ -174,47 +191,76 @@ async function confirmAction() { const provider = selected.value.provider const budget = maxRepairAttempts.value const requestKey = key.value + const requestTarget = reviewTarget.value selectedId.value = imageId pending.value = { kind, imageId } actionError.value = '' + // 保留当前抽屉的提交锁,在占用项目操作前读取来源并核对目标。 + await source.refresh() + if ( + key.value !== requestKey || + reviewTarget.value !== requestTarget || + props.disabled || + operation.value.pending || + !sourceCurrent.value + ) { + if (key.value === requestKey && reviewTarget.value === requestTarget) { + confirming.value = null + if (sourceCurrent.value) actionError.value = '当前操作状态已变化,请重新核对。' + } + pending.value = null + return + } const ok = await runOperation( projectId, `${kind === 'quality' ? '审核与修复' : kind === 'validate' ? '审核' : '设置主图'} · ${props.form.subject.name}`, async () => { - if (kind === 'quality') { - const result = await subjectImagesApi.generateQuality(formId, { - imageId, - provider, - maxRepairAttempts: budget - }) + return runGuardedImageRequest(requestTarget, async () => { + if (kind === 'quality') { + const result = await subjectImagesApi.generateQuality(formId, { + imageId, + provider, + maxRepairAttempts: budget + }) + if ( + !result || + result.subjectFormId !== formId || + result.initialImageId !== imageId || + !result.finalImageId || + typeof result.passed !== 'boolean' || + typeof result.primaryChanged !== 'boolean' || + !Array.isArray(result.attempts) || + result.maxRepairAttempts !== budget + ) + throw new Error('质量处理回执不完整,请刷新图库核对。') + if (key.value === requestKey && selected.value?.id === imageId) qualityResult.value = result + return null + } + if (kind === 'validate') { + const result = await subjectImagesApi.validate(formId, imageId) + if ( + !result || + result.imageId !== imageId || + result.subjectFormId !== formId || + result.subjectId !== subjectId || + typeof result.passed !== 'boolean' || + !Array.isArray(result.issues) + ) + throw new Error('审核结果与当前图片不匹配,请刷新后核对。') + if (key.value === requestKey && selected.value?.id === imageId) validation.value = result + return result + } + const result = await subjectImagesApi.setPrimary(formId, imageId) if ( + !result || + result.id !== imageId || result.subjectFormId !== formId || - result.initialImageId !== imageId || - !result.finalImageId || - !Array.isArray(result.attempts) || - result.maxRepairAttempts !== budget + !result.isPrimary || + result.status !== 'completed' ) - throw new Error('质量处理回执不完整,请刷新图库核对。') - if (key.value === requestKey && selected.value?.id === imageId) qualityResult.value = result + throw new Error('主图切换结果尚未确认,请刷新后核对。') return null - } - if (kind === 'validate') { - const result = await subjectImagesApi.validate(formId, imageId) - if (result.imageId !== imageId || result.subjectFormId !== formId || result.subjectId !== subjectId) - throw new Error('审核结果与当前图片不匹配,请刷新后核对。') - if (key.value === requestKey && selected.value?.id === imageId) validation.value = result - return result - } - const result = await subjectImagesApi.setPrimary(formId, imageId) - if ( - !result || - result.id !== imageId || - result.subjectFormId !== formId || - !result.isPrimary || - result.status !== 'completed' - ) - throw new Error('主图切换结果尚未确认,请刷新后核对。') - return null + }) }, result => result @@ -231,7 +277,7 @@ async function confirmAction() { if (key.value === requestKey) { confirming.value = null if (!ok) actionError.value = errorMessage(getOperation(projectId).cause) - await Promise.all([query.refresh(), source.refresh()]) + await refreshImages() if (ok) emit('changed') } pending.value = null @@ -247,7 +293,11 @@ async function confirmAction() { >
{{ images.length }} 条图片记录刷新图片
@@ -370,6 +420,10 @@ async function confirmAction() { title="该候选的实际生成输入" :value="source.data.value.providerInputSnapshot" /> + + + {{ reviewNotice }} +
- + string /** 跨表单开关稳定的计费核对目标。 */ recoveryTarget?: () => string + /** 首帧提交前已有候选,供恢复时区分历史记录。 */ + previousCandidateIds?: () => readonly string[] | undefined /** 当前完整生成参数。 */ input: () => Input /** 当前是否允许提交。 */ @@ -97,39 +100,6 @@ interface PreviewOptions Promise } -/** 同一浏览器标签页的待核对目标。记录不含提示词、图片或确认状态。 */ -const unresolvedGenerations = ref(new Set()) -const recoveryStoragePrefix = 'short-drama:image-request-unknown:' - -/** - * 恢复已提交但结果未知的保护,包括同标签页刷新。 - * @param target 当前正式生成目标 - * @returns 该目标是否有待核对的原请求 - */ -function hasUnknownGeneration(target: string) { - if (!target) return false - if (unresolvedGenerations.value.has(target)) return true - try { - return sessionStorage.getItem(recoveryStoragePrefix + target) === '1' - } catch { - return false - } -} - -/** - * 标记未知结果,禁止在当前标签页把未知当成失败再提交。 - * @param target 原生成请求的正式目标 - */ -function markUnknownGeneration(target: string) { - if (!target) return - unresolvedGenerations.value.add(target) - try { - sessionStorage.setItem(recoveryStoragePrefix + target, '1') - } catch { - // 浏览器存储不可用时,当前工作区仍保留内存保护。 - } -} - /** * 绑定预览与提交参数,处理过期响应、关闭及 409 重新确认。 * @param options 当前表单、正式预览与生成操作 @@ -159,11 +129,7 @@ export function useImageGenerationPreview options.recoveryTarget?.() || options.target()) /** 已提交但回执未知时,保留候选核对提示。 */ - const recoveryNotice = computed(() => - hasUnknownGeneration(recoveryKey.value) - ? '本次请求的结果和费用待核对。请先刷新候选与任务记录,并核对原请求。' - : '' - ) + const recoveryNotice = computed(() => (submitting.value ? '' : imageRequestNotice(recoveryKey.value))) /** 当前界面的预览必须完整且费用已确认。 */ const canSubmit = computed( () => @@ -234,25 +200,31 @@ export function useImageGenerationPreview { + const receipt = await options.generate({ ...input, expectedPreviewFingerprint: fingerprint }) + if (!receipt.accepted) + throw receipt.cause ?? new ApiError('当前暂不能提交,请刷新项目状态后重试。', 409) + return receipt + }, + { + evidence: previousCandidateIds + ? { previewFingerprint: fingerprint, previousCandidateIds } + : undefined, + rejectionStatuses: [400, 401, 403, 404, 409, 422] + } + ) } catch (cause) { result = { accepted: false, cause } } finally { submitting.value = false } - if ( - !result.accepted && - result.cause instanceof ApiError && - (result.cause.status === 0 || - result.cause.status >= 500 || - (result.cause.status >= 200 && result.cause.status < 300)) - ) { - markUnknownGeneration(recoveryTarget) - } if (current !== revision) return if (result.accepted) { options.open.value = false diff --git a/src/features/subject-images/image-request-guard.ts b/src/features/subject-images/image-request-guard.ts new file mode 100644 index 0000000..ab9cd4d --- /dev/null +++ b/src/features/subject-images/image-request-guard.ts @@ -0,0 +1,137 @@ +import { ref } from 'vue' +import { ApiError } from '../../lib/http' + +/** 按正式目标保留最少的提交证据,供已生成首帧的下载恢复核对。 */ +interface ImageRequestEvidence { + /** 本次确认并提交的生成输入指纹。 */ + previewFingerprint: string + /** 首帧提交前已存在的候选编号,旧候选恢复不能解除新请求。 */ + previousCandidateIds: readonly string[] +} + +/** 仅在正式接口能确定未计费时允许按错误状态解除标记。 */ +interface ImageRequestGuardOptions { + /** 首帧恢复时的候选关联信息。 */ + evidence?: ImageRequestEvidence + /** 对该入口可证明在付费前拒绝的 HTTP 状态。 */ + rejectionStatuses?: readonly number[] +} + +/** 当前标签页的提交记录,与表单关闭和页面刷新独立。 */ +interface ImageRequestMarker { + /** 每次提交独立的本地标识,用于拒绝迟到回执清除新记录。 */ + id: string + /** 仅可恢复的首帧请求需要绑定候选证据。 */ + evidence?: ImageRequestEvidence +} + +/** 沿用既有标记键,旧版只有待核对状态,无法关联到具体候选。 */ +const prefix = 'short-drama:image-request-unknown:' +/** 本标签页写入或清除标记时通知当前打开的界面。 */ +const revision = ref(0) + +/** + * 读取标签页记录,格式无法识别时保留保护。 + * @param target 正式目标 + * @returns 当前标记、旧版标记、存储不可用或空值 + */ +function readMarker(target: string): ImageRequestMarker | 'legacy' | 'unavailable' | null { + void revision.value + if (!target) return null + let stored: string | null + try { + stored = sessionStorage.getItem(prefix + target) + } catch { + return 'unavailable' + } + if (stored === null) return null + try { + const marker = JSON.parse(stored) as ImageRequestMarker | null + return marker && typeof marker.id === 'string' && marker.id ? marker : 'legacy' + } catch { + return 'legacy' + } +} + +/** + * 给付费入口提供当前待核对状态,浏览器无法保存保护时暂停提交。 + * @param target 正式目标 + * @returns 页面可读的阻断原因,空字符串表示可以提交 + */ +export function imageRequestNotice(target: string) { + const marker = readMarker(target) + if (marker === 'unavailable') return '浏览器无法保存提交记录,请检查存储设置后刷新。' + return marker ? '上次请求的结果和费用待核对。请先刷新候选与任务记录。' : '' +} + +/** + * 仅清除当前提交标记,迟到响应不能解除另一笔请求。 + * @param target 正式目标 + * @param markerId 本次提交标识 + */ +function clearMarker(target: string, markerId: string) { + const marker = readMarker(target) + if (!marker || typeof marker === 'string' || marker.id !== markerId) return + try { + sessionStorage.removeItem(prefix + target) + revision.value++ + } catch { + // 无法确认标记已清除时继续保留保护。 + } +} + +/** + * 先持久化再提交,收到已核对的回执或明确拒绝后才解锁。 + * @param target 同一目标共享的付费请求范围 + * @param submit 调用正式接口并核对回执 + * @param options 恢复证据及该入口明确拒绝的状态 + * @returns 经调用方核对的回执 + */ +export async function runGuardedImageRequest( + target: string, + submit: () => Promise, + options: ImageRequestGuardOptions = {} +): Promise { + const notice = imageRequestNotice(target) + if (notice) throw new Error(notice) + if (!target) throw new Error('当前图片目标尚未确认,请重新打开后操作。') + + const marker: ImageRequestMarker = { + id: `${Date.now()}:${revision.value}`, + evidence: options.evidence + } + try { + sessionStorage.setItem(prefix + target, JSON.stringify(marker)) + } catch { + throw new Error('浏览器无法保存提交记录,请检查存储设置后刷新。') + } + revision.value++ + + try { + const result = await submit() + clearMarker(target, marker.id) + return result + } catch (cause) { + // 断线、网关超时、畸形回执或审核后保存冲突继续待核查。 + if (cause instanceof ApiError && options.rejectionStatuses?.includes(cause.status)) + clearMarker(target, marker.id) + throw cause + } +} + +/** + * 同镜头的新候选与原指纹相符,且下载恢复已经验证成功时解除保护。 + * @param target 恢复候选所属镜头的正式目标 + * @param candidateId 服务确认已恢复的候选编号 + * @param fingerprint 该候选生成时的正式输入指纹 + */ +export function releaseRecoveredImageRequest(target: string, candidateId: string, fingerprint?: string | null) { + const marker = readMarker(target) + if (!marker || typeof marker === 'string' || !fingerprint) return + if ( + marker.evidence?.previewFingerprint === fingerprint && + Array.isArray(marker.evidence.previousCandidateIds) && + !marker.evidence.previousCandidateIds.includes(candidateId) + ) + clearMarker(target, marker.id) +} diff --git a/tests/features/production/public-assets.test.ts b/tests/features/production/public-assets.test.ts index 0cd34be..d21d1e8 100644 --- a/tests/features/production/public-assets.test.ts +++ b/tests/features/production/public-assets.test.ts @@ -61,6 +61,15 @@ const record = (workflowName: string, day: number, status: 'running' | 'complete } }) +/** + * 定位候选弹窗内的真实按钮。 + * @param label 按钮文本 + * @returns 对应的按钮 + */ +function recoveryButton(label: string) { + return [...document.querySelectorAll('button')].find(item => item.textContent?.trim() === label)! +} + describe('精简公开资产回归', () => { it('无内部字段的视频可播放,晋升使用后端权限,会话通过不能授权', async () => { const projectId = 'public-video-contract' @@ -156,6 +165,135 @@ describe('精简公开资产回归', () => { } }) + it.each([false, true])('只为本次恢复成功的首帧解锁(恢复回执丢失 %s)', async lostReceipt => { + const projectId = 'keyframe-download-guard' + const targetShot = { ...shot, shotId: 'download-guard-shot-' + lostReceipt } + const fingerprint = 'a'.repeat(64) + /** 已保存的失败候选,恢复目标绑定相同指纹及正式镜头。 */ + const failed = keyframeFixture({ + id: 'recover-current', + shotId: targetShot.shotId, + status: 'failed', + isPrimary: false, + imageUrl: null, + providerInputFingerprint: fingerprint, + recoveryRequired: true, + canRecoverSavedResult: true + }) + const historical = keyframeFixture({ + id: 'recover-history', + shotId: targetShot.shotId, + status: 'failed', + isPrimary: false, + imageUrl: null, + providerInputFingerprint: fingerprint, + recoveryRequired: false, + canRecoverSavedResult: true + }) + let rows = [historical] + let attempts = 0 + const fetcher = vi.fn().mockImplementation(async (url, init) => { + const path = String(url) + if (path.endsWith('/generation-models')) return Response.json({ data: imageCatalog }) + if (path.endsWith('/creative-profile')) return Response.json({ data: generationProfile(projectId) }) + if (path.endsWith('/keyframes')) return Response.json({ data: rows }) + if (path.endsWith('/keyframe/preview')) + return Response.json({ + data: { + shotId: targetShot.shotId, + provider: 'qwen-image', + model: 'qwen-image-3.0-pro', + generationConfig: {}, + referenceImages: [], + providerPrompt: '已确认预览', + previewFingerprint: fingerprint + } + }) + if (path.endsWith('/keyframe') && init?.method === 'POST') { + rows = [historical, failed] + if (lostReceipt) return Response.json({ data: { shotId: targetShot.shotId } }) + return Response.json({ message: '图片已生成但下载失败' }, { status: 500 }) + } + if (path.endsWith('/recover-saved-result')) { + const target = path.includes(historical.id) ? historical : failed + if (target.id === failed.id && ++attempts === 1) + return Response.json({ message: '本次下载恢复失败' }, { status: 503 }) + const recovered = { + ...target, + status: 'completed' as const, + imageUrl: '/storage/recovered.png', + recoveryRequired: false, + canRecoverSavedResult: false, + recoveryReason: 'provider_result_recovered' + } + rows = rows.map(item => (item.id === target.id ? recovered : item)) + if (target.id === failed.id && lostReceipt) + return Response.json({ message: '下载已恢复,回执连接中断' }, { status: 504 }) + return Response.json({ data: recovered }) + } + return Response.json({ data: [] }) + }) + vi.stubGlobal('fetch', fetcher) + const wrapper = mount(ShotProductionAssets, { + attachTo: document.body, + props: { + projectId, + shot: targetShot, + disabled: false, + keyframeReadiness: { + shotId: targetShot.shotId, + status: 'ready', + issues: [], + episodeNo: 1, + beatNo: 1, + shotNo: 1 + } + } + }) + /** 模拟同标签页刷新时仍可读取的提交标记。 */ + const lock = () => sessionStorage.getItem('short-drama:image-request-unknown:keyframe:' + targetShot.shotId) + try { + await flushPromises() + recoveryButton('生成首帧候选').click() + await flushPromises() + recoveryButton('预览实际生成输入').click() + await flushPromises() + document.querySelector('#confirm-keyframe-cost')!.click() + await flushPromises() + recoveryButton('确认生成首帧').click() + await flushPromises() + expect(lock()).not.toBeNull() + recoveryButton('取消').click() + await flushPromises() + recoveryButton('管理候选(2)').click() + await flushPromises() + recoveryButton('恢复已生成图片').click() + await flushPromises() + expect(lock()).not.toBeNull() + recoveryButton('恢复已生成图片').click() + await flushPromises() + expect(lock()).not.toBeNull() + recoveryButton('恢复已生成图片').click() + await flushPromises() + expect(lock()).toBeNull() + recoveryButton('关闭').click() + await flushPromises() + recoveryButton('生成首帧候选').click() + await flushPromises() + recoveryButton('预览实际生成输入').click() + await flushPromises() + document.querySelector('#confirm-keyframe-cost')!.click() + await flushPromises() + expect(recoveryButton('确认生成首帧').disabled).toBe(false) + expect( + fetcher.mock.calls.filter(([url, init]) => String(url).endsWith('/keyframe') && init?.method === 'POST') + ).toHaveLength(1) + } finally { + wrapper.unmount() + sessionStorage.removeItem('short-drama:image-request-unknown:keyframe:' + targetShot.shotId) + } + }) + it('主页面只展示主首帧,候选通过质量检查后才允许晋升', async () => { const projectId = 'keyframe-promotion-contract' const primary = keyframeFixture() diff --git a/tests/features/subject-images/generation-preview.test.ts b/tests/features/subject-images/generation-preview.test.ts index 91cc700..11170f1 100644 --- a/tests/features/subject-images/generation-preview.test.ts +++ b/tests/features/subject-images/generation-preview.test.ts @@ -135,6 +135,30 @@ describe('生图预览与版本确认', () => { expect(restored.recoveryNotice.value).toContain('费用待核对') expect(generate).toHaveBeenCalledOnce() }) + it('发出生成请求前先持久化标记,未回执时重开不能再次提交', async () => { + const key = 'short-drama:image-request-unknown:form:in-flight' + let finish!: (value: ImageGenerationSubmission) => void + const generate = vi.fn<() => Promise>( + () => + new Promise(resolve => { + finish = resolve + }) + ) + const first = setup(generate, undefined, 'form:in-flight').flow + await first.loadPreview() + first.acknowledged.value = true + const request = first.submit() + expect(sessionStorage.getItem(key)).not.toBeNull() + wrapper?.unmount() + const restored = setup(generate, undefined, 'form:in-flight').flow + await restored.loadPreview() + restored.acknowledged.value = true + await restored.submit() + expect(generate).toHaveBeenCalledTimes(1) + finish({ accepted: true }) + await request + expect(sessionStorage.getItem(key)).toBeNull() + }) it('关闭再打开相同参数后,旧预览响应不得回填', async () => { let resolve!: (value: ReturnType) => void const { flow, open } = setup( diff --git a/tests/features/subject-images/quality-flow.test.ts b/tests/features/subject-images/quality-flow.test.ts index 7a84863..f6005a8 100644 --- a/tests/features/subject-images/quality-flow.test.ts +++ b/tests/features/subject-images/quality-flow.test.ts @@ -1,5 +1,6 @@ import { validationPreviewResponse } from '../../fixtures/image-preview' import { mount, flushPromises, type VueWrapper } from '@vue/test-utils' +import { defineComponent, h } from 'vue' import { afterEach, describe, expect, it, vi } from 'vitest' import ImageGalleryDialog from '@/features/subject-images/components/ImageGalleryDialog.vue' import { getOperation } from '@/features/workflows/operations' @@ -97,6 +98,65 @@ describe('候选质量与主图门禁', () => { expect(button('设为主参考图').disabled).toBe(true) expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true) }) + it.each([504, 409])('审核回执 %s 后锁定同一候选的付费操作,重开图库仍保持锁定', async status => { + const image = imageFixture({ id: 'unknown-review-' + status, isPrimary: false, qualityPassed: true }) + const fetcher = vi.fn().mockImplementation(async (url, init) => { + if (String(url).endsWith('/validate/preview')) return validationPreviewResponse(String(url)) + if (init?.method === 'POST') return new Response(JSON.stringify({ message: '审核结果待核对' }), { status }) + return Response.json({ data: [image] }) + }) + vi.stubGlobal('fetch', fetcher) + const props = { projectId: 'quality-flow', form: formFixture(), disabled: false, open: true } + /** 正式父页在项目请求进行中会同步禁用图库写入。 */ + const parent = defineComponent({ + setup: () => () => h(ImageGalleryDialog, { ...props, disabled: getOperation(props.projectId).pending }) + }) + wrapper = mount(parent, { attachTo: document.body }) + await flushPromises() + button('审核此图片').click() + await flushPromises() + button('确认费用并审核').click() + await flushPromises() + wrapper.unmount() + wrapper = mount(parent, { attachTo: document.body }) + await flushPromises() + expect(document.body.textContent).toContain('费用待核对') + expect(button('审核此图片').disabled).toBe(true) + expect(button('审核与修复').disabled).toBe(true) + expect(button('设为主参考图').disabled).toBe(true) + button('刷新图片').click() + await flushPromises() + expect(button('审核此图片').disabled).toBe(true) + expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1) + }) + + it.each(['刷新图片', '确认费用并审核'])('同一候选来源变化后,%s 重新预检并阻止付费请求', async action => { + let current = true + const image = imageFixture({ id: 'stale-after-open', isPrimary: false, qualityPassed: true }) + const fetcher = vi + .fn() + .mockImplementation(async url => + String(url).endsWith('/validate/preview') + ? validationPreviewResponse(String(url), current) + : Response.json({ data: [image] }) + ) + vi.stubGlobal('fetch', fetcher) + wrapper = mount(ImageGalleryDialog, { + attachTo: document.body, + props: { projectId: 'quality-flow', form: formFixture(), disabled: false, open: true } + }) + await flushPromises() + expect(button('审核此图片').disabled).toBe(false) + button('审核此图片').click() + await flushPromises() + current = false + button(action).click() + await flushPromises() + expect(document.body.textContent).toContain('本次机位采用的几何已过期') + expect(button('审核此图片').disabled).toBe(true) + expect(button('设为主参考图').disabled).toBe(true) + expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true) + }) it('主图晋升 409 保留原主图,不乐观切换或自动重试', async () => { const original = imageFixture({ id: 'old' }) const fetcher = vi.fn().mockImplementation(async (url, init) =>