feat(short-drama-agent-front): 完善视觉资产审核流程

This commit is contained in:
GJ committed 2026-11-04 14:09:21 +08:00
1 parent dc8bb17a23
commit b88ad8770f
45 files changed
+2258 -352

No files matched your search

+9
View File
@@ -24,6 +24,7 @@ import StoryboardList from './components/StoryboardList.vue'
import StoryboardDiagnosis from './components/StoryboardDiagnosis.vue' import StoryboardDiagnosis from './components/StoryboardDiagnosis.vue'
import BreakdownCandidatePanel from './components/BreakdownCandidatePanel.vue' import BreakdownCandidatePanel from './components/BreakdownCandidatePanel.vue'
import StoryboardQualityRepair from './components/StoryboardQualityRepair.vue' import StoryboardQualityRepair from './components/StoryboardQualityRepair.vue'
import BreakdownDurationDiagnostics from './components/BreakdownDurationDiagnostics.vue'
import BreakdownIssuesDialog from './components/BreakdownIssuesDialog.vue' import BreakdownIssuesDialog from './components/BreakdownIssuesDialog.vue'
import CandidateRepairs from './components/CandidateRepairs.vue' import CandidateRepairs from './components/CandidateRepairs.vue'
import ActionExceptionRepair from './components/ActionExceptionRepair.vue' import ActionExceptionRepair from './components/ActionExceptionRepair.vue'
@@ -1119,6 +1120,14 @@ const isInitialEmpty = computed(
@locate="locateIssue" @locate="locateIssue"
@refresh="refreshCandidate" @refresh="refreshCandidate"
> >
<!-- 以下是失败候选与正式时长来源的只读核对 -->
<template #duration>
<BreakdownDurationDiagnostics
v-if="issuesOpen && projectId"
:project-id="projectId"
:checkpoint-id="latestCheckpoint?.checkpointId"
/>
</template>
<!-- 以下是只属于问题处理的人工修订与阶段恢复,不混入拆解启动配置 --> <!-- 以下是只属于问题处理的人工修订与阶段恢复,不混入拆解启动配置 -->
<template #repair> <template #repair>
<p v-if="breakdownBusy || operation.pending" role="status" class="text-xs leading-6 text-muted"> <p v-if="breakdownBusy || operation.pending" role="status" class="text-xs leading-6 text-muted">
+4 -1
View File
@@ -3,6 +3,7 @@ import type { CandidateCommitPreview, CandidateCommitCheckPreview } from './cand
/** 安全检查项与用户可理解的阻断原因共用一份映射。 */ /** 安全检查项与用户可理解的阻断原因共用一份映射。 */
export const candidateCheckLabels: Record<keyof CandidateCommitCheckPreview['checks'], string> = { export const candidateCheckLabels: Record<keyof CandidateCommitCheckPreview['checks'], string> = {
durationBudgetCurrent: '候选预算与当前正式时长一致',
qualityPolicyMatches: '质量规则与当前已确认版本一致', qualityPolicyMatches: '质量规则与当前已确认版本一致',
episodeNumbersMatch: '剧集范围与候选一致', episodeNumbersMatch: '剧集范围与候选一致',
episodeFingerprintsMatch: '剧本正文版本未变化', episodeFingerprintsMatch: '剧本正文版本未变化',
@@ -16,6 +17,7 @@ export const candidateCheckLabels: Record<keyof CandidateCommitCheckPreview['che
/** 必须逐项校验的固定安全门禁,不根据响应动态减少检查项。 */ /** 必须逐项校验的固定安全门禁,不根据响应动态减少检查项。 */
export const candidateCheckKeys = [ export const candidateCheckKeys = [
'qualityPolicyMatches', 'qualityPolicyMatches',
'durationBudgetCurrent',
'episodeNumbersMatch', 'episodeNumbersMatch',
'episodeFingerprintsMatch', 'episodeFingerprintsMatch',
'noActiveExecutions', 'noActiveExecutions',
@@ -42,7 +44,8 @@ export function candidatePreviewReady(
!preview || !preview ||
preview.status === 'already_committed' || preview.status === 'already_committed' ||
preview.projectId !== projectId || preview.projectId !== projectId ||
preview.checkpointId !== checkpointId preview.checkpointId !== checkpointId ||
!!preview.durationSourceIssue
) )
return false return false
// 外部 JSON 的布尔值必须严格为 true,不接受缺失值或字符串等真值。 // 外部 JSON 的布尔值必须严格为 true,不接受缺失值或字符串等真值。
@@ -147,8 +147,12 @@ export interface CandidateCommitCheckPreview {
/** 未提交分支不携带已提交状态。 */ status?: never /** 未提交分支不携带已提交状态。 */ status?: never
/** 关系来源阻断的原始说明。 */ relationIssues: string[] /** 关系来源阻断的原始说明。 */ relationIssues: string[]
/** 可供人工核对的原始关系,不代表已经确认删除。 */ relationRepairTargets: CandidateRelationTarget[] /** 可供人工核对的原始关系,不代表已经确认删除。 */ relationRepairTargets: CandidateRelationTarget[]
/** 当前正式预算来源冲突说明。 */
durationSourceIssue?: string | null
/** 剧本版本、活动任务及下游资产保护。 */ /** 剧本版本、活动任务及下游资产保护。 */
checks: { checks: {
/** 候选与正式预算版本一致。 */
durationBudgetCurrent: boolean
/** 候选使用的质量规则与当前明确确认版本一致。 */ /** 候选使用的质量规则与当前明确确认版本一致。 */
qualityPolicyMatches: boolean qualityPolicyMatches: boolean
/** 剧集编号一致。 */ /** 剧集编号一致。 */
@@ -12,6 +12,7 @@ import { breakdownApi } from '../api'
import { runOperation, getOperation } from '../../workflows/operations' import { runOperation, getOperation } from '../../workflows/operations'
import { projectsApi } from '../../projects/api' import { projectsApi } from '../../projects/api'
import { workflowCheckpoints } from '../../workflows/selectors' import { workflowCheckpoints } from '../../workflows/selectors'
import { userFacingText } from '../../../lib/user-facing-text'
import { ApiError, errorMessage } from '../../../lib/http' import { ApiError, errorMessage } from '../../../lib/http'
import { showActionFeedback, useActionMessage } from '../../../components/ui/useActionMessage' import { showActionFeedback, useActionMessage } from '../../../components/ui/useActionMessage'
@@ -86,6 +87,7 @@ const ready = computed(() => candidatePreviewReady(preview.value, props.projectI
const failedChecks = computed(() => const failedChecks = computed(() =>
current.value ? candidateCheckKeys.filter(key => current.value!.checks?.[key] !== true) : [] current.value ? candidateCheckKeys.filter(key => current.value!.checks?.[key] !== true) : []
) )
/** 原始关系只能来自本次安全预检,不解析问题字符串构造删除参数。 */ /** 原始关系只能来自本次安全预检,不解析问题字符串构造删除参数。 */
const targets = computed(() => current.value?.relationRepairTargets ?? []) const targets = computed(() => current.value?.relationRepairTargets ?? [])
/** 用户选择的关系仍需校验完整且定位唯一。 */ /** 用户选择的关系仍需校验完整且定位唯一。 */
@@ -398,6 +400,10 @@ async function commit() {
</section> </section>
</section> </section>
<!-- 以下是后端返回的关系问题与正式原文,窄屏自然改为单列 --> <!-- 以下是后端返回的关系问题与正式原文,窄屏自然改为单列 -->
<!-- 以下是正式时长预算的来源冲突 -->
<p v-if="current.durationSourceIssue" class="text-sm text-danger">
{{ userFacingText(current.durationSourceIssue) }}
</p>
<div v-if="targets.length || current.relationIssues?.length" class="grid min-w-0 gap-6 lg:grid-cols-2"> <div v-if="targets.length || current.relationIssues?.length" class="grid min-w-0 gap-6 lg:grid-cols-2">
<section class="min-w-0 space-y-4" aria-label="无来源关系"> <section class="min-w-0 space-y-4" aria-label="无来源关系">
<WorkspaceSectionHeading <WorkspaceSectionHeading
@@ -0,0 +1,192 @@
<script setup lang="ts">
import { computed } from 'vue'
import { NButton, NCollapse, NCollapseItem } from 'naive-ui'
import RawDataDetails from '../../../components/ui/RawDataDetails.vue'
import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHeading.vue'
import { useQuery } from '../../../composables/useQuery'
import { userFacingText } from '../../../lib/user-facing-text'
import { projectsApi } from '../../projects/api'
import { breakdownApi } from '../api'
import type { BreakdownDurationFailure, EpisodeShots } from '../types'
/** 时长诊断使用最新候选证据和正式预算的独立只读来源。 */
const props = defineProps<{
/** 当前项目编号。 */ projectId: string
/** 当前保存记录变化时刷新。 */ checkpointId?: string
}>()
/** 查询随保存记录更新,旧候选不会回填当前任务。 */
const key = computed(() => JSON.stringify([props.projectId, props.checkpointId]))
/** 正式结果和候选诊断独立读取,保留某一来源暂不可用时的另一份结果。 */
const query = useQuery(key, async (value, signal) => {
const [projectId] = JSON.parse(value) as [string, string?]
const [formal, latest] = await Promise.allSettled([
projectsApi.durationBudget(projectId, signal),
breakdownApi.latest(projectId, signal)
])
if (formal.status === 'fulfilled' && formal.value.projectId !== projectId)
throw new Error('时长资料与当前项目不匹配。')
if (latest.status === 'fulfilled' && latest.value?.projectId && latest.value.projectId !== projectId)
throw new Error('失败记录与当前项目不匹配。')
return { formal, latest }
})
/** 正式预算来自当前项目服务,包含尚无镜头的正式剧集。 */
const formal = computed(() =>
query.data.value?.formal.status === 'fulfilled' ? query.data.value.formal.value.episodes : []
)
/** 最新失败候选和原始预算快照保留用于诊断。 */
const latest = computed(() => (query.data.value?.latest.status === 'fulfilled' ? query.data.value.latest.value : null))
/** 只选最新记录中实际返回的完整失败候选。 */
const failures = computed(() => {
const entries = latest.value?.failureDetails?.details
return Array.isArray(entries)
? entries.filter(
(item): item is BreakdownDurationFailure =>
item?.kind === 'storyboard-duration-failure' &&
item.candidate?.episodePlan &&
Array.isArray(item.candidate?.beatShots)
)
: []
})
/**
* 失败时可能尚未产出预算审计,按已返回的镜头阶段估算供复盘。
* @param candidate 服务器返回的失败候选
* @returns 只读估算,不用于通过审核或修改正式分镜
*/
function estimateFailedBudget(candidate: EpisodeShots) {
const beatSuggestions = candidate.beatShots.flatMap(beat => {
const budget = candidate.episodePlan.beats.find(item => item.beatNo === beat.beatNo)?.estimatedDurationSeconds
if (!budget || !beat.shots.length) return []
const required = beat.shots.reduce((sum, shot) => {
const planning = shot.durationPlanning
const estimated = planning?.phases.reduce(
(total, phase) => total + phase.estimatedSeconds,
planning.transitionSeconds
)
const supported =
planning && estimated !== undefined && Math.abs(estimated - planning.recommendedDurationSeconds) <= 0.1
return sum + (supported ? Math.max(shot.durationSeconds, estimated) : shot.durationSeconds)
}, 0)
return [
{
beatNo: beat.beatNo,
requiredSeconds: Number(required.toFixed(2)),
deficitSeconds: required > budget + 0.1 ? Number((required - budget).toFixed(2)) : 0
}
]
})
if (!beatSuggestions.length) return undefined
return {
beatSuggestions,
minimumRequiredSeconds: Number(beatSuggestions.reduce((sum, beat) => sum + beat.requiredSeconds, 0).toFixed(2)),
deficitSeconds: Number(beatSuggestions.reduce((sum, beat) => sum + beat.deficitSeconds, 0).toFixed(2)),
estimated: true
}
}
/** 对应候选规划的目标版本、所有段落预算与已知缺口。 */
const plans = computed(() => {
const items = new Map((latest.value?.storyboardPlans ?? []).map(plan => [plan.episodeNo, plan]))
for (const failure of failures.value) items.set(failure.episodeNo, failure.candidate.episodePlan)
return [...items.values()].map(plan => ({
...plan,
report:
latest.value?.storyboardEpisodeDurationBudgets?.find(item => item.episodeNo === plan.episodeNo) ??
failures.value
.filter(item => item.episodeNo === plan.episodeNo)
.map(item => estimateFailedBudget(item.candidate))[0],
formal: formal.value.find(item => item.episodeNo === plan.episodeNo)
}))
})
</script>
<template>
<!-- 以下是正式时长与候选来源的只读诊断 -->
<section class="space-y-4" aria-label="时长预算诊断">
<WorkspaceSectionHeading
title="时长预算"
description="分别核对正式剧集目标和拆解时采用的预算。失败候选可用于复盘。"
/>
<p v-if="query.loading.value" class="text-sm text-muted">正在读取时长预算…</p>
<div v-else-if="query.error.value" class="space-y-2 text-sm">
<p>{{ query.error.value }}</p>
<NButton size="small" @click="query.refresh">重新读取预算</NButton>
</div>
<template v-else>
<p
v-if="query.data.value?.formal.status === 'rejected' || query.data.value?.latest.status === 'rejected'"
class="text-sm text-muted"
>
部分时长来源暂时无法读取。<NButton text size="small" @click="query.refresh">重新读取</NButton>
</p>
<ul v-if="formal.length" class="grid gap-2 sm:grid-cols-2 text-sm">
<li v-for="episode in formal" :key="episode.episodeNo">
第 {{ episode.episodeNo }} 集 · 正式目标
{{ episode.targetDurationSeconds == null ? '自动' : `${episode.targetDurationSeconds} 秒` }} ·
正式镜头
{{ episode.shotCount && episode.shotSeconds != null ? `${episode.shotSeconds} 秒` : '未生成' }}
</li>
</ul>
<NCollapse v-if="plans.length">
<NCollapseItem
v-for="plan in plans"
:key="plan.episodeNo"
:name="plan.episodeNo"
:title="`第 ${plan.episodeNo} 集 · 拆解预算快照`"
>
<div class="space-y-2 text-sm">
<p>
拆解时目标
{{
plan.targetDurationSeconds === undefined
? '历史未记录'
: plan.targetDurationSeconds === null
? '自动'
: `${plan.targetDurationSeconds} 秒`
}}
</p>
<p
v-if="plan.formal && plan.targetDurationSeconds !== plan.formal.targetDurationSeconds"
class="text-danger"
>
{{
plan.targetDurationSeconds === undefined
? '缺少原预算快照,请核对来源。'
: '拆解后的正式目标已变化,请核对来源。'
}}
</p>
<p v-if="plan.report">
<span v-if="'estimated' in plan.report">根据失败候选估算 · </span>动作最低需求
{{ plan.report.minimumRequiredSeconds }} 秒 · 段落缺口合计
{{ plan.report.deficitSeconds }} 秒
</p>
<ul class="space-y-2">
<li v-for="beat in plan.beats" :key="beat.beatNo">
段落 {{ beat.beatNo }} · {{ beat.title }} · 预算 {{ beat.estimatedDurationSeconds }} 秒
<span
v-for="gap in plan.report?.beatSuggestions.filter(
item => item.beatNo === beat.beatNo
)"
:key="gap.beatNo"
:class="{ 'text-danger': gap.deficitSeconds > 0 }"
>
· 最低需求 {{ gap.requiredSeconds }} 秒 · 缺口 {{ gap.deficitSeconds }} 秒
</span>
</li>
</ul>
</div>
</NCollapseItem>
</NCollapse>
<p
v-if="failures.length && latest?.workflowExecution?.errorMessage"
class="text-sm text-danger wrap-anywhere"
>
{{ userFacingText(latest.workflowExecution.errorMessage) }}
</p>
<RawDataDetails
v-for="(failure, index) in failures"
:key="index"
:title="`第 ${failure.episodeNo} 集 · 完整失败候选`"
:value="failure"
/>
</template>
</section>
</template>
@@ -68,6 +68,8 @@ const groups = computed(() => {
const count = computed(() => groups.value.reduce((total, group) => total + group.messages.length, 0)) const count = computed(() => groups.value.reduce((total, group) => total + group.messages.length, 0))
/** 等待离场后执行的定位。 */ /** 等待离场后执行的定位。 */
const pendingLocation = ref<ShotValidation['issues'][number] | null>(null) const pendingLocation = ref<ShotValidation['issues'][number] | null>(null)
/** 时长资料按需读取,与其它问题查询独立。 */
const diagnosticSections = ref<string[]>([])
/** /**
* 关闭问题抽屉后定位到对应剧集、节拍或镜头。 * 关闭问题抽屉后定位到对应剧集、节拍或镜头。
@@ -104,6 +106,12 @@ function finish() {
><span v-else-if="count">{{ count }} 项校验问题 · {{ groups.length }} 个位置</span ><span v-else-if="count">{{ count }} 项校验问题 · {{ groups.length }} 个位置</span
><span v-else>查看最近保存结果中的问题</span></template ><span v-else>查看最近保存结果中的问题</span></template
> >
<!-- 以下是独立的上游时长诊断 -->
<NCollapse v-if="$slots.duration" v-model:expanded-names="diagnosticSections" class="mb-5">
<NCollapseItem name="duration" title="查看时长预算与失败候选">
<slot v-if="diagnosticSections.includes('duration')" name="duration" />
</NCollapseItem>
</NCollapse>
<!-- 以下是当前版本的分类问题,历史错误不会混入当前问题数量 --> <!-- 以下是当前版本的分类问题,历史错误不会混入当前问题数量 -->
<div v-if="quality" class="space-y-5" :aria-busy="quality.loading"> <div v-if="quality" class="space-y-5" :aria-busy="quality.loading">
<p v-if="quality.loading" class="text-sm text-muted" role="status">正在读取当前候选审核…</p> <p v-if="quality.loading" class="text-sm text-muted" role="status">正在读取当前候选审核…</p>
+32
View File
@@ -93,6 +93,8 @@ export interface StoryboardBeat {
/** 单集分镜规划。 */ /** 单集分镜规划。 */
export interface EpisodePlan { export interface EpisodePlan {
/** 正式时长目标快照,空值为自动,缺失为历史未记录。 */
targetDurationSeconds?: number | null
episodeNo: number episodeNo: number
episodeTitle: string episodeTitle: string
storyGoal: string storyGoal: string
@@ -131,6 +133,30 @@ export interface ShotValidation {
issues: { episodeNo: number; beatNo?: number | null; shotNo?: number | null; message: string }[] issues: { episodeNo: number; beatNo?: number | null; shotNo?: number | null; message: string }[]
} }
/** 当前拆解候选的只读时长审计。 */
export interface BreakdownDurationBudget {
/** 正式集数。 */ episodeNo: number
/** 已规划的段落预算之和。 */ plannedSeconds: number
/** 当前镜头及动作所需最低总时长。 */ minimumRequiredSeconds: number
/** 局部段落缺口之和。 */ deficitSeconds: number
/** 局部段落的预算及缺口。 */
beatSuggestions: Array<{
/** 段落号。 */ beatNo: number
/** 原段落预算。 */ budgetSeconds: number
/** 最低需求。 */ requiredSeconds: number
/** 当前缺口。 */ deficitSeconds: number
}>
/** 当前需要人工核对。 */ needsReview: boolean
}
/** 最新失败保存记录中的完整实际候选。 */
export interface BreakdownDurationFailure {
/** 正式候选诊断类型。 */ kind: 'storyboard-duration-failure'
/** 失败集数。 */ episodeNo: number
/** 完整候选保留供诊断。 */ candidate: EpisodeShots
/** 此失败不自动恢复。 */ retryAutomatically: false
}
/** Breakdown 的最终成果及阶段 checkpoint 共有的可展示字段。 */ /** Breakdown 的最终成果及阶段 checkpoint 共有的可展示字段。 */
export interface BreakdownResult { export interface BreakdownResult {
subjectCandidates?: SubjectCandidate[] subjectCandidates?: SubjectCandidate[]
@@ -152,6 +178,12 @@ export interface WorkflowExecution {
/** latest 和 checkpoint 的恢复状态;失败 checkpoint 可能只有 execution。 */ /** latest 和 checkpoint 的恢复状态;失败 checkpoint 可能只有 execution。 */
export interface BreakdownState extends BreakdownResult { export interface BreakdownState extends BreakdownResult {
/** 最新保存记录编号。 */
checkpointId?: string
/** 当前服务端时长审计。 */
storyboardEpisodeDurationBudgets?: BreakdownDurationBudget[]
/** 失败详情仅用于诊断,不作为恢复请求参数。 */
failureDetails?: { /** 实际失败的结构化证据。 */ details?: unknown }
/** 快照所属项目;旧版观测响应可能缺省。 */ /** 快照所属项目;旧版观测响应可能缺省。 */
projectId?: string projectId?: string
/** 当前镜头动作质量决策,不从嵌套历史成果继承。 */ /** 当前镜头动作质量决策,不从嵌套历史成果继承。 */
+1 -1
View File
@@ -77,7 +77,7 @@ const latestVideoTaskLabel = computed(() =>
: `最近视频任务:${productionStatusLabel(videoStatusItem.value?.status ?? 'not_started')}` : `最近视频任务:${productionStatusLabel(videoStatusItem.value?.status ?? 'not_started')}`
) )
/** 首帧质量任务在关闭弹窗后仍可观察,刷新页面后恢复持久化句柄。 */ /** 首帧质量任务在关闭弹窗后仍可观察,刷新页面后恢复持久化句柄。 */
const keyframeQualityExecution = useWorkflowExecution(id, 'keyframe-quality') const keyframeQualityExecution = useWorkflowExecution(id, 'keyframe-quality', { discover: true })
/** /**
* 将首帧质量启动句柄交给页面级观察器,始终保存当前原项目归属。 * 将首帧质量启动句柄交给页面级观察器,始终保存当前原项目归属。
+17 -1
View File
@@ -159,9 +159,14 @@ export const productionApi = {
keyframeSpec: (shotId: string, signal?: AbortSignal) => keyframeSpec: (shotId: string, signal?: AbortSignal) =>
request<KeyframeSpec>(`${shotPath(shotId)}/keyframe-spec`, { signal }), request<KeyframeSpec>(`${shotPath(shotId)}/keyframe-spec`, { signal }),
/** 按本次请求选择的图片模型与参数预览最终输入,不创建首帧任务。 */ /** 按本次请求选择的图片模型与参数预览最终输入,不创建首帧任务。 */
previewKeyframe: (shotId: string, input: Pick<GenerateKeyframeInput, 'provider' | 'generationOptions'>) => previewKeyframe: (
shotId: string,
input: Pick<GenerateKeyframeInput, 'provider' | 'generationOptions'>,
signal?: AbortSignal
) =>
request<KeyframeGenerationPreview>(`${shotPath(shotId)}/keyframe/preview`, { request<KeyframeGenerationPreview>(`${shotPath(shotId)}/keyframe/preview`, {
method: 'POST', method: 'POST',
signal,
body: input body: input
}), }),
generateKeyframe: (shotId: string, input: GenerateKeyframeInput) => generateKeyframe: (shotId: string, input: GenerateKeyframeInput) =>
@@ -170,6 +175,17 @@ export const productionApi = {
body: input, body: input,
timeoutMs: 0 timeoutMs: 0
}), }),
/**
* 仅恢复已有首帧的下载,不重新发起生成。
* @param shotId 当前镜头
* @param keyframeId 已保存结果的候选
* @returns 同一候选更新后的记录
*/
recoverSavedKeyframe: (shotId: string, keyframeId: string) =>
request<ShotKeyframe>(`${shotPath(shotId)}/keyframes/${encodeURIComponent(keyframeId)}/recover-saved-result`, {
method: 'POST',
timeoutMs: 0
}),
setPrimaryKeyframe: (shotId: string, keyframeId: string) => setPrimaryKeyframe: (shotId: string, keyframeId: string) =>
request<ShotKeyframe | null>(`${shotPath(shotId)}/keyframes/${encodeURIComponent(keyframeId)}/primary`, { request<ShotKeyframe | null>(`${shotPath(shotId)}/keyframes/${encodeURIComponent(keyframeId)}/primary`, {
method: 'PUT' method: 'PUT'
@@ -23,10 +23,13 @@ const props = defineProps<{
blocked: boolean blocked: boolean
/** 只在当前源图编辑任务运行期间显示局部加载。 */ /** 只在当前源图编辑任务运行期间显示局部加载。 */
editing?: boolean editing?: boolean
/** 仅本候选在下载时显示加载。 */
recovering?: boolean
validationPassed: boolean | null validationPassed: boolean | null
confirming: boolean confirming: boolean
}>() }>()
const emit = defineEmits<{ quality: []; edit: []; select: []; confirm: []; cancel: []; history: [] }>() /** 用户显式触发候选审核、确认或免费恢复。 */
const emit = defineEmits<{ recover: []; quality: []; edit: []; select: []; confirm: []; cancel: []; history: [] }>()
/** 质量状态以数据库为准;会话内检查仅在历史状态未知时兜底。 */ /** 质量状态以数据库为准;会话内检查仅在历史状态未知时兜底。 */
const reviewKey = computed(() => const reviewKey = computed(() =>
props.item.status === 'completed' ? JSON.stringify([props.shotId, props.item.id, props.reviewRevision ?? 0]) : '' props.item.status === 'completed' ? JSON.stringify([props.shotId, props.item.id, props.reviewRevision ?? 0]) : ''
@@ -37,11 +40,21 @@ const reviewQuery = useQuery(reviewKey, (value, signal) => {
return qualityApi.keyframeQualityReview(shotId, keyframeId, signal) return qualityApi.keyframeQualityReview(shotId, keyframeId, signal)
}) })
const effectiveStatus = computed(() => reviewQuery.data.value?.effectiveQualityStatus ?? 'unknown') const effectiveStatus = computed(() => reviewQuery.data.value?.effectiveQualityStatus ?? 'unknown')
/** 其余未达可用门禁的独立质量状态。 */
const reviewLabels: Record<string, string> = {
stale: '审核来源过期',
blocked: '质量受阻',
insufficient_evidence: '审核证据不足',
unknown: '质量待确认'
}
/** 旧来源或已损坏的输入证据不能被会话中的历史通过覆盖。 */
const isPassed = computed( const isPassed = computed(
() => () =>
effectiveStatus.value === 'passed' || !props.stale &&
effectiveStatus.value === 'manual_accepted' || props.item.inputSnapshotStatus !== 'invalid' &&
(effectiveStatus.value === 'unknown' && props.validationPassed === true) (effectiveStatus.value === 'passed' ||
effectiveStatus.value === 'manual_accepted' ||
(effectiveStatus.value === 'unknown' && props.validationPassed === true))
) )
const canSelect = computed( const canSelect = computed(
() => () =>
@@ -49,6 +62,8 @@ const canSelect = computed(
!!props.item.imageUrl && !!props.item.imageUrl &&
props.item.source !== 'provider_variant' && props.item.source !== 'provider_variant' &&
!props.item.isPrimary && !props.item.isPrimary &&
!props.stale &&
props.item.inputSnapshotStatus !== 'invalid' &&
isPassed.value isPassed.value
) )
</script> </script>
@@ -71,7 +86,11 @@ const canSelect = computed(
<NTag v-if="item.source !== 'provider_variant'" size="small" :bordered="false"> <NTag v-if="item.source !== 'provider_variant'" size="small" :bordered="false">
{{ item.isPrimary ? '主首帧' : '候选首帧' }} {{ item.isPrimary ? '主首帧' : '候选首帧' }}
</NTag> </NTag>
<NTag v-if="effectiveStatus === 'manual_accepted'" size="small" type="success" :bordered="false" <NTag
v-if="effectiveStatus === 'manual_accepted' && isPassed"
size="small"
type="success"
:bordered="false"
>人工已接受</NTag >人工已接受</NTag
> >
<NTag v-else-if="isPassed" size="small" type="success" :bordered="false">质量通过</NTag> <NTag v-else-if="isPassed" size="small" type="success" :bordered="false">质量通过</NTag>
@@ -87,6 +106,13 @@ const canSelect = computed(
:bordered="false" :bordered="false"
>质量未通过</NTag >质量未通过</NTag
> >
<NTag
v-else-if="item.status === 'completed' && effectiveStatus !== 'passed'"
size="small"
:bordered="false"
>
{{ reviewLabels[effectiveStatus] ?? '质量待确认' }}
</NTag>
<NTag v-if="item.source === 'provider_variant'" size="small" :bordered="false">视频参考图</NTag> <NTag v-if="item.source === 'provider_variant'" size="small" :bordered="false">视频参考图</NTag>
<NTag v-if="item.isPrimary && stale" size="small" type="warning" :bordered="false">已过期</NTag> <NTag v-if="item.isPrimary && stale" size="small" type="warning" :bordered="false">已过期</NTag>
<!-- 以下是完整尺寸信息模块,数据缺失时隐藏 --> <!-- 以下是完整尺寸信息模块,数据缺失时隐藏 -->
@@ -95,6 +121,36 @@ const canSelect = computed(
> >
</div> </div>
<IssueHint v-if="item.error" :messages="[productionMessage(item.error)]" type="error" /> <IssueHint v-if="item.error" :messages="[productionMessage(item.error)]" type="error" />
<!-- 以下是来源记录与独立的免费恢复入口 -->
<p v-if="item.inputSnapshotStatus" class="mt-2 text-xs text-muted">
{{
{ recorded: '已保存生成输入', 'not-recorded': '历史生成输入未记录', invalid: '生成输入证据已失效' }[
item.inputSnapshotStatus
]
}}
<span v-if="item.providerInputFingerprint" :title="item.providerInputFingerprint">
· {{ item.providerInputFingerprint.slice(0, 12) }}</span
>
</p>
<p v-if="item.recoveryRequired" class="mt-2 text-xs text-muted">
{{
productionMessage(
item.recoveryReason ||
(item.canRecoverSavedResult
? '可以恢复已生成图片的下载。'
: '原请求结果待核查,请先核对候选和模型服务记录。')
)
}}
</p>
<NButton
v-if="item.canRecoverSavedResult"
class="mt-2"
size="small"
:disabled="blocked || recovering"
:loading="recovering"
@click="emit('recover')"
>恢复已生成图片</NButton
>
<p class="mt-2 text-[10px] text-muted">{{ formatDate(item.createdAt) }}</p> <p class="mt-2 text-[10px] text-muted">{{ formatDate(item.createdAt) }}</p>
<div v-if="item.status === 'completed' && item.imageUrl" class="mt-2 flex flex-wrap items-center gap-3"> <div v-if="item.status === 'completed' && item.imageUrl" class="mt-2 flex flex-wrap items-center gap-3">
<NButton text size="small" @click="emit('quality')"> <NButton text size="small" @click="emit('quality')">
@@ -1,6 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { userFacingText } from '../../../lib/user-facing-text' import { userFacingText } from '../../../lib/user-facing-text'
import FeedbackMessage from '../../../components/ui/FeedbackMessage.vue' import ImageGenerationPreview from '../../subject-images/components/ImageGenerationPreview.vue'
import { useImageGenerationPreview, type ImageGenerationSubmission } from '../../subject-images/generation-preview'
import ContextNotice from '../../../components/ui/ContextNotice.vue' import ContextNotice from '../../../components/ui/ContextNotice.vue'
@@ -17,7 +18,9 @@ import GenerationModelControls from '../../generation-config/components/Generati
import { AppDialog, FieldLabel } from '../../../components/ui' import { AppDialog, FieldLabel } from '../../../components/ui'
import { errorMessage } from '../../../lib/http' import { errorMessage } from '../../../lib/http'
import { productionApi } from '../api' import { productionApi } from '../api'
import type { GenerateKeyframeInput, KeyframeGenerationPreview } from '../types' import { directionLabel } from '../../storyboard/model'
import type { ShotDirection, ShotVisualState } from '../../storyboard/types'
import type { GenerateKeyframeInput } from '../types'
/** 单镜头首帧表单;所有新图先生成候选,通过质量检查后再人工晋升。 */ /** 单镜头首帧表单;所有新图先生成候选,通过质量检查后再人工晋升。 */
const props = defineProps<{ const props = defineProps<{
@@ -26,88 +29,89 @@ const props = defineProps<{
projectId: string projectId: string
disabled: boolean disabled: boolean
replacePrimary?: boolean replacePrimary?: boolean
/** 当前镜头的正式摄影设计。 */
direction?: ShotDirection | null
/** 当前镜头的正式画面即时状态。 */
visualState?: ShotVisualState | null
/** 仅发送已经确认的当前快照。 */
submitGeneration: (input: GenerateKeyframeInput) => Promise<ImageGenerationSubmission>
}>() }>()
const open = defineModel<boolean>('open', { default: false }) const open = defineModel<boolean>('open', { default: false })
const emit = defineEmits<{ generate: [input: GenerateKeyframeInput] }>() /** 生成参数表单,用于复用字段校验。 */
const formRef = ref<InstanceType<typeof AppForm> | null>(null) const formRef = ref<InstanceType<typeof AppForm> | null>(null)
const confirmed = ref(false) /** 摄影枚举复用分镜页面的中文展示。 */
const preview = ref<KeyframeGenerationPreview | null>(null) const directionSummary = computed(() =>
const previewError = ref('') props.direction
const previewPending = ref(false) ? Object.entries(props.direction)
.filter(([, value]) => value)
.map(([field, value]) => directionLabel(value, field))
.join(' · ')
: ''
)
const generationCatalog = ref<GenerationModelCatalog | null>(null) const generationCatalog = ref<GenerationModelCatalog | null>(null)
const generationCatalogError = ref('') const generationCatalogError = ref('')
const imageProvider = ref('') const imageProvider = ref('')
const imageGenerationOptions = ref<GenerationOptions>({}) const imageGenerationOptions = ref<GenerationOptions>({})
const projectAspectRatio = ref<CreativeProfileAspectRatio>('9:16') const projectAspectRatio = ref<CreativeProfileAspectRatio>('9:16')
const canSubmit = computed(() => !props.disabled && confirmed.value) /** 预览和生成复用当前请求字段,生成时再附加版本及候选标记。 */
/** 预览仅对应当前镜头、模型和参数;请求过期后不得覆盖新配置。 */ const generationInput = computed(() => ({
const previewRequestKey = computed(() => provider: imageProvider.value || undefined,
JSON.stringify([props.shotId, imageProvider.value, imageGenerationOptions.value]) generationOptions: imageGenerationOptions.value
) }))
watch(previewRequestKey, () => { /** 首帧与主体图片使用同一套预览确认与未知费用保护。 */
preview.value = null const {
previewError.value = '' preview,
acknowledged,
loading,
submitting,
error,
staleNotice,
recoveryNotice,
canSubmit,
loadPreview,
submit
} = useImageGenerationPreview({
open,
recoveryTarget: () => (props.shotId ? 'keyframe:' + props.shotId : ''),
target: () => JSON.stringify([props.shotId, props.direction, props.visualState]),
input: () => generationInput.value,
disabled: () => props.disabled || !imageProvider.value,
load: async (input, signal) => {
const shotId = props.shotId
const result = await productionApi.previewKeyframe(shotId, input, signal)
if (result?.shotId !== shotId) throw new Error('预览结果与当前镜头不匹配。')
return result
},
generate: input => props.submitGeneration({ ...input, setPrimary: false })
}) })
/** 切换镜头或重新打开时清空费用确认;新图一律先作为候选。 */ /** 切换镜头或重新打开时只读取模型配置,忽略已关闭弹窗的结果。 */
async function reset() { watch(
confirmed.value = false [() => props.shotId, () => props.projectId, open],
preview.value = null async ([, projectId, isOpen], _, onCleanup) => {
previewError.value = '' if (!isOpen) return
previewPending.value = false const controller = new AbortController()
generationCatalogError.value = '' onCleanup(() => controller.abort())
if (!open.value) return generationCatalog.value = null
try { generationCatalogError.value = ''
const [catalog, profile] = await Promise.all([ imageProvider.value = ''
generationConfigApi.catalog(), try {
generationConfigApi.profile(props.projectId) const [catalog, profile] = await Promise.all([
]) generationConfigApi.catalog(controller.signal),
generationCatalog.value = catalog generationConfigApi.profile(projectId, controller.signal)
projectAspectRatio.value = profile?.aspectRatio ?? '9:16' ])
imageProvider.value = profile?.imageProvider || catalog.defaults.imageProvider if (controller.signal.aborted) return
const selected = catalog.images.find(item => item.provider === imageProvider.value) generationCatalog.value = catalog
imageGenerationOptions.value = { ...selected?.defaults, ...profile?.imageOptions } projectAspectRatio.value = profile?.aspectRatio ?? '9:16'
} catch (cause) { imageProvider.value = profile?.imageProvider || catalog.defaults.imageProvider
generationCatalogError.value = errorMessage(cause) const selected = catalog.images.find(item => item.provider === imageProvider.value)
} imageGenerationOptions.value = { ...selected?.defaults, ...profile?.imageOptions }
} } catch (cause) {
watch([() => props.shotId, open], reset, { immediate: true }) if (!controller.signal.aborted) generationCatalogError.value = errorMessage(cause)
/** 发送当前模型与动态生成参数;图片尺寸统一由 generationOptions.size 管理。 */
function submit() {
if (!canSubmit.value) return
emit('generate', {
provider: imageProvider.value || undefined,
generationOptions: imageGenerationOptions.value,
setPrimary: false
})
open.value = false
reset()
}
/** 读取后端最终参考图选择与 Prompt,不创建首帧候选。 */
async function loadPreview() {
if (!props.shotId || previewPending.value) return
previewPending.value = true
previewError.value = ''
const requestKey = previewRequestKey.value
try {
const result = await productionApi.previewKeyframe(props.shotId, {
provider: imageProvider.value || undefined,
generationOptions: imageGenerationOptions.value
})
if (requestKey !== previewRequestKey.value || !open.value) return
if (!result || result.shotId !== props.shotId) throw new Error('预览结果与当前镜头不匹配。')
preview.value = result
} catch (cause) {
if (requestKey === previewRequestKey.value && open.value) {
preview.value = null
previewError.value = errorMessage(cause)
} }
} finally { },
previewPending.value = false { immediate: true }
} )
}
</script> </script>
<template> <template>
@@ -115,11 +119,12 @@ async function loadPreview() {
v-model:open="open" v-model:open="open"
:title="`${replacePrimary ? '生成替代候选' : '生成首帧候选'} · ${shotTitle}`" :title="`${replacePrimary ? '生成替代候选' : '生成首帧候选'} · ${shotTitle}`"
description="新图先作为候选;完成质量检查并通过后,才能设为主首帧。" description="新图先作为候选;完成质量检查并通过后,才能设为主首帧。"
:busy="submitting"
> >
<AppForm <AppForm
ref="formRef" ref="formRef"
:model="imageGenerationOptions" :model="imageGenerationOptions"
:disabled="disabled" :disabled="disabled || submitting"
:reset-key="`${open}:${shotId}`" :reset-key="`${open}:${shotId}`"
validate-on-change validate-on-change
@submit="submit" @submit="submit"
@@ -141,7 +146,7 @@ async function loadPreview() {
:provider="imageProvider" :provider="imageProvider"
:options="imageGenerationOptions" :options="imageGenerationOptions"
:aspect-ratio="projectAspectRatio" :aspect-ratio="projectAspectRatio"
:disabled="disabled" :disabled="disabled || submitting"
@update:provider="imageProvider = $event" @update:provider="imageProvider = $event"
@update:options="imageGenerationOptions = $event" @update:options="imageGenerationOptions = $event"
/> />
@@ -149,22 +154,53 @@ async function loadPreview() {
<ContextNotice v-else-if="generationCatalogError" type="warning" :show-icon="false" class="mt-5 text-xs"> <ContextNotice v-else-if="generationCatalogError" type="warning" :show-icon="false" class="mt-5 text-xs">
生成模型目录读取失败:{{ generationCatalogError }} 生成模型目录读取失败:{{ generationCatalogError }}
</ContextNotice> </ContextNotice>
<div class="mt-5 flex flex-wrap items-center gap-3"> <!-- 以下是正式摄影设计与画面状态 -->
<NButton :loading="previewPending" @click="loadPreview">预览实际生成输入</NButton> <NCollapse v-if="direction || visualState" class="mt-5">
<span class="text-xs text-muted">只读取参考图规划与最终画面描述,不调用图片模型。</span> <NCollapseItem v-if="direction" name="direction" title="当前镜头设计">
</div> <p class="text-xs leading-6">{{ directionSummary }}</p>
<FeedbackMessage v-if="previewError" :message="previewError" /> </NCollapseItem>
<div v-if="preview" class="panel mt-3 p-4 text-xs leading-6"> <NCollapseItem v-if="visualState" name="visual-state" title="当前画面状态">
<div class="flex flex-wrap items-center gap-2"> <p class="text-xs leading-6">
<strong>{{ preview.provider }} / {{ preview.model }}</strong> {{
<NTag size="small" :bordered="false"> [
已选 {{ preview.referencePlan.selected.length }} / visualState.timeOfDay,
{{ preview.referencePlan.totalCandidates }} 张 visualState.weather,
</NTag> visualState.atmosphere,
<NTag v-if="preview.referencePlan.omitted.length" size="small" type="warning" :bordered="false"> visualState.environmentTransientState,
省略 {{ preview.referencePlan.omitted.length }} 张 visualState.continuityNote
</NTag> ]
</div> .filter(Boolean)
.join(' · ')
}}
</p>
<p v-for="subject in visualState.subjects" :key="subject.subjectId" class="mt-2 text-xs leading-6">
{{
[
subject.subjectRef,
subject.formName,
subject.position,
subject.pose,
subject.expression,
subject.gaze,
subject.transientState
]
.filter(Boolean)
.join(' · ')
}}
</p>
</NCollapseItem>
</NCollapse>
<!-- 以下是最终模型输入和正式参考资产 -->
<ImageGenerationPreview
class="mt-5"
:preview="preview"
:loading="loading"
:disabled="!imageProvider || submitting"
:error="error"
:stale-notice="staleNotice || recoveryNotice"
@load="loadPreview"
/>
<div v-if="preview" class="mt-3 text-xs leading-6">
<!-- 规格审计仅提示导演约束风险,不阻止首帧生成。 --> <!-- 规格审计仅提示导演约束风险,不阻止首帧生成。 -->
<section <section
v-if="preview.specConsistencySummary" v-if="preview.specConsistencySummary"
@@ -201,43 +237,18 @@ async function loadPreview() {
</NCollapseItem> </NCollapseItem>
</NCollapse> </NCollapse>
</section> </section>
<ul v-if="preview.referencePlan.selected.length" class="mt-3 space-y-1 text-muted">
<li v-for="item in preview.referencePlan.selected" :key="`${item.role}:${item.imageId}`">
{{ item.subjectRef }} · {{ item.role }} · <code>{{ item.imageId }}</code>
</li>
</ul>
<NCollapse class="mt-3" :default-expanded-names="['prompt']">
<NCollapseItem name="prompt" title="本次实际使用的画面描述">
<p class="mt-3 whitespace-pre-wrap">{{ preview.providerPrompt }}</p>
</NCollapseItem>
<NCollapseItem
v-if="preview.referencePlan.omitted.length"
name="omitted"
title="未进入模型的参考图"
>
<ul class="mt-3 space-y-1 text-muted">
<li v-for="item in preview.referencePlan.omitted" :key="`${item.role}:${item.imageId}`">
{{ item.subjectRef }} · {{ item.role }} · <code>{{ item.imageId }}</code>
</li>
</ul>
</NCollapseItem>
<NCollapseItem name="config" title="生成配置">
<pre class="mt-3 whitespace-pre-wrap">{{
JSON.stringify(preview.generationConfig, null, 2)
}}</pre>
</NCollapseItem>
</NCollapse>
</div> </div>
<NCheckbox <NCheckbox
id="confirm-keyframe-cost" id="confirm-keyframe-cost"
v-model:checked="confirmed" v-model:checked="acknowledged"
:disabled="!preview || submitting || !!recoveryNotice"
class="mt-5 flex items-start gap-3 text-sm leading-6" class="mt-5 flex items-start gap-3 text-sm leading-6"
>我已确认调用图片模型可能产生费用,且当前没有相同镜头的生图任务。 >我已核对实际输入,并确认本次图片生成可能产生费用。
</NCheckbox> </NCheckbox>
</AppForm> </AppForm>
<template #footer> <template #footer>
<NButton @click="open = false">取消</NButton> <NButton :disabled="submitting" @click="open = false">取消</NButton>
<NButton :disabled="disabled || !confirmed" @click="formRef?.validate(submit)" type="primary" <NButton :disabled="!canSubmit" :loading="submitting" @click="formRef?.validate(submit)" type="primary"
>确认生成首帧</NButton >确认生成首帧</NButton
> >
</template> </template>
@@ -13,7 +13,7 @@ import { ImagePlus, RefreshCw } from '@lucide/vue'
import { AssetImage } from '../../../components/ui' import { AssetImage } from '../../../components/ui'
import { usePolling } from '../../../composables/usePolling' import { usePolling } from '../../../composables/usePolling'
import { useQuery } from '../../../composables/useQuery' import { useQuery } from '../../../composables/useQuery'
import { errorMessage } from '../../../lib/http' import { ApiError, errorMessage } from '../../../lib/http'
import { candidateDialogWidth } from '../../../lib/candidate-layout' import { candidateDialogWidth } from '../../../lib/candidate-layout'
import type { DesignedShot } from '../../storyboard/types' import type { DesignedShot } from '../../storyboard/types'
import { storyboardApi } from '../../storyboard/api' import { storyboardApi } from '../../storyboard/api'
@@ -328,7 +328,7 @@ const canGeneratePrompt = computed(
const canGenerateKeyframe = computed( const canGenerateKeyframe = computed(
() => () =>
!assetBlocked.value && !assetBlocked.value &&
!keyframes.value.some(item => ['pending', 'generating'].includes(item.status)) && !keyframes.value.some(item => item.recoveryRequired || ['pending', 'generating'].includes(item.status)) &&
!!props.keyframeReadiness && !!props.keyframeReadiness &&
props.keyframeReadiness.issues.length === 0 props.keyframeReadiness.issues.length === 0
) )
@@ -442,15 +442,38 @@ async function generatePrompt() {
await refreshAll() await refreshAll()
} }
/** 调用图片模型生成单镜头首帧;成功后重新读取候选和主图。 */ /**
* 提交已确认的首帧输入,并刷新该镜头候选。
* @param input 预览绑定的生成参数
* @returns 真实提交结果与可能的冲突
*/
async function generateKeyframe(input: GenerateKeyframeInput) { async function generateKeyframe(input: GenerateKeyframeInput) {
if (!canGenerateKeyframe.value) return if (!canGenerateKeyframe.value || !input.expectedPreviewFingerprint) return { accepted: false }
const shotId = props.shot.shotId const shotId = props.shot.shotId
await runOperation(props.projectId, `生成镜头 ${props.shot.shotNo} 首帧`, async () => { const projectId = props.projectId
const accepted = await runOperation(projectId, `生成镜头 ${props.shot.shotNo} 首帧`, async () => {
const result = await productionApi.generateKeyframe(shotId, input) const result = await productionApi.generateKeyframe(shotId, input)
if (!result || result.shotId !== shotId) throw new Error('接口未确认首帧生成结果。') if (!result || result.shotId !== shotId) throw new ApiError('首帧生成结果待核对。', 200)
}) })
await refreshAll() const cause = getOperation(projectId).cause
if (props.projectId === projectId && props.shot.shotId === shotId) await refreshAll()
return { accepted, cause }
}
/**
* 恢复原候选下载,只在服务明确有可恢复结果时允许。
* @param item 当前候选
*/
async function recoverSavedKeyframe(item: ShotKeyframe) {
if (assetBlocked.value || !item.canRecoverSavedResult || item.shotId !== props.shot.shotId) return
const projectId = props.projectId
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')
throw new Error('下载结果待核对,请刷新候选。')
})
if (projectId === props.projectId && shotId === props.shot.shotId) await refreshAll()
} }
/** 切换主首帧不调用模型,但会改变后续视频生成输入。 */ /** 切换主首帧不调用模型,但会改变后续视频生成输入。 */
@@ -966,6 +989,8 @@ defineExpose({ inspectSpecs, inspecting })
:shot-id="shot.shotId" :shot-id="shot.shotId"
:review-revision="reviewRevision" :review-revision="reviewRevision"
:item="item" :item="item"
:recovering="isOperationRunning(getOperation(projectId), `恢复已生成首帧 ${item.id}`)"
@recover="recoverSavedKeyframe(item)"
:editing=" :editing="
editSource?.id === item.id && editSource?.id === item.id &&
isOperationRunning(getOperation(projectId), `编辑镜头 ${shot.shotId} 首帧`) isOperationRunning(getOperation(projectId), `编辑镜头 ${shot.shotId} 首帧`)
@@ -1054,8 +1079,10 @@ defineExpose({ inspectSpecs, inspecting })
:shot-title="shot.title" :shot-title="shot.title"
:project-id="projectId" :project-id="projectId"
:replace-primary="keyframeStale" :replace-primary="keyframeStale"
:direction="shot.direction"
:visual-state="shot.visualState"
:disabled="!canGenerateKeyframe" :disabled="!canGenerateKeyframe"
@generate="generateKeyframe" :submit-generation="generateKeyframe"
/> />
</section> </section>
</template> </template>
+17 -15
View File
@@ -1,3 +1,4 @@
import type { ImageGenerationPreview } from '../subject-images/generation-preview'
import type { GenerationOptions, ResolvedGenerationConfig } from '../generation-config/types' import type { GenerationOptions, ResolvedGenerationConfig } from '../generation-config/types'
/** 项目生产链的就绪状态;进行中只会出现在视频阶段。 */ /** 项目生产链的就绪状态;进行中只会出现在视频阶段。 */
@@ -141,6 +142,16 @@ export interface VideoReadiness {
/** 首帧生成记录;成功图片与失败历史都保留。 */ /** 首帧生成记录;成功图片与失败历史都保留。 */
export interface ShotKeyframe { export interface ShotKeyframe {
/** 持久化的实际输入状态。 */
inputSnapshotStatus?: 'recorded' | 'not-recorded' | 'invalid'
/** 当次实际输入指纹。 */
providerInputFingerprint?: string | null
/** 中断后需核查已有请求。 */
recoveryRequired?: boolean
/** 保存的恢复原因。 */
recoveryReason?: string | null
/** 仅允许下载已知生成结果。 */
canRecoverSavedResult?: boolean
id: string id: string
shotId: string shotId: string
source: string | null source: string | null
@@ -221,15 +232,8 @@ export type ImageReferenceRole =
| 'style-prop' | 'style-prop'
| 'identity-anchor' | 'identity-anchor'
| 'form-primary' | 'form-primary'
| 'scene-form-view'
export interface KeyframePreviewReference { | 'layout-master'
originalImageNumber: number
subjectRef: string
module: string
role: ImageReferenceRole
imageId: string
imageUrl: string
}
export interface KeyframeReferencePlanItem { export interface KeyframeReferencePlanItem {
subjectId?: string subjectId?: string
@@ -251,7 +255,8 @@ export interface KeyframeSpecConsistencyIssue {
message: string message: string
} }
export interface KeyframeGenerationPreview { /** 正式镜头的最终图片输入与导演约束检查。 */
export interface KeyframeGenerationPreview extends ImageGenerationPreview {
specConsistencyIssues?: KeyframeSpecConsistencyIssue[] specConsistencyIssues?: KeyframeSpecConsistencyIssue[]
specConsistencySummary?: { specConsistencySummary?: {
warningCount: number warningCount: number
@@ -263,10 +268,6 @@ export interface KeyframeGenerationPreview {
episodeNo: number episodeNo: number
beatNo: number beatNo: number
shotNo: number shotNo: number
provider: string
model: string
generationConfig: Record<string, unknown>
references: KeyframePreviewReference[]
referencePlan: { referencePlan: {
provider: string provider: string
maxReferenceImages: number | null maxReferenceImages: number | null
@@ -275,7 +276,6 @@ export interface KeyframeGenerationPreview {
selected: KeyframeReferencePlanItem[] selected: KeyframeReferencePlanItem[]
omitted: KeyframeReferencePlanItem[] omitted: KeyframeReferencePlanItem[]
} }
providerPrompt: string
} }
/** 视频生成规格中的主体参考图。 */ /** 视频生成规格中的主体参考图。 */
@@ -326,6 +326,8 @@ export interface GenerateKeyframesInput {
/** 单镜头首帧生成参数。 */ /** 单镜头首帧生成参数。 */
export interface GenerateKeyframeInput { export interface GenerateKeyframeInput {
/** 用户确认的最终输入版本。 */
expectedPreviewFingerprint?: string
setPrimary: boolean setPrimary: boolean
provider?: string provider?: string
generationOptions?: Record<string, string | number | boolean> generationOptions?: Record<string, string | number | boolean>
+19 -13
View File
@@ -73,21 +73,25 @@ export function useProduction() {
async (key, signal) => { async (key, signal) => {
const [projectId, number, overwrite] = JSON.parse(key) as [string, number, boolean] const [projectId, number, overwrite] = JSON.parse(key) as [string, number, boolean]
if (!projectId || !number) return null if (!projectId || !number) return null
const [directions, prompts, keyframes, videos, videoStatus, videoInputPlanState] = await Promise.all([ const [directions, visualStates, prompts, keyframes, videos, videoStatus, videoInputPlanState] =
storyboardApi.directions(projectId, number, signal), await Promise.all([
productionApi.promptReadiness(projectId, overwrite, signal), storyboardApi.directions(projectId, number, signal),
productionApi.keyframeReadiness(projectId, overwrite, signal), storyboardApi.visualStates(projectId, number, signal).catch(() => null),
productionApi.videoReadiness(projectId, overwrite, signal), productionApi.promptReadiness(projectId, overwrite, signal),
productionApi.projectVideoStatus(projectId, signal), productionApi.keyframeReadiness(projectId, overwrite, signal),
productionApi productionApi.videoReadiness(projectId, overwrite, signal),
.videoInputPlans(projectId, number, signal) productionApi.projectVideoStatus(projectId, signal),
.then(data => ({ data, error: '' })) productionApi
.catch(cause => ({ data: null, error: errorMessage(cause) })) .videoInputPlans(projectId, number, signal)
]) .then(data => ({ data, error: '' }))
.catch(cause => ({ data: null, error: errorMessage(cause) }))
])
if (directions.projectId !== projectId || directions.episodeNo !== number) if (directions.projectId !== projectId || directions.episodeNo !== number)
throw new Error('镜头生产查询返回了不匹配的项目或剧集,请刷新后重试。') throw new Error('镜头生产查询返回了不匹配的项目或剧集,请刷新后重试。')
return { return {
directions, directions,
visualStates:
visualStates?.projectId === projectId && visualStates.episodeNo === number ? visualStates : null,
prompts, prompts,
keyframes, keyframes,
videos, videos,
@@ -112,7 +116,9 @@ export function useProduction() {
() => !!getStoryboardSession(id.value).invalidatedEpisodeSources[episodeNo.value] () => !!getStoryboardSession(id.value).invalidatedEpisodeSources[episodeNo.value]
) )
/** 当前剧集的正式镜头目录。 */ /** 当前剧集的正式镜头目录。 */
const shots = computed(() => mergeDesignedShots(query.data.value?.directions ?? null, null, source.value)) const shots = computed(() =>
mergeDesignedShots(query.data.value?.directions ?? null, query.data.value?.visualStates ?? null, source.value)
)
/** 明确指定的镜头不存在时不代选其它镜头;首次进入才选择第一镜。 */ /** 明确指定的镜头不存在时不代选其它镜头;首次进入才选择第一镜。 */
const shot = computed(() => const shot = computed(() =>
selectedShot.value ? shots.value.find(item => item.shotId === selectedShot.value) : shots.value[0] selectedShot.value ? shots.value.find(item => item.shotId === selectedShot.value) : shots.value[0]
@@ -134,7 +140,7 @@ export function useProduction() {
/** 当前工作区的响应式状态或派生业务条件。 */ /** 当前工作区的响应式状态或派生业务条件。 */
const session = computed(() => getProductionSession(id.value)) const session = computed(() => getProductionSession(id.value))
/** 普通首帧后台观察器,刷新页面后恢复真实执行状态。 */ /** 普通首帧后台观察器,刷新页面后恢复真实执行状态。 */
const keyframeExecution = useWorkflowExecution(id, 'keyframe-generation') const keyframeExecution = useWorkflowExecution(id, 'keyframe-generation', { discover: true })
const promptExecution = useWorkflowExecution(id, 'video-prompt') const promptExecution = useWorkflowExecution(id, 'video-prompt')
const videoExecution = useWorkflowExecution(id, 'video-quality') const videoExecution = useWorkflowExecution(id, 'video-quality')
/** 当前工作区的响应式状态或派生业务条件。 */ /** 当前工作区的响应式状态或派生业务条件。 */
@@ -34,6 +34,7 @@ import { useSubjectIdentity } from './useSubjectIdentity'
import { useProjectContext } from '../projects/context' import { useProjectContext } from '../projects/context'
import { useProjectStageAccess } from '../projects/useProjectStageAccess' import { useProjectStageAccess } from '../projects/useProjectStageAccess'
import StableAnchorQualityDialog from './components/StableAnchorQualityDialog.vue' import StableAnchorQualityDialog from './components/StableAnchorQualityDialog.vue'
import VisualFactRevisionDrawer from './components/VisualFactRevisionDrawer.vue'
import IdentityEditor from './components/IdentityEditor.vue' import IdentityEditor from './components/IdentityEditor.vue'
import SubjectIdentitySkeleton from './SubjectIdentitySkeleton.vue' import SubjectIdentitySkeleton from './SubjectIdentitySkeleton.vue'
import IdentityDetailSkeleton from './components/IdentityDetailSkeleton.vue' import IdentityDetailSkeleton from './components/IdentityDetailSkeleton.vue'
@@ -113,6 +114,21 @@ const identityBatchScopeLabel = computed(
/** 单主体稳定母版质量生成弹窗开关。 */ /** 单主体稳定母版质量生成弹窗开关。 */
const qualityOpen = ref(false) const qualityOpen = ref(false)
const imageOpen = ref(false) const imageOpen = ref(false)
/** 当前主体视觉事实修订抽屉。 */
const revisionOpen = ref(false)
watch(selectedId, () => {
revisionOpen.value = false
})
/** 保存后重读身份、全部形态与制作准入。 */
async function refreshVisualFacts() {
await Promise.all([
detail.refresh(),
catalog.refresh(),
castingQuery.refresh(),
projectContext.refreshStageReadiness()
])
}
/** 从失败记录重试时保留原视角,普通生成仍使用弹窗默认视角。 */ /** 从失败记录重试时保留原视角,普通生成仍使用弹窗默认视角。 */
const retryImageView = ref<IdentityViewType>() const retryImageView = ref<IdentityViewType>()
const castingOpen = ref(false) const castingOpen = ref(false)
@@ -921,6 +937,25 @@ function runNextAction() {
<p v-if="dirty" class="mt-3 text-xs text-muted"> <p v-if="dirty" class="mt-3 text-xs text-muted">
请先保存身份修改,再使用 AI 或生成图片。 请先保存身份修改,再使用 AI 或生成图片。
</p> </p>
<!-- 以下是未生图主体的原文事实修订入口 -->
<NButton
class="mt-4 workspace-action-button"
:disabled="detailBlocked || dirty"
@click="revisionOpen = true"
>核对与修订视觉事实</NButton
>
<VisualFactRevisionDrawer
v-if="revisionOpen"
:key="subject.id"
v-model:open="revisionOpen"
:project-id="projectId"
:subject-id="subject.id"
:subject-name="subject.name"
:disabled="detailBlocked || dirty"
@saved="refreshVisualFacts"
/>
<!-- 以下是主体身份文本准备 -->
<IdentityEditor <IdentityEditor
:saving="isOperationRunning(operation, '保存主体身份')" :saving="isOperationRunning(operation, '保存主体身份')"
:key="`${selectedId}:${editorRevision}`" :key="`${selectedId}:${editorRevision}`"
@@ -57,20 +57,31 @@ const generationInput = computed<GenerateCastingCandidateInput>(() => ({
generationOptions: { ...generationOptions.value } generationOptions: { ...generationOptions.value }
})) }))
/** 选角使用 primary 且不引用当前母版,与正式候选生成一致。 */ /** 选角使用 primary 且不引用当前母版,与正式候选生成一致。 */
const { preview, acknowledged, loading, submitting, error, staleNotice, canSubmit, loadPreview, submit } = const {
useImageGenerationPreview({ preview,
open, acknowledged,
target: () => JSON.stringify([props.subjectId, props.profile]), loading,
input: () => generationInput.value, submitting,
disabled: () => props.disabled || !valid.value, error,
load: (input, signal) => staleNotice,
subjectIdentityApi.previewImage( recoveryNotice,
props.subjectId, canSubmit,
{ ...input, viewType: 'primary', useAnchorReference: false }, loadPreview,
signal submit
), } = useImageGenerationPreview({
generate: input => props.submitGeneration(input) open,
}) recoveryTarget: () => (props.subjectId ? 'identity:' + props.subjectId : ''),
target: () => JSON.stringify([props.subjectId, props.profile]),
input: () => generationInput.value,
disabled: () => props.disabled || !valid.value,
load: (input, signal) =>
subjectIdentityApi.previewImage(
props.subjectId,
{ ...input, viewType: 'primary', useAnchorReference: false },
signal
),
generate: input => props.submitGeneration(input)
})
/** 当前描述草稿对应的表单模型。 */ /** 当前描述草稿对应的表单模型。 */
const formModel = computed(() => ({ prompt: prompt.value })) const formModel = computed(() => ({ prompt: prompt.value }))
</script> </script>
@@ -94,7 +105,7 @@ const formModel = computed(() => ({ prompt: prompt.value }))
> >
<ContextNotice type="info" :show-icon="false" class="text-xs"> <ContextNotice type="info" :show-icon="false" class="text-xs">
AI AI
会根据角色身份、项目视觉风格和选角要求生成一张新的候选图,不会复用当前身份母版。生成完成后,请在图库点击“确认选角并锁定”,将图片设为角色母版。 会根据角色身份、项目视觉风格和选角要求生成一张新的候选图,不会复用当前身份母版。生成后请在图库审核候选,通过后再确认选角并锁定身份。
</ContextNotice> </ContextNotice>
<NFormItem <NFormItem
class="block" class="block"
@@ -130,7 +141,7 @@ const formModel = computed(() => ({ prompt: prompt.value }))
:loading="loading" :loading="loading"
:disabled="disabled || submitting || !valid" :disabled="disabled || submitting || !valid"
:error="error" :error="error"
:stale-notice="staleNotice" :stale-notice="staleNotice || recoveryNotice"
@load="loadPreview" @load="loadPreview"
/> />
<NCheckbox <NCheckbox
@@ -129,6 +129,7 @@ defineExpose({ openCandidates, closeCandidates })
:identity-locked="identityLocked" :identity-locked="identityLocked"
:disabled="disabled" :disabled="disabled"
:pending-operation="pendingOperation" :pending-operation="pendingOperation"
:validation-result="validationResult"
:retry-disabled-reason="retryDisabledReason" :retry-disabled-reason="retryDisabledReason"
:active="true" :active="true"
:description="displayImage.isAnchor ? anchorDescription : undefined" :description="displayImage.isAnchor ? anchorDescription : undefined"
@@ -142,6 +143,7 @@ defineExpose({ openCandidates, closeCandidates })
v-if="validationResult && images.some(image => image.id === validationResult?.imageId) && !candidatesOpen" v-if="validationResult && images.some(image => image.id === validationResult?.imageId) && !candidatesOpen"
class="mt-5" class="mt-5"
:result="validationResult" :result="validationResult"
:module="module"
/> />
<!-- 以下是与镜头生产一致的底部图片操作模块 --> <!-- 以下是与镜头生产一致的底部图片操作模块 -->
<div class="identity-gallery-actions"> <div class="identity-gallery-actions">
@@ -169,6 +171,7 @@ defineExpose({ openCandidates, closeCandidates })
:identity-locked="identityLocked" :identity-locked="identityLocked"
:disabled="disabled" :disabled="disabled"
:pending-operation="pendingOperation" :pending-operation="pendingOperation"
:validation-result="validationResult"
:retry-disabled-reason="retryDisabledReason" :retry-disabled-reason="retryDisabledReason"
:active="candidatesOpen" :active="candidatesOpen"
@anchor="emit('anchor', $event)" @anchor="emit('anchor', $event)"
@@ -181,6 +184,7 @@ defineExpose({ openCandidates, closeCandidates })
v-if="validationResult && managedCandidates.some(image => image.id === validationResult?.imageId)" v-if="validationResult && managedCandidates.some(image => image.id === validationResult?.imageId)"
class="mt-5" class="mt-5"
:result="validationResult" :result="validationResult"
:module="module"
/> />
</AppDialog> </AppDialog>
</section> </section>
@@ -5,7 +5,8 @@ import { AppDialog, AssetImage, AssetOpenLink, StatusBadge } from '../../../comp
import { formatDate } from '../../../lib/format' import { formatDate } from '../../../lib/format'
import ConfirmAction from '../../workflows/ConfirmAction.vue' import ConfirmAction from '../../workflows/ConfirmAction.vue'
import { canBeAnchor, identityViewLabels } from '../model' import { canBeAnchor, identityViewLabels } from '../model'
import type { IdentityImage, IdentityImageOperation } from '../types' import { imageValidationPassed } from '../../subject-images/validation'
import type { IdentityImage, IdentityImageOperation, IdentityValidationResult } from '../types'
/** 母版与候选共用图片卡片,操作始终绑定卡片的正式图片编号。 */ /** 母版与候选共用图片卡片,操作始终绑定卡片的正式图片编号。 */
const props = defineProps<{ const props = defineProps<{
@@ -27,6 +28,8 @@ const props = defineProps<{
description?: string description?: string
/** 候选管理是否可见,关闭管理弹窗时同步收起错误浮层。 */ /** 候选管理是否可见,关闭管理弹窗时同步收起错误浮层。 */
active?: boolean active?: boolean
/** 只用于同一候选的已知审核证据。 */
validationResult?: IdentityValidationResult | null
}>() }>()
/** 卡片只请求父页面执行操作,不直接调用模型或修改母版。 */ /** 卡片只请求父页面执行操作,不直接调用模型或修改母版。 */
const emit = defineEmits<{ const emit = defineEmits<{
@@ -51,12 +54,19 @@ const confirmLoading = computed(
const validateLoading = computed( const validateLoading = computed(
() => props.pendingOperation?.imageId === props.image.id && props.pendingOperation.kind === 'validate' () => props.pendingOperation?.imageId === props.image.id && props.pendingOperation.kind === 'validate'
) )
/** 当前图片需要具备刚刚读取的明确审核结果。 */
const quality = computed(() =>
props.validationResult?.imageId === props.image.id
? imageValidationPassed(props.validationResult, props.module)
: null
)
/** 只有完成的 primary 可以确认,已锁定的当前母版不提供重复确认。 */ /** 只有完成的 primary 可以确认,已锁定的当前母版不提供重复确认。 */
const canSelect = computed( const canSelect = computed(
() => () =>
!props.disabled && !props.disabled &&
!props.pendingOperation && !props.pendingOperation &&
canBeAnchor(props.image) && canBeAnchor(props.image) &&
quality.value === true &&
(!props.image.isAnchor || (character.value && !props.identityLocked)) (!props.image.isAnchor || (character.value && !props.identityLocked))
) )
/** 卡片标识区分身份母版、母版候选和辅助视角,不重复强调当前状态。 */ /** 卡片标识区分身份母版、母版候选和辅助视角,不重复强调当前状态。 */
@@ -174,6 +184,13 @@ function regenerate() {
</NScrollbar> </NScrollbar>
</NPopover> </NPopover>
<NTag size="small" :bordered="false">{{ imageLabel }}</NTag> <NTag size="small" :bordered="false">{{ imageLabel }}</NTag>
<NTag
v-if="image.status === 'completed' && !image.isAnchor && image.viewType === 'primary'"
size="small"
:bordered="false"
>
{{ quality === null ? '待审核' : quality ? '审核通过' : '审核未通过或待复核' }}
</NTag>
<!-- 以下是母版身份锁定状态模块,紧邻图片下方的身份母版标签。 --> <!-- 以下是母版身份锁定状态模块,紧邻图片下方的身份母版标签。 -->
<NTag <NTag
v-if="image.isAnchor" v-if="image.isAnchor"
@@ -221,8 +238,8 @@ function regenerate() {
<ConfirmAction <ConfirmAction
:key="image.id" :key="image.id"
label="校验此身份图片" label="校验此身份图片"
:description="`将校验图片 ${image.id},会调用视觉模型并可能产生费用,不会切换母版。`" description="将核对当前候选,可能调用视觉模型并产生费用。审核后仍需人工确认母版。"
:disabled="disabled || !!pendingOperation" :disabled="disabled || !!pendingOperation || image.viewType !== 'primary'"
:loading="validateLoading" :loading="validateLoading"
acknowledgement acknowledgement
@confirm="emit('validate', image.id)" @confirm="emit('validate', image.id)"
@@ -241,12 +258,16 @@ function regenerate() {
> >
<!-- 以下是身份母版采纳的费用与门禁说明模块 --> <!-- 以下是身份母版采纳的费用与门禁说明模块 -->
<p class="text-sm leading-7 text-muted"> <p class="text-sm leading-7 text-muted">
确认时会核对当前来源和质量,可能调用视觉模型并产生审核费用。通过后才锁定并采纳;未通过时保留旧母版,不自动追加生图。 {{
character
? '将复核已保存的质量证据,通过后锁定并采纳。'
: '将复核已保存的质量证据。若审核记录失效,服务可能再次调用视觉模型并产生费用。'
}}
</p> </p>
<template #footer> <template #footer>
<NButton @click="confirming = false">取消</NButton> <NButton @click="confirming = false">取消</NButton>
<NButton :disabled="!canSelect" type="primary" @click="chooseAnchor">{{ <NButton :disabled="!canSelect" type="primary" @click="chooseAnchor">{{
character ? '确认演员选择' : '确认切换身份母版' character ? '确认演员选择' : '确认费用并切换母版'
}}</NButton> }}</NButton>
</template> </template>
</AppDialog> </AppDialog>
@@ -110,11 +110,13 @@ const {
submitting, submitting,
error: previewError, error: previewError,
staleNotice, staleNotice,
recoveryNotice,
canSubmit, canSubmit,
loadPreview, loadPreview,
submit submit
} = useImageGenerationPreview({ } = useImageGenerationPreview({
open, open,
recoveryTarget: () => (props.subjectId ? 'identity:' + props.subjectId : ''),
target: () => target: () =>
JSON.stringify([props.subjectId, props.images.filter(image => image.status === 'completed'), props.profile]), JSON.stringify([props.subjectId, props.images.filter(image => image.status === 'completed'), props.profile]),
input: () => generationInput.value, input: () => generationInput.value,
@@ -229,7 +231,7 @@ const rules = {
:loading="previewLoading" :loading="previewLoading"
:disabled="disabled || submitting || !valid" :disabled="disabled || submitting || !valid"
:error="previewError" :error="previewError"
:stale-notice="staleNotice" :stale-notice="staleNotice || recoveryNotice"
@load="loadPreview" @load="loadPreview"
/> />
<NCheckbox <NCheckbox
@@ -0,0 +1,334 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { NButton, NCheckbox, NCollapse, NCollapseItem, NInput, NSelect } from 'naive-ui'
import { AppDrawer } from '../../../components/ui'
import ContextNotice from '../../../components/ui/ContextNotice.vue'
import RawDataDetails from '../../../components/ui/RawDataDetails.vue'
import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHeading.vue'
import { useQuery } from '../../../composables/useQuery'
import { ApiError, errorMessage } from '../../../lib/http'
import { projectsApi } from '../../projects/api'
import { getOperation, runOperation } from '../../workflows/operations'
import { visualFactsApi, type VisualFactFormEdit, type VisualFactRevision } from '../visual-facts'
/** 仅修订当前项目中尚未生图的正式主体。 */
const props = defineProps<{
/** 正式项目编号。 */
projectId: string
/** 正式主体编号。 */
subjectId: string
/** 主体名称。 */
subjectName: string
/** 项目当前禁止写入。 */
disabled: boolean
}>()
/** 全屏修订界面可见状态。 */
const open = defineModel<boolean>('open', { default: false })
/** 保存后刷新身份、形态和制作状态。 */
const emit = defineEmits<{ saved: [] }>()
/** 请求只绑定当前打开的项目和主体。 */
const key = computed(() => (open.value ? JSON.stringify([props.projectId, props.subjectId]) : ''))
/** 同时读取正式来源正文及事实版本,来源选择器只显示双方能绑定的记录。 */
const query = useQuery(key, async (value, signal) => {
if (!value) return null
const [projectId, subjectId] = JSON.parse(value) as [string, string]
const [preview, project] = await Promise.all([
visualFactsApi.preview(subjectId, signal),
projectsApi.detail(projectId, signal)
])
if (preview.subjectId !== subjectId || project.id !== projectId) throw new Error('资料与当前主体不匹配。')
return { preview, project }
})
/** 原始主题以空选择区分,避免与真实剧集编号混用。 */
const sourceId = ref<string | null>(null)
/** 逐字原文由操作者明确填写。 */
const quote = ref('')
/** 主体稳定外观和叙事描述分别保留。 */
const appearance = ref('')
/** 可选修改的主体叙事说明。 */
const description = ref('')
/** 所有现存形态的人工草稿。 */
const forms = ref<VisualFactFormEdit[]>([])
/** 人工审阅人。 */
const operator = ref('')
/** 可追溯的人工修订理由。 */
const reason = ref('')
/** 只对本轮草稿和所选原文生效的明确确认。 */
const confirmed = ref(false)
/** 保存期间禁止重复提交或关闭。 */
const saving = ref(false)
/** 首次提交后显示完整校验。 */
const attempted = ref(false)
/** 当前写入失败说明。 */
const conflict = ref('')
/** 上次发生冲突的输入供人工对照,不作为新版本自动提交。 */
const previousDraft = ref<VisualFactRevision | null>(null)
/** 正式来源文本和版本直接从两个只读结果匹配。 */
const sources = computed(() => {
const data = query.data.value
if (!data) return []
const episodes = data.preview.sources.episodes.flatMap(source => {
const episode = data.project.episodes.find(item => item.id === source.id && item.episode === source.episode)
return episode
? [
{
value: source.id,
label: `第 ${source.episode} 集 · ${episode.title}`,
text: episode.content,
fingerprint: source.fingerprint
}
]
: []
})
return [
{
value: 'topic',
label: '原始主题',
text: data.project.topic,
fingerprint: data.preview.sources.topicFingerprint
},
...episodes
]
})
/** 当前原文展示与提交使用同一正式来源。 */
const source = computed(() => sources.value.find(item => item.value === sourceId.value))
watch(
() => query.data.value,
data => {
const facts = data?.preview.facts
appearance.value = facts?.appearancePrompt ?? ''
description.value = facts?.description ?? ''
forms.value =
facts?.forms.map(form => ({
formId: form.id,
description: form.description ?? '',
appearancePrompt: form.appearancePrompt ?? ''
})) ?? []
sourceId.value = null
operator.value = ''
reason.value = ''
attempted.value = false
confirmed.value = false
}
)
watch(sourceId, () => {
quote.value = ''
})
watch(
[appearance, description, forms, sourceId, quote, operator, reason],
() => {
confirmed.value = false
},
{ deep: true, flush: 'sync' }
)
watch(key, () => {
conflict.value = ''
previousDraft.value = null
})
/** 提交时校验全部形态和逐字证据,服务事务再次核对真实原文。 */
const validationError = computed(() => {
if (
!appearance.value.trim() ||
!forms.value.length ||
forms.value.length > 30 ||
forms.value.some(form => !form.description.trim() || !form.appearancePrompt.trim())
)
return '请填写主体外观和所有形态的说明与外观。'
if (!source.value || !quote.value.trim() || !source.value.text.includes(quote.value.trim()))
return '请选择原文来源,并粘贴其中逐字一致的引文。'
if (!operator.value.trim() || !reason.value.trim()) return '请填写修订人及修订原因。'
return ''
})
/** 提交当前版本一次,409 只重新读取资料,要求人工重新核对。 */
async function save() {
if (
saving.value ||
props.disabled ||
query.loading.value ||
query.error.value ||
!query.data.value?.preview.canRevise
)
return
attempted.value = true
const selected = source.value
if (validationError.value || !selected || !confirmed.value) return
const { projectId, subjectId } = props
const target = key.value
const preview = query.data.value.preview
const evidence = { quote: quote.value.trim(), expectedFingerprint: selected.fingerprint }
const input: VisualFactRevision = {
expectedVersion: preview.version,
appearancePrompt: appearance.value.trim(),
description: description.value.trim() || undefined,
forms: forms.value.map(form => ({
formId: form.formId,
description: form.description.trim(),
appearancePrompt: form.appearancePrompt.trim()
})),
source:
selected.value === 'topic'
? { kind: 'topic', ...evidence }
: { kind: 'episode', episodeId: selected.value, ...evidence },
operator: operator.value.trim(),
reason: reason.value.trim()
}
saving.value = true
conflict.value = ''
try {
const ok = await runOperation(
projectId,
'修订主体视觉事实',
async () => {
const result = await visualFactsApi.revise(subjectId, input)
if (result.subjectId !== subjectId || !result.revisionId)
throw new Error('保存结果待核对,请刷新资料。')
},
{ type: 'success', content: '视觉事实已保存。需要时可重新准备身份和形态描述。' }
)
if (key.value !== target) return
if (ok) {
emit('saved')
open.value = false
} else {
const cause = getOperation(projectId).cause
confirmed.value = false
if (cause instanceof ApiError && cause.status === 409) {
previousDraft.value = input
conflict.value = `${errorMessage(cause)} 将重新读取当前资料,请复核后再提交。`
await query.refresh()
}
}
} finally {
saving.value = false
}
}
</script>
<template>
<AppDrawer
v-model:open="open"
:title="`修订视觉事实 · ${subjectName}`"
description="依据原文纠正当前主体和全部形态。保存后需要重新准备受影响的身份和画面描述。"
:busy="saving"
>
<!-- 以下是当前可修订性和版本冲突反馈 -->
<div class="space-y-5">
<ContextNotice v-if="conflict" type="warning" :show-icon="false">{{ conflict }}</ContextNotice>
<RawDataDetails v-if="previousDraft" title="查看冲突前填写的修订与引文" :value="previousDraft" />
<ContextNotice v-if="query.error.value" type="error" :show-icon="false">{{
query.error.value
}}</ContextNotice>
<p v-else-if="query.loading.value" class="text-sm text-muted">正在读取事实与原文…</p>
<p v-else-if="query.data.value && !query.data.value.preview.canRevise" class="text-sm text-muted">
此主体当前无法修订。请检查是否已有身份或形态图片、身份已锁定,或项目还有任务进行中。
</p>
<template v-else-if="query.data.value">
<!-- 以下是主体与全部正式形态的事实编辑 -->
<section class="space-y-4">
<WorkspaceSectionHeading
title="主体与形态"
description="保留每个形态,分别填写可从原文支持的事实。"
/>
<label class="block text-sm"
>主体说明<NInput
v-model:value="description"
class="mt-2"
type="textarea"
:maxlength="12000"
:disabled="saving"
/></label>
<label class="block text-sm"
>主体稳定外观<NInput
v-model:value="appearance"
class="mt-2"
type="textarea"
:maxlength="12000"
:disabled="saving"
/></label>
<article v-for="(form, index) in forms" :key="form.formId" class="space-y-3">
<h3 class="text-sm font-medium">{{ query.data.value.preview.facts.forms[index]?.name }}</h3>
<label class="block text-sm"
>形态说明<NInput
v-model:value="form.description"
class="mt-2"
type="textarea"
:maxlength="12000"
:disabled="saving"
/></label>
<label class="block text-sm"
>形态外观<NInput
v-model:value="form.appearancePrompt"
class="mt-2"
type="textarea"
:maxlength="12000"
:disabled="saving"
/></label>
</article>
</section>
<!-- 以下是可追溯的原文、修订原因和人工确认 -->
<section class="space-y-4">
<WorkspaceSectionHeading
title="原文证据"
description="从原始主题或正式剧本中引用能直接支持本次修订的原句。"
/>
<NSelect
v-model:value="sourceId"
:options="sources"
placeholder="选择原文来源"
:disabled="saving"
aria-label="原文来源"
/>
<NCollapse v-if="source" :key="source.value">
<NCollapseItem name="original" title="查看完整原文">
<p class="max-h-64 overflow-y-auto whitespace-pre-wrap wrap-anywhere text-sm leading-7">
{{ source.text }}
</p>
</NCollapseItem>
</NCollapse>
<label class="block text-sm"
>逐字引文<NInput
v-model:value="quote"
class="mt-2"
type="textarea"
:maxlength="6000"
:disabled="saving"
/></label>
<label class="block text-sm"
>修订人<NInput v-model:value="operator" class="mt-2" :maxlength="120" :disabled="saving"
/></label>
<label class="block text-sm"
>修订原因<NInput
v-model:value="reason"
class="mt-2"
type="textarea"
:maxlength="4000"
:disabled="saving"
/></label>
<NCheckbox v-model:checked="confirmed" :disabled="saving"
>我已核对原文和全部形态,并确认保存本次修订。</NCheckbox
>
<p v-if="attempted && validationError" role="alert" class="text-sm text-danger">
{{ validationError }}
</p>
</section>
</template>
</div>
<template #footer>
<NButton :disabled="saving" @click="open = false">关闭</NButton>
<NButton
v-if="query.data.value?.preview.canRevise"
type="primary"
:loading="saving"
:disabled="disabled || !confirmed || query.loading.value || !!query.error.value"
@click="save"
>保存修订</NButton
>
<NButton v-else-if="query.error.value" :loading="query.loading.value" @click="query.refresh"
>重新读取</NButton
>
</template>
</AppDrawer>
</template>
@@ -1,3 +1,4 @@
import { ApiError } from '../../lib/http'
import { imageValidationPassed } from '../subject-images/validation' import { imageValidationPassed } from '../subject-images/validation'
import type { ImageGenerationSubmission } from '../subject-images/generation-preview' import type { ImageGenerationSubmission } from '../subject-images/generation-preview'
import { computed, ref, shallowRef, watch } from 'vue' import { computed, ref, shallowRef, watch } from 'vue'
@@ -271,9 +272,18 @@ export function useSubjectIdentity() {
*/ */
async function validateImage(imageId: string) { async function validateImage(imageId: string) {
const image = images.value.find(item => item.id === imageId) const image = images.value.find(item => item.id === imageId)
if (detailBlocked.value || !subject.value || image?.status !== 'completed' || !image.imageUrl) return if (
detailBlocked.value ||
!subject.value ||
image?.viewType !== 'primary' ||
image.status !== 'completed' ||
!image.imageUrl
)
return
const id = subject.value.id const id = subject.value.id
const name = subject.value.name const name = subject.value.name
const project = projectId.value
const module = subject.value.module
delete validationResults.value[id] delete validationResults.value[id]
const sourceKey = validationSourceKey.value const sourceKey = validationSourceKey.value
await runImageOperation( await runImageOperation(
@@ -284,12 +294,20 @@ export function useSubjectIdentity() {
const result = await subjectIdentityApi.validateImage(id, imageId) const result = await subjectIdentityApi.validateImage(id, imageId)
if (result.subjectId !== id || result.imageId !== imageId) if (result.subjectId !== id || result.imageId !== imageId)
throw new Error('身份校验回执与提交目标不匹配') throw new Error('身份校验回执与提交目标不匹配')
if (validationSourceKey.value === sourceKey) validationResults.value[id] = result if (validationSourceKey.value === sourceKey) {
await refreshImageConfirmation(project, id)
if (
projectId.value === project &&
selectedId.value === id &&
images.value.some(item => item.id === imageId && item.imageUrl === image.imageUrl)
)
validationResults.value[id] = result
}
return result return result
}, },
result => ({ result => ({
type: imageValidationPassed(result) ? 'success' : 'warning', type: imageValidationPassed(result, module) ? 'success' : 'warning',
content: `${name} 的身份图片校验${imageValidationPassed(result) ? '通过' : '未通过或待复核'}:${result.summary}` content: `${name} 的身份图片校验${imageValidationPassed(result, module) ? '通过' : '未通过或待复核'}:${result.summary}`
}) })
) )
} }
@@ -520,7 +538,7 @@ export function useSubjectIdentity() {
image.identityId !== identityId || image.identityId !== identityId ||
!['pending', 'generating'].includes(image.status) !['pending', 'generating'].includes(image.status)
) { ) {
throw new Error(image?.error || '身份参考图任务未成功创建,请刷新后重试。') throw new ApiError('身份参考图任务回执待核对,请刷新候选和任务。', 202)
} }
if (projectId.value === project && selectedId.value === id) { if (projectId.value === project && selectedId.value === id) {
// 先展示真实回执中的生成记录,后续读取失败也能保留状态并继续轮询。 // 先展示真实回执中的生成记录,后续读取失败也能保留状态并继续轮询。
@@ -555,7 +573,7 @@ export function useSubjectIdentity() {
async () => { async () => {
const image = await subjectIdentityApi.generateCastingCandidate(id, input) const image = await subjectIdentityApi.generateCastingCandidate(id, input)
if (!image || image.identityId !== identityId || !['pending', 'generating'].includes(image.status)) { if (!image || image.identityId !== identityId || !['pending', 'generating'].includes(image.status)) {
throw new Error(image?.error || '选角候选任务未成功创建,请刷新后重试。') throw new ApiError('角色候选任务回执待核对,请刷新候选和任务。', 202)
} }
if (projectId.value === project) if (projectId.value === project)
await Promise.all([ await Promise.all([
@@ -612,14 +630,16 @@ export function useSubjectIdentity() {
(subject.value?.module !== 'scene' && subject.value?.module !== 'prop') || (subject.value?.module !== 'scene' && subject.value?.module !== 'prop') ||
!identity.value || !identity.value ||
!image || !image ||
!canBeAnchor(image) !canBeAnchor(image) ||
validationResult.value?.imageId !== imageId ||
!imageValidationPassed(validationResult.value, subject.value.module)
) )
return return
const subjectId = subject.value.id const subjectId = subject.value.id
const identityId = identity.value.id const identityId = identity.value.id
const project = projectId.value const project = projectId.value
const name = subject.value.name const name = subject.value.name
await runImageOperation( const confirmed = await runImageOperation(
'confirm', 'confirm',
imageId, imageId,
`确认 ${name} 身份母版`, `确认 ${name} 身份母版`,
@@ -641,6 +661,10 @@ export function useSubjectIdentity() {
}, },
{ type: 'success', content: `${name} 的身份母版已确认并锁定。` } { type: 'success', content: `${name} 的身份母版已确认并锁定。` }
) )
if (!confirmed) {
delete validationResults.value[subjectId]
await refreshImageConfirmation(project, subjectId)
}
} }
/** /**
@@ -656,14 +680,16 @@ export function useSubjectIdentity() {
!!castingQuery.error.value || !!castingQuery.error.value ||
!identity.value || !identity.value ||
!image || !image ||
!canBeAnchor(image) !canBeAnchor(image) ||
validationResult.value?.imageId !== imageId ||
!imageValidationPassed(validationResult.value, subject.value.module)
) )
return return
const subjectId = subject.value.id const subjectId = subject.value.id
const identityId = identity.value.id const identityId = identity.value.id
const project = projectId.value const project = projectId.value
const name = subject.value.name const name = subject.value.name
await runImageOperation( const confirmed = await runImageOperation(
'confirm', 'confirm',
imageId, imageId,
`确认 ${name} 角色选角`, `确认 ${name} 角色选角`,
@@ -685,6 +711,10 @@ export function useSubjectIdentity() {
}, },
{ type: 'success', content: `${name} 的角色选角已确认,身份已锁定。` } { type: 'success', content: `${name} 的角色选角已确认,身份已锁定。` }
) )
if (!confirmed) {
delete validationResults.value[subjectId]
await refreshImageConfirmation(project, subjectId)
}
} }
return { return {
@@ -0,0 +1,104 @@
import { request } from '../../lib/http'
/** 修订必须完整保留每个已存在形态的绑定。 */
export interface VisualFactFormEdit {
/** 正式形态编号。 */
formId: string
/** 纠正后的形态说明。 */
description: string
/** 纠正后的形态外观。 */
appearancePrompt: string
}
/** 只读修订预览。 */
export interface VisualFactPreview {
/** 正式主体编号。 */
subjectId: string
/** 当前事实的并发版本。 */
version: string
/** 当前允许人工修订。 */
canRevise: boolean
/** 当前正式主体和全部形态。 */
facts: {
/** 主体说明。 */
description: string | null
/** 主体稳定外观。 */
appearancePrompt: string | null
/** 已存在的正式形态。 */
forms: Array<{
/** 正式形态编号。 */
id: string
/** 形态显示名称。 */
name: string
/** 当前形态说明。 */
description: string | null
/** 当前形态外观。 */
appearancePrompt: string | null
}>
}
/** 允许用于举证的正式原文版本。 */
sources: {
/** 原始主题的版本。 */
topicFingerprint: string
/** 正式剧集的原文版本。 */
episodes: Array<{
/** 正式剧集编号。 */
id: string
/** 用户可见的集数。 */
episode: number
/** 正文版本。 */
fingerprint: string
}>
}
}
/** 原文引证含同一来源的版本,原文变化由服务事务复核。 */
type VisualFactSource = {
/** 最新预览中的原文版本。 */
expectedFingerprint: string
/** 用户核对并填写的逐字原文。 */
quote: string
} & ({ /** 原始主题。 */ kind: 'topic' } | { /** 正式剧集。 */ kind: 'episode'; /** 剧集编号。 */ episodeId: string })
/** 明确的人工修订请求,沿用正式接口的严格字段。 */
export interface VisualFactRevision {
/** 最新事实版本。 */
expectedVersion: string
/** 主体稳定外观。 */
appearancePrompt: string
/** 可选修订主体说明。 */
description?: string
/** 全部现有形态。 */
forms: VisualFactFormEdit[]
/** 用户核对的原文证据。 */
source: VisualFactSource
/** 实际修订人员。 */
operator: string
/** 本次修订原因。 */
reason: string
}
/** 正式修订 API,读取免费,保存人工输入后不会触发生成。 */
export const visualFactsApi = {
/**
* 读取当前事实及可修订性。
* @param subjectId 正式主体编号
* @param signal 关闭抽屉时取消读取
* @returns 当前修订预览
*/
preview: (subjectId: string, signal?: AbortSignal) =>
request<VisualFactPreview>(`/subjects/${encodeURIComponent(subjectId)}/visual-facts/revision-preview`, {
signal
}),
/**
* 原子保存本次人工修订。
* @param subjectId 正式主体编号
* @param input 人工确认的事实、全部形态和来源
* @returns 已保存的正式修订回执
*/
revise: (subjectId: string, input: VisualFactRevision) =>
request<{ revisionId: string; subjectId: string; version: string; formIds: string[] }>(
`/subjects/${encodeURIComponent(subjectId)}/visual-facts/revisions`,
{ method: 'POST', body: input }
)
}
+18
View File
@@ -1,4 +1,5 @@
import { request } from '../../lib/http' import { request } from '../../lib/http'
import type { ProviderImageInputSnapshot } from './generation-preview'
import type { ImageValidationResult } from './validation' import type { ImageValidationResult } from './validation'
import type { import type {
GenerateFormImageInput, GenerateFormImageInput,
@@ -47,6 +48,23 @@ export const subjectImagesApi = {
listForms: (projectId: string, signal?: AbortSignal) => listForms: (projectId: string, signal?: AbortSignal) =>
request<SubjectFormAsset[]>(`/projects/${encodeURIComponent(projectId)}/subject-forms`, { signal }), request<SubjectFormAsset[]>(`/projects/${encodeURIComponent(projectId)}/subject-forms`, { signal }),
listImages: (formId: string, signal?: AbortSignal) => request<SubjectImage[]>(formPath(formId), { signal }), listImages: (formId: string, signal?: AbortSignal) => request<SubjectImage[]>(formPath(formId), { signal }),
/**
* 只读核对指定候选的来源及当时实际输入。
* @param formId 正式形态
* @param imageId 正式图片
* @param signal 取消过期读取
* @returns 当前来源与审核资格
*/
validationPreview: (formId: string, imageId: string, signal?: AbortSignal) =>
request<{
/** 正式形态编号。 */ subjectFormId: string
/** 正式图片编号。 */ imageId: string
/** 当前图片是否可审核。 */ canValidate: boolean
/** 正式来源是否仍有效。 */ sourceCurrent: boolean
/** 失效说明。 */ sourceStaleReason: string | null
/** 持久化的实际输入版本。 */ providerInputFingerprint: string | null
/** 持久化的实际输入证据。 */ providerInputSnapshot: ProviderImageInputSnapshot | null
}>(`${formPath(formId)}/${encodeURIComponent(imageId)}/validate/preview`, { signal }),
/** /**
* 用户确认费用后审核指定候选,不自动切换主图。 * 用户确认费用后审核指定候选,不自动切换主图。
* @param formId 正式形态编号 * @param formId 正式形态编号
@@ -0,0 +1,191 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { NButton, NCollapse, NCollapseItem, NTag } from 'naive-ui'
import { AssetImage } from '../../../components/ui'
import RawDataDetails from '../../../components/ui/RawDataDetails.vue'
import { useQuery } from '../../../composables/useQuery'
import { userFacingText } from '../../../lib/user-facing-text'
import { subjectIdentityApi } from '../../subject-identity/api'
import { sourceDiagnosticsApi } from '../source-diagnostics'
import type { SubjectFormAsset } from '../types'
/** 当前形态的来源诊断,展开后才读取。 */
const props = defineProps<{
/** 正式形态。 */ form: SubjectFormAsset
/** 当前项目编号。 */ projectId: string
}>()
/** 来源折叠区域的打开状态。 */
const expanded = ref<string[]>([])
/** 只按当前形态和项目读取,关闭取消旧请求。 */
const key = computed(() =>
expanded.value.length
? JSON.stringify([props.projectId, props.form.id, props.form.subjectId, props.form.subject.module])
: ''
)
/** 使用正式路由,区分道具规格和场景几何。 */
const query = useQuery(key, async (value, signal) => {
if (!value) return null
const [projectId, formId, subjectId, module] = JSON.parse(value) as string[]
if (module === 'prop') {
const prop = await sourceDiagnosticsApi.prop(formId!, signal)
if (prop.subjectFormId !== formId) throw new Error('规格与当前形态不匹配。')
return { prop }
}
const anchorId = props.form.subject.identity?.anchorImageId
const [layouts, images] = await Promise.all([
sourceDiagnosticsApi.scene(projectId!, subjectId!, formId!, signal),
anchorId ? subjectIdentityApi.listImages(subjectId!, signal) : []
])
return {
layouts,
anchor: images.find(image => image.id === anchorId && image.isAnchor && image.status === 'completed')
}
})
/** 道具当前有效规格或独立的缺失、过期状态。 */
const prop = computed(() => query.data.value?.prop)
/** 以原始部件顺序展示原始与当前数量。 */
const parts = computed(
() =>
prop.value?.spec?.parts.map(part => {
const state = prop.value?.spec?.formState?.changes.find(change => change.partId === part.id)
return { ...part, state, current: state?.visibleQuantity ?? part.quantity }
}) ?? []
)
/** 道具规格状态不等同于图片审核。 */
const statusLabels = { ready: '结构规格已就绪', stale: '结构来源已过期', missing: '尚未准备结构规格' }
/** 道具最近准备任务独立于当前规格和图片审核。 */
const attemptLabels: Record<string, string> = {
failed: '准备失败',
completed: '准备已结束',
pending: '等待准备',
running: '正在准备'
}
/**
* 查找该证据自己的正式剧集,不用另一个引用代替。
* @param id 当前证据的剧集编号
* @returns 用户可读的正式来源名称
*/
function episodeLabel(id: string) {
const episode = prop.value?.sourceEpisodes?.find(item => item.episodeId === id)
return episode ? `第 ${episode.episode} 集 · ${episode.title}` : '正式剧集(集数待核对)'
}
</script>
<template>
<!-- 以下是独立的形态来源诊断 -->
<NCollapse v-model:expanded-names="expanded" class="mt-5">
<NCollapseItem
name="source"
:title="form.subject.module === 'prop' ? '道具结构、来源与最近准备' : '场景几何与机位参考'"
>
<p v-if="query.loading.value" class="text-sm text-muted">正在核对来源…</p>
<div v-else-if="query.error.value" class="space-y-2 text-sm">
<p class="text-danger">{{ query.error.value }}</p>
<NButton size="small" @click="query.refresh">重新读取来源</NButton>
</div>
<!-- 以下是道具结构、来源和独立的准备任务记录 -->
<div v-else-if="prop" class="space-y-4 text-sm leading-6">
<NTag :bordered="false" size="small" :type="prop.status === 'stale' ? 'warning' : 'default'">{{
statusLabels[prop.status]
}}</NTag>
<p v-if="prop.status === 'stale' || prop.reason" class="text-muted">
{{ userFacingText(prop.reason, '请重新核对当前形态与剧本来源。') }}
</p>
<p v-if="prop.spec" class="font-medium">{{ prop.spec.semanticClass }}</p>
<ul v-if="parts.length" class="space-y-3">
<li v-for="part in parts" :key="part.id">
<strong>{{ part.name }}</strong> · 原始 {{ part.quantity }} 件 · 当前 {{ part.current }} 件
<template v-if="part.state">
<p>{{ part.state.description }} · {{ episodeLabel(part.state.evidence.episodeId) }}</p>
<blockquote class="whitespace-pre-wrap wrap-anywhere text-muted">
{{ part.state.evidence.quote }}
</blockquote>
</template>
</li>
</ul>
<section v-if="prop.ownershipEvidence?.length" class="space-y-3">
<h3 class="font-medium">部件归属证据</h3>
<div v-for="(item, index) in prop.ownershipEvidence" :key="index" class="space-y-1">
<strong>{{ item.name }} · 原文数量 {{ item.quantity }}</strong>
<p>数量来源 · {{ episodeLabel(item.episodeId) }}</p>
<blockquote class="whitespace-pre-wrap wrap-anywhere text-muted">
{{ item.sourceQuote }}
</blockquote>
<p>拆装来源 · {{ episodeLabel(item.relationEpisodeId) }}</p>
<blockquote class="whitespace-pre-wrap wrap-anywhere text-muted">
{{ item.relationQuote }}
</blockquote>
</div>
</section>
<section class="space-y-2">
<h3 class="font-medium">最近准备记录</h3>
<template v-if="prop.lastGenerationAttempt">
<p>
{{ prop.lastGenerationAttempt.sourceCurrent ? '对应当前来源' : '准备时的来源已过期' }} ·
{{ attemptLabels[prop.lastGenerationAttempt.status] ?? '结果待核对' }}
</p>
<p v-if="prop.lastGenerationAttempt.error">
{{ userFacingText(prop.lastGenerationAttempt.error) }}
</p>
<RawDataDetails title="完整候选与来源记录" :value="prop.lastGenerationAttempt" />
</template>
<p v-else class="text-muted">无独立模型准备记录。</p>
</section>
</div>
<!-- 以下是当前几何及真实机位参考 -->
<div v-else-if="query.data.value?.layouts" class="space-y-4 text-sm leading-6">
<div class="space-y-2">
<h3 class="font-medium">场景身份母版</h3>
<AssetImage
v-if="query.data.value.anchor?.imageUrl"
class="max-w-sm"
:src="query.data.value.anchor.imageUrl"
alt="场景身份母版"
object-fit="contain"
preview
/>
<p class="text-muted">
{{
query.data.value.anchor
? form.subject.identity?.isLocked
? '已确认并锁定'
: '已选母版 · 待锁定'
: '尚无已确认的场景身份母版。'
}}
</p>
</div>
<p v-if="!query.data.value.layouts.length" class="text-muted">尚无共享空间布局记录。</p>
<p v-else-if="query.data.value.layouts.length > 1" class="text-muted">
此场景关联多个布局,请在生成前核对唯一适用的空间范围。
</p>
<section v-for="layout in query.data.value.layouts" :key="layout.id" class="space-y-3">
<h3 class="font-medium">{{ layout.name }}</h3>
<p class="text-muted break-all">当前几何版本 {{ layout.version }}</p>
<p v-if="!layout.masters.length" class="text-muted">尚无当前形态的机位或全局空间参考。</p>
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<article v-for="master in layout.masters" :key="master.id" class="space-y-2">
<AssetImage
:src="master.imageUrl"
:alt="master.viewDescription || '全局空间参考'"
object-fit="contain"
preview
/>
<p>
{{ master.subjectFormId ? '当前形态机位' : '全局空间母版' }} ·
{{
master.spatialLayoutVersion !== layout.version
? '几何已过期'
: master.status === 'confirmed'
? '参考已确认'
: '参考未确认'
}}
</p>
<p v-if="master.viewDescription" class="text-muted">{{ master.viewDescription }}</p>
</article>
</div>
</section>
</div>
</NCollapseItem>
</NCollapse>
</template>
@@ -9,7 +9,6 @@ import GenerationModelControls from '../../generation-config/components/Generati
import type { CreativeProfile, GenerationModelCatalog, GenerationOptions } from '../../generation-config/types' import type { CreativeProfile, GenerationModelCatalog, GenerationOptions } from '../../generation-config/types'
import { subjectImagesApi } from '../api' import { subjectImagesApi } from '../api'
import { useImageGenerationPreview, type ImageGenerationSubmission } from '../generation-preview' import { useImageGenerationPreview, type ImageGenerationSubmission } from '../generation-preview'
import { primaryImage } from '../model'
import type { GenerateFormImageInput, SubjectFormAsset } from '../types' import type { GenerateFormImageInput, SubjectFormAsset } from '../types'
import ImageGenerationPreview from './ImageGenerationPreview.vue' import ImageGenerationPreview from './ImageGenerationPreview.vue'
@@ -34,34 +33,43 @@ const prompt = ref('')
const provider = ref('') const provider = ref('')
/** 当前模型动态参数。 */ /** 当前模型动态参数。 */
const generationOptions = ref<GenerationOptions>({}) const generationOptions = ref<GenerationOptions>({})
/** 明确选择质量通过后切换主图,默认只保留候选。 */
const setPrimary = ref(false)
/** 预览与生成共用同一份输入。 */ /** 预览与生成共用同一份输入。 */
const generationInput = computed<GenerateFormImageInput>(() => ({ const generationInput = computed<GenerateFormImageInput>(() => ({
...(prompt.value.trim() ? { prompt: prompt.value.trim() } : {}), ...(prompt.value.trim() ? { prompt: prompt.value.trim() } : {}),
provider: provider.value, provider: provider.value,
generationOptions: { ...generationOptions.value }, generationOptions: { ...generationOptions.value },
setPrimary: setPrimary.value setPrimary: false
})) }))
/** 表单模型用于统一禁用与间距。 */ /** 表单模型用于统一禁用与间距。 */
const formModel = computed(() => ({ prompt: prompt.value })) const formModel = computed(() => ({ prompt: prompt.value }))
/** 目标、参数与可见周期变化后废弃旧确认。 */ /** 目标、参数与可见周期变化后废弃旧确认。 */
const { preview, acknowledged, loading, submitting, error, staleNotice, canSubmit, loadPreview, submit } = const {
useImageGenerationPreview({ preview,
open, acknowledged,
target: () => loading,
JSON.stringify([props.form?.id, props.form?.generationPrompt, props.form?.subject.identity, props.profile]), submitting,
input: () => generationInput.value, error,
disabled: () => props.disabled || !props.form || !provider.value, staleNotice,
load: async (input, signal) => { recoveryNotice,
const formId = props.form!.id canSubmit,
const { setPrimary: _setPrimary, ...previewInput } = input loadPreview,
const result = await subjectImagesApi.preview(formId, previewInput, signal) submit
if (result.subjectFormId !== formId) throw new Error('预览结果与当前形态不匹配,请重新读取。') } = useImageGenerationPreview({
return result open,
}, recoveryTarget: () => (props.form ? 'form:' + props.form.id : ''),
generate: input => props.submitGeneration(props.form!.id, input) target: () =>
}) JSON.stringify([props.form?.id, props.form?.generationPrompt, props.form?.subject.identity, props.profile]),
input: () => generationInput.value,
disabled: () => props.disabled || !props.form || !provider.value,
load: async (input, signal) => {
const formId = props.form!.id
const { setPrimary: _setPrimary, ...previewInput } = input
const result = await subjectImagesApi.preview(formId, previewInput, signal)
if (result.subjectFormId !== formId) throw new Error('预览结果与当前形态不匹配,请重新读取。')
return result
},
generate: input => props.submitGeneration(props.form!.id, input)
})
/** 每次打开恢复项目配置,不沿用其它形态的草稿。 */ /** 每次打开恢复项目配置,不沿用其它形态的草稿。 */
watch( watch(
() => [open.value, props.form?.id], () => [open.value, props.form?.id],
@@ -70,7 +78,6 @@ watch(
const defaults = imageGenerationDefaults(props.catalog, props.profile) const defaults = imageGenerationDefaults(props.catalog, props.profile)
provider.value = defaults.provider provider.value = defaults.provider
generationOptions.value = defaults.options generationOptions.value = defaults.options
setPrimary.value = false
}, },
{ immediate: true } { immediate: true }
) )
@@ -118,24 +125,20 @@ watch(
@update:provider="provider = $event" @update:provider="provider = $event"
@update:options="generationOptions = $event" @update:options="generationOptions = $event"
/> />
<!-- 以下是主图切换选择模块,生成完成不等于审核通过 -->
<NCheckbox v-model:checked="setPrimary" :disabled="submitting">生成并通过质量审核后设为主参考图</NCheckbox>
<p v-if="setPrimary" class="text-xs leading-6 text-muted">
会调用视觉审核并可能产生额外费用。{{
form && primaryImage(form.images) ? '审核未通过时保留旧主图。' : '审核未通过时仅保留候选图。'
}}不会自动重试或追加生图。
</p>
<!-- 以下是与当前参数绑定的只读预览及费用确认模块 --> <!-- 以下是与当前参数绑定的只读预览及费用确认模块 -->
<ImageGenerationPreview <ImageGenerationPreview
:preview="preview" :preview="preview"
:loading="loading" :loading="loading"
:disabled="disabled || submitting || !form || !provider" :disabled="disabled || submitting || !form || !provider"
:error="error" :error="error"
:stale-notice="staleNotice" :stale-notice="staleNotice || recoveryNotice"
@load="loadPreview" @load="loadPreview"
/> />
<NCheckbox id="confirm-image-cost" v-model:checked="acknowledged" :disabled="!preview || submitting" <NCheckbox
>我已核对本次预览和主图选项,确认模型费用。</NCheckbox id="confirm-image-cost"
v-model:checked="acknowledged"
:disabled="!preview || submitting || !!recoveryNotice"
>我已核对本次预览,并确认图片生成可能产生费用。</NCheckbox
> >
</AppForm> </AppForm>
<template #footer> <template #footer>
@@ -1,5 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import RawDataDetails from '../../../components/ui/RawDataDetails.vue' import RawDataDetails from '../../../components/ui/RawDataDetails.vue'
import FormSourceDiagnostics from './FormSourceDiagnostics.vue'
import ImageValidationPanel from './ImageValidationPanel.vue' import ImageValidationPanel from './ImageValidationPanel.vue'
import { imageValidationPassed, type ImageValidationResult } from '../validation' import { imageValidationPassed, type ImageValidationResult } from '../validation'
import { errorMessage } from '../../../lib/http' import { errorMessage } from '../../../lib/http'
@@ -53,6 +54,29 @@ const images = computed(() => query.data.value ?? [])
const selected = computed( const selected = computed(
() => images.value.find(image => image.id === selectedId.value) ?? primaryImage(images.value) ?? images.value[0] () => images.value.find(image => image.id === selectedId.value) ?? primaryImage(images.value) ?? images.value[0]
) )
/** 仅对当前完成图查询来源;变化后旧结果不会开放操作。 */
const sourceKey = computed(() =>
key.value && selected.value?.status === 'completed' && selected.value.imageUrl
? JSON.stringify([key.value, selected.value.id])
: ''
)
/** 审核来源预检只读,不调用 Vision。 */
const source = useQuery(sourceKey, async (value, signal) => {
if (!value) return null
const [formId, imageId] = JSON.parse(value) as [string, string]
const result = await subjectImagesApi.validationPreview(formId, imageId, signal)
if (result.subjectFormId !== formId || result.imageId !== imageId) throw new Error('审核来源与当前图片不匹配。')
return result
})
/** 当前图片来源得到确认后才允许审核或晋升。 */
const sourceCurrent = computed(
() =>
!source.loading.value &&
!source.error.value &&
source.data.value?.imageId === selected.value?.id &&
source.data.value?.sourceCurrent === true &&
source.data.value?.canValidate === true
)
/** 项目内的真实活动锁。 */ /** 项目内的真实活动锁。 */
const operation = computed(() => getOperation(props.projectId)) const operation = computed(() => getOperation(props.projectId))
/** 历史复用图失去当前母版或基础形态条件时只供查看,不能重新设为主图。 */ /** 历史复用图失去当前母版或基础形态条件时只供查看,不能重新设为主图。 */
@@ -75,9 +99,13 @@ const canSetPrimary = computed(
selected.value?.status === 'completed' && selected.value?.status === 'completed' &&
!!selected.value.imageUrl && !!selected.value.imageUrl &&
!selected.value.isPrimary && !selected.value.isPrimary &&
selected.value.qualityPassed !== false && sourceCurrent.value &&
selected.value.qualityPassed === true &&
!selected.value.qualityIssues?.some(issue => issue.severity === 'error') && !selected.value.qualityIssues?.some(issue => issue.severity === 'error') &&
!(validation.value?.imageId === selected.value.id && !imageValidationPassed(validation.value)) && !(
validation.value?.imageId === selected.value.id &&
!imageValidationPassed(validation.value, props.form?.subject.module)
) &&
!reusedImageUnavailable.value !reusedImageUnavailable.value
) )
/** 已完成候选允许显式重新审核,即使此前质量未通过。 */ /** 已完成候选允许显式重新审核,即使此前质量未通过。 */
@@ -89,6 +117,7 @@ const canValidate = computed(
!query.loading.value && !query.loading.value &&
!query.error.value && !query.error.value &&
!hasRunningImages(images.value) && !hasRunningImages(images.value) &&
sourceCurrent.value &&
selected.value?.status === 'completed' && selected.value?.status === 'completed' &&
!!selected.value.imageUrl !!selected.value.imageUrl
) )
@@ -190,8 +219,8 @@ async function confirmAction() {
result => result =>
result result
? { ? {
type: imageValidationPassed(result) ? 'success' : 'warning', type: imageValidationPassed(result, props.form?.subject.module) ? 'success' : 'warning',
content: imageValidationPassed(result) content: imageValidationPassed(result, props.form?.subject.module)
? '本次图片审核通过,尚未切换主图。' ? '本次图片审核通过,尚未切换主图。'
: '本次图片审核未通过或待复核,原主图保留。' : '本次图片审核未通过或待复核,原主图保留。'
} }
@@ -202,7 +231,7 @@ async function confirmAction() {
if (key.value === requestKey) { if (key.value === requestKey) {
confirming.value = null confirming.value = null
if (!ok) actionError.value = errorMessage(getOperation(projectId).cause) if (!ok) actionError.value = errorMessage(getOperation(projectId).cause)
await query.refresh() await Promise.all([query.refresh(), source.refresh()])
if (ok) emit('changed') if (ok) emit('changed')
} }
pending.value = null pending.value = null
@@ -318,6 +347,29 @@ async function confirmAction() {
class="mt-3 whitespace-pre-wrap" class="mt-3 whitespace-pre-wrap"
>{{ userFacingText(selected.error) }}</ContextNotice >{{ userFacingText(selected.error) }}</ContextNotice
> >
<!-- 以下是当前来源状态与生成时输入证据 -->
<p v-if="source.loading.value" class="mt-3 text-xs text-muted">正在核对图片来源…</p>
<div v-else-if="source.error.value" class="mt-3 text-xs text-danger">
{{ source.error.value }} <NButton text size="small" @click="source.refresh">重新核对</NButton>
</div>
<p v-else-if="source.data.value && !sourceCurrent" class="mt-3 text-xs text-danger">
{{ userFacingText(source.data.value.sourceStaleReason, '图片来源或机位需要重新核对。') }}
</p>
<p v-if="selected.inputSnapshotStatus" class="mt-2 text-xs text-muted">
{{
{ recorded: '已保存生成输入', 'not-recorded': '历史生成输入未记录', invalid: '生成输入证据已失效' }[
selected.inputSnapshotStatus
]
}}
<span v-if="selected.providerInputFingerprint" :title="selected.providerInputFingerprint">
· {{ selected.providerInputFingerprint.slice(0, 12) }}</span
>
</p>
<RawDataDetails
v-if="source.data.value?.providerInputSnapshot"
title="该候选的实际生成输入"
:value="source.data.value.providerInputSnapshot"
/>
<!-- 以下是明确费用的候选审核和主图操作模块 --> <!-- 以下是明确费用的候选审核和主图操作模块 -->
<div class="mt-4 flex flex-wrap items-center gap-3"> <div class="mt-4 flex flex-wrap items-center gap-3">
<NButton <NButton
@@ -358,7 +410,12 @@ async function confirmAction() {
<p v-else-if="selected.status === 'completed'" class="mt-3 text-xs leading-6 text-muted"> <p v-else-if="selected.status === 'completed'" class="mt-3 text-xs leading-6 text-muted">
复用母版与单独审核形态是不同记录。最近审核记录不保证当前来源仍有效;来源或母版变化后需明确重新审核,切换主图时会再次检查。 复用母版与单独审核形态是不同记录。最近审核记录不保证当前来源仍有效;来源或母版变化后需明确重新审核,切换主图时会再次检查。
</p> </p>
<ImageValidationPanel v-if="validation?.imageId === selected.id" class="mt-5" :result="validation" /> <ImageValidationPanel
v-if="validation?.imageId === selected.id"
class="mt-5"
:result="validation"
:module="form?.subject.module"
/>
<!-- 以下是按明确预算完成的质量处理回执,失败不覆盖原主图 --> <!-- 以下是按明确预算完成的质量处理回执,失败不覆盖原主图 -->
<ContextNotice <ContextNotice
v-if="qualityResult" v-if="qualityResult"
@@ -440,6 +497,13 @@ async function confirmAction() {
<p v-else class="py-10 text-center text-sm text-muted"> <p v-else class="py-10 text-center text-sm text-muted">
{{ query.loading.value ? '正在读取图片记录…' : '此形态尚无图片记录,可以先生成一张。' }} {{ query.loading.value ? '正在读取图片记录…' : '此形态尚无图片记录,可以先生成一张。' }}
</p> </p>
<!-- 以下是道具与场景的上游来源检查,可独立于候选图片阅读 -->
<FormSourceDiagnostics
v-if="open && form && (form.subject.module === 'prop' || form.subject.module === 'scene')"
:key="form.id"
:form="form"
:project-id="projectId"
/>
<template #footer> <template #footer>
<NButton :disabled="!!pending" @click="confirming ? (confirming = null) : (open = false)">{{ <NButton :disabled="!!pending" @click="confirming ? (confirming = null) : (open = false)">{{
confirming ? '取消' : '关闭' confirming ? '取消' : '关闭'
@@ -2,6 +2,10 @@
import { computed } from 'vue' import { computed } from 'vue'
import { NButton, NCollapse, NCollapseItem, NTag } from 'naive-ui' import { NButton, NCollapse, NCollapseItem, NTag } from 'naive-ui'
import { Eye } from '@lucide/vue' import { Eye } from '@lucide/vue'
import RevealImage from '../../../components/ui/RevealImage.vue'
import { referenceImageUrl } from '../../../lib/assets'
import { userFacingText } from '../../../lib/user-facing-text'
import type { ImageReferenceBinding } from '../generation-preview'
import ContextNotice from '../../../components/ui/ContextNotice.vue' import ContextNotice from '../../../components/ui/ContextNotice.vue'
import RawDataDetails from '../../../components/ui/RawDataDetails.vue' import RawDataDetails from '../../../components/ui/RawDataDetails.vue'
import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHeading.vue' import WorkspaceSectionHeading from '../../../components/ui/WorkspaceSectionHeading.vue'
@@ -25,6 +29,7 @@ const emit = defineEmits<{ load: [] }>()
/** 参考职责统一中文展示,不展示内部图片编号。 */ /** 参考职责统一中文展示,不展示内部图片编号。 */
const roles: Record<string, string> = { const roles: Record<string, string> = {
'identity-anchor': '主体外观母版', 'identity-anchor': '主体外观母版',
'scene-form-view': '当前形态机位',
'layout-master': '空间布局母版', 'layout-master': '空间布局母版',
'style-character': '人物风格', 'style-character': '人物风格',
'style-scene': '场景风格', 'style-scene': '场景风格',
@@ -33,21 +38,43 @@ const roles: Record<string, string> = {
'form-primary': '形态主图', 'form-primary': '形态主图',
'structure-reference': '结构参考' 'structure-reference': '结构参考'
} }
/** 形态按真实顺序展示;身份预览从同源参考计划取得职责。 */ /** 实际发送地址只在本次预览中使用,限制为可信图片类型。 */
const references = computed(() => { const references = computed(() => {
if (props.preview?.references) const preview = props.preview
return props.preview.references.map(item => ({ if (!preview) return []
order: item.imageNumber, const selected = preview.referencePlan?.selected as
label: roles[item.role] ?? '图片参考' | Array<ImageReferenceBinding & { bindings?: ImageReferenceBinding[] }>
})) | undefined
const selected = props.preview?.referencePlan?.selected return preview.referenceImages.map((image, index) => {
return Array.isArray(selected) const reference = preview.references?.find(item => item.imageNumber === index + 1)
? selected.map((item: { role?: string }, index) => ({ const snapshot = preview.providerInputSnapshot?.references.find(item => item.imageNumber === index + 1)
order: index + 1, const plan = selected?.[index]
label: roles[item.role ?? ''] ?? '图片参考' return {
})) order: index + 1,
: [] src: /^data:image\/(png|jpeg|webp|gif|avif);base64,[a-z\d+/=]+$/i.test(image)
? image
: referenceImageUrl(image),
bindings:
snapshot?.bindings ??
reference?.bindings ??
plan?.bindings ??
(reference ? [{ role: reference.role, subjectRef: '' }] : plan ? [plan] : [])
}
})
}) })
/** 被省略的参考仍展示职责和服务返回的原因,不作为实际图片。 */
const omitted = computed(
() =>
props.preview?.referencePlan?.omitted as
| Array<
ImageReferenceBinding & {
imageId: string
reason?: string
bindings?: ImageReferenceBinding[]
}
>
| undefined
)
</script> </script>
<template> <template>
@@ -74,17 +101,60 @@ const references = computed(() => {
>{{ preview.actualProviderReferenceCount ?? preview.referenceImages.length }} 张参考图</NTag >{{ preview.actualProviderReferenceCount ?? preview.referenceImages.length }} 张参考图</NTag
> >
</div> </div>
<ul v-if="references.length" class="flex flex-wrap gap-x-5 gap-y-1 text-muted"> <!-- 以下是实际图片顺序和全部参考职责 -->
<li v-for="item in references" :key="item.order">图 {{ item.order }} · {{ item.label }}</li> <ul v-if="references.length" class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<li v-for="item in references" :key="item.order" class="min-w-0">
<div class="asset-image max-w-sm">
<RevealImage
v-if="item.src"
:src="item.src"
:alt="`参考图 ${item.order}`"
object-fit="contain"
preview
/>
<span v-else class="text-muted">图片无法预览</span>
</div>
<p class="mt-1 font-medium">图 {{ item.order }}</p>
<p v-for="(binding, index) in item.bindings" :key="index" class="wrap-anywhere text-muted">
{{ roles[binding.role] ?? '图片参考'
}}<template v-if="binding.subjectRef"> · {{ binding.subjectRef }}</template>
<template v-if="'viewDescription' in binding && binding.viewDescription">
· {{ binding.viewDescription }}</template
>
<template v-if="'spatialLayoutVersion' in binding && binding.spatialLayoutVersion">
· 几何版本 {{ binding.spatialLayoutVersion.slice(0, 12) }}</template
>
</p>
</li>
</ul> </ul>
<p v-else-if="!preview.referenceImages.length" class="text-muted">本次没有图片参考。</p> <p v-else class="text-muted">本次没有图片参考。</p>
<NCollapse :default-expanded-names="['prompt']"> <NCollapse :default-expanded-names="['prompt']">
<NCollapseItem name="prompt" title="本次实际使用的画面描述"> <NCollapseItem name="prompt" title="本次实际使用的画面描述">
<p class="whitespace-pre-wrap wrap-anywhere">{{ preview.providerPrompt }}</p> <p class="whitespace-pre-wrap wrap-anywhere">{{ preview.providerPrompt }}</p>
</NCollapseItem> </NCollapseItem>
<NCollapseItem v-if="omitted?.length" name="omitted" title="未进入模型的参考图">
<ul class="space-y-2">
<li v-for="(item, index) in omitted" :key="index">
{{
(item.bindings ?? [item])
.map(binding =>
[roles[binding.role] ?? '图片参考', binding.subjectRef]
.filter(Boolean)
.join(' · ')
)
.join('、')
}}
<p v-if="item.reason" class="text-muted">{{ userFacingText(item.reason) }}</p>
</li>
</ul>
</NCollapseItem>
</NCollapse> </NCollapse>
<RawDataDetails <RawDataDetails
:value="{ generationConfig: preview.generationConfig, referencePlan: preview.referencePlan }" :value="{
generationConfig: preview.generationConfig,
previewFingerprint: preview.previewFingerprint,
providerInputSnapshot: preview.providerInputSnapshot
}"
title="生成参数与参考图详情" title="生成参数与参考图详情"
/> />
</div> </div>
@@ -3,17 +3,30 @@ import { computed } from 'vue'
import { NCollapse, NCollapseItem, NTag } from 'naive-ui' import { NCollapse, NCollapseItem, NTag } from 'naive-ui'
import ContextNotice from '../../../components/ui/ContextNotice.vue' import ContextNotice from '../../../components/ui/ContextNotice.vue'
import { userFacingText } from '../../../lib/user-facing-text' import { userFacingText } from '../../../lib/user-facing-text'
import { imageValidationPassed, sourceRequirementRows, type ImageValidationResult } from '../validation' import {
characterCheckRows,
imageValidationPassed,
sourceRequirementRows,
type ImageValidationResult
} from '../validation'
/** 展示指定图片本次审核与原始定义对照,不推断主图或母版已采纳。 */ /** 展示指定图片本次审核与原始定义对照,不推断主图或母版已采纳。 */
const props = defineProps<{ const props = defineProps<{
/** 明确绑定当前图片的正式审核结果。 */ /** 明确绑定当前图片的正式审核结果。 */
result: ImageValidationResult result: ImageValidationResult
/** 当前正式主体模块。 */
module?: string
}>() }>()
/** 只有证据完整才使用成功状态。 */ /** 只有证据完整才使用成功状态。 */
const passed = computed(() => imageValidationPassed(props.result)) const passed = computed(() => imageValidationPassed(props.result, props.module))
/** 原文与观测按标识关联,内部标识不出现在标题中。 */ /** 原文与观测按标识关联,内部标识不出现在标题中。 */
const requirements = computed(() => sourceRequirementRows(props.result)) const requirements = computed(() => sourceRequirementRows(props.result))
/** 角色的四项独立审核证据。 */
const characterChecks = computed(() =>
props.module === 'character' || props.result.characterCheckResults ? characterCheckRows(props.result) : []
)
/** 分项状态使用可读中文,保留实际证据。 */
const checkLabels = { passed: '通过', failed: '未通过', needs_review: '待复核', not_applicable: '不适用' }
</script> </script>
<template> <template>
@@ -37,6 +50,17 @@ const requirements = computed(() => sourceRequirementRows(props.result))
>{{ userFacingText(issue.description) }} >{{ userFacingText(issue.description) }}
</li> </li>
</ul> </ul>
<!-- 以下是角色交付四项检查和像素证据 -->
<section v-if="characterChecks.length" class="space-y-3">
<h3 class="text-sm font-medium">角色交付检查</h3>
<ul class="grid gap-3 sm:grid-cols-2 text-xs leading-6">
<li v-for="{ check, label, item } in characterChecks" :key="check">
<strong>{{ label }} · {{ item ? checkLabels[item.status] : '待复核' }}</strong>
<p class="text-muted wrap-anywhere">{{ userFacingText(item?.evidence, '尚无完整审核证据。') }}</p>
</li>
</ul>
</section>
<!-- 以下是原始外观定义及明确数量的逐条审核模块 --> <!-- 以下是原始外观定义及明确数量的逐条审核模块 -->
<NCollapse v-if="requirements.length" :default-expanded-names="['source']"> <NCollapse v-if="requirements.length" :default-expanded-names="['source']">
<NCollapseItem name="source" title="原始外观定义核对"> <NCollapseItem name="source" title="原始外观定义核对">
@@ -1,7 +1,42 @@
import { computed, onBeforeUnmount, ref, shallowRef, watch, type Ref } from 'vue' import { computed, onBeforeUnmount, ref, shallowRef, watch, type Ref } from 'vue'
import { ApiError, errorMessage } from '../../lib/http' import { ApiError, errorMessage } from '../../lib/http'
/** 三类图片入口共用的实际生成预览。 */ /** 同一张实际参考图可承担多个来源职责。 */
export interface ImageReferenceBinding {
/** 业务主体引用。 */
subjectRef: string
/** 正式参考职责。 */
role: string
/** 当前形态的机位说明。 */
viewDescription?: string
/** 绑定的空间几何版本。 */
spatialLayoutVersion?: string
}
/** 服务端记录的最终输入,不含图片二进制。 */
export interface ProviderImageInputSnapshot {
/** 与执行一致的输入指纹。 */
fingerprint: string
/** 实际来源版本。 */
sourceFingerprint: string
/** 实际提交的参数。 */
generationOptions: Record<string, unknown>
/** 可选实际宽度。 */
width?: number
/** 可选实际高度。 */
height?: number
/** 实际负向描述。 */
negativePrompt?: string
/** 按实际发送顺序保存的图片和职责。 */
references: Array<{
/** 一基图片顺序。 */
imageNumber: number
/** 此物理图片上的全部职责。 */
bindings: ImageReferenceBinding[]
}>
}
/** 图片入口共用的实际生成预览。 */
export interface ImageGenerationPreview { export interface ImageGenerationPreview {
/** 实际供应方。 */ /** 实际供应方。 */
provider: string provider: string
@@ -17,6 +52,8 @@ export interface ImageGenerationPreview {
generationConfig: Record<string, unknown> generationConfig: Record<string, unknown>
/** 参考图顺序和职责等诊断信息。 */ /** 参考图顺序和职责等诊断信息。 */
referencePlan?: Record<string, unknown> referencePlan?: Record<string, unknown>
/** 已冻结的正式输入快照。 */
providerInputSnapshot?: ProviderImageInputSnapshot
/** 形态接口给出的有序参考图明细。 */ /** 形态接口给出的有序参考图明细。 */
references?: Array<{ references?: Array<{
/** 传入模型的顺序。 */ /** 传入模型的顺序。 */
@@ -27,6 +64,8 @@ export interface ImageGenerationPreview {
imageId: string imageId: string
/** 可展示的图片地址。 */ /** 可展示的图片地址。 */
imageUrl: string imageUrl: string
/** 同一实际参考图的全部职责。 */
bindings?: ImageReferenceBinding[]
}> }>
/** 含布局母版的真实参考图数量。 */ /** 含布局母版的真实参考图数量。 */
actualProviderReferenceCount?: number actualProviderReferenceCount?: number
@@ -46,6 +85,8 @@ interface PreviewOptions<Input extends object, Preview extends ImageGenerationPr
open: Ref<boolean> open: Ref<boolean>
/** 主体、形态及已有来源的稳定标识。 */ /** 主体、形态及已有来源的稳定标识。 */
target: () => string target: () => string
/** 跨表单开关稳定的计费核对目标。 */
recoveryTarget?: () => string
/** 当前完整生成参数。 */ /** 当前完整生成参数。 */
input: () => Input input: () => Input
/** 当前是否允许提交。 */ /** 当前是否允许提交。 */
@@ -56,6 +97,39 @@ interface PreviewOptions<Input extends object, Preview extends ImageGenerationPr
generate: (input: Input & { expectedPreviewFingerprint: string }) => Promise<ImageGenerationSubmission> 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 重新确认。 * 绑定预览与提交参数,处理过期响应、关闭及 409 重新确认。
* @param options 当前表单、正式预览与生成操作 * @param options 当前表单、正式预览与生成操作
@@ -82,6 +156,14 @@ export function useImageGenerationPreview<Input extends object, Preview extends
let revision = 0 let revision = 0
/** 预览请求取消句柄;生成提交不取消或重试。 */ /** 预览请求取消句柄;生成提交不取消或重试。 */
let controller: AbortController | undefined let controller: AbortController | undefined
/** 核对范围只绑定正式目标,切换参数不会解除。 */
const recoveryKey = computed(() => options.recoveryTarget?.() || options.target())
/** 已提交但回执未知时,保留候选核对提示。 */
const recoveryNotice = computed(() =>
hasUnknownGeneration(recoveryKey.value)
? '本次请求的结果和费用待核对。请先刷新候选与任务记录,并核对原请求。'
: ''
)
/** 当前界面的预览必须完整且费用已确认。 */ /** 当前界面的预览必须完整且费用已确认。 */
const canSubmit = computed( const canSubmit = computed(
() => () =>
@@ -89,6 +171,7 @@ export function useImageGenerationPreview<Input extends object, Preview extends
!options.disabled() && !options.disabled() &&
!submitting.value && !submitting.value &&
!loading.value && !loading.value &&
!recoveryNotice.value &&
!!preview.value && !!preview.value &&
acknowledged.value acknowledged.value
) )
@@ -124,10 +207,16 @@ export function useImageGenerationPreview<Input extends object, Preview extends
if ( if (
!result || !result ||
!/^[a-f0-9]{64}$/i.test(result.previewFingerprint) || !/^[a-f0-9]{64}$/i.test(result.previewFingerprint) ||
(result.providerInputSnapshot &&
result.providerInputSnapshot.fingerprint !== result.previewFingerprint) ||
!result.providerPrompt?.trim() || !result.providerPrompt?.trim() ||
!result.provider || !result.provider ||
!result.model || !result.model ||
!Array.isArray(result.referenceImages) !Array.isArray(result.referenceImages) ||
(result.actualProviderReferenceCount !== undefined &&
result.actualProviderReferenceCount !== result.referenceImages.length) ||
(result.providerInputSnapshot &&
result.providerInputSnapshot.references.length !== result.referenceImages.length)
) )
throw new Error('生成预览不完整,请刷新预览后再确认。') throw new Error('生成预览不完整,请刷新预览后再确认。')
preview.value = result preview.value = result
@@ -144,6 +233,7 @@ export function useImageGenerationPreview<Input extends object, Preview extends
const current = revision const current = revision
const input = JSON.parse(JSON.stringify(options.input())) as Input const input = JSON.parse(JSON.stringify(options.input())) as Input
const fingerprint = preview.value.previewFingerprint const fingerprint = preview.value.previewFingerprint
const recoveryTarget = recoveryKey.value
submitting.value = true submitting.value = true
error.value = '' error.value = ''
let result: ImageGenerationSubmission let result: ImageGenerationSubmission
@@ -154,6 +244,15 @@ export function useImageGenerationPreview<Input extends object, Preview extends
} finally { } finally {
submitting.value = false 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 (current !== revision) return
if (result.accepted) { if (result.accepted) {
options.open.value = false options.open.value = false
@@ -163,14 +262,27 @@ export function useImageGenerationPreview<Input extends object, Preview extends
if ( if (
result.cause instanceof ApiError && result.cause instanceof ApiError &&
result.cause.status === 409 && result.cause.status === 409 &&
result.cause.code === 'IMAGE_PREVIEW_STALE' (result.cause.code === 'IMAGE_PREVIEW_STALE' ||
(result.cause.details as { code?: string } | undefined)?.code === 'IMAGE_PREVIEW_STALE' ||
/^IMAGE_PREVIEW_STALE[::]/.test(result.cause.message))
) { ) {
invalidate() invalidate()
staleNotice.value = '生成依据或配置已变化,本次未生成图片。请核对更新后的预览并重新确认。' staleNotice.value = '生成依据或配置已变化,本次未生成图片。请核对更新后的预览并重新确认。'
await loadPreview() await loadPreview()
} else { } else if (!recoveryNotice.value) {
error.value = result.cause ? errorMessage(result.cause) : '当前暂不能提交,请刷新项目状态后重试。' error.value = result.cause ? errorMessage(result.cause) : '当前暂不能提交,请刷新项目状态后重试。'
} }
} }
return { preview, acknowledged, loading, submitting, error, staleNotice, canSubmit, loadPreview, submit } return {
preview,
acknowledged,
loading,
submitting,
error,
staleNotice,
recoveryNotice,
canSubmit,
loadPreview,
submit
}
} }
@@ -0,0 +1,114 @@
import { request } from '../../lib/http'
/** 服务端提供的道具当前规格及来源证据。 */
export interface PropStructureReadiness {
/** 正式形态编号。 */
subjectFormId: string
/** 仅表示规格有效,与图片质量分开。 */
status: 'ready' | 'missing' | 'stale'
/** 来源失效原因。 */
reason?: string | null
/** 当前有效的基础结构。 */
spec: {
/** 道具语义类别。 */
semanticClass: string
/** 原始部件及数量。 */
parts: Array<{
/** 部件编号。 */ id: string
/** 部件名称。 */ name: string
/** 基础数量。 */ quantity: number
}>
/** 由正式原文解析的当前状态。 */
formState?: {
/** 部件的当前变化和正式来源。 */
changes: Array<{
/** 基础部件编号。 */ partId: string
/** 当前状态说明。 */ description: string
/** 当前数量,包含明确缺失时的零。 */ visibleQuantity?: number
/** 正式剧集和逐字证据。 */ evidence: {
/** 剧集编号。 */ episodeId: string
/** 引文。 */ quote: string
}
}>
}
} | null
/** 当前状态投影,明确缺失的部件可不出现在列表。 */
currentSpec?: NonNullable<PropStructureReadiness['spec']>
/** 正式剧集来源。 */
sourceEpisodes?: Array<{
/** 剧集编号。 */ episodeId: string
/** 集数。 */ episode: number
/** 标题。 */ title: string
}>
/** 数量与拆装可能由不同剧集证明。 */
ownershipEvidence?: Array<{
/** 部件名称。 */ name: string
/** 原文明确的数量。 */ quantity: number
/** 数量证据的剧集编号。 */ episodeId: string
/** 数量证据原句。 */ sourceQuote: string
/** 拆装证据的剧集编号。 */ relationEpisodeId: string
/** 拆装证据原句。 */ relationQuote: string
}>
/** 实际尝试的结果,仅供诊断。 */
lastGenerationAttempt?: {
/** 是否仍对应当前来源。 */ sourceCurrent: boolean
/** 任务状态。 */ status: string
/** 原始失败原因。 */ error: string | null
/** 完整解析候选与纠正过程。 */ evidence: unknown
/** 当时输入与来源,仅供复核。 */ inputSnapshot: unknown
} | null
}
/** 共享空间布局与其几何版本。 */
interface SceneLayout {
/** 布局编号。 */ id: string
/** 布局名称。 */ name: string
/** 当前几何版本。 */ version: string
/** 同一布局涵盖的场景主体。 */ sceneSubjectIds: string[]
}
/** 布局内独立的全局参考或形态专属机位。 */
interface SceneMaster {
/** 参考资产编号。 */ id: string
/** 形态编号,空值表示全局。 */ subjectFormId: string | null
/** 当前目标机位。 */ viewDescription: string | null
/** 参考图片地址。 */ imageUrl: string
/** 服务保存的确认状态。 */ status: string
/** 当时采用的几何版本。 */ spatialLayoutVersion: string
}
/** 现有图库按需读取上游诊断,全程只读。 */
export const sourceDiagnosticsApi = {
/**
* 读取道具规格、来源和最近准备记录。
* @param formId 正式形态编号
* @param signal 关闭诊断时取消
* @returns 当前结构与历史证据
*/
prop: (formId: string, signal?: AbortSignal) =>
request<PropStructureReadiness>(`/subject-forms/${encodeURIComponent(formId)}/prop-structure-spec/readiness`, {
signal
}),
/**
* 读取当前场景几何及全局和当前形态的机位参考。
* @param projectId 正式项目编号
* @param subjectId 正式场景主体编号
* @param formId 正式形态编号
* @param signal 关闭诊断时取消
* @returns 按布局分组的实际参考及其记录状态
*/
async scene(projectId: string, subjectId: string, formId: string, signal?: AbortSignal) {
const path = `/projects/${encodeURIComponent(projectId)}/shared-spatial-layouts`
const layouts = (await request<SceneLayout[]>(path, { signal })).filter(layout =>
layout.sceneSubjectIds.includes(subjectId)
)
return Promise.all(
layouts.map(async layout => ({
...layout,
masters: (
await request<SceneMaster[]>(`${path}/${encodeURIComponent(layout.id)}/masters`, { signal })
).filter(master => master.subjectFormId === null || master.subjectFormId === formId)
}))
)
}
}
+4
View File
@@ -6,6 +6,10 @@ export type SubjectImageStatus = 'pending' | 'generating' | 'completed' | 'faile
/** 图库列表返回的图片元数据;正式图片 ID 与形态 ID 均来自数据库。 */ /** 图库列表返回的图片元数据;正式图片 ID 与形态 ID 均来自数据库。 */
export interface SubjectImage { export interface SubjectImage {
/** 生成时的输入记录状态,包含失败候选。 */
inputSnapshotStatus?: 'recorded' | 'not-recorded' | 'invalid'
/** 实际生成输入指纹。 */
providerInputFingerprint?: string | null
/** 最近一次结构化质量结论;缺失或 null 不代表通过。 */ /** 最近一次结构化质量结论;缺失或 null 不代表通过。 */
qualityPassed?: boolean | null qualityPassed?: boolean | null
/** 最近一次质量问题;最新可用性仍以制作准备检查为准。 */ /** 最近一次质量问题;最新可用性仍以制作准备检查为准。 */
@@ -158,7 +158,7 @@ export function useSubjectImages() {
const ok = await runOperation(projectId, `提交 ${form.subject.name} · ${form.name} 图片生成`, async () => { const ok = await runOperation(projectId, `提交 ${form.subject.name} · ${form.name} 图片生成`, async () => {
const image = await subjectImagesApi.generate(formId, input) const image = await subjectImagesApi.generate(formId, input)
if (!image || image.subjectFormId !== formId || !['pending', 'generating'].includes(image.status)) if (!image || image.subjectFormId !== formId || !['pending', 'generating'].includes(image.status))
throw new Error(image?.error || '图片生成任务未成功创建,请刷新后重试。') throw new ApiError('图片任务回执待核对,请刷新候选和任务。', 202)
}) })
const cause = getOperation(projectId).cause const cause = getOperation(projectId).cause
if (ok && id.value === projectId) { if (ok && id.value === projectId) {
+40 -1
View File
@@ -46,6 +46,24 @@ export interface SourceVisualRequirementResult {
}> }>
} }
/** 角色交付检查名称与展示文案。 */
export const characterCheckLabels = {
presentation: '画面交付要求',
skinWithinImage: '单图肤色与肤质',
skinAcrossReferences: '跨图肤色一致性',
identityAcrossReferences: '跨图身份一致性'
} as const
/** 单项角色质量证据。 */
export interface CharacterCheckResult {
/** 正式审核项。 */
check: keyof typeof characterCheckLabels
/** 实际检查状态。 */
status: 'passed' | 'failed' | 'needs_review' | 'not_applicable'
/** 像素观察或不适用原因。 */
evidence: string
}
/** 身份与形态图片共用的正式视觉审核结果。 */ /** 身份与形态图片共用的正式视觉审核结果。 */
export interface ImageValidationResult { export interface ImageValidationResult {
/** 正式主体编号。 */ /** 正式主体编号。 */
@@ -68,6 +86,8 @@ export interface ImageValidationResult {
physicalStructureValid?: boolean physicalStructureValid?: boolean
/** 空间布局是否有效。 */ /** 空间布局是否有效。 */
spatialLayoutValid?: boolean spatialLayoutValid?: boolean
/** 角色交付审核分项。 */
characterCheckResults?: CharacterCheckResult[]
/** 本次质量问题。 */ /** 本次质量问题。 */
issues: ImageQualityIssue[] issues: ImageQualityIssue[]
/** 业务摘要。 */ /** 业务摘要。 */
@@ -122,14 +142,33 @@ export function sourceRequirementRows(result: ImageValidationResult) {
}) })
} }
/**
* 将四项角色证据按固定顺序展示,缺失与重复均标为待复核。
* @param result 当前图片审核结果
* @returns 每项名称和唯一证据
*/
export function characterCheckRows(result: ImageValidationResult) {
return Object.entries(characterCheckLabels).map(([check, label]) => {
const matches = result.characterCheckResults?.filter(item => item.check === check) ?? []
const item = matches.length === 1 && matches[0]?.evidence?.trim() ? matches[0] : undefined
return { check, label, item }
})
}
/** /**
* 展示成功必须同时具备服务端通过结论和完整原始定义证据。 * 展示成功必须同时具备服务端通过结论和完整原始定义证据。
* @param result 当前图片审核结果 * @param result 当前图片审核结果
* @param module 当前主体模块
* @returns 是否可以展示本次审核通过 * @returns 是否可以展示本次审核通过
*/ */
export function imageValidationPassed(result: ImageValidationResult): boolean { export function imageValidationPassed(result: ImageValidationResult, module?: string): boolean {
return ( return (
result.passed === true && result.passed === true &&
(!(module === 'character' || result.characterCheckResults) ||
characterCheckRows(result).every(
({ check, item }) =>
item?.status === 'passed' || (check !== 'presentation' && item?.status === 'not_applicable')
)) &&
result.sourceRequirementsPassed === true && result.sourceRequirementsPassed === true &&
Array.isArray(result.sourceVisualRequirements) && Array.isArray(result.sourceVisualRequirements) &&
!result.issues.some(issue => issue.severity === 'error') && !result.issues.some(issue => issue.severity === 'error') &&
@@ -201,6 +201,13 @@ const settledItems = computed(() => {
}) })
/** 首帧质量后台任务使用独立的通过与修复失败统计,不套用普通生图字段。 */ /** 首帧质量后台任务使用独立的通过与修复失败统计,不套用普通生图字段。 */
const keyframeQuality = computed(() => props.execution?.workflowName === 'keyframe-quality') const keyframeQuality = computed(() => props.execution?.workflowName === 'keyframe-quality')
/** 首帧工作流中断时按持久化恢复说明处理,不推断可重试。 */
const keyframeRecovery = computed(
() =>
(keyframeQuality.value || props.execution?.workflowName === 'keyframe-generation') &&
result.value.recoveryRequired === true &&
result.value.retryAutomatically === false
)
/** 首帧编辑复用质量工作流,最终回执不属于批量质量统计。 */ /** 首帧编辑复用质量工作流,最终回执不属于批量质量统计。 */
const keyframeEdit = computed(() => props.execution?.metadata?.action === 'edit-keyframe') const keyframeEdit = computed(() => props.execution?.metadata?.action === 'edit-keyframe')
/** 只接受后端完整的质量计数,畸形或缺失结果不显示全成功。 */ /** 只接受后端完整的质量计数,畸形或缺失结果不显示全成功。 */
@@ -537,6 +544,10 @@ function isInputMode(value: unknown, inputMode: string): boolean {
{{ diagnosisCount('failed') ?? '待确认' }} 镜。 {{ diagnosisCount('failed') ?? '待确认' }} 镜。
</p> </p>
</div> </div>
<!-- 以下是首帧工作流中断后的人工核查说明 -->
<p v-if="keyframeRecovery" class="mt-3 text-xs leading-6">
首帧任务中断,费用与结果待核对。请先查看已保存候选并核对原请求,再决定后续操作。
</p>
<!-- 以下是非拆解任务的 Naive 详情折叠模块 --> <!-- 以下是非拆解任务的 Naive 详情折叠模块 -->
<NCollapse v-if="!breakdownTask && !embedded" class="mt-3 text-xs text-muted"> <NCollapse v-if="!breakdownTask && !embedded" class="mt-3 text-xs text-muted">
<NCollapseItem name="task-details" title="任务详情"> <NCollapseItem name="task-details" title="任务详情">
+15
View File
@@ -93,6 +93,20 @@ export function userFacingText(value: string | null | undefined, fallback = '暂
const codeLabels: Record<string, string> = { const codeLabels: Record<string, string> = {
...configurationErrorLabels, ...configurationErrorLabels,
PROP_STRUCTURE_SPEC_NOT_READY: '道具结构规格尚未就绪,请在形态图片的“图片准备检查”中准备资料后重新预览。', PROP_STRUCTURE_SPEC_NOT_READY: '道具结构规格尚未就绪,请在形态图片的“图片准备检查”中准备资料后重新预览。',
SUBJECT_VISUAL_FACTS_STALE: '主体、形态或原文版本已变化,请重新核对。',
SUBJECT_VISUAL_FACTS_LOCKED: '主体已有图片、身份已锁定或项目任务正在进行,当前无法修订。',
SUBJECT_VISUAL_FACTS_SOURCE_INVALID: '逐字引文与当前正式原文不匹配。',
SUBJECT_VISUAL_FACTS_FORM_BINDING: '形态列表已变化,请核对全部正式形态。',
IMAGE_REQUIRED_REFERENCE_MISSING: '缺少必要参考图,请先准备并确认正式资产。',
IMAGE_REFERENCE_CAPACITY_EXCEEDED: '必要参考图超出当前模型容量。',
IMAGE_INPUT_STALE: '图片使用的正式来源已变化。',
IMAGE_INPUT_SNAPSHOT_INVALID: '图片的实际生成输入记录已失效。',
SCENE_FORM_VIEW_REFERENCE_INVALID: '当前形态的机位参考不匹配。',
SCENE_FORM_VIEW_REFERENCE_UNCONFIRMED: '当前形态机位尚未确认。',
SCENE_FORM_VIEW_REFERENCE_STALE: '机位参考采用的几何版本已过期。',
DURATION_BUDGET_SOURCE_STALE: '正式剧集预算已变化,请重新核对。',
DURATION_BUDGET_SOURCE: '缺少可核对的正式预算快照。',
DURATION_BUDGET: '动作需求与当前时长预算冲突。',
IMAGE_PREVIEW_STALE: '生成依据或配置已变化,请重新预览并确认后再生成。', IMAGE_PREVIEW_STALE: '生成依据或配置已变化,请重新预览并确认后再生成。',
INVALID_IMAGE_PREVIEW_FINGERPRINT: '预览版本无效,请重新读取生成预览。', INVALID_IMAGE_PREVIEW_FINGERPRINT: '预览版本无效,请重新读取生成预览。',
QUALITY_POLICY_RECONFIRM_REQUIRED: '质量规则或正式分镜来源需要重新核对并确认。', QUALITY_POLICY_RECONFIRM_REQUIRED: '质量规则或正式分镜来源需要重新核对并确认。',
@@ -108,6 +122,7 @@ export function userFacingText(value: string | null | undefined, fallback = '暂
) )
if (code === 'PROP_STRUCTURE_SPEC_NOT_READY' || code === 'INVALID_IMAGE_PREVIEW_FINGERPRINT') if (code === 'PROP_STRUCTURE_SPEC_NOT_READY' || code === 'INVALID_IMAGE_PREVIEW_FINGERPRINT')
return codeLabels[code]! return codeLabels[code]!
if (code === 'DURATION_BUDGET' && /^[::]\s*\{/.test(text.slice(code.length))) return codeLabels[code]!
if (code) if (code)
text = text =
text text
@@ -0,0 +1,69 @@
import { flushPromises, mount } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import BreakdownDurationDiagnostics from '@/features/breakdown/components/BreakdownDurationDiagnostics.vue'
afterEach(() => vi.unstubAllGlobals())
describe('时长冲突诊断', () => {
it('分开显示正式目标与失败候选预算,诊断只发出 GET', async () => {
const plan = {
episodeNo: 2,
targetDurationSeconds: 45,
beats: [{ beatNo: 3, title: '拆卸', estimatedDurationSeconds: 9 }]
}
const fetcher = vi.fn<typeof fetch>(
async url =>
new Response(
JSON.stringify({
data: String(url).endsWith('/duration-budget')
? {
projectId: 'duration-project',
episodes: [
{ episodeNo: 2, targetDurationSeconds: 60, shotCount: 0, shotSeconds: null }
]
}
: {
projectId: 'duration-project',
storyboardPlans: [plan],
storyboardEpisodeDurationBudgets: [
{
episodeNo: 2,
minimumRequiredSeconds: 10,
deficitSeconds: 1,
beatSuggestions: [
{ beatNo: 3, budgetSeconds: 9, requiredSeconds: 10, deficitSeconds: 1 }
]
}
],
failureDetails: {
details: [
{
kind: 'storyboard-duration-failure',
episodeNo: 2,
candidate: { episodeNo: 2, episodePlan: plan, beatShots: [] },
retryAutomatically: false
}
]
}
}
})
)
)
vi.stubGlobal('fetch', fetcher)
const wrapper = mount(BreakdownDurationDiagnostics, { props: { projectId: 'duration-project' } })
try {
await flushPromises()
expect(wrapper.text()).toContain('正式目标 60 秒')
expect(wrapper.text()).toContain('正式镜头 未生成')
expect(wrapper.text()).toContain('完整失败候选')
await wrapper.get('.n-collapse-item__header-main').trigger('click')
await flushPromises()
expect(wrapper.text()).toMatch(/拆解时目标\s+45 秒/)
expect(wrapper.text()).toContain('正式目标已变化')
expect(wrapper.text()).toMatch(/最低需求 10 秒 · 缺口 1 秒/)
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
} finally {
wrapper.unmount()
}
})
})
+58 -29
View File
@@ -197,44 +197,64 @@ describe('镜头生产数据契约', () => {
expect(fetcher.mock.calls[1]?.[1]?.method).toBe('GET') expect(fetcher.mock.calls[1]?.[1]?.method).toBe('GET')
}) })
it('所有首帧生成都先成为候选,并要求费用确认', async () => { it('首帧只提交用户核对过的版本,替换也先保存候选', async () => {
/** 弹窗打开时只读取模型目录和项目配置,测试不依赖真实后端。 */ const fingerprint = 'a'.repeat(64)
const submitGeneration = vi.fn<() => Promise<{ accepted: boolean }>>(async () => ({ accepted: true }))
const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => { const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => {
const path = String(url) const path = String(url)
if (path === '/api/generation-models') return new Response(JSON.stringify({ data: imageCatalog })) if (path === '/api/generation-models') return new Response(JSON.stringify({ data: imageCatalog }))
if (path === '/api/projects/project-1/creative-profile') if (path === '/api/projects/project-1/creative-profile')
return new Response(JSON.stringify({ data: generationProfile('project-1') })) return new Response(JSON.stringify({ data: generationProfile('project-1') }))
throw new Error(`首帧弹窗出现未预期请求:${path}`) const shotId = path.match(/storyboard-shots\/([^/]+)/)?.[1]
return new Response(
JSON.stringify({
data: {
shotId,
previewFingerprint: fingerprint,
provider: 'qwen-image',
model: 'qwen-image-3.0-pro',
providerPrompt: '完整首帧画面描述',
generationConfig: {},
referenceImages: []
}
})
)
}) })
vi.stubGlobal('fetch', fetcher) vi.stubGlobal('fetch', fetcher)
wrapper = mount(KeyframeDialog, { wrapper = mount(KeyframeDialog, {
attachTo: document.body, attachTo: document.body,
props: { open: true, shotId: 'shot-1', shotTitle: '开场', projectId: 'project-1', disabled: false } props: {
open: true,
shotId: 'shot-1',
shotTitle: '开场',
projectId: 'project-1',
disabled: false,
submitGeneration
}
}) })
await flushPromises() await flushPromises()
expect(button('确认生成首帧').disabled).toBe(true) expect(button('确认生成首帧').disabled).toBe(true)
document.querySelector<HTMLInputElement>('#confirm-keyframe-cost')!.click() for (const shotId of ['shot-1', 'shot-2']) {
await flushPromises() if (shotId === 'shot-2') {
button('确认生成首帧').click() await wrapper.setProps({ open: false })
await flushPromises() await wrapper.setProps({ open: true, shotId, replacePrimary: true })
expect(wrapper.emitted('generate')).toEqual([ await flushPromises()
[{ provider: 'qwen-image', generationOptions: { size: '2048*2048' }, setPrimary: false }] }
]) button('预览实际生成输入').click()
await flushPromises()
await wrapper.setProps({ open: false }) expect(button('确认生成首帧').disabled).toBe(true)
await flushPromises() document.querySelector<HTMLInputElement>('#confirm-keyframe-cost')!.click()
await wrapper.setProps({ open: true, shotId: 'shot-2', replacePrimary: true }) await flushPromises()
await flushPromises() button('确认生成首帧').click()
expect(document.body.textContent).toContain('生成替代候选') await flushPromises()
document.querySelector<HTMLInputElement>('#confirm-keyframe-cost')!.click() }
await flushPromises() expect(submitGeneration).toHaveBeenCalledTimes(2)
button('确认生成首帧').click() expect(submitGeneration).toHaveBeenLastCalledWith({
await flushPromises() provider: 'qwen-image',
expect(wrapper.emitted('generate')?.at(-1)).toEqual([ generationOptions: { size: '2048*2048' },
{ provider: 'qwen-image', generationOptions: { size: '2048*2048' }, setPrimary: false } setPrimary: false,
]) expectedPreviewFingerprint: fingerprint
expect(fetcher).toHaveBeenCalledTimes(4) })
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
}) })
it('首帧生成前可预览后端最终选图规划和 Prompt', async () => { it('首帧生成前可预览后端最终选图规划和 Prompt', async () => {
@@ -277,6 +297,8 @@ describe('镜头生产数据契约', () => {
model: 'image-model', model: 'image-model',
generationConfig: {}, generationConfig: {},
references: [], references: [],
previewFingerprint: 'a'.repeat(64),
referenceImages: ['/storage/preview.png'],
referencePlan: { referencePlan: {
provider: 'seedream', provider: 'seedream',
maxReferenceImages: 4, maxReferenceImages: 4,
@@ -307,7 +329,14 @@ describe('镜头生产数据契约', () => {
vi.stubGlobal('fetch', fetcher) vi.stubGlobal('fetch', fetcher)
wrapper = mount(KeyframeDialog, { wrapper = mount(KeyframeDialog, {
attachTo: document.body, attachTo: document.body,
props: { open: true, shotId: 'shot-1', shotTitle: '开场', projectId: 'project-1', disabled: false } props: {
open: true,
shotId: 'shot-1',
shotTitle: '开场',
projectId: 'project-1',
disabled: false,
submitGeneration: vi.fn<() => Promise<{ accepted: boolean }>>(async () => ({ accepted: true }))
}
}) })
await flushPromises() await flushPromises()
button('预览实际生成输入').click() button('预览实际生成输入').click()
@@ -318,8 +347,8 @@ describe('镜头生产数据契约', () => {
provider: 'seedream', provider: 'seedream',
generationOptions: {} generationOptions: {}
}) })
expect(document.body.textContent).toContain('已选 1 / 2 张') expect(document.body.textContent).toContain('1 张参考图')
expect(document.body.textContent).toContain('省略 1 张') expect(document.body.textContent).toContain('未进入模型的参考图')
expect(document.body.textContent).toContain('最终首帧 Prompt') expect(document.body.textContent).toContain('最终首帧 Prompt')
expect(wrapper.emitted('generate')).toBeUndefined() expect(wrapper.emitted('generate')).toBeUndefined()
}) })
@@ -1,4 +1,4 @@
import { imagePreviewFixture } from '../../fixtures/image-preview' import { approvedCharacter, imagePreviewFixture } from '../../fixtures/image-preview'
import { imageCatalog, generationProfile } from '../../fixtures/generation' import { imageCatalog, generationProfile } from '../../fixtures/generation'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -259,6 +259,31 @@ describe('身份图与母版契约', () => {
expect(wrapper.emitted('regenerate')).toEqual([['failed-front']]) expect(wrapper.emitted('regenerate')).toEqual([['failed-front']])
}) })
it('角色交付分项失败时不能以总结果通过开启选角', async () => {
const candidate = identityImageFixture({ id: 'candidate', isAnchor: false })
const failed = approvedCharacter(candidate.id)
failed.characterCheckResults![0] = {
check: 'presentation',
status: 'failed',
evidence: '胸口出现未经授权的文字。'
}
wrapper = mount(IdentityGallery, {
attachTo: document.body,
props: {
subjectName: '林夏',
module: 'character',
identityLocked: false,
disabled: false,
images: [candidate],
validationResult: failed
}
})
await flushPromises()
expect(button('确认选角并锁定').disabled).toBe(true)
expect(wrapper.text()).toContain('胸口出现未经授权的文字。')
expect(wrapper.text()).toContain('跨图身份一致性 · 不适用')
expect(wrapper.emitted('anchor')).toBeUndefined()
})
it('明确确认目标后才提交指定候选,刷新同一母版保持管理弹窗,新母版返回后关闭弹窗', async () => { it('明确确认目标后才提交指定候选,刷新同一母版保持管理弹窗,新母版返回后关闭弹窗', async () => {
const anchor = identityImageFixture({ id: 'anchor' }) const anchor = identityImageFixture({ id: 'anchor' })
const candidate = identityImageFixture({ id: 'candidate', isAnchor: false }) const candidate = identityImageFixture({ id: 'candidate', isAnchor: false })
@@ -269,7 +294,8 @@ describe('身份图与母版契约', () => {
module: 'character', module: 'character',
identityLocked: true, identityLocked: true,
disabled: false, disabled: false,
images: [anchor, candidate] images: [anchor, candidate],
validationResult: approvedCharacter(candidate.id)
} }
}) })
button('管理候选(1)').click() button('管理候选(1)').click()
@@ -464,7 +490,8 @@ describe('身份图与母版契约', () => {
module: 'character', module: 'character',
identityLocked: false, identityLocked: false,
disabled: false, disabled: false,
images: [identityImageFixture({ isAnchor: true })] images: [identityImageFixture({ isAnchor: true })],
validationResult: approvedCharacter('identity-image-1')
} }
}) })
button('确认选角并锁定').click() button('确认选角并锁定').click()
@@ -20,7 +20,8 @@ function setup(
generate = vi.fn<() => Promise<ImageGenerationSubmission>>( generate = vi.fn<() => Promise<ImageGenerationSubmission>>(
async (): Promise<ImageGenerationSubmission> => ({ accepted: true }) async (): Promise<ImageGenerationSubmission> => ({ accepted: true })
), ),
load = vi.fn<() => Promise<ReturnType<typeof imagePreviewFixture>>>(async () => imagePreviewFixture()) load = vi.fn<() => Promise<ReturnType<typeof imagePreviewFixture>>>(async () => imagePreviewFixture()),
target = 'form-1'
) { ) {
const open = ref(true), const open = ref(true),
prompt = ref('初始描述') prompt = ref('初始描述')
@@ -30,7 +31,7 @@ function setup(
setup() { setup() {
flow = useImageGenerationPreview({ flow = useImageGenerationPreview({
open, open,
target: () => 'form-1', target: () => target,
input: () => ({ prompt: prompt.value }), input: () => ({ prompt: prompt.value }),
disabled: () => false, disabled: () => false,
load, load,
@@ -65,7 +66,7 @@ describe('生图预览与版本确认', () => {
it('明确的预览过期 409 只重新预览,不自动重复收费请求', async () => { it('明确的预览过期 409 只重新预览,不自动重复收费请求', async () => {
const generate = vi.fn<() => Promise<ImageGenerationSubmission>>(async () => ({ const generate = vi.fn<() => Promise<ImageGenerationSubmission>>(async () => ({
accepted: false, accepted: false,
cause: new ApiError('过期', 409, undefined, 'IMAGE_PREVIEW_STALE') cause: new ApiError('IMAGE_PREVIEW_STALE: 来源已变化', 409, { code: 'IMAGE_PREVIEW_STALE' })
})) }))
const { flow, open, load } = setup(generate) const { flow, open, load } = setup(generate)
await flow.loadPreview() await flow.loadPreview()
@@ -93,6 +94,47 @@ describe('生图预览与版本确认', () => {
expect(flow.error.value).toContain('活动任务') expect(flow.error.value).toContain('活动任务')
expect(flow.acknowledged.value).toBe(false) expect(flow.acknowledged.value).toBe(false)
}) })
it.each(['IMAGE_REQUIRED_REFERENCE_MISSING', 'IMAGE_REFERENCE_CAPACITY_EXCEEDED'])(
'参考图阻断 %s 时禁止生成',
async code => {
const { flow, generate } = setup(
undefined,
vi.fn(async () => {
throw new ApiError(code, 409, { code })
})
)
await flow.loadPreview()
flow.acknowledged.value = true
await flow.submit()
expect(flow.canSubmit.value).toBe(false)
expect(generate).not.toHaveBeenCalled()
}
)
it('计费未知后即使重读免费预览也不重复发起同一目标', async () => {
const generate = vi.fn<() => Promise<ImageGenerationSubmission>>(async () => ({
accepted: false,
cause: new ApiError('连接中断', 0)
}))
const { flow, open, prompt } = setup(generate, undefined, 'form-unknown')
await flow.loadPreview()
flow.acknowledged.value = true
await flow.submit()
open.value = false
open.value = true
prompt.value = '新参数'
await flow.loadPreview()
flow.acknowledged.value = true
await flow.submit()
expect(flow.canSubmit.value).toBe(false)
expect(generate).toHaveBeenCalledOnce()
wrapper?.unmount()
const restored = setup(generate, undefined, 'form-unknown').flow
await restored.loadPreview()
restored.acknowledged.value = true
await restored.submit()
expect(restored.recoveryNotice.value).toContain('费用待核对')
expect(generate).toHaveBeenCalledOnce()
})
it('关闭再打开相同参数后,旧预览响应不得回填', async () => { it('关闭再打开相同参数后,旧预览响应不得回填', async () => {
let resolve!: (value: ReturnType<typeof imagePreviewFixture>) => void let resolve!: (value: ReturnType<typeof imagePreviewFixture>) => void
const { flow, open } = setup( const { flow, open } = setup(
+16 -8
View File
@@ -1,3 +1,4 @@
import { validationPreviewResponse } from '../../fixtures/image-preview'
import { imagePreviewFixture } from '../../fixtures/image-preview' import { imagePreviewFixture } from '../../fixtures/image-preview'
import { imageCatalog, generationProfile } from '../../fixtures/generation' import { imageCatalog, generationProfile } from '../../fixtures/generation'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
@@ -48,7 +49,13 @@ describe('形态图片选择与操作', () => {
imageFixture({ id: 'candidate', isPrimary: false, imageUrl: '/storage/candidate.png' }), imageFixture({ id: 'candidate', isPrimary: false, imageUrl: '/storage/candidate.png' }),
imageFixture({ id: 'failed', isPrimary: false, status: 'failed', imageUrl: null, error: '生成失败详情' }) imageFixture({ id: 'failed', isPrimary: false, status: 'failed', imageUrl: null, error: '生成失败详情' })
] ]
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({ data: rows }))) const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async url =>
String(url).endsWith('/validate/preview')
? validationPreviewResponse(String(url))
: new Response(JSON.stringify({ data: rows }))
)
vi.stubGlobal('fetch', fetcher) vi.stubGlobal('fetch', fetcher)
wrapper = mount(ImageGalleryDialog, { wrapper = mount(ImageGalleryDialog, {
attachTo: document.body, attachTo: document.body,
@@ -74,8 +81,8 @@ describe('形态图片选择与操作', () => {
await flushPromises() await flushPromises()
expect(document.querySelector('.asset-image-preview')?.textContent).toContain('本次生成失败') expect(document.querySelector('.asset-image-preview')?.textContent).toContain('本次生成失败')
expect(button('设为主参考图').disabled).toBe(true) expect(button('设为主参考图').disabled).toBe(true)
expect(fetcher).toHaveBeenCalledOnce() expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/images'))).toHaveLength(1)
expect(fetcher.mock.calls[0]![1]?.method).toBe('GET') expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
expect(wrapper.emitted('changed')).toBeUndefined() expect(wrapper.emitted('changed')).toBeUndefined()
}) })
@@ -253,7 +260,8 @@ describe('形态图片选择与操作', () => {
it('图库不自动生图,主图切换经确认后 PUT,失败图片不能设主图', async () => { it('图库不自动生图,主图切换经确认后 PUT,失败图片不能设主图', async () => {
vi.useFakeTimers() vi.useFakeTimers()
let primary = false let primary = false
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (_url, init) => { const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (String(url).endsWith('/validate/preview')) return validationPreviewResponse(String(url))
if (init?.method === 'PUT') { if (init?.method === 'PUT') {
primary = true primary = true
return new Response(JSON.stringify({ data: imageFixture() })) return new Response(JSON.stringify({ data: imageFixture() }))
@@ -261,7 +269,7 @@ describe('形态图片选择与操作', () => {
return new Response( return new Response(
JSON.stringify({ JSON.stringify({
data: [ data: [
imageFixture({ isPrimary: primary }), imageFixture({ isPrimary: primary, qualityPassed: true }),
imageFixture({ imageFixture({
id: 'failed', id: 'failed',
isPrimary: false, isPrimary: false,
@@ -279,15 +287,15 @@ describe('形态图片选择与操作', () => {
props: { projectId: 'gallery-test', form: formFixture('gallery-test'), open: true, disabled: false } props: { projectId: 'gallery-test', form: formFixture('gallery-test'), open: true, disabled: false }
}) })
await flushPromises() await flushPromises()
expect(fetcher.mock.calls).toHaveLength(1) expect(fetcher.mock.calls).toHaveLength(2)
await vi.advanceTimersByTimeAsync(30_000) await vi.advanceTimersByTimeAsync(30_000)
expect(fetcher.mock.calls).toHaveLength(1) expect(fetcher.mock.calls).toHaveLength(2)
await expandSections() await expandSections()
expect(document.body.textContent).not.toContain('本次实际提示词') expect(document.body.textContent).not.toContain('本次实际提示词')
expect(document.querySelector('[role="dialog"] script')).toBeNull() expect(document.querySelector('[role="dialog"] script')).toBeNull()
button('设为主参考图').click() button('设为主参考图').click()
await flushPromises() await flushPromises()
expect(fetcher.mock.calls).toHaveLength(1) expect(fetcher.mock.calls).toHaveLength(2)
button('确认费用并设为主图').click() button('确认费用并设为主图').click()
await flushPromises() await flushPromises()
expect(fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')?.[0]).toBe( expect(fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')?.[0]).toBe(
@@ -1,3 +1,4 @@
import { validationPreviewResponse } from '../../fixtures/image-preview'
import { mount, flushPromises, type VueWrapper } from '@vue/test-utils' import { mount, flushPromises, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest' import { afterEach, describe, expect, it, vi } from 'vitest'
import ImageGalleryDialog from '@/features/subject-images/components/ImageGalleryDialog.vue' import ImageGalleryDialog from '@/features/subject-images/components/ImageGalleryDialog.vue'
@@ -34,25 +35,26 @@ describe('候选质量与主图门禁', () => {
qualityPassed: false, qualityPassed: false,
qualityIssues: [{ type: 'form_mismatch', severity: 'error', description: '原始数量不一致' }] qualityIssues: [{ type: 'form_mismatch', severity: 'error', description: '原始数量不一致' }]
}) })
const fetcher = vi.fn<typeof fetch>().mockImplementation( const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) =>
async (_url, init) => String(url).endsWith('/validate/preview')
new Response( ? validationPreviewResponse(String(url))
JSON.stringify({ : new Response(
data: JSON.stringify({
init?.method === 'POST' data:
? { init?.method === 'POST'
subjectId: 'subject-db-1', ? {
subjectFormId: 'form-db-1', subjectId: 'subject-db-1',
imageId: 'candidate', subjectFormId: 'form-db-1',
passed: false, imageId: 'candidate',
sourceRequirementsPassed: false, passed: false,
sourceVisualRequirements: [], sourceRequirementsPassed: false,
summary: '需核对数量', sourceVisualRequirements: [],
issues: [] summary: '需核对数量',
} issues: []
: [candidate, original] }
}) : [candidate, original]
) })
)
) )
vi.stubGlobal('fetch', fetcher) vi.stubGlobal('fetch', fetcher)
wrapper = mount(ImageGalleryDialog, { wrapper = mount(ImageGalleryDialog, {
@@ -67,7 +69,7 @@ describe('候选质量与主图门禁', () => {
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true) expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
button('审核此图片').click() button('审核此图片').click()
await flushPromises() await flushPromises()
expect(fetcher).toHaveBeenCalledOnce() expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
button('确认费用并审核').click() button('确认费用并审核').click()
await flushPromises() await flushPromises()
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1) expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1)
@@ -75,16 +77,38 @@ describe('候选质量与主图门禁', () => {
expect(original.isPrimary).toBe(true) expect(original.isPrimary).toBe(true)
expect(document.body.textContent).toContain('需核对数量') expect(document.body.textContent).toContain('需核对数量')
}) })
it('来源过期禁止发起审核与主图确认,保留该候选', async () => {
const image = imageFixture({ isPrimary: false, qualityPassed: true })
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async url =>
String(url).endsWith('/validate/preview')
? validationPreviewResponse(String(url), false)
: new Response(JSON.stringify({ 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(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 () => { it('主图晋升 409 保留原主图,不乐观切换或自动重试', async () => {
const original = imageFixture({ id: 'old' }) const original = imageFixture({ id: 'old' })
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (_url, init) => const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) =>
init?.method === 'PUT' String(url).endsWith('/validate/preview')
? new Response(JSON.stringify({ message: '审核证据已过期,请明确重新审核' }), { status: 409 }) ? validationPreviewResponse(String(url))
: new Response( : init?.method === 'PUT'
JSON.stringify({ ? new Response(JSON.stringify({ message: '审核证据已过期,请明确重新审核' }), { status: 409 })
data: [imageFixture({ id: 'candidate', isPrimary: false, qualityPassed: true }), original] : new Response(
}) JSON.stringify({
) data: [imageFixture({ id: 'candidate', isPrimary: false, qualityPassed: true }), original]
})
)
) )
vi.stubGlobal('fetch', fetcher) vi.stubGlobal('fetch', fetcher)
wrapper = mount(ImageGalleryDialog, { wrapper = mount(ImageGalleryDialog, {
@@ -105,26 +129,27 @@ describe('候选质量与主图门禁', () => {
}) })
it('质量处理默认预算为零,只有明确确认后发出一次请求', async () => { it('质量处理默认预算为零,只有明确确认后发出一次请求', async () => {
const image = imageFixture({ isPrimary: false }) const image = imageFixture({ isPrimary: false })
const fetcher = vi.fn<typeof fetch>().mockImplementation( const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) =>
async (_url, init) => String(url).endsWith('/validate/preview')
new Response( ? validationPreviewResponse(String(url))
JSON.stringify({ : new Response(
data: JSON.stringify({
init?.method === 'POST' data:
? { init?.method === 'POST'
subjectFormId: 'form-db-1', ? {
initialImageId: image.id, subjectFormId: 'form-db-1',
finalImageId: image.id, initialImageId: image.id,
passed: false, finalImageId: image.id,
repaired: false, passed: false,
repairAttempts: 0, repaired: false,
maxRepairAttempts: 0, repairAttempts: 0,
primaryChanged: false, maxRepairAttempts: 0,
attempts: [] primaryChanged: false,
} attempts: []
: [image] }
}) : [image]
) })
)
) )
vi.stubGlobal('fetch', fetcher) vi.stubGlobal('fetch', fetcher)
wrapper = mount(ImageGalleryDialog, { wrapper = mount(ImageGalleryDialog, {
@@ -0,0 +1,66 @@
import { flushPromises, mount } from '@vue/test-utils'
import { NCollapse } from 'naive-ui'
import { afterEach, describe, expect, it, vi } from 'vitest'
import FormSourceDiagnostics from '@/features/subject-images/components/FormSourceDiagnostics.vue'
import { formFixture } from '@/features/subject-images/testing/fixtures'
afterEach(() => vi.unstubAllGlobals())
describe('道具与场景来源诊断', () => {
it.each([
['missing', '尚未准备结构规格'],
['stale', '结构来源已过期']
])('道具 %s 只读取原文和历史,不调用生成', async (status, label) => {
const form = formFixture('source-project')
form.subject.module = 'prop'
const fetcher = vi.fn<typeof fetch>(
async () =>
new Response(
JSON.stringify({
data: {
subjectFormId: form.id,
status,
spec: null,
sourceEpisodes: [
{ episodeId: 'origin', episode: 1, title: '基础形态' },
{ episodeId: 'change', episode: 2, title: '拆卸' }
],
ownershipEvidence: [
{
name: '搭扣',
quantity: 2,
episodeId: 'origin',
sourceQuote: '工具箱有两个搭扣',
relationEpisodeId: 'change',
relationQuote: '搭扣从工具箱脱落'
}
],
lastGenerationAttempt: {
status: 'failed',
sourceCurrent: false,
error: '无法核对归属',
evidence: { candidates: [{ semanticClass: '工具箱' }] },
inputSnapshot: {}
}
}
})
)
)
vi.stubGlobal('fetch', fetcher)
const wrapper = mount(FormSourceDiagnostics, { props: { form, projectId: 'source-project' } })
try {
await flushPromises()
expect(fetcher).not.toHaveBeenCalled()
wrapper.getComponent(NCollapse).vm.$emit('update:expandedNames', ['source'])
await flushPromises()
expect(wrapper.text()).toContain(label)
expect(wrapper.text()).toContain('数量来源 · 第 1 集')
expect(wrapper.text()).toContain('拆装来源 · 第 2 集')
expect(wrapper.text()).toContain('准备时的来源已过期')
expect(fetcher.mock.calls).toHaveLength(1)
expect(fetcher.mock.calls[0]?.[1]?.method).toBe('GET')
} finally {
wrapper.unmount()
}
})
})
+13 -1
View File
@@ -1,3 +1,4 @@
import { approvedCharacter } from '../../fixtures/image-preview'
import { imagePreviewFixture } from '../../fixtures/image-preview' import { imagePreviewFixture } from '../../fixtures/image-preview'
import { preparationFixture } from '../storyboard-preparation/fixtures' import { preparationFixture } from '../storyboard-preparation/fixtures'
import { generationProfile, imageCatalog } from '../../fixtures/generation' import { generationProfile, imageCatalog } from '../../fixtures/generation'
@@ -1176,6 +1177,7 @@ describe('视觉风格与主体身份工作区', () => {
expect(getOperation(fixture.id).pending).toBe(true) expect(getOperation(fixture.id).pending).toBe(true)
finish( finish(
jsonResponse({ jsonResponse({
...approvedCharacter('identity-image-1'),
subjectId: 'subject-db-1', subjectId: 'subject-db-1',
imageId: 'identity-image-1', imageId: 'identity-image-1',
passed, passed,
@@ -1203,6 +1205,8 @@ describe('视觉风格与主体身份工作区', () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => { const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (String(url).endsWith('/subject-forms')) return jsonResponse([form]) if (String(url).endsWith('/subject-forms')) return jsonResponse([form])
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture()) if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture())
if (init?.method === 'POST' && String(url).endsWith('/validate'))
return jsonResponse(approvedCharacter('candidate'))
if (init?.method === 'PUT') { if (init?.method === 'PUT') {
selected = true selected = true
return jsonResponse({ return jsonResponse({
@@ -1219,10 +1223,13 @@ describe('视觉风格与主体身份工作区', () => {
stubFetch(fetcher) stubFetch(fetcher)
await mountAssets('identity') await mountAssets('identity')
expect(wrapper!.find('.identity-anchor-grid').exists()).toBe(true) expect(wrapper!.find('.identity-anchor-grid').exists()).toBe(true)
expect(button('设为身份母版').disabled).toBe(true)
wrapper!.findComponent(IdentityGallery).vm.$emit('validate', 'candidate')
await flushPromises()
button('设为身份母版').click() button('设为身份母版').click()
await flushPromises() await flushPromises()
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'PUT')).toBe(false) expect(fetcher.mock.calls.some(([, init]) => init?.method === 'PUT')).toBe(false)
button('确认切换身份母版').click() button('确认费用并切换母版').click()
await flushPromises() await flushPromises()
expect(fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')?.[0]).toBe( expect(fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')?.[0]).toBe(
'/api/subjects/subject-db-1/identity/images/candidate/stable-anchor' '/api/subjects/subject-db-1/identity/images/candidate/stable-anchor'
@@ -1338,6 +1345,8 @@ describe('视觉风格与主体身份工作区', () => {
] ]
}) })
if (path.endsWith('/identity/images')) return jsonResponse([{ ...candidate, isAnchor: selected }]) if (path.endsWith('/identity/images')) return jsonResponse([{ ...candidate, isAnchor: selected }])
if (init?.method === 'POST' && path.endsWith('/validate'))
return jsonResponse(approvedCharacter(candidate.id))
if (init?.method === 'PUT' && path.endsWith('/casting')) { if (init?.method === 'PUT' && path.endsWith('/casting')) {
locked = true locked = true
selected = true selected = true
@@ -1354,6 +1363,9 @@ describe('视觉风格与主体身份工作区', () => {
await mountAssets('identity') await mountAssets('identity')
expect(wrapper!.text()).toContain('待确认选角') expect(wrapper!.text()).toContain('待确认选角')
expect(wrapper!.find('.identity-anchor-grid').exists()).toBe(true) expect(wrapper!.find('.identity-anchor-grid').exists()).toBe(true)
expect(button('确认选角并锁定').disabled).toBe(true)
wrapper!.findComponent(IdentityGallery).vm.$emit('validate', candidate.id)
await flushPromises()
button('确认选角并锁定').click() button('确认选角并锁定').click()
await flushPromises() await flushPromises()
button('确认演员选择').click() button('确认演员选择').click()
+1
View File
@@ -206,6 +206,7 @@ export function commitPreview(overrides: Partial<CandidateCommitCheckPreview> =
relationRepairTargets: [], relationRepairTargets: [],
checks: { checks: {
qualityPolicyMatches: true, qualityPolicyMatches: true,
durationBudgetCurrent: true,
episodeNumbersMatch: true, episodeNumbersMatch: true,
episodeFingerprintsMatch: true, episodeFingerprintsMatch: true,
noActiveExecutions: true, noActiveExecutions: true,
+49
View File
@@ -1,3 +1,8 @@
import {
characterCheckLabels,
type CharacterCheckResult,
type ImageValidationResult
} from '@/features/subject-images/validation'
import type { SubjectImageGenerationPreview } from '@/features/subject-images/types' import type { SubjectImageGenerationPreview } from '@/features/subject-images/types'
/** /**
@@ -17,3 +22,47 @@ export function imagePreviewFixture(subjectFormId = 'form-db-1'): SubjectImageGe
references: [] references: []
} }
} }
/**
* 返回绑定当前图库图像的只读审核来源。
* @param url 正式预检路径
* @param sourceCurrent 来源是否仍有效
* @returns 对应当前图片的预检响应
*/
export function validationPreviewResponse(url: string, sourceCurrent = true) {
const [, subjectFormId, imageId] = url.match(/subject-forms\/([^/]+)\/images\/([^/]+)\/validate\/preview$/) ?? []
return new Response(
JSON.stringify({
data: {
subjectFormId,
imageId,
sourceCurrent,
canValidate: sourceCurrent,
sourceStaleReason: sourceCurrent ? null : '本次机位采用的几何已过期',
providerInputSnapshot: null,
providerInputFingerprint: null
}
})
)
}
/**
* 模拟已通过明确审核的角色候选。
* @param imageId 当前候选
* @returns 四项完整的像素审核证据
*/
export function approvedCharacter(imageId: string): ImageValidationResult {
return {
subjectId: 'subject-db-1',
imageId,
passed: true,
sourceRequirementsPassed: true,
sourceVisualRequirements: [],
summary: '已核对图像',
issues: [],
characterCheckResults: (Object.keys(characterCheckLabels) as CharacterCheckResult['check'][]).map(check => ({
check,
status: check.endsWith('References') ? 'not_applicable' : 'passed',
evidence: '具体观察结果'
}))
}
}