fix(short-drama-agent-front): 修复图片重复提交与首帧恢复

This commit is contained in:
GJ committed 2026-11-04 15:10:20 +08:00
1 parent b88ad8770f
commit ecb0423153
8 files changed
+508 -85

No files matched your search

@@ -33,6 +33,8 @@ const props = defineProps<{
direction?: ShotDirection | null
/** 当前镜头的正式画面即时状态。 */
visualState?: ShotVisualState | null
/** 提交前已有候选,用于区分下载恢复与历史候选。 */
previousCandidateIds?: readonly string[]
/** 仅发送已经确认的当前快照。 */
submitGeneration: (input: GenerateKeyframeInput) => Promise<ImageGenerationSubmission>
}>()
@@ -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,
@@ -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"
/>
</section>
@@ -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() {
>
<div class="flex items-center justify-between gap-3">
<span class="text-xs text-muted">{{ images.length }} 条图片记录</span
><NButton :disabled="query.loading.value || !!pending" @click="query.refresh" text size="small"
><NButton
:disabled="query.loading.value || source.loading.value || !!pending"
@click="refreshImages"
text
size="small"
><RefreshCw :size="13" :class="{ 'animate-spin': query.loading.value }" />刷新图片
</NButton>
</div>
@@ -370,6 +420,10 @@ async function confirmAction() {
title="该候选的实际生成输入"
:value="source.data.value.providerInputSnapshot"
/>
<!-- 以下是待核查的提交状态,保留候选和只读刷新。 -->
<ContextNotice v-if="reviewNotice && !pending" type="warning" :show-icon="false" class="mt-3">
{{ reviewNotice }}
</ContextNotice>
<!-- 以下是明确费用的候选审核和主图操作模块 -->
<div class="mt-4 flex flex-wrap items-center gap-3">
<NButton
@@ -472,9 +526,7 @@ async function confirmAction() {
}}
</ContextNotice>
<div v-if="confirming === 'quality'" class="mt-4 space-y-2">
<label for="quality-repair-budget" class="block text-xs"
>最多额外生成次数(0 表示只审核,不追加生图)</label
>
<label for="quality-repair-budget" class="block text-xs">最多额外生成次数(0 表示不追加生图)</label>
<NInputNumber
:input-props="{ id: 'quality-repair-budget' }"
v-model:value="maxRepairAttempts"
@@ -1,5 +1,6 @@
import { computed, onBeforeUnmount, ref, shallowRef, watch, type Ref } from 'vue'
import { ApiError, errorMessage } from '../../lib/http'
import { imageRequestNotice, runGuardedImageRequest } from './image-request-guard'
/** 同一张实际参考图可承担多个来源职责。 */
export interface ImageReferenceBinding {
@@ -87,6 +88,8 @@ interface PreviewOptions<Input extends object, Preview extends ImageGenerationPr
target: () => string
/** 跨表单开关稳定的计费核对目标。 */
recoveryTarget?: () => string
/** 首帧提交前已有候选,供恢复时区分历史记录。 */
previousCandidateIds?: () => readonly string[] | undefined
/** 当前完整生成参数。 */
input: () => Input
/** 当前是否允许提交。 */
@@ -97,39 +100,6 @@ interface PreviewOptions<Input extends object, Preview extends ImageGenerationPr
generate: (input: Input & { expectedPreviewFingerprint: string }) => Promise<ImageGenerationSubmission>
}
/** 同一浏览器标签页的待核对目标。记录不含提示词、图片或确认状态。 */
const unresolvedGenerations = ref(new Set<string>())
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<Input extends object, Preview extends
/** 核对范围只绑定正式目标,切换参数不会解除。 */
const recoveryKey = computed(() => 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<Input extends object, Preview extends
const input = JSON.parse(JSON.stringify(options.input())) as Input
const fingerprint = preview.value.previewFingerprint
const recoveryTarget = recoveryKey.value
const previousCandidateIds = options.previousCandidateIds?.()
submitting.value = true
error.value = ''
let result: ImageGenerationSubmission
try {
result = await options.generate({ ...input, expectedPreviewFingerprint: fingerprint })
result = await runGuardedImageRequest(
recoveryTarget,
async () => {
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
@@ -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<T>(
target: string,
submit: () => Promise<T>,
options: ImageRequestGuardOptions = {}
): Promise<T> {
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)
}