fix(short-drama-agent-front): 修复代码格式检查问题

This commit is contained in:
GJ committed 2026-10-21 17:04:02 +08:00
1 parent 81d6a85260
commit 48fce3975f
86 files changed
+5339 -1061

No files matched your search

+10 -3
View File
@@ -2,15 +2,22 @@
import { NCollapse, NCollapseItem } from 'naive-ui'
/** 原始诊断与生成参数仅供高级核对,默认收起,不替代普通用户的中文摘要。 */
withDefaults(defineProps<{
withDefaults(
defineProps<{
/** 原始数据保持不变,便于核对技术问题。 */
value: unknown
/** 中文高级入口名称。 */
title?: string
}>(), { title: '高级详情(原始数据)' })
}>(),
{ title: '高级详情(原始数据)' }
)
</script>
<template>
<!-- 以下是默认收起的高级数据模块,统一使用 Naive 折叠组件 -->
<NCollapse class="mt-3"><NCollapseItem name="raw-data" :title="title"><pre class="whitespace-pre-wrap break-words text-xs leading-6">{{ JSON.stringify(value, null, 2) }}</pre></NCollapseItem></NCollapse>
<NCollapse class="mt-3"
><NCollapseItem name="raw-data" :title="title">
<pre class="whitespace-pre-wrap break-words text-xs leading-6">{{ JSON.stringify(value, null, 2) }}</pre>
</NCollapseItem></NCollapse
>
</template>
+184 -35
View File
@@ -92,9 +92,21 @@ const plans = computed(() => result.value?.storyboardPlans ?? [])
const shots = computed(() => result.value?.storyboardEpisodeShots ?? [])
const summary = computed(() => snapshot.value?.taskSummary)
/** 候选审核读取完成前不展示旧错误。 */
const validation = computed(() => quality.value.structureValid === null ? undefined : { valid: quality.value.structureValid, issues: quality.value.structuralIssues })
const validation = computed(() =>
quality.value.structureValid === null
? undefined
: { valid: quality.value.structureValid, issues: quality.value.structuralIssues }
)
/** 数据来源在桌面和移动端正文均明确显示,候选数量不冒充正式资产。 */
const sourceLabel = computed(() => ({ candidate: '拆解候选 · 尚未提交正式结果', formal: '正式拆解结果', history: '历史结果 · 仅供回看', empty: '' })[quality.value.source])
const sourceLabel = computed(
() =>
({
candidate: '拆解候选 · 尚未提交正式结果',
formal: '正式拆解结果',
history: '历史结果 · 仅供回看',
empty: ''
})[quality.value.source]
)
const operation = computed(() => getOperation(projectId.value))
/** 分镜阅读和诊断入口共用当前剧集,不维护独立的诊断集号输入。 */
const selectedEpisodeNo = ref<number>()
@@ -204,17 +216,25 @@ async function locateIssue(issue: ShotValidation['issues'][number]) {
selectedEpisodeNo.value = issue.episodeNo
await nextTick()
if (issue.beatNo)
await storyboardList.value?.locate({
await storyboardList.value?.locate(
{
episodeNo: issue.episodeNo,
beatNo: issue.beatNo,
...(issue.shotNo ? { shotNo: issue.shotNo } : {})
}, { problem: true })
},
{ problem: true }
)
}
const taskStopped = computed(() => execution.value?.status === 'failed' || execution.value?.status === 'completed')
/** 后续候选修订已替代旧任务结果时,只在明确的历史记录中展示回执。 */
const executionHistorical = computed(() => {
const record = backgroundExecution.query.data.value
return !!record && !!latestCheckpoint.value && !!record.completedAt && Date.parse(latestCheckpoint.value.createdAt) > Date.parse(record.completedAt)
return (
!!record &&
!!latestCheckpoint.value &&
!!record.completedAt &&
Date.parse(latestCheckpoint.value.createdAt) > Date.parse(record.completedAt)
)
})
/** 后台拆解结束后自动刷新项目、Checkpoint 与正式主体/分镜数据。 */
watch(
@@ -244,10 +264,32 @@ const hasBreakdownIssues = computed(() =>
)
/** 问题按钮按真实问题类型展示,不把质量待审或执行异常误称为结构校验失败。 */
const issueEntryLabel = computed(() =>
quality.value.error ? '候选审核待刷新' : validation.value?.valid === false ? '分镜校验未通过' : pendingQuality.value ? '分镜质量待修订' : '拆解问题待处理'
quality.value.error
? '候选审核待刷新'
: validation.value?.valid === false
? '分镜校验未通过'
: pendingQuality.value
? '分镜质量待修订'
: '拆解问题待处理'
)
/** 当前状态颜色只取当前质量和活动任务,不继承历史执行失败。 */
const qualityStatus = computed(() => breakdownBusy.value ? 'running' : quality.value.loading ? 'pending' : quality.value.needsRefresh ? 'unknown' : currentWorkflowError.value ? 'failed' : quality.value.problems.length ? 'blocked' : quality.value.structureValid === true ? quality.value.isCandidate ? 'candidate_pending' : 'completed' : 'unknown')
const qualityStatus = computed(() =>
breakdownBusy.value
? 'running'
: quality.value.loading
? 'pending'
: quality.value.needsRefresh
? 'unknown'
: currentWorkflowError.value
? 'failed'
: quality.value.problems.length
? 'blocked'
: quality.value.structureValid === true
? quality.value.isCandidate
? 'candidate_pending'
: 'completed'
: 'unknown'
)
/** 当前生命周期与审核文案集中展示。 */
const qualityLabel = computed(() => {
if (breakdownBusy.value) return '拆解进行中'
@@ -271,8 +313,9 @@ const issueActionsDisabled = computed(
operation.value.pending ||
breakdownBusy.value ||
backgroundExecution.discovering.value ||
!!backgroundExecution.discoveryError.value
|| quality.value.loading || !!quality.value.error
!!backgroundExecution.discoveryError.value ||
quality.value.loading ||
!!quality.value.error
)
const configValid = computed(
() => Number.isSafeInteger(groupSize.value) && groupSize.value > 0 && modules.value.length > 0
@@ -304,7 +347,13 @@ watch(
() => {
const executionError = currentWorkflowError.value
const invalid = quality.value.issueCount > 0
if (quality.value.needsRefresh || quality.value.loading || breakdownBusy.value || backgroundExecution.discovering.value) return
if (
quality.value.needsRefresh ||
quality.value.loading ||
breakdownBusy.value ||
backgroundExecution.discovering.value
)
return
if ((!executionError && !invalid) || notifiedIssues.has(issueSignature.value)) return
notifiedIssues.add(issueSignature.value)
actionMessage?.warning(
@@ -361,10 +410,20 @@ const rulesAcknowledged = ref(false)
/** 每次真实模型启动仍需核对后台任务是否停止。 */
const startAcknowledged = ref(false)
/** 规则、目标或步骤变化后重新确认,不沿用旧勾选。 */
watch([startPolicy.reviewOpen, startPolicy.editorKey, startScope], () => { rulesAcknowledged.value = false })
watch(startPolicy.startOpen, () => { startAcknowledged.value = false })
watch([startPolicy.reviewOpen, startPolicy.editorKey, startScope], () => {
rulesAcknowledged.value = false
})
watch(startPolicy.startOpen, () => {
startAcknowledged.value = false
})
/** 关闭整个设置时中断只读确认,不能在关闭后打开迟到的弹窗。 */
watch(toolsOpen, shown => { if (!shown) startPolicy.cancel() }, { flush: 'sync' })
watch(
toolsOpen,
shown => {
if (!shown) startPolicy.cancel()
},
{ flush: 'sync' }
)
/** 校验用户编辑的规则,成功后进入普通启动确认;此步骤不运行模型。 */
async function confirmStartRules() {
@@ -452,7 +511,11 @@ async function run(action: BreakdownAction) {
id,
labels[action],
async () => {
const started = await breakdownApi.run(id, action, action === 'start' ? { ...input.value, ...permit! } : undefined)
const started = await breakdownApi.run(
id,
action,
action === 'start' ? { ...input.value, ...permit! } : undefined
)
await backgroundExecution.track(started.executionId)
return started
},
@@ -460,8 +523,13 @@ async function run(action: BreakdownAction) {
)
await refresh()
const cause = operation.value.cause
if (!success && action === 'start' && id === projectId.value && cause instanceof ApiError &&
['QUALITY_POLICY_NOT_CONFIRMED', 'QUALITY_POLICY_VERSION_CONFLICT'].includes(cause.code ?? ''))
if (
!success &&
action === 'start' &&
id === projectId.value &&
cause instanceof ApiError &&
['QUALITY_POLICY_NOT_CONFIRMED', 'QUALITY_POLICY_VERSION_CONFLICT'].includes(cause.code ?? '')
)
await startPolicy.prepare()
}
@@ -533,8 +601,13 @@ const rules = {
@closed="finishOpeningIssues"
>
<!-- 以下是在同一全屏抽屉内核对真实质量规则的模块,不叠加第二个抽屉 -->
<div v-if="startPolicy.reviewOpen.value && startPolicy.policy.value" class="breakdown-policy-review">
<p class="text-sm leading-6 text-muted">请核对动作与物理规则,修改将在继续时保存。确认会保存到当前项目,规则未变时不再重复提醒。</p>
<div
v-if="startPolicy.reviewOpen.value && startPolicy.policy.value"
class="breakdown-policy-review"
>
<p class="text-sm leading-6 text-muted">
请核对动作与物理规则,修改将在继续时保存。确认会保存到当前项目,规则未变时不再重复提醒。
</p>
<QualityPolicySettings
ref="qualityForm"
:key="startPolicy.editorKey.value"
@@ -542,13 +615,22 @@ const rules = {
:initial-policy="startPolicy.policy.value"
:disabled="!canStart || startPolicy.busy.value"
/>
<NCheckbox v-model:checked="rulesAcknowledged" :disabled="startPolicy.busy.value || !canStart" class="mt-5">
<NCheckbox
v-model:checked="rulesAcknowledged"
:disabled="startPolicy.busy.value || !canStart"
class="mt-5"
>
我已核对本次拆解使用的质量规则
</NCheckbox>
<p v-if="startPolicy.error.value" role="alert" class="mt-4 text-sm text-danger">{{ startPolicy.error.value }}</p>
<p v-if="startPolicy.error.value" role="alert" class="mt-4 text-sm text-danger">
{{ startPolicy.error.value }}
</p>
</div>
<!-- 以下是拆解分组设置模块,规则确认时保留已有预览和草稿 -->
<section v-show="!startPolicy.reviewOpen.value" class="panel workspace-panel breakdown-settings-panel">
<section
v-show="!startPolicy.reviewOpen.value"
class="panel workspace-panel breakdown-settings-panel"
>
<p
v-if="backgroundExecution.discoveryError.value"
class="mb-4 text-xs leading-6 text-danger"
@@ -658,7 +740,9 @@ const rules = {
type="primary"
:disabled="!canStart || startPolicy.busy.value"
@click="startPolicy.prepare"
><template #icon><ShieldCheck :size="16" aria-hidden="true" /></template>{{ candidateOnly ? '生成拆解候选' : '开始拆解' }}</NButton>
><template #icon><ShieldCheck :size="16" aria-hidden="true" /></template
>{{ candidateOnly ? '生成拆解候选' : '开始拆解' }}</NButton
>
</div>
<div class="flex flex-wrap gap-2">
<div v-for="group in preview.groups" :key="group.groupId" class="group-chip">
@@ -667,7 +751,13 @@ const rules = {
</div>
</div>
</div>
<p v-if="startPolicy.error.value && !startPolicy.startOpen.value" role="alert" class="mt-4 text-sm text-danger">{{ startPolicy.error.value }}</p>
<p
v-if="startPolicy.error.value && !startPolicy.startOpen.value"
role="alert"
class="mt-4 text-sm text-danger"
>
{{ startPolicy.error.value }}
</p>
<p v-if="project.status === 'generating'" class="mt-4 text-xs text-danger">
剧本仍在生成,暂不允许启动拆解,避免读取到不完整的剧集。
</p>
@@ -688,8 +778,17 @@ const rules = {
@refresh="refreshCandidate"
/>
<!-- 以下是明确标记的历史执行回执,旧任务结论不表示当前候选质量 -->
<component :is="executionHistorical ? NCollapse : 'div'" v-if="backgroundExecution.executionId.value" v-show="!startPolicy.reviewOpen.value" :class="{ 'breakdown-execution-history': executionHistorical }">
<component :is="executionHistorical ? NCollapseItem : 'div'" :name="executionHistorical ? 'history' : undefined" :title="executionHistorical ? '历史拆解执行记录(不代表当前质量)' : undefined">
<component
:is="executionHistorical ? NCollapse : 'div'"
v-if="backgroundExecution.executionId.value"
v-show="!startPolicy.reviewOpen.value"
:class="{ 'breakdown-execution-history': executionHistorical }"
>
<component
:is="executionHistorical ? NCollapseItem : 'div'"
:name="executionHistorical ? 'history' : undefined"
:title="executionHistorical ? '历史拆解执行记录(不代表当前质量)' : undefined"
>
<WorkflowExecutionPanel
v-if="backgroundExecution.executionId.value"
:title="executionHistorical ? '历史拆解任务' : '剧本拆解任务'"
@@ -706,22 +805,52 @@ const rules = {
<!-- 以下是固定的规则确认底栏,返回不记录确认,继续不会直接调用模型 -->
<template v-if="startPolicy.reviewOpen.value" #footer>
<NButton :disabled="startPolicy.saving.value" @click="startPolicy.cancel">取消</NButton>
<NButton type="primary" :loading="startPolicy.busy.value" :disabled="!rulesAcknowledged || !qualityForm?.canSave || startPolicy.busy.value || !canStart" @click="confirmStartRules"><template #icon><ShieldCheck :size="16" aria-hidden="true" /></template>确认规则并继续</NButton>
<NButton
type="primary"
:loading="startPolicy.busy.value"
:disabled="
!rulesAcknowledged || !qualityForm?.canSave || startPolicy.busy.value || !canStart
"
@click="confirmStartRules"
><template #icon><ShieldCheck :size="16" aria-hidden="true" /></template
>确认规则并继续</NButton
>
</template>
</WorkspaceTools>
<!-- 以下是每次真实模型调用前的费用与任务确认,规则未变时直接进入此步骤 -->
<AppDialog
:open="startPolicy.startOpen.value"
:title="candidateOnly ? '生成拆解候选' : '开始拆解'"
:description="candidateOnly ? '将按当前分组调用模型生成主体、形态与分镜候选,可能产生模型费用。现有正式数据会保留,候选需经独立确认后才提交。' : '将按当前预览启动完整拆解并调用模型,可能产生模型费用。抽取结束后仍需完成主体整理、分镜生成与入库。'"
:description="
candidateOnly
? '将按当前分组调用模型生成主体、形态与分镜候选,可能产生模型费用。现有正式数据会保留,候选需经独立确认后才提交。'
: '将按当前预览启动完整拆解并调用模型,可能产生模型费用。抽取结束后仍需完成主体整理、分镜生成与入库。'
"
:busy="operation.pending"
@update:open="updateStartOpen"
>
<NCheckbox v-if="records.length > 0" v-model:checked="startAcknowledged" :disabled="startPolicy.busy.value">我已确认后台任务停止,当前没有同项目的生成或拆解任务在运行。</NCheckbox>
<p v-if="startPolicy.error.value" role="alert" class="mt-4 text-sm text-danger">{{ startPolicy.error.value }}</p>
<NCheckbox
v-if="records.length > 0"
v-model:checked="startAcknowledged"
:disabled="startPolicy.busy.value"
>我已确认后台任务停止,当前没有同项目的生成或拆解任务在运行。</NCheckbox
>
<p v-if="startPolicy.error.value" role="alert" class="mt-4 text-sm text-danger">
{{ startPolicy.error.value }}
</p>
<template #footer>
<NButton :disabled="operation.pending" @click="startPolicy.cancel">取消</NButton>
<NButton type="primary" :loading="startPolicy.reading.value" :disabled="!canStart || startPolicy.busy.value || (records.length > 0 && !startAcknowledged)" @click="confirmStart"><template #icon><ShieldCheck :size="16" aria-hidden="true" /></template>确认{{ candidateOnly ? '生成拆解候选' : '开始拆解' }}</NButton>
<NButton
type="primary"
:loading="startPolicy.reading.value"
:disabled="
!canStart || startPolicy.busy.value || (records.length > 0 && !startAcknowledged)
"
@click="confirmStart"
><template #icon><ShieldCheck :size="16" aria-hidden="true" /></template>确认{{
candidateOnly ? '生成拆解候选' : '开始拆解'
}}</NButton
>
</template>
</AppDialog>
</div>
@@ -736,7 +865,9 @@ const rules = {
<template v-else>
<section class="breakdown-results-section" :data-breakdown-source="quality.source">
<!-- 以下是候选与正式数据来源提示,手机也不隐藏,防止把候选镜头当作正式资产 -->
<p v-if="sourceLabel" class="text-xs text-muted" role="status">{{ sourceLabel }}<span v-if="quality.loading"> · 正在读取当前质量审核…</span></p>
<p v-if="sourceLabel" class="text-xs text-muted" role="status">
{{ sourceLabel }}<span v-if="quality.loading"> · 正在读取当前质量审核…</span>
</p>
<div class="result-toolbar tabs-toolbar">
<NTabs v-model:value="tab" class="workspace-tabs" type="line" size="small" aria-label="拆解结果"
><!-- 以下是仅显示分类名称的拆解标签模块,主体数量保留在搜索统计中 -->
@@ -803,13 +934,21 @@ const rules = {
v-model:episode-no="selectedEpisodeNo"
:plans="plans"
:episodes="shots"
:diagnosis-disabled="quality.source !== 'formal' || breakdownBusy || backgroundExecution.discovering.value"
:diagnosis-disabled="
quality.source !== 'formal' ||
breakdownBusy ||
backgroundExecution.discovering.value
"
@diagnose="openShotDiagnosis"
>
<!-- 以下是跟随当前剧集的一行诊断摘要,诊断弹窗独立于列表滚动 -->
<template #diagnosis>
<StoryboardDiagnosis
v-if="quality.source === 'formal' && !breakdownBusy && !backgroundExecution.discovering.value"
v-if="
quality.source === 'formal' &&
!breakdownBusy &&
!backgroundExecution.discovering.value
"
ref="diagnosisPanel"
:project-id="projectId"
:episode-no="currentEpisodeNo"
@@ -902,7 +1041,14 @@ const rules = {
</p>
<!-- 以下是从当前动作冲突带入角色和动作的例外入口,独立保存规则且保留旧例外 -->
<ActionExceptionRepair
v-if="issuesOpen && qualityObservation.source.value.state && quality.source !== 'history' && quality.actionBlocks.some(block => [...block.blockingCodes, ...block.warningCodes].includes('action_resource_conflict'))"
v-if="
issuesOpen &&
qualityObservation.source.value.state &&
quality.source !== 'history' &&
quality.actionBlocks.some(block =>
[...block.blockingCodes, ...block.warningCodes].includes('action_resource_conflict')
)
"
:project-id="projectId"
:checkpoint-id="latestCheckpoint?.checkpointId || ''"
:state="qualityObservation.source.value.state"
@@ -962,7 +1108,10 @@ const rules = {
<style>
/* 历史折叠只保留一层内容留白,避免 Naive 内容间距叠加任务卡片的 mt-4。 */
.breakdown-execution-history.n-collapse .n-collapse-item .n-collapse-item__content-wrapper .n-collapse-item__content-inner {
.breakdown-execution-history.n-collapse
.n-collapse-item
.n-collapse-item__content-wrapper
.n-collapse-item__content-inner {
padding-top: 8px;
}
.breakdown-execution-history .breakdown-execution-panel {
+6 -1
View File
@@ -29,7 +29,12 @@ import WorkspacePage from '../../components/ui/WorkspacePage.vue'
<!-- 以下是分类标签与操作入口占位模块 -->
<div class="breakdown-skeleton-tabs">
<div class="breakdown-skeleton-tab-labels">
<span v-for="tab in 5" :key="tab" class="breakdown-skeleton-tab"><NSkeleton :class="{ 'breakdown-skeleton-task-label': tab === 5 }" :width="tab === 5 ? 56 : 28" :height="14" /></span>
<span v-for="tab in 5" :key="tab" class="breakdown-skeleton-tab"
><NSkeleton
:class="{ 'breakdown-skeleton-task-label': tab === 5 }"
:width="tab === 5 ? 56 : 28"
:height="14"
/></span>
</div>
<div class="breakdown-skeleton-tab-actions">
<NSkeleton class="breakdown-skeleton-icon breakdown-skeleton-mobile-settings" />
+36 -11
View File
@@ -29,28 +29,53 @@ export interface ActionExceptionTarget extends CandidateShotLocation {
* @returns 可添加精确例外的真实目标;历史、缺失或无效证据不产生目标
*/
export function actionExceptionTargets(state: BreakdownState, quality: BreakdownQuality): ActionExceptionTarget[] {
if (!['candidate', 'formal'].includes(quality.source) || quality.loading || quality.needsRefresh || quality.error) return []
if (!['candidate', 'formal'].includes(quality.source) || quality.loading || quality.needsRefresh || quality.error)
return []
const targets = new Map<string, ActionExceptionTarget>()
for (const block of quality.actionBlocks) {
if (![...block.blockingCodes, ...block.warningCodes].includes('action_resource_conflict')) continue
const shot = state.storyboardEpisodeShots?.find(episode => episode.episodeNo === block.episodeNo)
?.beatShots.find(beat => beat.beatNo === block.beatNo)?.shots.find(item => item.shotNo === block.shotNo)
const shot = state.storyboardEpisodeShots
?.find(episode => episode.episodeNo === block.episodeNo)
?.beatShots.find(beat => beat.beatNo === block.beatNo)
?.shots.find(item => item.shotNo === block.shotNo)
if (!shot?.requiredActions?.length || !shot.durationPlanning) continue
for (const [index, phase] of shot.durationPlanning.phases.entries()) {
// 与后端审计一致:只接受本阶段、已存在动作及镜头主体的明确占用证据。
const resources = (phase.resourceOccupancy ?? []).filter(item =>
shot.subjectRefs.includes(item.ownerRef) && phase.actionIds?.includes(item.actionId) &&
const resources = (phase.resourceOccupancy ?? []).filter(
item =>
shot.subjectRefs.includes(item.ownerRef) &&
phase.actionIds?.includes(item.actionId) &&
shot.requiredActions!.some(action => action.id === item.actionId) &&
actionResourceOptions.some(option => option.value === item.resource))
actionResourceOptions.some(option => option.value === item.resource)
)
for (const [leftIndex, left] of resources.entries()) {
for (const right of resources.slice(leftIndex + 1)) {
if (left.ownerRef !== right.ownerRef || left.resource !== right.resource || left.actionId === right.actionId) continue
if (left.shareable && right.shareable && !['support', 'move'].includes(left.usage) && !['support', 'move'].includes(right.usage)) continue
if (
left.ownerRef !== right.ownerRef ||
left.resource !== right.resource ||
left.actionId === right.actionId
)
continue
if (
left.shareable &&
right.shareable &&
!['support', 'move'].includes(left.usage) &&
!['support', 'move'].includes(right.usage)
)
continue
const key = `${block.episodeNo}/${block.beatNo}/${block.shotNo}/${index + 1}/${left.ownerRef}/${left.resource}`
const target = targets.get(key) ?? {
key, episodeNo: block.episodeNo, beatNo: block.beatNo, shotNo: block.shotNo,
phaseNo: index + 1, shotTitle: shot.title, ownerRef: left.ownerRef, resource: left.resource,
ownerName: state.subjectCandidates?.find(subject => subject.ref === left.ownerRef)?.name || left.ownerRef,
key,
episodeNo: block.episodeNo,
beatNo: block.beatNo,
shotNo: block.shotNo,
phaseNo: index + 1,
shotTitle: shot.title,
ownerRef: left.ownerRef,
resource: left.resource,
ownerName:
state.subjectCandidates?.find(subject => subject.ref === left.ownerRef)?.name ||
left.ownerRef,
actions: []
}
for (const actionId of [left.actionId, right.actionId]) {
+34 -8
View File
@@ -14,7 +14,14 @@ import type {
LegacyActionDiagnosisResults
} from './types'
import type { WorkflowExecutionStart } from '../workflows/execution.types'
import type { CandidateRevalidation, CandidateCommitPreview, CandidateSubjectRepairInput, CandidateSubjectRepairResult, CandidateActionRepairInput, CandidateActionRepairResult } from './candidate.types'
import type {
CandidateRevalidation,
CandidateCommitPreview,
CandidateSubjectRepairInput,
CandidateSubjectRepairResult,
CandidateActionRepairInput,
CandidateActionRepairResult
} from './candidate.types'
import type {
QualityRepairPlan,
QualityRepairCandidates,
@@ -32,7 +39,10 @@ export const breakdownApi = {
* @returns 不调用模型的检查结果
*/
diagnosisPreflight: (id: string, shotId: string, signal?: AbortSignal) =>
request<DiagnosisPreflight>(`/projects/${encodeURIComponent(id)}/breakdown/storyboard-legacy-action-diagnosis-preflight/${encodeURIComponent(shotId)}`, { signal }),
request<DiagnosisPreflight>(
`/projects/${encodeURIComponent(id)}/breakdown/storyboard-legacy-action-diagnosis-preflight/${encodeURIComponent(shotId)}`,
{ signal }
),
/**
* 查看指定镜头的诊断历史及版本失效情况。
* @param id 项目编号
@@ -41,7 +51,10 @@ export const breakdownApi = {
* @returns 最近诊断历史
*/
diagnosisHistory: (id: string, shotId: string, signal?: AbortSignal) =>
request<DiagnosisHistory>(`/projects/${encodeURIComponent(id)}/breakdown/storyboard-legacy-action-diagnoses/${encodeURIComponent(shotId)}`, { signal }),
request<DiagnosisHistory>(
`/projects/${encodeURIComponent(id)}/breakdown/storyboard-legacy-action-diagnoses/${encodeURIComponent(shotId)}`,
{ signal }
),
/**
* 核对指定诊断能否进入人工修订,不自动应用建议。
* @param id 项目编号
@@ -51,7 +64,10 @@ export const breakdownApi = {
* @returns 候选及资产、来源和版本限制
*/
diagnosisRepairReadiness: (id: string, shotId: string, diagnosisId: string, signal?: AbortSignal) =>
request<DiagnosisRepairReadiness>(`/projects/${encodeURIComponent(id)}/breakdown/storyboard-legacy-action-repair-readiness/${encodeURIComponent(shotId)}/${encodeURIComponent(diagnosisId)}`, { signal }),
request<DiagnosisRepairReadiness>(
`/projects/${encodeURIComponent(id)}/breakdown/storyboard-legacy-action-repair-readiness/${encodeURIComponent(shotId)}/${encodeURIComponent(diagnosisId)}`,
{ signal }
),
/**
* 只读重新审核当前候选,不提供正式提交许可。
@@ -60,7 +76,9 @@ export const breakdownApi = {
* @returns 版本化质量审核
*/
revalidateCandidate: (id: string, signal?: AbortSignal) =>
request<CandidateRevalidation>(`/projects/${encodeURIComponent(id)}/breakdown/candidate-revalidation`, { signal }),
request<CandidateRevalidation>(`/projects/${encodeURIComponent(id)}/breakdown/candidate-revalidation`, {
signal
}),
/**
* 只读检查剧本与下游资产的正式提交安全条件。
* @param id 当前项目
@@ -68,7 +86,9 @@ export const breakdownApi = {
* @returns 版本化安全检查
*/
candidateCommitPreview: (id: string, signal?: AbortSignal) =>
request<CandidateCommitPreview>(`/projects/${encodeURIComponent(id)}/breakdown/candidate-commit-preview`, { signal }),
request<CandidateCommitPreview>(`/projects/${encodeURIComponent(id)}/breakdown/candidate-commit-preview`, {
signal
}),
/**
* 用户确认后补齐候选主体引用与真实形态。
* @param id 当前项目
@@ -76,7 +96,10 @@ export const breakdownApi = {
* @returns 新候选检查点
*/
repairCandidateSubject: (id: string, input: CandidateSubjectRepairInput) =>
request<CandidateSubjectRepairResult>(`/projects/${encodeURIComponent(id)}/breakdown/candidate-subject-repair`, { method: 'POST', body: input }),
request<CandidateSubjectRepairResult>(
`/projects/${encodeURIComponent(id)}/breakdown/candidate-subject-repair`,
{ method: 'POST', body: input }
),
/**
* 用户确认后批量修订候选动作描述,不触发模型。
* @param id 当前项目
@@ -84,7 +107,10 @@ export const breakdownApi = {
* @returns 新候选检查点及剩余待审剧集
*/
repairCandidateActions: (id: string, input: CandidateActionRepairInput) =>
request<CandidateActionRepairResult>(`/projects/${encodeURIComponent(id)}/breakdown/candidate-action-batch-repair`, { method: 'POST', body: input }),
request<CandidateActionRepairResult>(
`/projects/${encodeURIComponent(id)}/breakdown/candidate-action-batch-repair`,
{ method: 'POST', body: input }
),
/**
* 读取当前仍被质量审核阻断的镜头。
* @param id 当前项目编号
+15 -2
View File
@@ -13,7 +13,16 @@ export const candidateCheckLabels: Record<keyof CandidateCommitPreview['checks']
noProtectedShots: '没有需要保护的镜头资产'
}
/** 必须逐项校验的固定安全门禁,不根据响应动态减少检查项。 */
export const candidateCheckKeys = ['qualityPolicyMatches', 'episodeNumbersMatch', 'episodeFingerprintsMatch', 'noActiveExecutions', 'noActiveVideos', 'noSubjectIdentities', 'noSubjectImages', 'noProtectedShots'] as const
export const candidateCheckKeys = [
'qualityPolicyMatches',
'episodeNumbersMatch',
'episodeFingerprintsMatch',
'noActiveExecutions',
'noActiveVideos',
'noSubjectIdentities',
'noSubjectImages',
'noProtectedShots'
] as const
/**
* 安全预检查必须逐项通过且属于当前项目和候选,不能只相信 ready。
@@ -22,7 +31,11 @@ export const candidateCheckKeys = ['qualityPolicyMatches', 'episodeNumbersMatch'
* @param checkpointId 当前候选版本
* @returns 是否可进入最终确认
*/
export function candidatePreviewReady(preview: CandidateCommitPreview | null, projectId: string, checkpointId?: string): boolean {
export function candidatePreviewReady(
preview: CandidateCommitPreview | null,
projectId: string,
checkpointId?: string
): boolean {
if (!preview || preview.projectId !== projectId || preview.checkpointId !== checkpointId) return false
// 外部 JSON 的布尔值必须严格为 true,不接受缺失值或字符串等真值。
const flags: unknown[] = [preview.readOnly, preview.ready, ...candidateCheckKeys.map(key => preview.checks?.[key])]
+8 -4
View File
@@ -91,15 +91,19 @@ export interface CandidateRevalidation {
/** 当前动作阻断或资源冲突。 */
actionQualityBlocks: CandidateActionBlock[]
/** 阻断镜头的原始动作规划。 */
actionRepairTargets: Array<CandidateActionBlock & {
actionRepairTargets: Array<
CandidateActionBlock & {
/** 缺少原始镜头时禁止修复。 */
shot: Pick<StoryboardShot, 'title' | 'description' | 'visualFocus' | 'durationSeconds' | 'subjectRefs'> & {
shot:
| (Pick<StoryboardShot, 'title' | 'description' | 'visualFocus' | 'durationSeconds' | 'subjectRefs'> & {
/** 原始动作,不提供 kind 编辑入口。 */
requiredActions: NonNullable<StoryboardShot['requiredActions']>
/** 原始阶段规划。 */
durationPlanning: StoryboardShot['durationPlanning'] | null
} | null
}>
})
| null
}
>
/** 道具引用检查。 */
propReferenceDiagnostics: CandidatePropDiagnostic[]
/** 没有对应动作阻断的残留待审剧集,仍需明确处理。 */
@@ -50,14 +50,28 @@ const notice = ref('')
/** 项目级写操作锁。 */
const operation = computed(() => getOperation(props.projectId))
/** 当前审核与原始数据必须属于同一项目和最新检查点。 */
const current = computed(() => !!props.checkpointId && props.quality.checkpointId === props.checkpointId &&
(!props.state.projectId || props.state.projectId === props.projectId) && ['candidate', 'formal'].includes(props.quality.source))
const current = computed(
() =>
!!props.checkpointId &&
props.quality.checkpointId === props.checkpointId &&
(!props.state.projectId || props.state.projectId === props.projectId) &&
['candidate', 'formal'].includes(props.quality.source)
)
/** 只从真实审核和阶段证据生成目标。 */
const targets = computed(() => current.value ? actionExceptionTargets(props.state, props.quality) : [])
const targets = computed(() => (current.value ? actionExceptionTargets(props.state, props.quality) : []))
/** 已有例外原样展示,保存新项不会删除或替换它们。 */
const exceptions = computed(() => receipt.value?.policy.actionExceptions ?? [])
/** 用户可以提交的时机,所有外部活动锁都需要满足。 */
const writable = computed(() => current.value && !!receipt.value && !props.disabled && !operation.value.pending && !loading.value && !checking.value && !writing.value)
const writable = computed(
() =>
current.value &&
!!receipt.value &&
!props.disabled &&
!operation.value.pending &&
!loading.value &&
!checking.value &&
!writing.value
)
/** 失效代次与可取消的只读请求。 */
let generation = 0
/** 当前规则查询的取消控制器。 */
@@ -87,8 +101,11 @@ async function load() {
try {
const result = await read(id, controller.signal)
if (version === generation) receipt.value = result
} catch (cause) { if (version === generation) error.value = errorMessage(cause) }
finally { if (version === generation) loading.value = false }
} catch (cause) {
if (version === generation) error.value = errorMessage(cause)
} finally {
if (version === generation) loading.value = false
}
}
/**
@@ -97,7 +114,12 @@ async function load() {
* @returns 是否已经保存对应例外
*/
function exists(target: ActionExceptionTarget): boolean {
return exceptions.value.some(item => item.code === 'action_resource_conflict' && item.ownerRef === target.ownerRef && item.resource === target.resource)
return exceptions.value.some(
item =>
item.code === 'action_resource_conflict' &&
item.ownerRef === target.ownerRef &&
item.resource === target.resource
)
}
/**
@@ -139,24 +161,45 @@ async function save() {
error.value = ''
try {
const latest = await read(id, controller.signal)
if (version !== generation || props.disabled || operation.value.pending || !current.value ||
!targets.value.some(item => JSON.stringify(item) === targetSignature)) return
if (
version !== generation ||
props.disabled ||
operation.value.pending ||
!current.value ||
!targets.value.some(item => JSON.stringify(item) === targetSignature)
)
return
receipt.value = latest
if (exists(target)) { notice.value = '这个角色的对应部位已有例外,已保留现有设置。'; selected.value = null; return }
if (exists(target)) {
notice.value = '这个角色的对应部位已有例外,已保留现有设置。'
selected.value = null
return
}
if (exceptions.value.length >= 30) throw new Error('动作例外最多 30 项,当前不能继续添加。')
const input = policyDraft(latest.policy)
input.actionExceptions = [...(input.actionExceptions ?? []), {
code: 'action_resource_conflict', ownerRef: target.ownerRef, resource: target.resource, reason: reason.value.trim()
}]
input.actionExceptions = [
...(input.actionExceptions ?? []),
{
code: 'action_resource_conflict',
ownerRef: target.ownerRef,
resource: target.resource,
reason: reason.value.trim()
}
]
const signature = qualityPolicySignature(input)
writing.value = true
const success = await runOperation(id, '正在保存动作例外', async () => {
const success = await runOperation(
id,
'正在保存动作例外',
async () => {
const result = await projectsApi.saveQualityPolicy(id, input, latest.revision)
validateQualityPolicyReceipt(result, id)
if (result.projectId !== id || qualityPolicySignature(result.policy) !== signature)
throw new Error('规则保存回执与提交内容不一致,请重新读取确认。')
if (version === generation) receipt.value = { ...result, policy: policyDraft(result.policy) }
}, { type: 'info', content: '动作例外已保存,当前分镜仍需审核,不会自动放行提交。' })
},
{ type: 'info', content: '动作例外已保存,当前分镜仍需审核,不会自动放行提交。' }
)
if (version !== generation) return
if (success) {
selected.value = null
@@ -164,18 +207,32 @@ async function save() {
notice.value = '动作例外已保存。当前分镜仍需审核,不会自动标记通过或修改正式结果。'
emit('refresh')
} else error.value = operation.value.error
} catch (cause) { if (version === generation) error.value = errorMessage(cause) }
finally { if (version === generation) { checking.value = false; writing.value = false } }
} catch (cause) {
if (version === generation) error.value = errorMessage(cause)
} finally {
if (version === generation) {
checking.value = false
writing.value = false
}
}
}
/** 修改原因时清除旧校验,打开空白草稿不提前报错。 */
watch(reason, () => { issue.value = '' })
watch(reason, () => {
issue.value = ''
})
/** 当前问题的动作证据变化后撤销旧草稿,不能把旧动作的确认套到新动作。 */
watch(targets, items => {
watch(
targets,
items => {
if (selected.value && !items.some(item => JSON.stringify(item) === JSON.stringify(selected.value))) cancel()
}, { flush: 'sync' })
},
{ flush: 'sync' }
)
/** 切换版本后清空旧草稿和读取,迟到响应不得回填或提交。 */
watch(() => [props.projectId, props.checkpointId], () => {
watch(
() => [props.projectId, props.checkpointId],
() => {
generation++
controller?.abort()
receipt.value = null
@@ -188,33 +245,76 @@ watch(() => [props.projectId, props.checkpointId], () => {
checking.value = false
writing.value = false
void load()
}, { immediate: true, flush: 'sync' })
},
{ immediate: true, flush: 'sync' }
)
/** 父抽屉只在真实写入期间锁定,普通读取仍可关闭。 */
watch(writing, value => emit('busy', value), { flush: 'sync' })
onScopeDispose(() => { generation++; controller?.abort(); emit('busy', false) })
onScopeDispose(() => {
generation++
controller?.abort()
emit('busy', false)
})
</script>
<template>
<!-- 以下是拆解后从具体冲突添加动作例外的模块,角色和动作均不可自由输入 -->
<section class="workspace-panel space-y-4" aria-label="动作例外修订">
<WorkspaceSectionHeading title="动作例外" description="只为剧本明确允许的特殊动作添加例外。角色、部位和动作从当前问题自动带入,你只需填写允许原因。" />
<WorkspaceSectionHeading
title="动作例外"
description="只为剧本明确允许的特殊动作添加例外。角色、部位和动作从当前问题自动带入,你只需填写允许原因。"
/>
<p v-if="loading" role="status" class="text-xs text-muted">正在读取已有动作例外…</p>
<div v-if="error" role="alert" class="space-y-2 text-sm text-danger"><p>{{ error }}</p><NButton v-if="!receipt" :disabled="loading" @click="load">重新读取规则</NButton></div>
<div v-if="error" role="alert" class="space-y-2 text-sm text-danger">
<p>{{ error }}</p>
<NButton v-if="!receipt" :disabled="loading" @click="load">重新读取规则</NButton>
</div>
<QualityPolicyExceptions :exceptions="exceptions" />
<p v-if="!targets.length && !loading" class="text-xs leading-6 text-muted">当前没有能准确带入角色与动作的冲突。缺少动作证据或其他结构错误时,请先使用人工修订。</p>
<p v-if="!targets.length && !loading" class="text-xs leading-6 text-muted">
当前没有能准确带入角色与动作的冲突。缺少动作证据或其他结构错误时,请先使用人工修订。
</p>
<article v-for="target in targets" :key="target.key" class="space-y-3" :data-exception-target="target.key">
<div class="flex flex-wrap items-center justify-between gap-3">
<p class="text-sm">第 {{ target.episodeNo }} 集 · 节拍 {{ target.beatNo }} · 镜头 {{ target.shotNo }} · 阶段 {{ target.phaseNo }}</p>
<NButton v-if="selected?.key !== target.key" :disabled="!writable || exists(target)" @click="select(target)"><template #icon><Plus :size="15" aria-hidden="true" /></template>{{ exists(target) ? '已有例外' : '添加例外' }}</NButton>
<p class="text-sm">
第 {{ target.episodeNo }} 集 · 节拍 {{ target.beatNo }} · 镜头 {{ target.shotNo }} · 阶段
{{ target.phaseNo }}
</p>
<NButton
v-if="selected?.key !== target.key"
:disabled="!writable || exists(target)"
@click="select(target)"
><template #icon><Plus :size="15" aria-hidden="true" /></template
>{{ exists(target) ? '已有例外' : '添加例外' }}</NButton
>
</div>
<p class="text-sm">{{ target.ownerName }}({{ target.ownerRef }}) · {{ actionResourceOptions.find(option => option.value === target.resource)?.label }}</p>
<ul class="space-y-1 pl-5 text-xs leading-6 text-muted list-disc"><li v-for="action in target.actions" :key="action">{{ action }}</li></ul>
<p class="text-sm">
{{ target.ownerName }}({{ target.ownerRef }}) ·
{{ actionResourceOptions.find(option => option.value === target.resource)?.label }}
</p>
<ul class="space-y-1 pl-5 text-xs leading-6 text-muted list-disc">
<li v-for="action in target.actions" :key="action">{{ action }}</li>
</ul>
<!-- 以下是只填写原因的例外草稿,后端实际范围是同一角色的对应部位 -->
<div v-if="selected?.key === target.key" class="space-y-3">
<p class="text-xs leading-6 text-muted">此例外按项目保存,同一角色或物品在其他镜头中的同类占用冲突也会受影响;其他错误仍会检查。</p>
<NFormItem label="允许原因"><NInput v-model:value="reason" type="textarea" aria-label="动作例外允许原因" placeholder="填写剧本中明确允许这样做的设定" :autosize="{ minRows: 2, maxRows: 6 }" :disabled="disabled || checking || writing" /></NFormItem>
<p class="text-xs leading-6 text-muted">
此例外按项目保存,同一角色或物品在其他镜头中的同类占用冲突也会受影响;其他错误仍会检查。
</p>
<NFormItem label="允许原因"
><NInput
v-model:value="reason"
type="textarea"
aria-label="动作例外允许原因"
placeholder="填写剧本中明确允许这样做的设定"
:autosize="{ minRows: 2, maxRows: 6 }"
:disabled="disabled || checking || writing"
/></NFormItem>
<p v-if="issue" role="alert" class="text-xs text-danger">{{ issue }}</p>
<div class="flex flex-wrap justify-end gap-2"><NButton :disabled="writing" @click="cancel">取消</NButton><NButton type="primary" :disabled="!writable" :loading="checking || writing" @click="save"><template #icon><Plus :size="15" aria-hidden="true" /></template>保存动作例外</NButton></div>
<div class="flex flex-wrap justify-end gap-2">
<NButton :disabled="writing" @click="cancel">取消</NButton
><NButton type="primary" :disabled="!writable" :loading="checking || writing" @click="save"
><template #icon><Plus :size="15" aria-hidden="true" /></template>保存动作例外</NButton
>
</div>
</div>
</article>
<p v-if="notice" role="status" class="text-xs leading-6 text-muted">{{ notice }}</p>
@@ -51,17 +51,40 @@ let controller: AbortController | undefined
/** 拒绝忽略取消信号后返回的旧响应。 */
let version = 0
/** 当前候选生成或提交后的面板。 */
const isCandidate = computed(() => props.state?.candidateOnly === true && (props.quality.isCandidate || props.quality.committed))
const isCandidate = computed(
() => props.state?.candidateOnly === true && (props.quality.isCandidate || props.quality.committed)
)
/** 后端持久化标记优先,成功回执只在当前会话补充防重复锁。 */
const committed = computed(() => props.quality.committed || submittedId.value === `${props.projectId}:${props.checkpointId}`)
const committed = computed(
() => props.quality.committed || submittedId.value === `${props.projectId}:${props.checkpointId}`
)
/** 审核通过后只允许请求预检查,绝不直接允许写入。 */
const canCheck = computed(() => !props.disabled && !operation.value.pending && !committed.value && props.quality.canRequestCommitPreview && props.quality.checkpointId === props.checkpointId)
const canCheck = computed(
() =>
!props.disabled &&
!operation.value.pending &&
!committed.value &&
props.quality.canRequestCommitPreview &&
props.quality.checkpointId === props.checkpointId
)
/** 逐项与版本确认后的预检查结果。 */
const ready = computed(() => candidatePreviewReady(preview.value, props.projectId, props.checkpointId))
/** 仅展示具体未通过的安全检查。 */
const failedChecks = computed(() => preview.value ? candidateCheckKeys.filter(key => preview.value!.checks?.[key] !== true).map(key => candidateCheckLabels[key]) : [])
const failedChecks = computed(() =>
preview.value
? candidateCheckKeys.filter(key => preview.value!.checks?.[key] !== true).map(key => candidateCheckLabels[key])
: []
)
/** 当前候选规模与正式资产区别标注。 */
const counts = computed(() => ({ subjects: props.state?.subjectCandidates?.length ?? 0, episodes: props.state?.storyboardEpisodeShots?.length ?? 0, shots: props.state?.storyboardEpisodeShots?.reduce((sum, episode) => sum + episode.beatShots.reduce((total, beat) => total + beat.shots.length, 0), 0) ?? 0 }))
const counts = computed(() => ({
subjects: props.state?.subjectCandidates?.length ?? 0,
episodes: props.state?.storyboardEpisodeShots?.length ?? 0,
shots:
props.state?.storyboardEpisodeShots?.reduce(
(sum, episode) => sum + episode.beatShots.reduce((total, beat) => total + beat.shots.length, 0),
0
) ?? 0
}))
/** 撤销旧检查与确认,版本变化后不能复用提交许可。 */
function invalidate() {
@@ -73,8 +96,22 @@ function invalidate() {
acknowledged.value = false
checkError.value = ''
}
watch([() => props.projectId, () => props.checkpointId, () => props.quality.canRequestCommitPreview, () => props.quality.committed], invalidate, { flush: 'sync' })
watch(() => props.disabled, disabled => { if (disabled && !committing.value) invalidate() })
watch(
[
() => props.projectId,
() => props.checkpointId,
() => props.quality.canRequestCommitPreview,
() => props.quality.committed
],
invalidate,
{ flush: 'sync' }
)
watch(
() => props.disabled,
disabled => {
if (disabled && !committing.value) invalidate()
}
)
onScopeDispose(invalidate)
/** 安全检查通过后才展示最终确认;不调用任何写接口。 */
@@ -89,7 +126,8 @@ async function check() {
try {
const result = await breakdownApi.candidateCommitPreview(id, controller.signal)
if (current !== version) return
if (result.projectId !== id || result.checkpointId !== checkpointId || result.readOnly !== true) throw new Error('候选安全预检查已过期,请刷新后重新检查。')
if (result.projectId !== id || result.checkpointId !== checkpointId || result.readOnly !== true)
throw new Error('候选安全预检查已过期,请刷新后重新检查。')
preview.value = result
if (candidatePreviewReady(result, id, checkpointId)) confirmOpen.value = true
else showActionFeedback(message, '候选暂不能提交,请处理未通过的安全检查。', 'warning')
@@ -98,7 +136,15 @@ async function check() {
checkError.value = errorMessage(cause)
showActionFeedback(message, checkError.value, 'error')
}
} finally { if (current === version) checking.value = false }
} finally {
if (current === version) checking.value = false
}
}
/** 取消最终确认时关闭弹窗并清除勾选,保留本次安全预检查结果。 */
function cancelConfirmation() {
confirmOpen.value = false
acknowledged.value = false
}
/** 最终确认时重新核对版本和全部安全门禁,随后交由后端事务提交。 */
@@ -108,16 +154,39 @@ async function commit() {
const checkpointId = props.checkpointId
const checkedVersion = version
committing.value = true
const ok = await runOperation(id, '正在提交拆解候选', async () => {
const ok = await runOperation(
id,
'正在提交拆解候选',
async () => {
const records = await projectsApi.checkpoints(id)
const latest = workflowCheckpoints(records, 'breakdown').at(-1)
if (!checkpointId || latest?.checkpointId !== checkpointId || latest.state.storyboardPersisted || latest.state.candidateCommitted || props.projectId !== id || props.checkpointId !== checkpointId) throw new Error('拆解候选版本已变化或已经提交,请刷新后重新确认。')
if (
!checkpointId ||
latest?.checkpointId !== checkpointId ||
latest.state.storyboardPersisted ||
latest.state.candidateCommitted ||
props.projectId !== id ||
props.checkpointId !== checkpointId
)
throw new Error('拆解候选版本已变化或已经提交,请刷新后重新确认。')
const checked = await breakdownApi.candidateCommitPreview(id)
if (checkedVersion !== version || !props.quality.canRequestCommitPreview || !candidatePreviewReady(checked, id, checkpointId) || props.projectId !== id || props.checkpointId !== checkpointId) throw new Error('提交安全条件已变化,请重新检查候选。')
if (
checkedVersion !== version ||
!props.quality.canRequestCommitPreview ||
!candidatePreviewReady(checked, id, checkpointId) ||
props.projectId !== id ||
props.checkpointId !== checkpointId
)
throw new Error('提交安全条件已变化,请重新检查候选。')
const receipt = await breakdownApi.commitCandidate(id)
if (receipt.projectId !== id) throw new Error('提交回执所属项目不一致,请刷新确认。')
return receipt
}, receipt => ({ type: 'success', content: `拆解结果已保存并采用:${receipt.subjectCount} 个主体、${receipt.episodeCount} 集、${receipt.shotCount} 个镜头。` }))
},
receipt => ({
type: 'success',
content: `拆解结果已保存并采用:${receipt.subjectCount} 个主体、${receipt.episodeCount} 集、${receipt.shotCount} 个镜头。`
})
)
if (props.projectId === id) {
if (ok) submittedId.value = `${id}:${checkpointId}`
invalidate()
@@ -129,25 +198,77 @@ async function commit() {
<template>
<!-- 以下是候选质量与安全提交模块,不使用只读审核结果替代事务门禁 -->
<section v-if="isCandidate" class="workspace-panel space-y-4" :class="{ 'breakdown-candidate-committed': committed }" aria-label="拆解候选">
<section
v-if="isCandidate"
class="workspace-panel space-y-4"
:class="{ 'breakdown-candidate-committed': committed }"
aria-label="拆解候选"
>
<div class="flex flex-wrap items-center justify-between gap-3">
<h3 class="text-sm font-medium">{{ committed ? '拆解结果已保存并采用' : '待确认的拆解候选' }}</h3>
<span class="text-xs text-muted">{{ committed ? '正式主体' : '候选主体' }} {{ counts.subjects }} · {{ counts.episodes }} 集 · {{ counts.shots }} 镜</span>
<span class="text-xs text-muted"
>{{ committed ? '正式主体' : '候选主体' }} {{ counts.subjects }} · {{ counts.episodes }} 集 ·
{{ counts.shots }} 镜</span
>
</div>
<p class="text-xs leading-6 text-muted">{{ committed ? '本次拆解出的人物、场景、道具和分镜已保存,后续制作会使用这份结果。' : '候选尚未写入正式资产,质量审核后还需通过安全预检查。' }}</p>
<p v-if="!committed" class="text-xs text-muted" role="status">{{ quality.loading ? '正在重新审核当前候选…' : quality.needsRefresh ? '这份拆解结果的检查状态尚未确认,请点击“重新检查”。' : quality.canRequestCommitPreview ? '候选质量审核通过,可执行提交安全预检查。' : '候选仍有待处理问题,请先修订。' }}</p>
<p class="text-xs leading-6 text-muted">
{{
committed
? '本次拆解出的人物、场景、道具和分镜已保存,后续制作会使用这份结果。'
: '候选尚未写入正式资产,质量审核后还需通过安全预检查。'
}}
</p>
<p v-if="!committed" class="text-xs text-muted" role="status">
{{
quality.loading
? '正在重新审核当前候选…'
: quality.needsRefresh
? '这份拆解结果的检查状态尚未确认,请点击“重新检查”。'
: quality.canRequestCommitPreview
? '候选质量审核通过,可执行提交安全预检查。'
: '候选仍有待处理问题,请先修订。'
}}
</p>
<!-- 以下是尚未采用结果的检查与确认操作,采用后不再显示操作区域 -->
<div v-if="!committed" class="flex flex-wrap items-center gap-3">
<NButton :disabled="!canCheck" :loading="checking || committing" @click="check">提交候选为正式结果</NButton>
<WorkspaceRefreshButton label="重新检查" :loading="quality.loading" :disabled="operation.pending || checking" @refresh="emit('refresh')" />
<WorkspaceRefreshButton
label="重新检查"
:loading="quality.loading"
:disabled="operation.pending || checking"
@refresh="emit('refresh')"
/>
</div>
<section v-if="failedChecks.length" class="problem-surface p-4" aria-label="未通过的提交安全检查"><p class="mb-2 text-sm">提交安全检查未通过</p><ul class="list-inside list-disc space-y-2 text-xs"><li v-for="label in failedChecks" :key="label">{{ label }}</li></ul></section>
<section v-if="failedChecks.length" class="problem-surface p-4" aria-label="未通过的提交安全检查">
<p class="mb-2 text-sm">提交安全检查未通过</p>
<ul class="list-inside list-disc space-y-2 text-xs">
<li v-for="label in failedChecks" :key="label">{{ label }}</li>
</ul>
</section>
<p v-if="checkError" class="text-xs text-danger" role="alert">{{ checkError }}</p>
<!-- 以下是通过只读预检查后才出现的最终确认,取消和关闭撤销确认 -->
<AppDialog v-model:open="confirmOpen" title="确认提交候选为正式结果" :busy="committing" description="将替换正式主体、形态与分镜。保存时还会检查剧本是否变化,以及已有制作成果是否受到影响。">
<p class="text-sm">本次候选:{{ counts.subjects }} 个主体、{{ counts.episodes }} 集、{{ counts.shots }} 个镜头。</p>
<NCheckbox v-model:checked="acknowledged" class="mt-5">我已确认替换正式结果,当前没有同项目的制作任务在运行。</NCheckbox>
<template #footer><NButton :disabled="committing" @click="confirmOpen = false; acknowledged = false">取消</NButton><NButton type="primary" :loading="committing" :disabled="!acknowledged || !ready || !canCheck" @click="commit">确认提交候选为正式结果</NButton></template>
<AppDialog
v-model:open="confirmOpen"
title="确认提交候选为正式结果"
:busy="committing"
description="将替换正式主体、形态与分镜。保存时还会检查剧本是否变化,以及已有制作成果是否受到影响。"
>
<p class="text-sm">
本次候选:{{ counts.subjects }} 个主体、{{ counts.episodes }} 集、{{ counts.shots }} 个镜头。
</p>
<NCheckbox v-model:checked="acknowledged" class="mt-5"
>我已确认替换正式结果,当前没有同项目的制作任务在运行。</NCheckbox
>
<template #footer
><NButton :disabled="committing" @click="cancelConfirmation">取消</NButton
><NButton
type="primary"
:loading="committing"
:disabled="!acknowledged || !ready || !canCheck"
@click="commit"
>确认提交候选为正式结果</NButton
></template
>
</AppDialog>
</section>
</template>
@@ -35,10 +35,24 @@ const open = defineModel<boolean>('open', { default: false })
/** 抽屉关闭后再定位正文,避免焦点陷阱阻止定位。 */
const emit = defineEmits<{ locate: [issue: ShotValidation['issues'][number]]; refresh: [] }>()
/** 问题类型统一分类,缺失精确坐标时只提供剧集查看。 */
const problemGroups = computed(() => ([
['subject', '主体引用缺失'], ['binding', '形态绑定异常'], ['structure', '分镜结构校验'],
['action', '动作质量阻断'], ['pending', '待审核剧集'], ['workflow', '当前执行异常']
] as const).map(([type, label]) => ({ type, label, items: props.quality?.problems.filter(item => item.type === type) ?? [] })).filter(group => group.items.length))
const problemGroups = computed(() =>
(
[
['subject', '主体引用缺失'],
['binding', '形态绑定异常'],
['structure', '分镜结构校验'],
['action', '动作质量阻断'],
['pending', '待审核剧集'],
['workflow', '当前执行异常']
] as const
)
.map(([type, label]) => ({
type,
label,
items: props.quality?.problems.filter(item => item.type === type) ?? []
}))
.filter(group => group.items.length)
)
/** 相同镜头的问题合并为一组,重复消息不重复显示。 */
const groups = computed(() => {
const result = new Map<string, BreakdownIssueGroup>()
@@ -78,25 +92,64 @@ function finish() {
<!-- 以下是全屏展示的拆解执行错误与分镜校验问题模块 -->
<AppDrawer v-model:open="open" title="拆解问题" :busy="busy" class="breakdown-issues-drawer" @closed="finish">
<template #description
><span v-if="quality">{{ quality.isCandidate ? '当前候选' : quality.source === 'history' ? '历史结果(当前质量未确认)' : '当前正式结果' }} · 结构 {{ quality.structuralCount }} 项 · 动作 {{ quality.actionBlocks.length }} 镜</span
><span v-if="quality"
>{{
quality.isCandidate
? '当前候选'
: quality.source === 'history'
? '历史结果(当前质量未确认)'
: '当前正式结果'
}}
· 结构 {{ quality.structuralCount }} 项 · 动作 {{ quality.actionBlocks.length }} 镜</span
><span v-else-if="count">{{ count }} 项校验问题 · {{ groups.length }} 个位置</span
><span v-else>查看最近保存结果中的问题</span></template
>
<!-- 以下是当前版本的分类问题,历史错误不会混入当前问题数量 -->
<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>
<div v-else-if="quality.error" class="problem-surface p-5 space-y-3"><p class="text-sm break-words">{{ quality.error }}</p><NButton @click="emit('refresh')">重新读取审核</NButton></div>
<div v-else-if="quality.error" class="problem-surface p-5 space-y-3">
<p class="text-sm break-words">{{ quality.error }}</p>
<NButton @click="emit('refresh')">重新读取审核</NButton>
</div>
<template v-else>
<section v-for="group in problemGroups" :key="group.type" class="space-y-3" :aria-label="group.label">
<h3 class="text-sm font-medium">{{ group.label }} · {{ group.items.length }}</h3>
<article v-for="item in group.items" :key="item.key" class="workspace-panel problem-surface space-y-3 break-words" :data-problem-type="item.type">
<div v-if="item.location" class="flex flex-wrap items-center justify-between gap-3"><p class="text-sm">第 {{ item.location.episodeNo }} 集<span v-if="item.location.beatNo"> · 节拍 {{ item.location.beatNo }}</span><span v-if="item.location.shotNo"> · 镜头 {{ item.location.shotNo }}</span><span class="ml-3 text-xs text-muted">待处理</span></p><NButton v-if="locatable" text size="small" @click="locate(item.location)">{{ item.location.beatNo ? '定位分镜' : '查看本集' }}</NButton></div>
<p class="text-sm leading-6">{{ userFacingText(item.message) }}</p><p v-if="item.codes.length" class="text-xs text-muted break-all">需要处理:{{ item.codes.map(qualityIssueLabel).join('、') }}</p>
<article
v-for="item in group.items"
:key="item.key"
class="workspace-panel problem-surface space-y-3 break-words"
:data-problem-type="item.type"
>
<div v-if="item.location" class="flex flex-wrap items-center justify-between gap-3">
<p class="text-sm">
第 {{ item.location.episodeNo }} 集<span v-if="item.location.beatNo">
· 节拍 {{ item.location.beatNo }}</span
><span v-if="item.location.shotNo"> · 镜头 {{ item.location.shotNo }}</span
><span class="ml-3 text-xs text-muted">待处理</span>
</p>
<NButton v-if="locatable" text size="small" @click="locate(item.location)">{{
item.location.beatNo ? '定位分镜' : '查看本集'
}}</NButton>
</div>
<p class="text-sm leading-6">{{ userFacingText(item.message) }}</p>
<p v-if="item.codes.length" class="text-xs text-muted break-all">
需要处理:{{ item.codes.map(qualityIssueLabel).join('、') }}
</p>
</article>
</section>
<p v-if="!quality.issueCount && !workflowError" class="text-sm text-muted">当前版本没有待处理的质量问题。</p>
<p v-if="!quality.issueCount && !workflowError" class="text-sm text-muted">
当前版本没有待处理的质量问题。
</p>
<!-- 以下是使用 Naive 折叠组件的历史记录,默认收起且不计入当前问题 -->
<NCollapse v-if="quality.historyIssues.length" class="text-xs text-muted" data-history-issues><NCollapseItem name="history" :title="`历史审核记录 · ${quality.historyIssues.length} 项(不计入当前问题)`"><p v-for="(item, index) in quality.historyIssues" :key="index" class="mt-3 break-words">第 {{ item.episodeNo }} 集 · {{ userFacingText(item.message) }}</p></NCollapseItem></NCollapse>
<NCollapse v-if="quality.historyIssues.length" class="text-xs text-muted" data-history-issues
><NCollapseItem
name="history"
:title="`历史审核记录 · ${quality.historyIssues.length} 项(不计入当前问题)`"
><p v-for="(item, index) in quality.historyIssues" :key="index" class="mt-3 break-words">
第 {{ item.episodeNo }} 集 · {{ userFacingText(item.message) }}
</p></NCollapseItem
></NCollapse
>
</template>
</div>
<div class="space-y-4">
@@ -40,9 +40,21 @@ const emit = defineEmits<{ refresh: [] }>()
/** 项目写锁与统一消息反馈。 */
const operation = computed(() => getOperation(props.projectId))
/** 必须匹配当前检查点与项目的审核。 */
const review = computed(() => props.review?.checkpointId === props.checkpointId && props.review.projectId === props.projectId ? props.review : null)
const review = computed(() =>
props.review?.checkpointId === props.checkpointId && props.review.projectId === props.projectId
? props.review
: null
)
/** 只有明确候选且没有活动操作才允许修订。 */
const writable = computed(() => !!review.value && props.state.candidateOnly === true && !props.state.storyboardPersisted && !props.state.candidateCommitted && !props.disabled && !operation.value.pending)
const writable = computed(
() =>
!!review.value &&
props.state.candidateOnly === true &&
!props.state.storyboardPersisted &&
!props.state.candidateCommitted &&
!props.disabled &&
!operation.value.pending
)
/** 已选择的镜头坐标键。 */
const targetKey = ref('')
/** 从真实主体选项中选择的引用。 */
@@ -67,15 +79,24 @@ const targets = computed(() => {
const values = new Map<string, CandidateShotLocation & { refs: string[] }>()
const add = (location: CandidateShotLocation, subjectReference: string) => {
if (!props.state.subjectCandidates?.some(subject => subject.ref === subjectReference)) return
const shot = props.state.storyboardEpisodeShots?.find(item => item.episodeNo === location.episodeNo)?.beatShots.find(item => item.beatNo === location.beatNo)?.shots.find(item => item.shotNo === location.shotNo)
if (!shot || shot.subjectRefs.includes(subjectReference) || shot.subjectBindings?.some(item => item.subjectRef === subjectReference)) return
const shot = props.state.storyboardEpisodeShots
?.find(item => item.episodeNo === location.episodeNo)
?.beatShots.find(item => item.beatNo === location.beatNo)
?.shots.find(item => item.shotNo === location.shotNo)
if (
!shot ||
shot.subjectRefs.includes(subjectReference) ||
shot.subjectBindings?.some(item => item.subjectRef === subjectReference)
)
return
const key = positionKey(location)
const value = values.get(key) ?? { ...location, refs: [] }
if (!value.refs.includes(subjectReference)) value.refs.push(subjectReference)
values.set(key, value)
}
for (const item of review.value?.missingSubjectRefs ?? []) {
if (item.beatNo && item.shotNo && item.subject) add({ episodeNo: item.episodeNo, beatNo: item.beatNo, shotNo: item.shotNo }, item.subject.ref)
if (item.beatNo && item.shotNo && item.subject)
add({ episodeNo: item.episodeNo, beatNo: item.beatNo, shotNo: item.shotNo }, item.subject.ref)
}
for (const item of review.value?.propReferenceDiagnostics ?? []) {
if (!item.shotHasSubject && !item.shotHasBinding) add(item, item.subjectRef)
@@ -85,26 +106,68 @@ const targets = computed(() => {
/** 当前镜头的可信缺失引用选项。 */
const target = computed(() => targets.value.find(item => positionKey(item) === targetKey.value))
/** 主体只取当前候选,禁止任意输入。 */
const subjectOptions = computed(() => (props.state.subjectCandidates ?? []).filter(item => target.value?.refs.includes(item.ref)).map(item => ({ label: `${item.name}(${item.ref})`, value: item.ref })))
const subjectOptions = computed(() =>
(props.state.subjectCandidates ?? [])
.filter(item => target.value?.refs.includes(item.ref))
.map(item => ({ label: `${item.name}(${item.ref})`, value: item.ref }))
)
/** 形态严格按真实主体 profileId 过滤。 */
const formOptions = computed(() => {
const subject = props.state.subjectCandidates?.find(item => item.ref === subjectRef.value)
return (props.state.subjectForms ?? []).filter(item => item.profileId === subject?.profileId).map(item => ({ label: item.formName || item.name, value: item.formId }))
return (props.state.subjectForms ?? [])
.filter(item => item.profileId === subject?.profileId)
.map(item => ({ label: item.formName || item.name, value: item.formId }))
})
/** 可提交主体目标,切换任何字段后都会撤销先前确认。 */
const subjectReady = computed(() => writable.value && !!target.value && subjectOptions.value.some(item => item.value === subjectRef.value) && formOptions.value.some(item => item.value === formId.value))
const subjectReady = computed(
() =>
writable.value &&
!!target.value &&
subjectOptions.value.some(item => item.value === subjectRef.value) &&
formOptions.value.some(item => item.value === formId.value)
)
/** 多镜头修复摘要只取用户选择的真实动作。 */
const repairs = computed(() => actionDrafts.value.filter(item => item.selected).map(({ episodeNo, beatNo, shotNo, actionId, description }) => ({ episodeNo, beatNo, shotNo, actionId, description: description.trim() })))
const repairs = computed(() =>
actionDrafts.value
.filter(item => item.selected)
.map(({ episodeNo, beatNo, shotNo, actionId, description }) => ({
episodeNo,
beatNo,
shotNo,
actionId,
description: description.trim()
}))
)
/** 每个选中动作都必须提供非空的、经过人工改写的过程描述。 */
const actionReady = computed(() => writable.value && repairs.value.length > 0 && actionDrafts.value.filter(item => item.selected).every(item => !!item.description.trim() && item.description.trim() !== item.original.trim()))
const actionReady = computed(
() =>
writable.value &&
repairs.value.length > 0 &&
actionDrafts.value
.filter(item => item.selected)
.every(item => !!item.description.trim() && item.description.trim() !== item.original.trim())
)
/** 主体修复的最终确认摘要。 */
const subjectSummary = computed(() => `只更新候选检查点,不修改正式资产。目标:${targetKey.value};主体:${subjectRef.value};形态:${formOptions.value.find(item => item.value === formId.value)?.label ?? ''}。`)
const subjectSummary = computed(
() =>
`只更新候选检查点,不修改正式资产。目标:${targetKey.value};主体:${subjectRef.value};形态:${formOptions.value.find(item => item.value === formId.value)?.label ?? ''}。`
)
/** 批量修复的最终确认摘要,描述变化后必须重新确认。 */
const actionSummary = computed(() => `只更新候选,不调用模型。共 ${repairs.value.length} 个动作:${repairs.value.map(item => `${positionKey(item)} · ${item.actionId}:${item.description}`).join(';')}`)
const actionSummary = computed(
() =>
`只更新候选,不调用模型。共 ${repairs.value.length} 个动作:${repairs.value.map(item => `${positionKey(item)} · ${item.actionId}:${item.description}`).join(';')}`
)
watch(targetKey, () => { subjectRef.value = ''; formId.value = '' })
watch(subjectRef, () => { formId.value = '' })
watch([() => props.projectId, () => props.checkpointId, review], () => {
watch(targetKey, () => {
subjectRef.value = ''
formId.value = ''
})
watch(subjectRef, () => {
formId.value = ''
})
watch(
[() => props.projectId, () => props.checkpointId, review],
() => {
const version = `${props.projectId}:${props.checkpointId}`
if (version !== draftVersion) {
draftVersion = version
@@ -117,26 +180,56 @@ watch([() => props.projectId, () => props.checkpointId, review], () => {
actionDrafts.value = review.value.actionRepairTargets.flatMap(item => {
if (!item.blockingCodes.includes('state_used_as_action_phase') || !item.shot) return []
const shot = item.shot
return shot.requiredActions.filter(action => action.kind === 'state' && shot.durationPlanning?.phases.some(phase => phase.actionIds?.includes(action.id))).map(action => ({
episodeNo: item.episodeNo, beatNo: item.beatNo, shotNo: item.shotNo,
key: `${positionKey(item)}/${action.id}`, actionId: action.id, selected: false,
description: '', original: action.description, title: shot.title,
parallel: shot.durationPlanning?.phases.some(phase => phase.actionIds?.includes(action.id) && phase.actionIds.length > 1) ?? false
return shot.requiredActions
.filter(
action =>
action.kind === 'state' &&
shot.durationPlanning?.phases.some(phase => phase.actionIds?.includes(action.id))
)
.map(action => ({
episodeNo: item.episodeNo,
beatNo: item.beatNo,
shotNo: item.shotNo,
key: `${positionKey(item)}/${action.id}`,
actionId: action.id,
selected: false,
description: '',
original: action.description,
title: shot.title,
parallel:
shot.durationPlanning?.phases.some(
phase => phase.actionIds?.includes(action.id) && phase.actionIds.length > 1
) ?? false
}))
})
}, { immediate: true })
},
{ immediate: true }
)
/** 用户确认后提交单镜头主体补齐,成功后重读真实新版本。 */
async function repairSubject() {
if (!subjectReady.value || !target.value) return
const id = props.projectId
const checkpointId = props.checkpointId
const input = { expectedCheckpointId: checkpointId, episodeNo: target.value.episodeNo, beatNo: target.value.beatNo, shotNo: target.value.shotNo, subjectRef: subjectRef.value, formId: formId.value }
const ok = await runOperation(id, '修复候选主体引用', async () => {
const input = {
expectedCheckpointId: checkpointId,
episodeNo: target.value.episodeNo,
beatNo: target.value.beatNo,
shotNo: target.value.shotNo,
subjectRef: subjectRef.value,
formId: formId.value
}
const ok = await runOperation(
id,
'修复候选主体引用',
async () => {
const receipt = await breakdownApi.repairCandidateSubject(id, input)
if (!receipt.checkpointId || receipt.checkpointId === checkpointId) throw new Error('未确认候选新版本,请刷新审核后核对。')
if (!receipt.checkpointId || receipt.checkpointId === checkpointId)
throw new Error('未确认候选新版本,请刷新审核后核对。')
return receipt
}, { type: 'success', content: '候选引用已修订,正在重新读取审核结果。' })
},
{ type: 'success', content: '候选引用已修订,正在重新读取审核结果。' }
)
if (ok && props.projectId === id) emit('refresh')
}
@@ -146,11 +239,17 @@ async function repairActions() {
const id = props.projectId
const checkpointId = props.checkpointId
const input = { expectedCheckpointId: checkpointId, repairs: structuredClone(repairs.value) }
const ok = await runOperation(id, '批量修复候选动作', async () => {
const ok = await runOperation(
id,
'批量修复候选动作',
async () => {
const receipt = await breakdownApi.repairCandidateActions(id, input)
if (!receipt.checkpointId || receipt.checkpointId === checkpointId) throw new Error('未确认候选新版本,请刷新审核后核对。')
if (!receipt.checkpointId || receipt.checkpointId === checkpointId)
throw new Error('未确认候选新版本,请刷新审核后核对。')
return receipt
}, { type: 'success', content: '候选动作已修订,正在重新读取审核结果。' })
},
{ type: 'success', content: '候选动作已修订,正在重新读取审核结果。' }
)
if (ok && props.projectId === id) emit('refresh')
}
</script>
@@ -158,28 +257,99 @@ async function repairActions() {
<template>
<!-- 以下是仅针对候选的主体与形态补齐模块 -->
<section v-if="targets.length" class="workspace-panel space-y-4" aria-label="候选主体修复">
<WorkspaceSectionHeading title="补齐候选主体引用" description="选择当前缺失引用及该主体已有形态,确认后保存为新的候选版本。" />
<WorkspaceSectionHeading
title="补齐候选主体引用"
description="选择当前缺失引用及该主体已有形态,确认后保存为新的候选版本。"
/>
<div class="grid grid-cols-1 gap-4 lg:grid-cols-3">
<NFormItem label="目标镜头"><NSelect v-model:value="targetKey" aria-label="主体修复目标镜头" :disabled="!writable" :options="targets.map(item => ({ label: `第 ${item.episodeNo} 集 · 节拍 ${item.beatNo} · 镜头 ${item.shotNo}`, value: positionKey(item) }))" /></NFormItem>
<NFormItem label="候选主体"><NSelect v-model:value="subjectRef" aria-label="待补齐候选主体" :disabled="!writable || !target" :options="subjectOptions" /></NFormItem>
<NFormItem label="已有形态"><NSelect v-model:value="formId" aria-label="候选主体已有形态" :disabled="!writable || !subjectRef" :options="formOptions" /></NFormItem>
<NFormItem label="目标镜头"
><NSelect
v-model:value="targetKey"
aria-label="主体修复目标镜头"
:disabled="!writable"
:options="
targets.map(item => ({
label: `第 ${item.episodeNo} 集 · 节拍 ${item.beatNo} · 镜头 ${item.shotNo}`,
value: positionKey(item)
}))
"
/></NFormItem>
<NFormItem label="候选主体"
><NSelect
v-model:value="subjectRef"
aria-label="待补齐候选主体"
:disabled="!writable || !target"
:options="subjectOptions"
/></NFormItem>
<NFormItem label="已有形态"
><NSelect
v-model:value="formId"
aria-label="候选主体已有形态"
:disabled="!writable || !subjectRef"
:options="formOptions"
/></NFormItem>
</div>
<ConfirmAction :key="`${checkpointId}:${subjectSummary}`" label="修复候选主体引用" :description="subjectSummary" :disabled="!subjectReady" :loading="isOperationRunning(operation, '修复候选主体引用')" @confirm="repairSubject" />
<ConfirmAction
:key="`${checkpointId}:${subjectSummary}`"
label="修复候选主体引用"
:description="subjectSummary"
:disabled="!subjectReady"
:loading="isOperationRunning(operation, '修复候选主体引用')"
@confirm="repairSubject"
/>
</section>
<!-- 以下是动作质量阻断的批量语义修订模块,不提供 kind 修改或自动修复 -->
<section v-if="review?.actionQualityBlocks.length" class="workspace-panel space-y-4" aria-label="候选批量动作修复">
<WorkspaceSectionHeading title="批量修订候选动作" description="仅展示当前阻断镜头。逐项选择并填写可观察的动作过程,提交前核对修复摘要。" />
<p v-if="!actionDrafts.length" class="text-xs text-muted">当前阻断不属于批量接口支持的结果状态引用问题,无法在此自动修订。</p>
<article v-for="draft in actionDrafts" :key="draft.key" class="candidate-action-draft space-y-3 p-4" :data-action-id="draft.actionId">
<NCheckbox v-model:checked="draft.selected" :disabled="!writable">第 {{ draft.episodeNo }} 集 · 节拍 {{ draft.beatNo }} · 镜头 {{ draft.shotNo }} · {{ draft.title }} · {{ draft.actionId }}</NCheckbox>
<WorkspaceSectionHeading
title="批量修订候选动作"
description="仅展示当前阻断镜头。逐项选择并填写可观察的动作过程,提交前核对修复摘要。"
/>
<p v-if="!actionDrafts.length" class="text-xs text-muted">
当前阻断不属于批量接口支持的结果状态引用问题,无法在此自动修订。
</p>
<article
v-for="draft in actionDrafts"
:key="draft.key"
class="candidate-action-draft space-y-3 p-4"
:data-action-id="draft.actionId"
>
<NCheckbox v-model:checked="draft.selected" :disabled="!writable"
>第 {{ draft.episodeNo }} 集 · 节拍 {{ draft.beatNo }} · 镜头 {{ draft.shotNo }} · {{ draft.title }} ·
{{ draft.actionId }}</NCheckbox
>
<p class="text-xs leading-6 text-muted">原始状态:{{ draft.original }}</p>
<p v-if="draft.parallel" class="text-xs text-danger">这个动作与其他动作同时发生。请先核对它们的关系,避免修改后互相冲突。</p>
<NInput v-model:value="draft.description" type="textarea" :disabled="!writable || !draft.selected" :input-props="{ 'aria-label': `动作 ${draft.key} 修订描述` }" placeholder="请人工填写动作如何发生,不能只把结果状态改名" :autosize="{ minRows: 3, maxRows: 8 }" />
<p v-if="draft.parallel" class="text-xs text-danger">
这个动作与其他动作同时发生。请先核对它们的关系,避免修改后互相冲突。
</p>
<NInput
v-model:value="draft.description"
type="textarea"
:disabled="!writable || !draft.selected"
:input-props="{ 'aria-label': `动作 ${draft.key} 修订描述` }"
placeholder="请人工填写动作如何发生,不能只把结果状态改名"
:autosize="{ minRows: 3, maxRows: 8 }"
/>
</article>
<p v-if="repairs.length" class="text-xs leading-6 text-muted break-words" aria-label="批量修复摘要">{{ actionSummary }}</p>
<ConfirmAction v-if="actionDrafts.length" :key="`${checkpointId}:${actionSummary}`" label="批量修复候选动作" :description="actionSummary" :disabled="!actionReady" :loading="isOperationRunning(operation, '批量修复候选动作')" @confirm="repairActions" />
<p v-if="repairs.length" class="text-xs leading-6 text-muted break-words" aria-label="批量修复摘要">
{{ actionSummary }}
</p>
<ConfirmAction
v-if="actionDrafts.length"
:key="`${checkpointId}:${actionSummary}`"
label="批量修复候选动作"
:description="actionSummary"
:disabled="!actionReady"
:loading="isOperationRunning(operation, '批量修复候选动作')"
@confirm="repairActions"
/>
</section>
<p v-if="operation.error && ['修复候选主体引用', '批量修复候选动作'].includes(operation.label)" role="alert" class="text-xs text-danger break-words">{{ operation.error }}</p>
<p
v-if="operation.error && ['修复候选主体引用', '批量修复候选动作'].includes(operation.label)"
role="alert"
class="text-xs text-danger break-words"
>
{{ operation.error }}
</p>
</template>
<style>
@@ -31,18 +31,42 @@ const revisions = ref<StoryboardHandRepairHistory | null>(null)
/** 当前诊断对应的修订资格。 */
const readiness = ref<DiagnosisRepairReadiness | null>(null)
/** 两类记录均已成功读到空结果时,使用同一条空状态,读取失败不冒充暂无记录。 */
const noRecords = computed(() => !loading.value && !error.value && !!history.value && !!revisions.value &&
history.value.revisions.length === 0 && revisions.value.revisions.length === 0)
const noRecords = computed(
() =>
!loading.value &&
!error.value &&
!!history.value &&
!!revisions.value &&
history.value.revisions.length === 0 &&
revisions.value.revisions.length === 0
)
/** 当前列表与资格必须同时有效,不能把旧诊断或直接应用标记解释成修订许可。 */
const repairEligible = computed(() => readiness.value?.eligible === true && readiness.value.requiresManualReview === true &&
readiness.value.canApplyDirectly === false && readiness.value.willCallModel === false && readiness.value.willModifyAssets === false &&
props.shot.status === 'conflict_found' && props.shot.policyStatus === 'current' && props.shot.shotStale === false)
const repairEligible = computed(
() =>
readiness.value?.eligible === true &&
readiness.value.requiresManualReview === true &&
readiness.value.canApplyDirectly === false &&
readiness.value.willCallModel === false &&
readiness.value.willModifyAssets === false &&
props.shot.status === 'conflict_found' &&
props.shot.policyStatus === 'current' &&
props.shot.shotStale === false
)
/** 只读请求加载,始终允许关闭主窗口。 */
const loading = ref(false)
/** 保留可重试的查询错误。 */
const error = ref('')
/** 同镜头诊断和版本状态组成请求身份。 */
const target = computed(() => JSON.stringify([props.projectId, props.shot.shotId, props.shot.diagnosisId, props.shot.policyStatus, props.shot.shotStale, props.shot.latestRepairId]))
const target = computed(() =>
JSON.stringify([
props.projectId,
props.shot.shotId,
props.shot.diagnosisId,
props.shot.policyStatus,
props.shot.shotStale,
props.shot.latestRepairId
])
)
/** 请求代次用于拦截迟到结果。 */
let version = 0
/** 只读请求关闭时取消。 */
@@ -52,36 +76,80 @@ let controller: AbortController | undefined
async function load() {
if (loading.value) return
const current = ++version
const id = props.projectId, shotId = props.shot.shotId, diagnosisId = props.shot.diagnosisId
controller?.abort(); controller = new AbortController()
loading.value = true; error.value = ''
const id = props.projectId,
shotId = props.shot.shotId,
diagnosisId = props.shot.diagnosisId
controller?.abort()
controller = new AbortController()
loading.value = true
error.value = ''
try {
const [records, checked, changes] = await Promise.all([
breakdownApi.diagnosisHistory(id, shotId, controller.signal),
diagnosisId ? breakdownApi.diagnosisRepairReadiness(id, shotId, diagnosisId, controller.signal) : Promise.resolve(null),
diagnosisId
? breakdownApi.diagnosisRepairReadiness(id, shotId, diagnosisId, controller.signal)
: Promise.resolve(null),
preparationApi.revisions(id, shotId, controller.signal)
])
if (current !== version) return
if (changes.projectId !== id || changes.shotId !== shotId || !Array.isArray(changes.revisions) || records.projectId !== id || records.shotId !== shotId || !Array.isArray(records.revisions) ||
checked && (checked.projectId !== id || checked.shotId !== shotId || checked.diagnosisId !== diagnosisId))
if (
changes.projectId !== id ||
changes.shotId !== shotId ||
!Array.isArray(changes.revisions) ||
records.projectId !== id ||
records.shotId !== shotId ||
!Array.isArray(records.revisions) ||
(checked && (checked.projectId !== id || checked.shotId !== shotId || checked.diagnosisId !== diagnosisId))
)
throw new Error('记录与当前镜头不一致,请重新读取。')
history.value = records; readiness.value = checked; revisions.value = changes
} catch (cause) { if (current === version) error.value = errorMessage(cause) }
finally { if (current === version) loading.value = false }
history.value = records
readiness.value = checked
revisions.value = changes
} catch (cause) {
if (current === version) error.value = errorMessage(cause)
} finally {
if (current === version) loading.value = false
}
}
/** 收起或切换上下文时废弃旧请求,不把旧资格沿用到新版本。 */
function reset() { version++; controller?.abort(); loading.value = false; history.value = null; readiness.value = null; revisions.value = null; error.value = '' }
watch(expanded, value => { if (value.includes('review')) void load(); else reset() })
watch(target, () => { reset(); if (expanded.value.includes('review')) void load() })
function reset() {
version++
controller?.abort()
loading.value = false
history.value = null
readiness.value = null
revisions.value = null
error.value = ''
}
watch(expanded, value => {
if (value.includes('review')) void load()
else reset()
})
watch(target, () => {
reset()
if (expanded.value.includes('review')) void load()
})
onScopeDispose(reset)
</script>
<template>
<!-- 以下是指定诊断的只读修订条件与历史记录,普通列表不暴露内部编号 -->
<div class="diagnosis-shot-tools">
<NButton size="small" :aria-label="showDetails ? '收起修订条件与历史' : '修订条件与诊断历史'" :title="showDetails ? '收起修订条件与历史' : '修订条件与诊断历史'" :aria-expanded="showDetails" @click="expanded = showDetails ? [] : ['review']"><template #icon><History :size="15" aria-hidden="true" /></template><span class="diagnosis-action-label">{{ showDetails ? '收起修订条件与历史' : '修订条件与诊断历史' }}</span></NButton>
<NButton
size="small"
:aria-label="showDetails ? '收起修订条件与历史' : '修订条件与诊断历史'"
:title="showDetails ? '收起修订条件与历史' : '修订条件与诊断历史'"
:aria-expanded="showDetails"
@click="expanded = showDetails ? [] : ['review']"
><template #icon><History :size="15" aria-hidden="true" /></template
><span class="diagnosis-action-label">{{
showDetails ? '收起修订条件与历史' : '修订条件与诊断历史'
}}</span></NButton
>
<!-- 以下是与定位、复查和历史入口同排的刷新操作,不在展开正文另起一组工具。 -->
<NButton v-if="showDetails" size="small" :loading="loading" @click="load"><template #icon><RefreshCw :size="14" aria-hidden="true" /></template>刷新记录</NButton>
<NButton v-if="showDetails" size="small" :loading="loading" @click="load"
><template #icon><RefreshCw :size="14" aria-hidden="true" /></template>刷新记录</NButton
>
<NCollapse v-show="showDetails" v-model:expanded-names="expanded" class="diagnosis-shot-details">
<NCollapseItem name="review" title="修订条件与诊断历史">
<div class="space-y-3 text-xs leading-6">
@@ -89,22 +157,56 @@ onScopeDispose(reset)
<p v-if="loading" role="status" class="text-muted">正在核对当前镜头记录…</p>
<p v-else-if="noRecords" class="text-muted">暂无修订或 AI 诊断记录。</p>
<section v-if="readiness" class="space-y-2" aria-label="当前诊断修订条件">
<p>{{ repairEligible ? '已满足人工修订的前提,仍需人工核对完整动作。' : '当前暂不能按这份诊断修订镜头。' }}</p>
<p v-for="reason in readiness.blockingReasons" :key="reason" class="text-muted">{{ diagnosisReason(reason) }}</p>
<p v-if="repairEligible" class="text-muted">可点击“查看并修订动作”,读取当前正式规划后再明确保存。</p>
<article v-for="(candidate, index) in readiness.repairCandidates" :key="index" class="space-y-1">
<p>阶段 {{ candidate.phaseNo }} · {{ candidate.characterRef }}</p><p>{{ userFacingText(candidate.suggestion) }}</p>
<p>
{{
repairEligible
? '已满足人工修订的前提,仍需人工核对完整动作。'
: '当前暂不能按这份诊断修订镜头。'
}}
</p>
<p v-for="reason in readiness.blockingReasons" :key="reason" class="text-muted">
{{ diagnosisReason(reason) }}
</p>
<p v-if="repairEligible" class="text-muted">
可点击“查看并修订动作”,读取当前正式规划后再明确保存。
</p>
<article
v-for="(candidate, index) in readiness.repairCandidates"
:key="index"
class="space-y-1"
>
<p>阶段 {{ candidate.phaseNo }} · {{ candidate.characterRef }}</p>
<p>{{ userFacingText(candidate.suggestion) }}</p>
</article>
</section>
<section v-if="revisions?.revisions.length" class="space-y-3" aria-label="正式修订历史">
<p class="font-medium">正式修订 · {{ revisions.count }} 条</p>
<article v-for="record in revisions.revisions" :key="record.id" class="space-y-1"><p class="text-muted">{{ formatDate(record.createdAt) }}</p><p>{{ record.reason }}</p></article>
<article v-for="record in revisions.revisions" :key="record.id" class="space-y-1">
<p class="text-muted">{{ formatDate(record.createdAt) }}</p>
<p>{{ record.reason }}</p>
</article>
</section>
<section v-if="history?.revisions.length" class="space-y-3" aria-label="诊断历史">
<p class="font-medium">AI 诊断 · {{ history.count }} 条</p>
<article v-for="record in history.revisions" :key="record.id" class="space-y-1">
<p>{{ formatDate(record.createdAt) }} · {{ diagnosisStatusLabels[record.effectiveStatus as keyof typeof diagnosisStatusLabels] || '结果待核对' }}</p>
<p class="text-muted">{{ record.shotStale ? '镜头已变化' : '镜头内容一致' }} · {{ record.policyStatus === 'current' ? '规则版本一致' : record.policyStatus === 'stale' ? '规则版本已变化' : '缺少规则版本' }}</p>
<p>
{{ formatDate(record.createdAt) }} ·
{{
diagnosisStatusLabels[
record.effectiveStatus as keyof typeof diagnosisStatusLabels
] || '结果待核对'
}}
</p>
<p class="text-muted">
{{ record.shotStale ? '镜头已变化' : '镜头内容一致' }} ·
{{
record.policyStatus === 'current'
? '规则版本一致'
: record.policyStatus === 'stale'
? '规则版本已变化'
: '缺少规则版本'
}}
</p>
<RawDataDetails :value="record" title="完整诊断证据(高级)" />
</article>
</section>
@@ -115,12 +217,23 @@ onScopeDispose(reset)
</template>
<style scoped>
.diagnosis-shot-tools { display: contents; }
.diagnosis-shot-tools > .n-button { min-height: 34px; }
.diagnosis-shot-tools {
display: contents;
}
.diagnosis-shot-tools > .n-button {
min-height: 34px;
}
/* 展开仍由 Naive 组件管理;入口使用独立可聚焦按钮,避免重复折叠标题。 */
.diagnosis-shot-details { flex-basis: 100%; min-width: 0; }
.diagnosis-shot-details :deep(.n-collapse-item__header) { display: none; }
.diagnosis-shot-details {
flex-basis: 100%;
min-width: 0;
}
.diagnosis-shot-details :deep(.n-collapse-item__header) {
display: none;
}
/* 隐藏默认折叠标题后清除两层顶部留白,正文与卡片操作共用间距。 */
.diagnosis-shot-details :deep(.n-collapse-item__content-wrapper),
.diagnosis-shot-details :deep(.n-collapse-item__content-inner) { padding-top: 0; }
.diagnosis-shot-details :deep(.n-collapse-item__content-inner) {
padding-top: 0;
}
</style>
@@ -123,7 +123,13 @@ function updateTransition(resource: ResourceOccupancy, value: 'release' | 'trans
:disabled="disabled"
/></NFormItem>
<NCheckbox v-model:checked="action.mustPerformInShot" :disabled="disabled">本镜必须完成</NCheckbox>
<NButton class="icon-button" :aria-label="`移除动作 ${index + 1}`" :disabled="disabled" @click="draft.requiredActions.splice(index, 1)"><template #icon><Trash2 :size="16" /></template></NButton>
<NButton
class="icon-button"
:aria-label="`移除动作 ${index + 1}`"
:disabled="disabled"
@click="draft.requiredActions.splice(index, 1)"
><template #icon><Trash2 :size="16" /></template
></NButton>
</div>
</section>
<!-- 以下是动作阶段编辑模块,同阶段动作视为同时发生 -->
@@ -143,7 +149,13 @@ function updateTransition(resource: ResourceOccupancy, value: 'release' | 'trans
>
<div class="flex flex-wrap items-center justify-between gap-3">
<h4 class="text-sm">阶段 {{ index + 1 }}</h4>
<NButton class="icon-button" :aria-label="`移除阶段 ${index + 1}`" :disabled="disabled" @click="draft.durationPlanning.phases.splice(index, 1)"><template #icon><Trash2 :size="16" /></template></NButton>
<NButton
class="icon-button"
:aria-label="`移除阶段 ${index + 1}`"
:disabled="disabled"
@click="draft.durationPlanning.phases.splice(index, 1)"
><template #icon><Trash2 :size="16" /></template
></NButton>
</div>
<NFormItem label="阶段描述"
><NInput v-model:value="phase.action" :aria-label="`阶段 ${index + 1} 描述`" :disabled="disabled"
@@ -199,7 +211,13 @@ function updateTransition(resource: ResourceOccupancy, value: 'release' | 'trans
:disabled="disabled"
/></NFormItem>
<NCheckbox v-model:checked="hand.shareable" :disabled="disabled">可共享</NCheckbox>
<NButton class="icon-button" :aria-label="`移除阶段 ${index + 1} 手部证据 ${handIndex + 1}`" :disabled="disabled" @click="phase.handOccupancy?.splice(handIndex, 1)"><template #icon><Trash2 :size="16" /></template></NButton>
<NButton
class="icon-button"
:aria-label="`移除阶段 ${index + 1} 手部证据 ${handIndex + 1}`"
:disabled="disabled"
@click="phase.handOccupancy?.splice(handIndex, 1)"
><template #icon><Trash2 :size="16" /></template
></NButton>
</div>
<div
v-for="(resource, resourceIndex) in phase.resourceOccupancy"
@@ -235,9 +253,32 @@ function updateTransition(resource: ResourceOccupancy, value: 'release' | 'trans
:disabled="disabled"
/></NFormItem>
<NCheckbox v-model:checked="resource.shareable" :disabled="disabled">可共享</NCheckbox>
<NFormItem label="持续对象" :show-feedback="false"><NInput :value="resource.continuityRef || ''" placeholder="仅填写已有明确对象引用" :disabled="disabled" @update:value="updateContinuity(resource, $event)" /></NFormItem>
<NFormItem label="释放或交接" :show-feedback="false"><NSelect :value="resource.transition ?? null" clearable :options="[{ label: '明确释放', value: 'release' }, { label: '明确交接', value: 'transfer' }]" placeholder="未声明" :disabled="disabled" @update:value="updateTransition(resource, $event)" /></NFormItem>
<NButton class="icon-button" :aria-label="`移除阶段 ${index + 1} 资源证据 ${resourceIndex + 1}`" :disabled="disabled" @click="phase.resourceOccupancy?.splice(resourceIndex, 1)"><template #icon><Trash2 :size="16" /></template></NButton>
<NFormItem label="持续对象" :show-feedback="false"
><NInput
:value="resource.continuityRef || ''"
placeholder="仅填写已有明确对象引用"
:disabled="disabled"
@update:value="updateContinuity(resource, $event)"
/></NFormItem>
<NFormItem label="释放或交接" :show-feedback="false"
><NSelect
:value="resource.transition ?? null"
clearable
:options="[
{ label: '明确释放', value: 'release' },
{ label: '明确交接', value: 'transfer' }
]"
placeholder="未声明"
:disabled="disabled"
@update:value="updateTransition(resource, $event)"
/></NFormItem>
<NButton
class="icon-button"
:aria-label="`移除阶段 ${index + 1} 资源证据 ${resourceIndex + 1}`"
:disabled="disabled"
@click="phase.resourceOccupancy?.splice(resourceIndex, 1)"
><template #icon><Trash2 :size="16" /></template
></NButton>
</div>
</section>
</section>
@@ -3,7 +3,19 @@ import { computed, inject, onScopeDispose, ref, watch } from 'vue'
import { NButton, NCollapse, NCollapseItem, NInputNumber, NSelect, NSpin, NTag } from 'naive-ui'
import { RefreshCw, ScanLine, MapPin, RotateCcw, Wrench, CircleCheck, CircleAlert } from '@lucide/vue'
import { breakdownApi } from '../api'
import { diagnosisInput, diagnosisStatusLabels, scopeDiagnosisShots, summarizeDiagnosis, diagnosisHasAttention, diagnosisOptionalReview, diagnosisAuditLabel, diagnosisAuditHasProblem, diagnosisCanStart, diagnosisReason, bodyDimensionLabels } from '../diagnosis'
import {
diagnosisInput,
diagnosisStatusLabels,
scopeDiagnosisShots,
summarizeDiagnosis,
diagnosisHasAttention,
diagnosisOptionalReview,
diagnosisAuditLabel,
diagnosisAuditHasProblem,
diagnosisCanStart,
diagnosisReason,
bodyDimensionLabels
} from '../diagnosis'
import type { DiagnosisLocation, DiagnosisScope } from '../diagnosis'
import type {
LegacyActionDiagnosisPreview,
@@ -51,7 +63,10 @@ const dialogOpen = ref(false)
/** 首批诊断数据完成前保留固定加载区域,不渲染会闪现的空结果。 */
const dialogDataReady = ref(false)
/** 等待弹窗离场后再转移焦点,避免焦点陷阱把定位焦点拉回。 */
const pendingLocation = ref<{ /** 正式镜头坐标。 */ location: DiagnosisLocation; /** 当前有明确问题。 */ problem: boolean } | null>(null)
const pendingLocation = ref<{
/** 正式镜头坐标。 */ location: DiagnosisLocation
/** 当前有明确问题。 */ problem: boolean
} | null>(null)
/** 等诊断抽屉离场后打开正式动作修订,不叠加主界面。 */
const pendingRepair = ref<PreparationIssue | null>(null)
/** 已交接到正式修订的真实目标。 */
@@ -141,9 +156,7 @@ const visibleShots = computed(() =>
scopedShots.value.filter(
shot =>
resultFilter.value === 'all' ||
(resultFilter.value === 'review'
? diagnosisOptionalReview(shot)
: diagnosisHasAttention(shot))
(resultFilter.value === 'review' ? diagnosisOptionalReview(shot) : diagnosisHasAttention(shot))
)
)
@@ -158,7 +171,9 @@ async function readCurrentReview(projectId: string): Promise<boolean | null> {
await projectContext.refreshStageReadiness()
const state = projectContext.stageReadiness.value
return state?.projectId === projectId ? state.breakdown.ready === true : null
} catch { return null }
} catch {
return null
}
}
/** 预览展示范围内的实际镜头总数,不把待补证据数量冒充付费数量。 */
const previewCount = computed(() => previews.value?.reduce((sum, item) => sum + item.candidateCount, 0) ?? 0)
@@ -177,7 +192,8 @@ const canStart = computed(
!previewBusy.value &&
!execution.active.value &&
!starting.value &&
(scope.value.kind !== 'shot' || diagnosisCanStart(preflight.value, props.projectId, previews.value?.[0]?.candidates[0]?.shotId ?? ''))
(scope.value.kind !== 'shot' ||
diagnosisCanStart(preflight.value, props.projectId, previews.value?.[0]?.candidates[0]?.shotId ?? ''))
)
/** 费用确认使用当前预览范围及并发,不虚构模型价格。 */
const confirmation = computed(
@@ -187,7 +203,12 @@ const confirmation = computed(
/** 当前正式检查结果复用导航的权威状态,不使用独立 AI 记录数量推测审核结论。 */
const formalReviewState = computed(() => {
const state = projectContext?.stageReadiness.value
if (projectContext?.error.value || projectContext?.project.value?.id !== props.projectId || state?.projectId !== props.projectId) return null
if (
projectContext?.error.value ||
projectContext?.project.value?.id !== props.projectId ||
state?.projectId !== props.projectId
)
return null
return state.breakdown.ready === true
})
/** 顶部优先显示实际问题与正式审核结果,独立 AI 记录仅使用中性的可选检查说明。 */
@@ -281,10 +302,17 @@ async function loadPreview() {
if (version !== previewVersion) return
if (target.kind === 'shot') {
const candidate = data[0]?.candidates[0]
if (!candidate || data.length !== 1 || data[0]!.candidates.length !== 1) throw new Error('未取得唯一的正式镜头,请刷新结果。')
if (!candidate || data.length !== 1 || data[0]!.candidates.length !== 1)
throw new Error('未取得唯一的正式镜头,请刷新结果。')
const checked = await breakdownApi.diagnosisPreflight(id, candidate.shotId)
if (version !== previewVersion) return
if (checked.projectId !== id || checked.shotId !== candidate.shotId || checked.episodeNo !== target.episodeNo || checked.beatNo !== target.beatNo || checked.shotNo !== target.shotNo)
if (
checked.projectId !== id ||
checked.shotId !== candidate.shotId ||
checked.episodeNo !== target.episodeNo ||
checked.beatNo !== target.beatNo ||
checked.shotNo !== target.shotNo
)
throw new Error('检查结果与当前镜头不一致,请重新预览。')
preflight.value = checked
}
@@ -395,14 +423,25 @@ function open(location?: DiagnosisLocation) {
* @param problem 是否存在当前明确的问题
*/
function locate(location: DiagnosisLocation, problem = false) {
pendingLocation.value = { location: { episodeNo: location.episodeNo, beatNo: location.beatNo, shotNo: location.shotNo }, problem }
pendingLocation.value = {
location: { episodeNo: location.episodeNo, beatNo: location.beatNo, shotNo: location.shotNo },
problem
}
dialogOpen.value = false
}
/** 弹窗关闭动画结束后定位镜头,键盘焦点与正文高亮保持一致。 */
function finishLocate() {
if (pendingLocation.value) { const target = pendingLocation.value; pendingLocation.value = null; emit('locate', target.location, target.problem) }
if (pendingRepair.value) { repairTarget.value = pendingRepair.value; pendingRepair.value = null; repairOpen.value = true }
if (pendingLocation.value) {
const target = pendingLocation.value
pendingLocation.value = null
emit('locate', target.location, target.problem)
}
if (pendingRepair.value) {
repairTarget.value = pendingRepair.value
pendingRepair.value = null
repairOpen.value = true
}
}
/**
@@ -412,7 +451,13 @@ function finishLocate() {
function requestRepair(item: LegacyActionDiagnosisResults['shots'][number]) {
if (!dialogOpen.value || starting.value || execution.active.value) return
pendingLocation.value = null
pendingRepair.value = { episodeNo: item.episodeNo, beatNo: item.beatNo, shotNo: item.shotNo, shotId: item.shotId, message: `核对当前正式镜头:${item.title}` }
pendingRepair.value = {
episodeNo: item.episodeNo,
beatNo: item.beatNo,
shotNo: item.shotNo,
shotId: item.shotId,
message: `核对当前正式镜头:${item.title}`
}
dialogOpen.value = false
}
@@ -430,17 +475,28 @@ async function startDiagnosis() {
if (!previous) return
const checked = await breakdownApi.diagnosisPreflight(id, previous.shotId)
if (version !== previewVersion || !dialogOpen.value || !diagnosisCanStart(checked, id, previous.shotId)) {
if (version === previewVersion) { preflight.value = checked; void loadResults() }
if (version === previewVersion) {
preflight.value = checked
void loadResults()
}
return
}
const latestPreview = await breakdownApi.legacyActionDiagnosisPreview(id, target.episodeNo, target.beatNo, target.shotNo)
const latestPreview = await breakdownApi.legacyActionDiagnosisPreview(
id,
target.episodeNo,
target.beatNo,
target.shotNo
)
if (version !== previewVersion || !dialogOpen.value) return
if (JSON.stringify(latestPreview.candidates) !== JSON.stringify(previews.value?.[0]?.candidates)) {
previews.value = null
throw new Error('镜头内容已变化,请重新预览后确认诊断。')
}
preflight.value = checked
if (checked.policyRevision !== previous.policyRevision || checked.policyFingerprint !== previous.policyFingerprint) {
if (
checked.policyRevision !== previous.policyRevision ||
checked.policyFingerprint !== previous.policyFingerprint
) {
previews.value = null
throw new Error('诊断使用的质量规则已变化,请重新预览后确认。')
}
@@ -539,7 +595,14 @@ defineExpose({ open })
>
<NTag v-if="execution.active.value" type="info" size="small" :bordered="false">诊断中</NTag>
</div>
<NButton text size="small" class="diagnosis-summary-trigger" :disabled="!projectId" aria-haspopup="dialog" :aria-expanded="dialogOpen" @click="open()"
<NButton
text
size="small"
class="diagnosis-summary-trigger"
:disabled="!projectId"
aria-haspopup="dialog"
:aria-expanded="dialogOpen"
@click="open()"
>查看诊断</NButton
>
</div>
@@ -556,7 +619,10 @@ defineExpose({ open })
<div v-if="dialogDataReady" class="diagnosis-dialog-content">
<!-- 以下是当前范围模块,剧集编号始终与阅读列表一致 -->
<section class="diagnosis-section diagnosis-scope-bar" aria-label="诊断范围">
<div class="diagnosis-scope-heading"><h3>诊断范围</h3><span class="text-xs text-muted">{{ scopeLabel }}</span></div>
<div class="diagnosis-scope-heading">
<h3>诊断范围</h3>
<span class="text-xs text-muted">{{ scopeLabel }}</span>
</div>
<div class="diagnosis-scope-controls">
<NButton
size="small"
@@ -595,15 +661,46 @@ defineExpose({ open })
<p v-if="resultsError" class="text-danger" role="alert">{{ resultsError }}</p>
<template v-else-if="results">
<!-- 以下是面向日常操作的结论摘要,正式审核通过且没有实际问题时使用成功底色 -->
<div class="diagnosis-result-overview" :class="{ 'problem-surface': repairCount > 0, 'diagnosis-result-success': reviewed === true && counts.total > 0 && repairCount === 0 }">
<CircleAlert v-if="repairCount" :size="20" class="text-danger" aria-hidden="true" />
<CircleCheck v-else-if="reviewed === true && counts.total" :size="20" class="text-(--app-success)" aria-hidden="true" />
<div
class="diagnosis-result-overview"
:class="{
'problem-surface': repairCount > 0,
'diagnosis-result-success':
reviewed === true && counts.total > 0 && repairCount === 0
}"
>
<CircleAlert
v-if="repairCount"
:size="20"
class="text-danger"
aria-hidden="true"
/>
<CircleCheck
v-else-if="reviewed === true && counts.total"
:size="20"
class="text-(--app-success)"
aria-hidden="true"
/>
<ScanLine v-else :size="20" class="text-muted" aria-hidden="true" />
<div class="min-w-0 space-y-1">
<p class="font-medium">{{ !counts.total ? '当前范围尚无镜头' : repairCount ? `有 ${repairCount} 个镜头需要处理` : '当前范围没有需要修复的镜头' }}</p>
<p class="text-xs text-muted">{{ scopeLabel }} · 共 {{ counts.total }} 个镜头</p>
<p v-if="reviewed === true" class="text-xs text-muted">当前正式分镜已审核通过,AI 复查可按需进行。</p>
<p v-else-if="reviewed === false" class="text-xs text-muted">正式分镜检查待确认,请查看制作前检查。</p>
<p class="font-medium">
{{
!counts.total
? '当前范围尚无镜头'
: repairCount
? `有 ${repairCount} 个镜头需要处理`
: '当前范围没有需要修复的镜头'
}}
</p>
<p class="text-xs text-muted">
{{ scopeLabel }} · 共 {{ counts.total }} 个镜头
</p>
<p v-if="reviewed === true" class="text-xs text-muted">
当前正式分镜已审核通过,AI 复查可按需进行。
</p>
<p v-else-if="reviewed === false" class="text-xs text-muted">
正式分镜检查待确认,请查看制作前检查。
</p>
</div>
</div>
<div class="diagnosis-results-toolbar">
@@ -626,7 +723,9 @@ defineExpose({ open })
counts.total === 0
? '当前范围尚无镜头。'
: resultFilter === 'attention'
? reviewed === true ? '额外检查可按需进行,无需为继续制作重复运行。' : '这里只展示已检出的问题,额外 AI 复查可按需进行。'
? reviewed === true
? '额外检查可按需进行,无需为继续制作重复运行。'
: '这里只展示已检出的问题,额外 AI 复查可按需进行。'
: resultFilter === 'review'
? '当前没有可选复查记录。'
: '当前筛选下没有镜头。'
@@ -639,7 +738,12 @@ defineExpose({ open })
tabindex="0"
aria-label="镜头诊断列表"
>
<article v-for="item in visibleShots" :key="item.shotId" class="diagnosis-result-item" :class="{ 'problem-surface': diagnosisHasAttention(item) }">
<article
v-for="item in visibleShots"
:key="item.shotId"
class="diagnosis-result-item"
:class="{ 'problem-surface': diagnosisHasAttention(item) }"
>
<div class="diagnosis-section-heading">
<span class="text-xs text-muted"
>第 {{ item.episodeNo }} 集 / 节拍 {{ item.beatNo }} / 镜头
@@ -649,7 +753,8 @@ defineExpose({ open })
:type="
diagnosisHasAttention(item)
? 'error'
: item.status === 'no_conflict_found' && !diagnosisHasAttention(item)
: item.status === 'no_conflict_found' &&
!diagnosisHasAttention(item)
? 'success'
: 'default'
"
@@ -667,33 +772,124 @@ defineExpose({ open })
{{ userFacingText(description) }}
</p>
<!-- 以下是修订状态、局部手部检查与 AI 全身疑点,结论各自保留 -->
<p v-if="item.repairStatus === 'repaired' && reviewed === true && !diagnosisHasAttention(item)" class="text-xs text-muted">已修订并审核通过,AI 复查可选。</p>
<p v-else-if="item.requiresPostRepairDiagnosis" class="text-xs text-muted">镜头已修订,可按需进行 AI 复查。</p>
<p v-else-if="item.repairStatus === 'repaired'" class="text-xs text-muted">镜头已修订,已有当前版本 AI 诊断</p>
<p v-else-if="item.repairStatus === 'repair_history_stale'" class="text-xs text-muted">此前修订记录已过期</p>
<p v-if="item.shotStale" class="text-xs text-muted">镜头内容已变化,旧诊断不作为当前结论。</p>
<p v-if="item.policyStatus === 'stale'" class="text-xs text-muted">质量规则已变化,需要重新核对。</p>
<p v-else-if="item.policyStatus === 'unknown'" class="text-xs text-muted">旧诊断没有完整的质量规则记录。</p>
<div v-if="item.resourceAudit && diagnosisAuditHasProblem(item.resourceAudit)" class="space-y-1 text-xs text-muted"><p>{{ diagnosisAuditLabel(item.resourceAudit) }}<template v-if="item.resourceAudit.expectedActionCount > 0"> · 已覆盖 {{ item.resourceAudit.coveredActionCount }} / {{ item.resourceAudit.expectedActionCount }} 个动作</template></p></div>
<div v-else-if="!item.resourceAudit && item.handAudit && diagnosisAuditHasProblem(item.handAudit)" class="space-y-1 text-xs text-muted">
<p>{{ diagnosisAuditLabel(item.handAudit, true) }}<template v-if="item.handAudit.expectedActionCount > 0"> · 手部动作证据 {{ item.handAudit.coveredActionCount }} / {{ item.handAudit.expectedActionCount }}</template></p>
<p
v-if="
item.repairStatus === 'repaired' &&
reviewed === true &&
!diagnosisHasAttention(item)
"
class="text-xs text-muted"
>
已修订并审核通过,AI 复查可选。
</p>
<p v-else-if="item.requiresPostRepairDiagnosis" class="text-xs text-muted">
镜头已修订,可按需进行 AI 复查。
</p>
<p v-else-if="item.repairStatus === 'repaired'" class="text-xs text-muted">
镜头已修订,已有当前版本 AI 诊断
</p>
<p
v-else-if="item.repairStatus === 'repair_history_stale'"
class="text-xs text-muted"
>
此前修订记录已过期
</p>
<p v-if="item.shotStale" class="text-xs text-muted">
镜头内容已变化,旧诊断不作为当前结论。
</p>
<p v-if="item.policyStatus === 'stale'" class="text-xs text-muted">
质量规则已变化,需要重新核对。
</p>
<p v-else-if="item.policyStatus === 'unknown'" class="text-xs text-muted">
旧诊断没有完整的质量规则记录。
</p>
<div
v-if="
item.resourceAudit && diagnosisAuditHasProblem(item.resourceAudit)
"
class="space-y-1 text-xs text-muted"
>
<p>
{{ diagnosisAuditLabel(item.resourceAudit)
}}<template v-if="item.resourceAudit.expectedActionCount > 0">
· 已覆盖 {{ item.resourceAudit.coveredActionCount }} /
{{ item.resourceAudit.expectedActionCount }} 个动作</template
>
</p>
</div>
<article v-for="(finding, index) in item.bodyMotionFindings" :key="index" class="space-y-1 text-xs">
<p>{{ bodyDimensionLabels[finding.dimension] || '其他动作' }} · {{ finding.status === 'conflict' ? '发现冲突' : finding.status === 'needs_review' ? '需要复核' : '证据不足' }}</p>
<p>{{ userFacingText(finding.description) }}</p><p class="text-muted">原文:{{ finding.quote }}</p>
<div
v-else-if="
!item.resourceAudit &&
item.handAudit &&
diagnosisAuditHasProblem(item.handAudit)
"
class="space-y-1 text-xs text-muted"
>
<p>
{{ diagnosisAuditLabel(item.handAudit, true)
}}<template v-if="item.handAudit.expectedActionCount > 0">
· 手部动作证据 {{ item.handAudit.coveredActionCount }} /
{{ item.handAudit.expectedActionCount }}</template
>
</p>
</div>
<article
v-for="(finding, index) in item.bodyMotionFindings"
:key="index"
class="space-y-1 text-xs"
>
<p>
{{ bodyDimensionLabels[finding.dimension] || '其他动作' }} ·
{{
finding.status === 'conflict'
? '发现冲突'
: finding.status === 'needs_review'
? '需要复核'
: '证据不足'
}}
</p>
<p>{{ userFacingText(finding.description) }}</p>
<p class="text-muted">原文:{{ finding.quote }}</p>
</article>
<!-- 以下是明确的卡片操作区,按钮有独立底面和图标,不与说明混在一起 -->
<div class="diagnosis-card-actions workspace-action-group">
<NButton size="small" aria-label="定位镜头" title="定位镜头" @click="locate(item, diagnosisHasAttention(item))"><template #icon><MapPin :size="15" aria-hidden="true" /></template><span class="diagnosis-action-label">定位镜头</span></NButton>
<NButton v-if="diagnosisOptionalReview(item) || diagnosisHasAttention(item)" size="small" aria-label="可选 AI 复查" title="可选 AI 复查" :disabled="starting || execution.active.value" @click="open(item)"><template #icon><RotateCcw :size="15" aria-hidden="true" /></template><span class="diagnosis-action-label">可选 AI 复查</span></NButton>
<NButton v-if="diagnosisHasAttention(item)" size="small" aria-label="查看并修订动作" title="查看并修订动作" :disabled="starting || execution.active.value" @click="requestRepair(item)"><template #icon><Wrench :size="15" aria-hidden="true" /></template><span class="diagnosis-action-label">查看并修订动作</span></NButton>
<NButton
size="small"
aria-label="定位镜头"
title="定位镜头"
@click="locate(item, diagnosisHasAttention(item))"
><template #icon><MapPin :size="15" aria-hidden="true" /></template
><span class="diagnosis-action-label">定位镜头</span></NButton
>
<NButton
v-if="diagnosisOptionalReview(item) || diagnosisHasAttention(item)"
size="small"
aria-label="可选 AI 复查"
title="可选 AI 复查"
:disabled="starting || execution.active.value"
@click="open(item)"
><template #icon
><RotateCcw :size="15" aria-hidden="true" /></template
><span class="diagnosis-action-label">可选 AI 复查</span></NButton
>
<NButton
v-if="diagnosisHasAttention(item)"
size="small"
aria-label="查看并修订动作"
title="查看并修订动作"
:disabled="starting || execution.active.value"
@click="requestRepair(item)"
><template #icon><Wrench :size="15" aria-hidden="true" /></template
><span class="diagnosis-action-label">查看并修订动作</span></NButton
>
<DiagnosisShotDetails :project-id="projectId" :shot="item" />
</div>
</article>
</div>
</template>
<p v-else class="text-muted">{{ resultsBusy ? '正在读取当前范围结果…' : '尚未读取结果' }}</p>
<p v-else class="text-muted">
{{ resultsBusy ? '正在读取当前范围结果…' : '尚未读取结果' }}
</p>
</section>
<!-- 以下是实际检出的手部冲突,普通区域仅展示明确问题,不因缺少记录提示修复。 -->
<section v-if="!handError && handDiagnostics?.diagnostics.length" class="diagnosis-section">
@@ -736,10 +932,20 @@ defineExpose({ open })
<section class="diagnosis-section">
<NCollapse class="diagnosis-evidence-collapse" :default-expanded-names="[]">
<NCollapseItem name="advanced-checks">
<template #header><span class="diagnosis-evidence-title">高级检查详情</span></template>
<template #header
><span class="diagnosis-evidence-title">高级检查详情</span></template
>
<template #header-extra="{ collapsed }">
<NButton v-if="!collapsed" text size="small" class="diagnosis-refresh-button" :loading="handBusy" @click.stop="loadHandDiagnostics">
<template #icon><RefreshCw :size="14" aria-hidden="true" /></template>刷新校验
<NButton
v-if="!collapsed"
text
size="small"
class="diagnosis-refresh-button"
:loading="handBusy"
@click.stop="loadHandDiagnostics"
>
<template #icon><RefreshCw :size="14" aria-hidden="true" /></template
>刷新校验
</NButton>
</template>
<!-- 以下是紧凑的记录摘要,仅展示有值的分类,重复解释合并为末尾说明 -->
@@ -747,9 +953,18 @@ defineExpose({ open })
<section v-if="results" class="diagnosis-inspection-row">
<h4 class="font-medium">AI 复查记录</h4>
<div class="diagnosis-counts">
<span>本范围 {{ counts.total }} 镜</span><span v-if="counts.conflict" class="text-danger">发现冲突 {{ counts.conflict }} 镜</span>
<span v-if="counts.insufficient">依据不足 {{ counts.insufficient }} 镜</span><span v-if="counts.invalid">依据不可用 {{ counts.invalid }} 镜</span>
<span v-if="counts.stale">旧记录 {{ counts.stale }} 镜</span><span v-if="counts.pending">暂无记录 {{ counts.pending }} 镜</span><span v-if="counts.clear">未发现冲突 {{ counts.clear }} 镜</span>
<span>本范围 {{ counts.total }} 镜</span
><span v-if="counts.conflict" class="text-danger"
>发现冲突 {{ counts.conflict }} 镜</span
>
<span v-if="counts.insufficient"
>依据不足 {{ counts.insufficient }} 镜</span
><span v-if="counts.invalid"
>依据不可用 {{ counts.invalid }} 镜</span
>
<span v-if="counts.stale">旧记录 {{ counts.stale }} 镜</span
><span v-if="counts.pending">暂无记录 {{ counts.pending }} 镜</span
><span v-if="counts.clear">未发现冲突 {{ counts.clear }} 镜</span>
</div>
</section>
<p v-if="handError" class="text-danger" role="alert">{{ handError }}</p>
@@ -757,11 +972,25 @@ defineExpose({ open })
<h4 class="font-medium">当前复查范围</h4>
<div v-if="previews" class="diagnosis-counts">
<span>{{ scopeLabel }} · {{ previewCount }} 个镜头</span>
<span v-if="previews.some(item => item.invalidSnapshotCount > 0)" class="text-danger">镜头信息无法读取 {{ previews.reduce((sum, item) => sum + item.invalidSnapshotCount, 0) }} 镜</span>
<span
v-if="previews.some(item => item.invalidSnapshotCount > 0)"
class="text-danger"
>镜头信息无法读取
{{
previews.reduce(
(sum, item) => sum + item.invalidSnapshotCount,
0
)
}}
镜</span
>
</div>
<p v-else class="text-muted">尚未预览,可在底部预览范围。</p>
</section>
<p class="text-muted">仅查看已有记录,不调用 AI;未填写记录不代表镜头有误,也不改变正式审核结果。</p>
<p class="text-muted">
仅查看已有记录,不调用
AI;未填写记录不代表镜头有误,也不改变正式审核结果。
</p>
</div>
</NCollapseItem>
</NCollapse>
@@ -769,10 +998,17 @@ defineExpose({ open })
</div>
<!-- 以下是与检查结果采用相同背景和内边距的可选复查模块,执行操作统一保留在弹窗底栏 -->
<section class="diagnosis-section diagnosis-review-panel" aria-label="可选 AI 复查设置">
<div class="diagnosis-section-heading"><h3>AI 复查</h3><NTag size="small" :bordered="false">可选</NTag></div>
<div class="diagnosis-section-heading">
<h3>AI 复查</h3>
<NTag size="small" :bordered="false">可选</NTag>
</div>
<p class="diagnosis-review-description text-sm">需要额外检查动作是否合理时,再运行此项。</p>
<p class="text-xs text-muted mt-2">已审核的分镜可继续制作,无需重复复查。</p>
<div class="diagnosis-review-scope"><span class="text-xs text-muted">本次复查范围</span><p class="font-medium">{{ scopeLabel }}</p><p class="text-xs text-muted">已有当前版本有效结果的镜头将跳过。</p></div>
<div class="diagnosis-review-scope">
<span class="text-xs text-muted">本次复查范围</span>
<p class="font-medium">{{ scopeLabel }}</p>
<p class="text-xs text-muted">已有当前版本有效结果的镜头将跳过。</p>
</div>
<!-- 以下是使用 Naive UI 折叠组件的高级设置模块,默认收起 -->
<NCollapse class="diagnosis-advanced">
<NCollapseItem name="advanced-settings">
@@ -796,7 +1032,9 @@ defineExpose({ open })
<p v-if="preflight.shouldDiagnose">已完成来源预检查,正式诊断仍会再次核对当前版本。</p>
</div>
<p v-if="previewError" class="text-danger" role="alert">{{ previewError }}</p>
<p class="text-xs text-muted mt-3">AI 复查会产生模型费用,仅保存检查记录,不修改镜头。请先在底部预览范围,再确认启动。</p>
<p class="text-xs text-muted mt-3">
AI 复查会产生模型费用,仅保存检查记录,不修改镜头。请先在底部预览范围,再确认启动。
</p>
<p v-if="execution.active.value" class="text-xs text-muted mt-3">
诊断任务进行中,可关闭弹窗继续查看分镜。
</p>
@@ -999,9 +1237,18 @@ defineExpose({ open })
background: var(--app-danger-soft);
}
/* 卡片操作在所有尺寸保留图标和完整文字,空间不足时按按钮自然换行。 */
.diagnosis-card-actions { display: flex; flex-wrap: wrap; gap: 8px; padding-top: 8px; }
.diagnosis-card-actions .n-button { min-height: 34px; }
.diagnosis-result-item { padding: 20px; }
.diagnosis-card-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding-top: 8px;
}
.diagnosis-card-actions .n-button {
min-height: 34px;
}
.diagnosis-result-item {
padding: 20px;
}
.diagnosis-result-item .n-tag {
flex-shrink: 0;
}
@@ -28,7 +28,13 @@ const locatedPosition = ref('')
/** 定位来自当前明确的问题时才使用错误底色,普通查看不能推断问题。 */
const locatedProblem = ref(false)
/** 正文刷新后清除旧定位,避免已修订镜头继续沿用错误标记。 */
watch(() => props.episodes, () => { locatedPosition.value = ''; locatedProblem.value = false })
watch(
() => props.episodes,
() => {
locatedPosition.value = ''
locatedProblem.value = false
}
)
/** 定位样式的业务依据,与镜头坐标及诊断请求字段分开。 */
interface LocateOptions {
/** 是否来自当前实际问题,未提供时使用中性定位。 */
@@ -91,8 +97,8 @@ defineExpose({ locate })
value: item.episodeNo
}))
"
></NSelect
></div>
></NSelect>
</div>
<div class="breakdown-storyboard-summary">
<span v-if="plan" class="breakdown-storyboard-count"
>{{ plan.beats.length }} 个节拍 ·
@@ -119,7 +125,11 @@ defineExpose({ locate })
class="beat-section"
tabindex="-1"
:data-shot-position="`${plan.episodeNo}-${beat.beatNo}`"
:class="{ 'diagnosis-located': locatedPosition === `${plan.episodeNo}-${beat.beatNo}`, 'diagnosis-problem-located': locatedProblem && locatedPosition === `${plan.episodeNo}-${beat.beatNo}` }"
:class="{
'diagnosis-located': locatedPosition === `${plan.episodeNo}-${beat.beatNo}`,
'diagnosis-problem-located':
locatedProblem && locatedPosition === `${plan.episodeNo}-${beat.beatNo}`
}"
>
<div class="beat-heading">
<span class="beat-number">{{ String(beat.beatNo).padStart(2, '0') }}</span>
@@ -145,7 +155,8 @@ defineExpose({ locate })
:data-shot-position="`${plan.episodeNo}-${beat.beatNo}-${shot.shotNo}`"
:class="{
'diagnosis-located': locatedPosition === `${plan.episodeNo}-${beat.beatNo}-${shot.shotNo}`,
'diagnosis-problem-located': locatedProblem && locatedPosition === `${plan.episodeNo}-${beat.beatNo}-${shot.shotNo}`
'diagnosis-problem-located':
locatedProblem && locatedPosition === `${plan.episodeNo}-${beat.beatNo}-${shot.shotNo}`
}"
>
<div class="shot-label">
+57 -18
View File
@@ -92,7 +92,8 @@ export function diagnosisReason(code: string): string {
QUALITY_POLICY_NOT_CONFIRMED: '请先确认项目质量规则。',
QUALITY_POLICY_VERSION_CONFLICT: '质量规则已更新,请重新核对。',
QUALITY_POLICY_SNAPSHOT_UNKNOWN: '本次 AI 复查缺少可信的质量规则记录,暂时不能启动。请在制作前检查中核对来源。',
QUALITY_POLICY_SNAPSHOT_INVALID: '本次 AI 复查无法使用现有质量规则记录,暂时不能启动。请在制作前检查中核对来源。',
QUALITY_POLICY_SNAPSHOT_INVALID:
'本次 AI 复查无法使用现有质量规则记录,暂时不能启动。请在制作前检查中核对来源。',
QUALITY_POLICY_SNAPSHOT_STALE: '分镜与质量规则版本不一致,请核对最新拆解结果。',
STORYBOARD_SOURCE_MISMATCH: '镜头与已提交分镜不一致,请刷新最新结果后核对。'
}
@@ -107,12 +108,23 @@ export function diagnosisReason(code: string): string {
* @returns 是否可以进入费用确认
*/
export function diagnosisCanStart(value: DiagnosisPreflight | null, projectId: string, shotId: string): boolean {
return !!value && value.projectId === projectId && value.shotId === shotId &&
value.eligibleForFurtherValidation === true && value.shouldDiagnose === true && value.existingValid === false &&
Array.isArray(value.errors) && value.errors.length === 0 && value.requiresExecutionValidation === true &&
Number.isSafeInteger(value.policyRevision) && value.policyRevision! >= 0 &&
typeof value.policyFingerprint === 'string' && /^[a-f\d]{64}$/.test(value.policyFingerprint) &&
value.willCallModel === false && value.willModifyAssets === false
return (
!!value &&
value.projectId === projectId &&
value.shotId === shotId &&
value.eligibleForFurtherValidation === true &&
value.shouldDiagnose === true &&
value.existingValid === false &&
Array.isArray(value.errors) &&
value.errors.length === 0 &&
value.requiresExecutionValidation === true &&
Number.isSafeInteger(value.policyRevision) &&
value.policyRevision! >= 0 &&
typeof value.policyFingerprint === 'string' &&
/^[a-f\d]{64}$/.test(value.policyFingerprint) &&
value.willCallModel === false &&
value.willModifyAssets === false
)
}
/**
@@ -123,8 +135,15 @@ export function diagnosisCanStart(value: DiagnosisPreflight | null, projectId: s
export function diagnosisHasAttention(shot: LegacyActionDiagnosisResults['shots'][number]): boolean {
const audit = shot.resourceAudit ?? shot.handAudit
if (diagnosisAuditHasProblem(audit)) return true
const current = shot.status !== 'stale' && shot.shotStale !== true && shot.policyStatus !== 'stale' && shot.policyStatus !== 'unknown'
return current && (shot.status === 'conflict_found' || !!shot.bodyMotionFindings?.some(item => item.status === 'conflict'))
const current =
shot.status !== 'stale' &&
shot.shotStale !== true &&
shot.policyStatus !== 'stale' &&
shot.policyStatus !== 'unknown'
return (
current &&
(shot.status === 'conflict_found' || !!shot.bodyMotionFindings?.some(item => item.status === 'conflict'))
)
}
/**
@@ -133,7 +152,10 @@ export function diagnosisHasAttention(shot: LegacyActionDiagnosisResults['shots'
* @returns 是否存在明确冲突或不可用的结构化信息
*/
export function diagnosisAuditHasProblem(audit: DiagnosisHandAudit | undefined): boolean {
return !!audit && (audit.issueCount > 0 || ['conflict_found', 'invalid_evidence', 'invalid_snapshot'].includes(audit.status))
return (
!!audit &&
(audit.issueCount > 0 || ['conflict_found', 'invalid_evidence', 'invalid_snapshot'].includes(audit.status))
)
}
/**
@@ -143,8 +165,13 @@ export function diagnosisAuditHasProblem(audit: DiagnosisHandAudit | undefined):
*/
export function diagnosisOptionalReview(shot: LegacyActionDiagnosisResults['shots'][number]): boolean {
const audit = shot.resourceAudit ?? shot.handAudit
return !diagnosisHasAttention(shot) && (shot.status !== 'no_conflict_found' || shot.requiresPostRepairDiagnosis === true ||
!!shot.bodyMotionFindings?.length || !!audit && ['partial_evidence', 'insufficient_evidence'].includes(audit.status))
return (
!diagnosisHasAttention(shot) &&
(shot.status !== 'no_conflict_found' ||
shot.requiresPostRepairDiagnosis === true ||
!!shot.bodyMotionFindings?.length ||
(!!audit && ['partial_evidence', 'insufficient_evidence'].includes(audit.status)))
)
}
/**
@@ -161,17 +188,29 @@ export function diagnosisAuditLabel(audit: DiagnosisHandAudit, handOnly = false)
/** 免费手部检查的结论,不能据此标记 AI 已通过。 */
export const handAuditLabels: Record<DiagnosisHandAudit['status'], string> = {
insufficient_evidence: '手部记录尚未覆盖', invalid_snapshot: '镜头记录不完整', invalid_evidence: '手部证据无效',
conflict_found: '手部仍有冲突', partial_evidence: '部分动作尚未覆盖手部检查', no_conflict_found: '现有手部证据未发现冲突'
insufficient_evidence: '手部记录尚未覆盖',
invalid_snapshot: '镜头记录不完整',
invalid_evidence: '手部证据无效',
conflict_found: '手部仍有冲突',
partial_evidence: '部分动作尚未覆盖手部检查',
no_conflict_found: '现有手部证据未发现冲突'
}
/** 全身动作维度的中文说明。 */
export const bodyDimensionLabels: Record<string, string> = {
feet: '脚部动作', balance: '身体平衡', gaze: '视线方向', prop_interaction: '道具交互',
physical_continuity: '动作衔接', cross_shot_continuity: '镜头间衔接'
feet: '脚部动作',
balance: '身体平衡',
gaze: '视线方向',
prop_interaction: '道具交互',
physical_continuity: '动作衔接',
cross_shot_continuity: '镜头间衔接'
}
/** 通用动作资源结论不冒充覆盖全部剧情语义。 */
export const resourceAuditLabels: typeof handAuditLabels = {
insufficient_evidence: '动作记录尚未覆盖', invalid_snapshot: '镜头记录不完整', invalid_evidence: '动作占用证据无效',
conflict_found: '动作占用仍有冲突', partial_evidence: '部分动作占用记录尚未覆盖', no_conflict_found: '现有动作占用证据未发现冲突'
insufficient_evidence: '动作记录尚未覆盖',
invalid_snapshot: '镜头记录不完整',
invalid_evidence: '动作占用证据无效',
conflict_found: '动作占用仍有冲突',
partial_evidence: '部分动作占用记录尚未覆盖',
no_conflict_found: '现有动作占用证据未发现冲突'
}
+7 -1
View File
@@ -51,7 +51,13 @@ export interface BodyMotionFinding {
/** 不调用模型的手部证据复检,与 AI 诊断独立。 */
export interface DiagnosisHandAudit {
/** 证据完整性或冲突结论。 */
status: 'insufficient_evidence' | 'invalid_snapshot' | 'invalid_evidence' | 'conflict_found' | 'partial_evidence' | 'no_conflict_found'
status:
| 'insufficient_evidence'
| 'invalid_snapshot'
| 'invalid_evidence'
| 'conflict_found'
| 'partial_evidence'
| 'no_conflict_found'
/** 检出的冲突数。 */
issueCount: number
/** 有效证据数量。 */
+174 -28
View File
@@ -75,7 +75,14 @@ export interface BreakdownQuality {
export function normalizeBreakdownState(state: BreakdownState): BreakdownState {
// 新版候选只信任顶层;旧版无候选标记的快照才兼容嵌套成果。
const result: BreakdownResult = state.candidateOnly === true ? {} : { ...state.breakdownResult }
for (const key of ['subjectCandidates', 'subjectForms', 'storyboardPlans', 'storyboardEpisodeShots', 'storyboardShotValidation', 'storyboardNeedsManualReview'] as const) {
for (const key of [
'subjectCandidates',
'subjectForms',
'storyboardPlans',
'storyboardEpisodeShots',
'storyboardShotValidation',
'storyboardNeedsManualReview'
] as const) {
if (state[key] !== undefined) Object.assign(result, { [key]: state[key] })
}
if (result.storyboardEpisodeShots?.length) {
@@ -93,7 +100,12 @@ export function normalizeBreakdownState(state: BreakdownState): BreakdownState {
* @returns 是否含可回看的资产内容
*/
function hasBreakdownData(record: Checkpoint): boolean {
return Boolean(record.state.breakdownResult || record.state.subjectCandidates || record.state.storyboardEpisodeShots || record.state.storyboardPlans)
return Boolean(
record.state.breakdownResult ||
record.state.subjectCandidates ||
record.state.storyboardEpisodeShots ||
record.state.storyboardPlans
)
}
/**
@@ -104,13 +116,34 @@ function hasBreakdownData(record: Checkpoint): boolean {
export function selectBreakdownSource(records: Checkpoint[]): BreakdownSource {
const latest = records.at(-1)
if (!latest) return { kind: 'empty', state: null }
const formal = records.toReversed().find(record => hasBreakdownData(record) && (record.state.storyboardPersisted === true || record.state.candidateCommitted === true || record.state.candidateOnly !== true))
const formal = records
.toReversed()
.find(
record =>
hasBreakdownData(record) &&
(record.state.storyboardPersisted === true ||
record.state.candidateCommitted === true ||
record.state.candidateOnly !== true)
)
if (latest.state.candidateOnly === true || hasBreakdownData(latest) || latest.state.runConfig) {
const state = normalizeBreakdownState(latest.state)
return { checkpoint: latest, state, formal, kind: state.storyboardPersisted === true || state.candidateCommitted === true || state.candidateOnly !== true ? 'formal' : 'candidate' }
return {
checkpoint: latest,
state,
formal,
kind:
state.storyboardPersisted === true || state.candidateCommitted === true || state.candidateOnly !== true
? 'formal'
: 'candidate'
}
}
const previous = records.toReversed().find(hasBreakdownData)
return { kind: previous ? 'history' : 'empty', checkpoint: previous, state: previous ? normalizeBreakdownState(previous.state) : null, formal }
return {
kind: previous ? 'history' : 'empty',
checkpoint: previous,
state: previous ? normalizeBreakdownState(previous.state) : null,
formal
}
}
/**
@@ -120,11 +153,29 @@ export function selectBreakdownSource(records: Checkpoint[]): BreakdownSource {
* @param checkpointId 当前候选版本
* @returns 原始有效审核结果
*/
export function assertCandidateReview(review: CandidateRevalidation, projectId: string, checkpointId: string): CandidateRevalidation {
export function assertCandidateReview(
review: CandidateRevalidation,
projectId: string,
checkpointId: string
): CandidateRevalidation {
if (!review || review.projectId !== projectId || review.checkpointId !== checkpointId)
throw new Error('候选审核版本已过期,请刷新候选状态。')
const arrayKeys = ['previousIssues', 'currentIssues', 'missingSubjectRefs', 'actionQualityBlocks', 'actionRepairTargets', 'pendingQualityEpisodeNos', 'propReferenceDiagnostics', 'pendingWithoutActionBlocks'] as const
if (!review.candidateValidation || typeof review.candidateValidation.valid !== 'boolean' || !Array.isArray(review.candidateValidation.issues) || !arrayKeys.every(key => Array.isArray(review[key])))
const arrayKeys = [
'previousIssues',
'currentIssues',
'missingSubjectRefs',
'actionQualityBlocks',
'actionRepairTargets',
'pendingQualityEpisodeNos',
'propReferenceDiagnostics',
'pendingWithoutActionBlocks'
] as const
if (
!review.candidateValidation ||
typeof review.candidateValidation.valid !== 'boolean' ||
!Array.isArray(review.candidateValidation.issues) ||
!arrayKeys.every(key => Array.isArray(review[key]))
)
throw new Error('候选审核响应不完整,请刷新候选状态。')
return review
}
@@ -137,46 +188,141 @@ export function assertCandidateReview(review: CandidateRevalidation, projectId:
* @param error 读取失败或版本过期原因
* @returns 页面、问题抽屉与提交面板共享的质量状态
*/
export function breakdownQuality(source: BreakdownSource, review: CandidateRevalidation | null, loading = false, error = ''): BreakdownQuality {
export function breakdownQuality(
source: BreakdownSource,
review: CandidateRevalidation | null,
loading = false,
error = ''
): BreakdownQuality {
const candidate = source.kind === 'candidate'
const current = candidate && review?.checkpointId === source.checkpoint?.checkpointId ? review : null
const known = candidate ? !!current && !loading && !error : source.kind === 'formal'
const structuralIssues = known ? candidate ? current!.currentIssues : source.state?.storyboardShotValidation?.issues ?? [] : []
const validation = known ? candidate ? current!.currentIssues.length === 0 : source.state?.storyboardShotValidation?.valid ?? null : null
const actionBlocks = known ? candidate ? current!.actionQualityBlocks : (source.state?.storyboardActionQualityDecisions ?? []).filter(item => item.status === 'blocked' || item.warningCodes.includes('action_resource_conflict')).map(item => ({ ...item, isPendingEpisode: true })) : []
const pendingEpisodeNos = known ? candidate ? current!.pendingQualityEpisodeNos : source.state?.storyboardPendingQualityEpisodeNos ?? [] : []
const structuralIssues = known
? candidate
? current!.currentIssues
: (source.state?.storyboardShotValidation?.issues ?? [])
: []
const validation = known
? candidate
? current!.currentIssues.length === 0
: (source.state?.storyboardShotValidation?.valid ?? null)
: null
const actionBlocks = known
? candidate
? current!.actionQualityBlocks
: (source.state?.storyboardActionQualityDecisions ?? [])
.filter(item => item.status === 'blocked' || item.warningCodes.includes('action_resource_conflict'))
.map(item => ({ ...item, isPendingEpisode: true }))
: []
const pendingEpisodeNos = known
? candidate
? current!.pendingQualityEpisodeNos
: (source.state?.storyboardPendingQualityEpisodeNos ?? [])
: []
const problems: BreakdownProblem[] = structuralIssues.map((item, index) => ({
key: `structure-${item.episodeNo}-${item.beatNo}-${item.shotNo}-${index}`,
type: item.message.includes('主体引用缺失') ? 'subject' : /绑定|形态|Form/.test(item.message) ? 'binding' : 'structure',
type: item.message.includes('主体引用缺失')
? 'subject'
: /绑定|形态|Form/.test(item.message)
? 'binding'
: 'structure',
location: item,
message: item.message,
codes: []
}))
for (const block of actionBlocks) problems.push({ key: `action-${block.episodeNo}-${block.beatNo}-${block.shotNo}`, type: 'action', location: { ...block, message: '动作质量待修订' }, message: '当前动作规划仍有阻断或资源冲突。', codes: [...new Set([...block.blockingCodes, ...block.warningCodes])] })
for (const episodeNo of pendingEpisodeNos.filter(no => !actionBlocks.some(item => item.episodeNo === no))) problems.push({ key: `pending-${episodeNo}`, type: 'pending', location: { episodeNo, message: '剧集仍标记为待审核' }, message: '该集仍标记为待审核,当前没有动作阻断明细,请重新核对审核状态。', codes: [] })
for (const block of actionBlocks)
problems.push({
key: `action-${block.episodeNo}-${block.beatNo}-${block.shotNo}`,
type: 'action',
location: { ...block, message: '动作质量待修订' },
message: '当前动作规划仍有阻断或资源冲突。',
codes: [...new Set([...block.blockingCodes, ...block.warningCodes])]
})
for (const episodeNo of pendingEpisodeNos.filter(no => !actionBlocks.some(item => item.episodeNo === no)))
problems.push({
key: `pending-${episodeNo}`,
type: 'pending',
location: { episodeNo, message: '剧集仍标记为待审核' },
message: '该集仍标记为待审核,当前没有动作阻断明细,请重新核对审核状态。',
codes: []
})
if (current && known) {
for (const diagnostic of current.propReferenceDiagnostics) {
if (diagnostic.beatAllowsSubject && diagnostic.shotHasSubject && diagnostic.shotHasBinding) continue
if (problems.some(item => item.location?.episodeNo === diagnostic.episodeNo && item.location.beatNo === diagnostic.beatNo && item.location.shotNo === diagnostic.shotNo && item.message.includes(diagnostic.subjectRef))) continue
problems.push({ key: `prop-${diagnostic.episodeNo}-${diagnostic.beatNo}-${diagnostic.shotNo}-${diagnostic.subjectRef}`, type: 'subject', location: { ...diagnostic, message: '道具引用或形态绑定缺失' }, message: `道具 ${diagnostic.subjectName}(${diagnostic.subjectRef})的节拍引用、镜头引用或形态绑定不完整。`, codes: [] })
if (
problems.some(
item =>
item.location?.episodeNo === diagnostic.episodeNo &&
item.location.beatNo === diagnostic.beatNo &&
item.location.shotNo === diagnostic.shotNo &&
item.message.includes(diagnostic.subjectRef)
)
)
continue
problems.push({
key: `prop-${diagnostic.episodeNo}-${diagnostic.beatNo}-${diagnostic.shotNo}-${diagnostic.subjectRef}`,
type: 'subject',
location: { ...diagnostic, message: '道具引用或形态绑定缺失' },
message: `道具 ${diagnostic.subjectName}(${diagnostic.subjectRef})的节拍引用、镜头引用或形态绑定不完整。`,
codes: []
})
}
for (const [index, message] of current.candidateValidation.issues.entries()) {
if (message === 'Storyboard 质量审核未通过' && structuralIssues.length || message === '仍存在待处理的分镜质量问题' && pendingEpisodeNos.length) continue
problems.push({ key: `candidate-${index}`, type: /Form|形态|绑定/.test(message) ? 'binding' : 'structure', message, codes: [] })
if (
(message === 'Storyboard 质量审核未通过' && structuralIssues.length) ||
(message === '仍存在待处理的分镜质量问题' && pendingEpisodeNos.length)
)
continue
problems.push({
key: `candidate-${index}`,
type: /Form|形态|绑定/.test(message) ? 'binding' : 'structure',
message,
codes: []
})
}
}
if (known && ((validation === false && !problems.some(item => ['structure', 'subject', 'binding'].includes(item.type))) || (current?.candidateValidation.valid === false && !problems.length))) {
problems.push({ key: 'validation-unknown', type: 'structure', message: '当前版本校验未通过,服务端未提供具体结构问题,请重新读取审核。', codes: [] })
if (
known &&
((validation === false && !problems.some(item => ['structure', 'subject', 'binding'].includes(item.type))) ||
(current?.candidateValidation.valid === false && !problems.length))
) {
problems.push({
key: 'validation-unknown',
type: 'structure',
message: '当前版本校验未通过,服务端未提供具体结构问题,请重新读取审核。',
codes: []
})
}
const structuralCount = problems.filter(item => ['structure', 'subject', 'binding'].includes(item.type)).length
const structureValid = validation === null ? null : validation && structuralCount === 0
return {
source: source.kind, checkpointId: source.checkpoint?.checkpointId, isCandidate: candidate,
source: source.kind,
checkpointId: source.checkpoint?.checkpointId,
isCandidate: candidate,
committed: source.state?.storyboardPersisted === true || source.state?.candidateCommitted === true,
structureValid, actionStatus: known ? actionBlocks.length || pendingEpisodeNos.length ? 'blocked' : 'passed' : 'unknown',
structuralIssues, structuralCount, actionBlocks, pendingEpisodeNos, problems,
historyIssues: current?.previousIssues ?? [], issueCount: problems.length,
canRequestCommitPreview: candidate && known && current!.candidateValidation.valid && structureValid === true && !problems.length && !candidateCommitIssue({ ...source.state, workflowExecution: undefined, storyboardShotValidation: { valid: true, issues: [] }, storyboardPendingQualityEpisodeNos: pendingEpisodeNos }),
needsRefresh: candidate && (!known || !!error), loading: candidate && loading, error: candidate ? error : ''
structureValid,
actionStatus: known ? (actionBlocks.length || pendingEpisodeNos.length ? 'blocked' : 'passed') : 'unknown',
structuralIssues,
structuralCount,
actionBlocks,
pendingEpisodeNos,
problems,
historyIssues: current?.previousIssues ?? [],
issueCount: problems.length,
canRequestCommitPreview:
candidate &&
known &&
current!.candidateValidation.valid &&
structureValid === true &&
!problems.length &&
!candidateCommitIssue({
...source.state,
workflowExecution: undefined,
storyboardShotValidation: { valid: true, issues: [] },
storyboardPendingQualityEpisodeNos: pendingEpisodeNos
}),
needsRefresh: candidate && (!known || !!error),
loading: candidate && loading,
error: candidate ? error : ''
}
}
+4 -2
View File
@@ -72,8 +72,10 @@ export function actionDraftIssue(draft: ShotActionDraft): string {
)
return '阶段衔接与建议时长需填写有效秒数。'
for (const phase of planning.phases) {
if (phase.resourceOccupancy?.some(item => item.transition && !item.continuityRef?.trim())) return '释放或交接需要填写明确的持续对象。'
if (phase.resourceOccupancy?.some(item => item.transition === 'release' && item.usage !== 'other')) return '明确释放不能同时声明持有或支撑,请核对资源用途。'
if (phase.resourceOccupancy?.some(item => item.transition && !item.continuityRef?.trim()))
return '释放或交接需要填写明确的持续对象。'
if (phase.resourceOccupancy?.some(item => item.transition === 'release' && item.usage !== 'other'))
return '明确释放不能同时声明持有或支撑,请核对资源用途。'
if (!phase.action.trim()) return '请填写每个阶段的动作描述。'
if (!Number.isFinite(phase.estimatedSeconds) || phase.estimatedSeconds <= 0) return '阶段时长必须大于 0 秒。'
const references = [
+15 -3
View File
@@ -17,7 +17,9 @@ export function useBreakdownQuality(projectId: Ref<string>, checkpoints: Ref<Che
/** 当前生命周期与正式数据分别选择。 */
const source = computed(() => selectBreakdownSource(workflowCheckpoints(checkpoints.value, 'breakdown')))
/** 审核请求只绑定尚未提交的候选及其项目。 */
const key = computed(() => source.value.kind === 'candidate' ? `${projectId.value}:${source.value.checkpoint?.checkpointId}` : '')
const key = computed(() =>
source.value.kind === 'candidate' ? `${projectId.value}:${source.value.checkpoint?.checkpointId}` : ''
)
/** 仅存放当前版本已验证的审核。 */
const review = ref<CandidateRevalidation | null>(null)
/** 审核区域的独立加载状态。 */
@@ -56,7 +58,10 @@ export function useBreakdownQuality(projectId: Ref<string>, checkpoints: Ref<Che
showActionFeedback(message, error.value, 'error')
}
} finally {
if (version === generation) { loading.value = false; pending = null }
if (version === generation) {
loading.value = false
pending = null
}
}
})()
return pending
@@ -70,7 +75,14 @@ export function useBreakdownQuality(projectId: Ref<string>, checkpoints: Ref<Che
loading.value = false
error.value = ''
}
watch(key, () => { invalidate(); void refresh() }, { immediate: true, flush: 'sync' })
watch(
key,
() => {
invalidate()
void refresh()
},
{ immediate: true, flush: 'sync' }
)
onScopeDispose(invalidate)
/** 页面、问题与提交面板共用一个结论。 */
const quality = computed(() => breakdownQuality(source.value, review.value, loading.value, error.value))
@@ -3,7 +3,9 @@ import { projectsApi } from '../projects/api'
import { policyDraft } from '../projects/quality-policy'
import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from '../projects/types'
import {
qualityPolicyConfirmed, qualityPolicySignature, validateQualityPolicyReceipt
qualityPolicyConfirmed,
qualityPolicySignature,
validateQualityPolicyReceipt
} from '../projects/quality-policy-confirmation'
import { errorMessage } from '../../lib/http'
import { showActionFeedback, useActionMessage } from '../../components/ui/useActionMessage'
@@ -57,7 +59,11 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
/** 用户可重试的错误反馈。 */
const error = ref('')
/** 编辑器只在服务端版本变化时重建,失败保留草稿。 */
const editorKey = computed(() => policy.value ? `${policy.value.projectId}:${policy.value.revision}:${policy.value.fingerprint}:${qualityPolicySignature(policy.value.policy)}` : '')
const editorKey = computed(() =>
policy.value
? `${policy.value.projectId}:${policy.value.revision}:${policy.value.fingerprint}:${qualityPolicySignature(policy.value.policy)}`
: ''
)
/** 应用统一消息层。 */
const message = useActionMessage()
/** 取消项目或配置变更前的旧请求。 */
@@ -105,7 +111,9 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
error.value = errorMessage(cause)
showActionFeedback(message, error.value, 'error')
}
} finally { if (current === generation) reading.value = false }
} finally {
if (current === generation) reading.value = false
}
}
/**
@@ -128,7 +136,11 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
const draftSignature = qualityPolicySignature(draft)
let result = await read(id, signal)
if (current !== generation || !allowed.value) return false
if (result.revision !== reviewed.revision || result.fingerprint !== reviewed.fingerprint || qualityPolicySignature(result.policy) !== expected) {
if (
result.revision !== reviewed.revision ||
result.fingerprint !== reviewed.fingerprint ||
qualityPolicySignature(result.policy) !== expected
) {
policy.value = result
showActionFeedback(message, '质量规则已在其他位置更新,请重新核对后确认。', 'warning')
return false
@@ -146,16 +158,27 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
// 确认是独立写入;确认按钮只在用户明确核对后才调用此接口。
reading.value = false
saving.value = true
const confirmed = validateQualityPolicyReceipt(await projectsApi.confirmQualityPolicy(id, result.revision), id)
const confirmed = validateQualityPolicyReceipt(
await projectsApi.confirmQualityPolicy(id, result.revision),
id
)
if (current !== generation || !allowed.value) return false
if (!qualityPolicyConfirmed(confirmed) || confirmed.revision !== result.revision ||
confirmed.fingerprint !== result.fingerprint || qualityPolicySignature(confirmed.policy) !== draftSignature)
if (
!qualityPolicyConfirmed(confirmed) ||
confirmed.revision !== result.revision ||
confirmed.fingerprint !== result.fingerprint ||
qualityPolicySignature(confirmed.policy) !== draftSignature
)
throw new Error('质量规则确认结果不一致,请重新核对。')
saving.value = false
reading.value = true
result = await read(id, signal)
if (current !== generation || !allowed.value) return false
if (!qualityPolicyConfirmed(result) || result.revision !== confirmed.revision || result.fingerprint !== confirmed.fingerprint) {
if (
!qualityPolicyConfirmed(result) ||
result.revision !== confirmed.revision ||
result.fingerprint !== confirmed.fingerprint
) {
policy.value = result
showActionFeedback(message, '质量规则已变化,请重新核对后确认。', 'warning')
return false
@@ -173,7 +196,10 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
}
return false
} finally {
if (current === generation) { reading.value = false; saving.value = false }
if (current === generation) {
reading.value = false
saving.value = false
}
}
}
@@ -194,7 +220,12 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
const result = await read(id, controller.signal)
if (current !== generation || !allowed.value) return false
const signature = qualityPolicySignature(result.policy)
if (signature !== preparedSignature || !qualityPolicyConfirmed(result) || result.revision !== policy.value?.revision || result.fingerprint !== policy.value?.fingerprint) {
if (
signature !== preparedSignature ||
!qualityPolicyConfirmed(result) ||
result.revision !== policy.value?.revision ||
result.fingerprint !== policy.value?.fingerprint
) {
policy.value = result
preparedSignature = ''
startOpen.value = false
@@ -202,7 +233,13 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
showActionFeedback(message, '质量规则已变化,请重新确认后再启动拆解。', 'warning')
return false
}
permit = { projectId: id, scope: currentScope, signature, revision: result.revision, fingerprint: result.fingerprint }
permit = {
projectId: id,
scope: currentScope,
signature,
revision: result.revision,
fingerprint: result.fingerprint
}
startOpen.value = false
return true
} catch (cause) {
@@ -211,7 +248,9 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
showActionFeedback(message, error.value, 'error')
}
return false
} finally { if (current === generation) reading.value = false }
} finally {
if (current === generation) reading.value = false
}
}
/**
@@ -221,9 +260,16 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
function consumePermit(): { expectedRevision: number } | null {
const current = permit
permit = null
return current && allowed.value && current.projectId === projectId.value && current.scope === scope.value &&
policy.value && qualityPolicyConfirmed(policy.value) && current.revision === policy.value.revision &&
current.fingerprint === policy.value.fingerprint ? { expectedRevision: current.revision } : null
return current &&
allowed.value &&
current.projectId === projectId.value &&
current.scope === scope.value &&
policy.value &&
qualityPolicyConfirmed(policy.value) &&
current.revision === policy.value.revision &&
current.fingerprint === policy.value.fingerprint
? { expectedRevision: current.revision }
: null
}
/** 用户取消只读确认时撤销未完成请求,保存请求进行中禁止重复取消。 */
@@ -231,7 +277,27 @@ export function useBreakdownStartPolicy(projectId: Ref<string>, scope: Ref<strin
if (!saving.value) reset()
}
watch([projectId, scope], reset, { flush: 'sync' })
watch(allowed, value => { if (!value) reset() }, { flush: 'sync' })
watch(
allowed,
value => {
if (!value) reset()
},
{ flush: 'sync' }
)
onScopeDispose(reset)
return { policy, reviewOpen, startOpen, reading, saving, busy, error, editorKey, prepare, confirmRules, verifyStart, consumePermit, cancel }
return {
policy,
reviewOpen,
startOpen,
reading,
saving,
busy,
error,
editorKey,
prepare,
confirmRules,
verifyStart,
consumePermit,
cancel
}
}
@@ -215,7 +215,11 @@ async function save() {
emit('saved', profile.value)
} catch (cause) {
if (!disposed && props.projectId === projectId)
showActionFeedback(feedback, errorMessage(cause), cause instanceof ApiError && cause.status === 409 ? 'warning' : 'error')
showActionFeedback(
feedback,
errorMessage(cause),
cause instanceof ApiError && cause.status === 409 ? 'warning' : 'error'
)
} finally {
saving.value = false
}
@@ -103,7 +103,11 @@ function selectValue(key: string): string | number | null {
:show-feedback="false"
>
<!-- 以下是生成参数标签与说明提示模块 -->
<template #label><FieldLabel :label="userFacingText(item.label, item.label)" :description="userFacingText(item.description)" /></template>
<template #label
><FieldLabel
:label="userFacingText(item.label, item.label)"
:description="userFacingText(item.description)"
/></template>
<div class="generation-model-field-control">
<div v-if="item.type === 'boolean'" class="generation-model-toggle">
<NSwitch
@@ -70,7 +70,10 @@ function constrainedOptions(schema: GenerationOptionSchema, current: string | nu
}
}
if (typeof schema.providerDefault === 'string' || typeof schema.providerDefault === 'number') {
options.push({ label: userFacingText(String(schema.providerDefault), String(schema.providerDefault)), value: schema.providerDefault })
options.push({
label: userFacingText(String(schema.providerDefault), String(schema.providerDefault)),
value: schema.providerDefault
})
}
if (typeof current === 'string' || typeof current === 'number') {
options.push({ label: userFacingText(String(current), String(current)), value: current })
@@ -17,7 +17,12 @@ defineProps<{
<p class="text-xs leading-6 text-muted">这些例外会继续保留。新增例外请在拆解后的具体动作问题中填写。</p>
<ul class="mt-3 space-y-3">
<li v-for="(item, index) in exceptions" :key="index" class="space-y-1 break-words text-sm">
<p>{{ item.ownerRef }} · {{ actionResourceOptions.find(option => option.value === item.resource)?.label || item.resource }}</p>
<p>
{{ item.ownerRef }} ·
{{
actionResourceOptions.find(option => option.value === item.resource)?.label || item.resource
}}
</p>
<p class="text-xs leading-6 text-muted">{{ item.reason }}</p>
</li>
</ul>
@@ -35,22 +35,37 @@ const policy = ref<ProjectQualityPolicy | null>(null)
let savedGeneralSignature = ''
/** 整体表现方式及通俗示例,仅说明含义,不自动修改动作许可。 */
const physicsOptions = [
{ value: 'realistic', label: '写实物理', description: '按现实生活中的规律设计动作,例如跳起需要借力,物品失去支撑会落下。' },
{ value: 'stylized', label: '风格化表现', description: '适合卡通、喜剧,让动作更有戏剧感;具体允许哪些夸张动作,还需在下方勾选。' },
{ value: 'fantasy', label: '幻想表现', description: '适合仙侠、魔法等故事,按故事设定设计动作;飞行、法术等能力仍需在下方明确允许。' }
{
value: 'realistic',
label: '写实物理',
description: '按现实生活中的规律设计动作,例如跳起需要借力,物品失去支撑会落下。'
},
{
value: 'stylized',
label: '风格化表现',
description: '适合卡通、喜剧,让动作更有戏剧感;具体允许哪些夸张动作,还需在下方勾选。'
},
{
value: 'fantasy',
label: '幻想表现',
description: '适合仙侠、魔法等故事,按故事设定设计动作;飞行、法术等能力仍需在下方明确允许。'
}
]
/** 当前选择的说明始终显示,关闭下拉菜单后也能了解含义。 */
const physicsDescription = computed(() => physicsOptions.find(option => option.value === policy.value?.physicsMode)?.description ?? '')
const physicsDescription = computed(
() => physicsOptions.find(option => option.value === policy.value?.physicsMode)?.description ?? ''
)
/**
* 下拉选项同时展示名称与说明,窄屏可自然换行。
* @param option Naive UI 提供的当前选项
* @returns 包含通俗说明的选项内容
*/
const renderPhysicsLabel: SelectRenderLabel = option => h('div', { class: 'grid min-w-0 gap-1 py-1 whitespace-normal' }, [
const renderPhysicsLabel: SelectRenderLabel = option =>
h('div', { class: 'grid min-w-0 gap-1 py-1 whitespace-normal' }, [
h('span', { class: 'text-sm leading-6' }, String(option.label ?? '')),
h('span', { class: 'text-xs leading-5 text-muted' }, String(option.description ?? ''))
])
])
/**
* 选择框只显示简短名称,完整说明放在控件下方,避免撑高或截断控件。
@@ -70,9 +85,21 @@ interface MotionPermissionOption {
}
/** 三类许可的区别直接展示,不依赖悬停或术语理解。 */
const motionPermissions: MotionPermissionOption[] = [
{ field: 'allowExaggeratedMotion', label: '允许夸张动作', description: '把正常动作做得更夸张,例如惊讶时大幅后仰、跑步时摆臂更大;不等于允许悬空或法术。' },
{ field: 'allowNonPhysicalActions', label: '允许非物理动作', description: '允许现实中做不到的动作,例如身体像橡皮一样拉长、没有支撑也能悬空。' },
{ field: 'allowSupernaturalAbilities', label: '允许超自然能力', description: '允许角色使用法术或特殊能力,例如瞬间移动、隔空移动物品、凭空变出火焰。' }
{
field: 'allowExaggeratedMotion',
label: '允许夸张动作',
description: '把正常动作做得更夸张,例如惊讶时大幅后仰、跑步时摆臂更大;不等于允许悬空或法术。'
},
{
field: 'allowNonPhysicalActions',
label: '允许非物理动作',
description: '允许现实中做不到的动作,例如身体像橡皮一样拉长、没有支撑也能悬空。'
},
{
field: 'allowSupernaturalAbilities',
label: '允许超自然能力',
description: '允许角色使用法术或特殊能力,例如瞬间移动、隔空移动物品、凭空变出火焰。'
}
]
/** 仅在用户点击保存时产生校验反馈,不在读取或新增空白例外时提前报错。 */
const issue = ref('')
@@ -113,7 +140,7 @@ async function load() {
notice.value = ''
issue.value = ''
try {
const result = props.initialPolicy ?? await projectsApi.qualityPolicy(id, controller.signal)
const result = props.initialPolicy ?? (await projectsApi.qualityPolicy(id, controller.signal))
if (current !== version) return
validateQualityPolicyReceipt(result, id)
savedGeneralSignature = qualityPolicySignature({ ...result.policy, actionExceptions: [] })
@@ -154,7 +181,8 @@ async function save() {
if (qualityPolicySignature({ ...latest.policy, actionExceptions: [] }) !== savedGeneralSignature)
throw new Error('质量规则已在其他位置更新,请重新打开配置后再保存。')
// 例外由问题修订入口管理,基础配置永远合并服务端最新例外,不提交隐藏的旧副本。
if (latest.policy.actionExceptions) input.actionExceptions = latest.policy.actionExceptions.map(item => ({ ...item }))
if (latest.policy.actionExceptions)
input.actionExceptions = latest.policy.actionExceptions.map(item => ({ ...item }))
else delete input.actionExceptions
loading.value = false
saving.value = true
@@ -164,12 +192,17 @@ async function save() {
savedGeneralSignature = qualityPolicySignature({ ...result.policy, actionExceptions: [] })
policy.value = policyDraft(result.policy)
rulesText.value = policy.value.customRules.join('\n')
notice.value = result.confirmed ? '质量规则已保存,当前版本已经确认。' : '质量规则已保存。下次启动拆解前需要核对并确认。'
notice.value = result.confirmed
? '质量规则已保存,当前版本已经确认。'
: '质量规则已保存。下次启动拆解前需要核对并确认。'
emit('saved')
} catch (cause) {
if (current === version) error.value = errorMessage(cause)
} finally {
if (current === version) { saving.value = false; loading.value = false }
if (current === version) {
saving.value = false
loading.value = false
}
}
}
@@ -210,21 +243,32 @@ defineExpose({ save, canSave, validatedDraft })
:virtual-scroll="false"
:disabled="disabled || saving"
/>
<p id="quality-physics-mode-help" class="text-xs leading-6 text-muted">{{ physicsDescription }}</p>
<p id="quality-physics-mode-help" class="text-xs leading-6 text-muted">
{{ physicsDescription }}
</p>
</div>
</NFormItem>
<!-- 以下是动作许可及其日常示例,桌面按列对齐,手机逐项展示 -->
<div class="grid gap-4 sm:grid-cols-3">
<div v-for="permission in motionPermissions" :key="permission.field" class="min-w-0 space-y-2">
<NCheckbox v-model:checked="policy[permission.field]" :disabled="disabled || saving" :aria-describedby="`quality-${permission.field}-help`">{{ permission.label }}</NCheckbox>
<p :id="`quality-${permission.field}-help`" class="pl-6 text-xs leading-6 text-muted">{{ permission.description }}</p>
<NCheckbox
v-model:checked="policy[permission.field]"
:disabled="disabled || saving"
:aria-describedby="`quality-${permission.field}-help`"
>{{ permission.label }}</NCheckbox
>
<p :id="`quality-${permission.field}-help`" class="pl-6 text-xs leading-6 text-muted">
{{ permission.description }}
</p>
</div>
</div>
</section>
<!-- 以下是逐行声明的自定义规则模块 -->
<NFormItem label="自定义规则" :label-props="{ for: 'quality-custom-rules' }">
<div class="quality-policy-field">
<p id="quality-custom-rules-help" class="text-xs leading-6 text-muted">补充这个故事允许的特殊情况或需要遵守的要求,每行一条,最多 30 条。</p>
<p id="quality-custom-rules-help" class="text-xs leading-6 text-muted">
补充这个故事允许的特殊情况或需要遵守的要求,每行一条,最多 30 条。
</p>
<NInput
v-model:value="rulesText"
type="textarea"
@@ -149,7 +149,12 @@ const confirmationDescription = computed(
<!-- 以下是项目配置缺失的恢复入口,保存后仍须重新检查制作条件。 -->
<div v-if="configurationRequired" class="mt-3 flex flex-wrap items-center gap-3">
<span class="text-xs text-muted">请先保存项目生成配置,再重新检查制作条件。</span>
<NButton v-if="openProjectSettings" class="workspace-action-button" :disabled="operation.pending" @click="openProjectSettings">
<NButton
v-if="openProjectSettings"
class="workspace-action-button"
:disabled="operation.pending"
@click="openProjectSettings"
>
<template #icon><Settings2 :size="15" aria-hidden="true" /></template>前往项目配置
</NButton>
</div>
@@ -63,7 +63,11 @@ export async function checkPipeline(projectId: string, scope: ProductionStartInp
if (entry.ready !== true) throw new Error(entry.reason || '请先完成正式分镜检查与人工审核,再进入制作计划。')
const project = await projectsApi.detail(projectId)
if (project.id !== projectId) throw new Error('预检返回了其他项目的数据,请重新读取。')
await assertCurrentStoryboardDesigns(projectId, project.episodes.map(item => item.episode), entry.derivedAssets.shotCount)
await assertCurrentStoryboardDesigns(
projectId,
project.episodes.map(item => item.episode),
entry.derivedAssets.shotCount
)
const profile = await generationConfigApi.profile(projectId)
if (!profile) throw new ProductionConfigurationRequiredError()
const providers = {
@@ -255,7 +259,12 @@ export function useAdvancedProduction() {
let submitted = false
await runOperation(projectId, '高级串联生产', async () => {
const result = await checkPipeline(projectId, scope.value).catch(cause => {
if (!disposed && id.value === projectId && confirmedVersion === version && cause instanceof ProductionConfigurationRequiredError) {
if (
!disposed &&
id.value === projectId &&
confirmedVersion === version &&
cause instanceof ProductionConfigurationRequiredError
) {
check.value = null
configurationRequired.value = true
}
@@ -23,7 +23,6 @@ const ACCEPTED_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp'])
const MAX_FILE_SIZE = 20 * 1024 * 1024
const categoryPattern = /^[a-z0-9_-]+$/
/** 全局接口一次返回全部图片及所属剧本,避免按项目产生 N 次请求。 */
const query = useQuery(ref('all-project-assets'), (_, signal) => projectAssetsApi.listAll(signal))
/** 上传需要列出包括尚无资产在内的全部剧本。 */
@@ -56,7 +55,12 @@ const uploadProjectOptions = computed(() =>
.map(project => ({ label: projectName(project), value: project.id }))
)
/** 筛选只展示已有分类,显示中文且仍提交原始分类值。 */
const categoryOptions = computed(() => assetCategoryOptions(assets.value.map(asset => asset.category), false))
const categoryOptions = computed(() =>
assetCategoryOptions(
assets.value.map(asset => asset.category),
false
)
)
const filteredAssets = computed(() => {
const keyword = search.value.trim().toLowerCase()
return assets.value.filter(asset => {
@@ -81,8 +85,6 @@ function projectName(project: Pick<ProjectAssetProject, 'title' | 'topic'>) {
return project.title?.trim() || project.topic
}
function formatBytes(value: number) {
if (value < 1024) return `${value} B`
if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KB`
@@ -320,14 +322,25 @@ async function removeAsset() {
:busy="busy"
>
<FeedbackMessage v-if="actionError" :message="actionError" />
<AppForm id="library-upload-form" :model="uploadForm" :rules="formRules" :disabled="busy" class="mt-5" @submit="uploadAsset">
<AppForm
id="library-upload-form"
:model="uploadForm"
:rules="formRules"
:disabled="busy"
class="mt-5"
@submit="uploadAsset"
>
<p class="mb-4 text-sm">{{ selectedFile?.name }} · {{ formatBytes(selectedFile?.size ?? 0) }}</p>
<NFormItem path="projectId" label="所属剧本">
<NSelect v-model:value="uploadForm.projectId" filterable :options="uploadProjectOptions" />
</NFormItem>
<NFormItem path="name" label="素材名称"><NInput v-model:value="uploadForm.name" /></NFormItem>
<NFormItem path="category" label="素材分类">
<AssetCategorySelect v-model:value="uploadForm.category" :categories="assets.map(asset => asset.category)" :disabled="busy" />
<AssetCategorySelect
v-model:value="uploadForm.category"
:categories="assets.map(asset => asset.category)"
:disabled="busy"
/>
</NFormItem>
</AppForm>
<template #footer>
@@ -344,7 +357,14 @@ async function removeAsset() {
wide
>
<FeedbackMessage v-if="actionError" :message="actionError" />
<AppForm id="library-edit-form" :model="editForm" :rules="formRules" :disabled="busy" class="mt-5" @submit="updateAsset">
<AppForm
id="library-edit-form"
:model="editForm"
:rules="formRules"
:disabled="busy"
class="mt-5"
@submit="updateAsset"
>
<div v-if="selectedAsset" class="asset-management-layout">
<AssetImage
:src="selectedAsset.publicUrl"
@@ -357,9 +377,15 @@ async function removeAsset() {
<NFormItem label="所属剧本">
<NInput :value="projectName(selectedAsset.project)" disabled />
</NFormItem>
<NFormItem path="name" label="素材名称" :label-props="{ for: 'library-asset-name' }"><NInput v-model:value="editForm.name" :input-props="{ id: 'library-asset-name' }" /></NFormItem>
<NFormItem path="name" label="素材名称" :label-props="{ for: 'library-asset-name' }"
><NInput v-model:value="editForm.name" :input-props="{ id: 'library-asset-name' }"
/></NFormItem>
<NFormItem path="category" label="素材分类">
<AssetCategorySelect v-model:value="editForm.category" :categories="assets.map(asset => asset.category)" :disabled="busy" />
<AssetCategorySelect
v-model:value="editForm.category"
:categories="assets.map(asset => asset.category)"
:disabled="busy"
/>
</NFormItem>
<dl class="asset-detail-grid">
<dt>原始文件名</dt>
@@ -393,7 +419,9 @@ async function removeAsset() {
</NPopconfirm>
<div class="ml-auto flex gap-2">
<NButton :disabled="busy" @click="editOpen = false">取消</NButton>
<NButton type="primary" attr-type="submit" form="library-edit-form" :loading="busy">保存修改</NButton>
<NButton type="primary" attr-type="submit" form="library-edit-form" :loading="busy"
>保存修改</NButton
>
</div>
</div>
</template>
@@ -525,7 +553,13 @@ async function removeAsset() {
}
/* 弹窗通过 Teleport 展示,使用视口适配,不依赖页面容器查询。 */
@media (max-width: 640px) {
.asset-management-layout { grid-template-columns: minmax(0, 1fr); }
.asset-management-preview { --asset-detail-image-max-height: min(36dvh, 320px); max-width: 100%; justify-self: center; }
.asset-management-layout {
grid-template-columns: minmax(0, 1fr);
}
.asset-management-preview {
--asset-detail-image-max-height: min(36dvh, 320px);
max-width: 100%;
justify-self: center;
}
}
</style>
@@ -23,7 +23,6 @@ const ACCEPTED_TYPES = new Set(['image/jpeg', 'image/png', 'image/webp'])
const MAX_FILE_SIZE = 20 * 1024 * 1024
const categoryPattern = /^[a-z0-9_-]+$/
const { projectId, blocked } = useProjectMutationGuard()
const query = useQuery(projectId, async (id, signal) => {
const assets = await projectAssetsApi.list(id, signal)
@@ -63,8 +62,6 @@ const formRules = {
)
}
function metadataOriginalName(value: unknown) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return ''
const originalName = (value as Record<string, unknown>).originalName
@@ -265,16 +262,29 @@ async function removeAsset(asset: ProjectAsset) {
description="填写名称并选择分类,方便之后查找和使用这张图片。"
:busy="blocked"
>
<AppForm id="project-upload-form" :model="uploadForm" :rules="formRules" :disabled="blocked" class="mt-5" @submit="uploadAsset">
<AppForm
id="project-upload-form"
:model="uploadForm"
:rules="formRules"
:disabled="blocked"
class="mt-5"
@submit="uploadAsset"
>
<p class="mb-4 text-sm">{{ selectedFile?.name }} · {{ formatBytes(selectedFile?.size ?? 0) }}</p>
<NFormItem path="name" label="素材名称"><NInput v-model:value="uploadForm.name" /></NFormItem>
<NFormItem path="category" label="素材分类">
<AssetCategorySelect v-model:value="uploadForm.category" :categories="assets.map(asset => asset.category)" :disabled="blocked" />
<AssetCategorySelect
v-model:value="uploadForm.category"
:categories="assets.map(asset => asset.category)"
:disabled="blocked"
/>
</NFormItem>
</AppForm>
<template #footer>
<NButton :disabled="blocked" @click="uploadOpen = false">取消</NButton>
<NButton type="primary" attr-type="submit" form="project-upload-form" :loading="blocked">确认上传</NButton>
<NButton type="primary" attr-type="submit" form="project-upload-form" :loading="blocked"
>确认上传</NButton
>
</template>
</AppDialog>
@@ -284,13 +294,27 @@ async function removeAsset(asset: ProjectAsset) {
description="只修改名称和分类,不会替换图片文件或修改已保存的引用地址。"
:busy="blocked"
>
<AppForm id="project-edit-form" :model="editForm" :rules="formRules" :disabled="blocked" class="mt-5" @submit="updateAsset">
<AppForm
id="project-edit-form"
:model="editForm"
:rules="formRules"
:disabled="blocked"
class="mt-5"
@submit="updateAsset"
>
<NFormItem path="name" label="素材名称"><NInput v-model:value="editForm.name" /></NFormItem>
<NFormItem path="category" label="素材分类"><AssetCategorySelect v-model:value="editForm.category" :categories="assets.map(asset => asset.category)" :disabled="blocked" /></NFormItem>
<NFormItem path="category" label="素材分类"
><AssetCategorySelect
v-model:value="editForm.category"
:categories="assets.map(asset => asset.category)"
:disabled="blocked"
/></NFormItem>
</AppForm>
<template #footer>
<NButton :disabled="blocked" @click="editOpen = false">取消</NButton>
<NButton type="primary" attr-type="submit" form="project-edit-form" :loading="blocked">保存修改</NButton>
<NButton type="primary" attr-type="submit" form="project-edit-form" :loading="blocked"
>保存修改</NButton
>
</template>
</AppDialog>
</WorkspacePage>
+14 -4
View File
@@ -1,7 +1,14 @@
/** 素材分类的展示名称;取值仍使用现有接口约定,不改写已保存分类。 */
const labels: Record<string, string> = {
overall: '综合', character: '人物', scene: '场景', prop: '道具', reference: '参考素材',
'visual-style': '视觉风格', subjects: '主体图片', keyframes: '首帧图片', videos: '视频素材'
overall: '综合',
character: '人物',
scene: '场景',
prop: '道具',
reference: '参考素材',
'visual-style': '视觉风格',
subjects: '主体图片',
keyframes: '首帧图片',
videos: '视频素材'
}
/**
@@ -9,7 +16,9 @@ const labels: Record<string, string> = {
* @param value 原始分类
* @returns 分类展示名称
*/
export function assetCategoryLabel(value: string): string { return labels[value] ?? value }
export function assetCategoryLabel(value: string): string {
return labels[value] ?? value
}
/**
* 为上传、编辑及筛选复用中文分类选项,原始值不受影响。
@@ -19,5 +28,6 @@ export function assetCategoryLabel(value: string): string { return labels[value]
*/
export function assetCategoryOptions(values: string[], defaults = true) {
return [...new Set([...(defaults ? Object.keys(labels) : []), ...values])]
.toSorted().map(value => ({ label: assetCategoryLabel(value), value }))
.toSorted()
.map(value => ({ label: assetCategoryLabel(value), value }))
}
@@ -4,12 +4,15 @@ import { NSelect } from 'naive-ui'
import { assetCategoryOptions } from '../categories'
/** 素材分类使用中文选择,仍保留已有分类和自定义分类能力。 */
const props = withDefaults(defineProps<{
const props = withDefaults(
defineProps<{
/** 已有素材的分类,避免编辑时丢失自定义值。 */
categories?: string[]
/** 提交时禁止修改。 */
disabled?: boolean
}>(), { categories: () => [] })
}>(),
{ categories: () => [] }
)
/** 表单和请求始终保存原始分类值。 */
const value = defineModel<string>('value', { default: '' })
/** 常用分类及已有自定义分类共用同一份中文选项。 */
@@ -18,5 +21,14 @@ const options = computed(() => assetCategoryOptions([...props.categories, ...(va
<template>
<!-- 以下是中文分类选择模块,自定义取值仍由表单按接口要求校验 -->
<NSelect :value="value" :options="options" :disabled="disabled" filterable tag placeholder="选择分类,或输入自定义分类" aria-label="素材分类" @update:value="value = String($event ?? '')" />
<NSelect
:value="value"
:options="options"
:disabled="disabled"
filterable
tag
placeholder="选择分类,或输入自定义分类"
aria-label="素材分类"
@update:value="value = String($event ?? '')"
/>
</template>
+27 -6
View File
@@ -260,7 +260,9 @@ onScopeDispose(() => {
<!-- 以下是项目标题与全局配置入口模块,首次读取保留标题及两个操作的真实占位 -->
<NPageHeader @back="router.push('/projects')">
<template #title>
<div v-if="isProjectInitialLoading" class="project-title project-title-loading" aria-hidden="true"><NSkeleton :height="16" /></div>
<div v-if="isProjectInitialLoading" class="project-title project-title-loading" aria-hidden="true">
<NSkeleton :height="16" />
</div>
<NEllipsis v-else class="project-title" :tooltip="false">{{
context.project.value?.title || context.project.value?.topic || ''
}}</NEllipsis>
@@ -270,13 +272,28 @@ onScopeDispose(() => {
<div class="project-header-actions flex items-center gap-2">
<template v-if="isProjectInitialLoading">
<NSkeleton class="project-header-action-placeholder" aria-hidden="true" />
<NSkeleton class="project-header-action-placeholder project-header-config-placeholder" aria-hidden="true" />
<NSkeleton
class="project-header-action-placeholder project-header-config-placeholder"
aria-hidden="true"
/>
</template>
<template v-else>
<StoryboardPreparation v-if="context.project.value?.id === id" :key="id" :project-id="id" :disabled="!!context.error.value" @changed="context.refresh()" />
<StoryboardPreparation
v-if="context.project.value?.id === id"
:key="id"
:project-id="id"
:disabled="!!context.error.value"
@changed="context.refresh()"
/>
<WorkspaceActionTooltip label="项目配置" mobile-only>
<NButton class="workspace-action-button" size="small" aria-label="项目配置" :disabled="!context.project.value" @click="settingsOpen = true"
><template #icon><Settings2 :size="15" aria-hidden="true" /></template><span class="project-config-label">项目配置</span></NButton
<NButton
class="workspace-action-button"
size="small"
aria-label="项目配置"
:disabled="!context.project.value"
@click="settingsOpen = true"
><template #icon><Settings2 :size="15" aria-hidden="true" /></template
><span class="project-config-label">项目配置</span></NButton
>
</WorkspaceActionTooltip>
</template>
@@ -438,5 +455,9 @@ onScopeDispose(() => {
<style scoped>
/* 窄屏的两个项目操作统一显示图标,保留按钮的完整可访问名称。 */
@media (max-width: 639px) { .project-config-label { display: none; } }
@media (max-width: 639px) {
.project-config-label {
display: none;
}
}
</style>
+2 -1
View File
@@ -43,7 +43,8 @@ export const projectsApi = {
*/
confirmQualityPolicy: (id: string, expectedRevision: number) =>
request<ProjectQualityPolicyResult>(`/projects/${encodeURIComponent(id)}/quality-policy/confirm`, {
method: 'POST', body: { expectedRevision }
method: 'POST',
body: { expectedRevision }
}),
list: (signal?: AbortSignal) => request<Project[]>('/projects', { signal }),
detail: (id: string, signal?: AbortSignal) =>
@@ -7,8 +7,11 @@ import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from './types'
* @returns 可精确比较的内容签名,不是后端授权令牌
*/
export function qualityPolicySignature(policy: ProjectQualityPolicy): string {
if (!policy || !Array.isArray(policy.customRules) ||
(policy.actionExceptions !== undefined && !Array.isArray(policy.actionExceptions)))
if (
!policy ||
!Array.isArray(policy.customRules) ||
(policy.actionExceptions !== undefined && !Array.isArray(policy.actionExceptions))
)
throw new Error('质量规则响应不完整,请重新读取。')
const issue = policyIssue(policy)
if (issue) throw new Error(issue)
@@ -34,13 +37,26 @@ export function qualityPolicySignature(policy: ProjectQualityPolicy): string {
* @param projectId 当前项目
* @returns 已核对的完整回执
*/
export function validateQualityPolicyReceipt(result: ProjectQualityPolicyResult, projectId: string): ProjectQualityPolicyResult {
export function validateQualityPolicyReceipt(
result: ProjectQualityPolicyResult,
projectId: string
): ProjectQualityPolicyResult {
if (!result || result.projectId !== projectId) throw new Error('质量规则所属项目不一致,请重新读取。')
qualityPolicySignature(result.policy)
if (!Number.isSafeInteger(result.revision) || result.revision < 0 ||
!/^[a-f\d]{64}$/.test(result.fingerprint) || typeof result.confirmed !== 'boolean' ||
!(result.confirmedRevision === null || Number.isSafeInteger(result.confirmedRevision) && result.confirmedRevision >= 0) ||
!(result.confirmedAt === null || typeof result.confirmedAt === 'string' && Number.isFinite(Date.parse(result.confirmedAt))))
if (
!Number.isSafeInteger(result.revision) ||
result.revision < 0 ||
!/^[a-f\d]{64}$/.test(result.fingerprint) ||
typeof result.confirmed !== 'boolean' ||
!(
result.confirmedRevision === null ||
(Number.isSafeInteger(result.confirmedRevision) && result.confirmedRevision >= 0)
) ||
!(
result.confirmedAt === null ||
(typeof result.confirmedAt === 'string' && Number.isFinite(Date.parse(result.confirmedAt)))
)
)
throw new Error('质量规则确认信息不完整,请重新读取。')
if (result.confirmed && !qualityPolicyConfirmed(result)) throw new Error('质量规则确认版本不一致,请重新读取。')
return result
@@ -52,6 +68,10 @@ export function validateQualityPolicyReceipt(result: ProjectQualityPolicyResult,
* @returns 当前修订是否已经明确确认
*/
export function qualityPolicyConfirmed(result: ProjectQualityPolicyResult): boolean {
return result.confirmed === true && result.confirmedRevision === result.revision &&
typeof result.confirmedAt === 'string' && Number.isFinite(Date.parse(result.confirmedAt))
return (
result.confirmed === true &&
result.confirmedRevision === result.revision &&
typeof result.confirmedAt === 'string' &&
Number.isFinite(Date.parse(result.confirmedAt))
)
}
@@ -24,13 +24,38 @@ const busy = ref(false)
/** 同项目活动任务与真实请求互斥。 */
const locked = computed(() => getOperation(props.projectId).pending || hasActiveWorkflowExecution(props.projectId))
/** 只有真实保存回执通过后关闭,局部修订不自动标记审核通过。 */
function saved() { open.value = false; emit('saved') }
function saved() {
open.value = false
emit('saved')
}
</script>
<template>
<!-- 以下是独立正式修订抽屉,正文与底栏同步铺满视口 -->
<AppDrawer v-model:open="open" title="修订当前正式镜头" :busy="busy" description="读取当前正式动作,保存前会再次核对版本、任务和已有素材。修订后仍需重新检查。">
<FormalRepairEditor v-if="open && issue" ref="editor" :project-id="projectId" :issue="issue" :disabled="locked" @busy="busy = $event" @saved="saved" />
<template #footer><NButton :disabled="busy" @click="open = false">取消</NButton><NButton type="primary" :disabled="busy || locked || !editor?.canSave" :loading="busy" @click="editor?.save()"><template #icon><Save :size="15" /></template>保存本次修订</NButton></template>
<AppDrawer
v-model:open="open"
title="修订当前正式镜头"
:busy="busy"
description="读取当前正式动作,保存前会再次核对版本、任务和已有素材。修订后仍需重新检查。"
>
<FormalRepairEditor
v-if="open && issue"
ref="editor"
:project-id="projectId"
:issue="issue"
:disabled="locked"
@busy="busy = $event"
@saved="saved"
/>
<template #footer
><NButton :disabled="busy" @click="open = false">取消</NButton
><NButton
type="primary"
:disabled="busy || locked || !editor?.canSave"
:loading="busy"
@click="editor?.save()"
><template #icon><Save :size="15" /></template>保存本次修订</NButton
></template
>
</AppDrawer>
</template>
@@ -8,7 +8,13 @@ import ConfirmAction from '../workflows/ConfirmAction.vue'
import { actionDraft, actionDraftIssue } from '../breakdown/repair'
import type { ShotActionDraft } from '../breakdown/repair.types'
import { preparationApi } from './api'
import type { PreparationIssue, FormalShotRepairPreview, LocatedStoryboardShot, BeatSubjectPreview, FormalRepairResult } from './types'
import type {
PreparationIssue,
FormalShotRepairPreview,
LocatedStoryboardShot,
BeatSubjectPreview,
FormalRepairResult
} from './types'
import { errorMessage } from '../../lib/http'
import { userFacingText } from '../../lib/user-facing-text'
import { getOperation, runOperation } from '../workflows/operations'
@@ -48,11 +54,28 @@ const candidateReason = ref('')
/** 主体问题与动作问题使用各自正式 API。 */
const subjectMode = computed(() => !!props.issue.subjectRef)
/** 当前目标是否具备进一步操作前提,版本实际保存前仍会核对。 */
const canSave = computed(() => !!target.value && !props.disabled && !loading.value && !writing.value &&
(subjectMode.value ? !!beat.value?.candidate || subjectCheck.value?.written === false : !!draft.value && preview.value?.classification.status !== 'unchanged'))
const canSave = computed(
() =>
!!target.value &&
!props.disabled &&
!loading.value &&
!writing.value &&
(subjectMode.value
? !!beat.value?.candidate || subjectCheck.value?.written === false
: !!draft.value && preview.value?.classification.status !== 'unchanged')
)
/** 同一阶段或动作证据变化后撤销旧确认。 */
watch(draft, () => { acknowledged.value = false; issueText.value = '' }, { deep: true })
watch(reason, () => { issueText.value = '' })
watch(
draft,
() => {
acknowledged.value = false
issueText.value = ''
},
{ deep: true }
)
watch(reason, () => {
issueText.value = ''
})
/** 迟到响应隔离。 */
let version = 0
/** 当前只读请求。 */
@@ -60,105 +83,303 @@ let controller: AbortController | undefined
/** 从精确坐标或明确的正式 ID 读取当前版本,不代选相邻镜头。 */
async function load() {
const current = ++version, id = props.projectId, issue = props.issue
controller?.abort(); controller = new AbortController()
loading.value = true; error.value = ''; acknowledged.value = false; preview.value = null; target.value = null; draft.value = null; beat.value = null; subjectCheck.value = null
const current = ++version,
id = props.projectId,
issue = props.issue
controller?.abort()
controller = new AbortController()
loading.value = true
error.value = ''
acknowledged.value = false
preview.value = null
target.value = null
draft.value = null
beat.value = null
subjectCheck.value = null
try {
if (!issue.shotNo) throw new Error('这个问题没有唯一镜头位置,请先核对原分镜。')
let located: LocatedStoryboardShot
if (issue.shotId) {
const result = await preparationApi.repairPreview(id, issue.shotId, controller.signal)
if (current !== version) return
if (result.projectId !== id || result.shotId !== issue.shotId || !/^[a-f\d]{64}$/.test(result.expectedFingerprint)) throw new Error('镜头读取结果不一致。')
located = { projectId: id, shotId: issue.shotId, episodeNo: issue.episodeNo, beatNo: issue.beatNo, shotNo: issue.shotNo, expectedFingerprint: result.expectedFingerprint, written: false }
if (
result.projectId !== id ||
result.shotId !== issue.shotId ||
!/^[a-f\d]{64}$/.test(result.expectedFingerprint)
)
throw new Error('镜头读取结果不一致。')
located = {
projectId: id,
shotId: issue.shotId,
episodeNo: issue.episodeNo,
beatNo: issue.beatNo,
shotNo: issue.shotNo,
expectedFingerprint: result.expectedFingerprint,
written: false
}
if (!subjectMode.value) preview.value = result
} else located = await preparationApi.locate(id, { episodeNo: issue.episodeNo, beatNo: issue.beatNo, shotNo: issue.shotNo }, controller.signal)
} else
located = await preparationApi.locate(
id,
{ episodeNo: issue.episodeNo, beatNo: issue.beatNo, shotNo: issue.shotNo },
controller.signal
)
if (current !== version) return
if (located.projectId !== id || located.episodeNo !== issue.episodeNo || located.beatNo !== issue.beatNo || located.shotNo !== issue.shotNo || !located.shotId || !/^[a-f\d]{64}$/.test(located.expectedFingerprint)) throw new Error('目标镜头与当前问题不一致,请刷新。')
if (
located.projectId !== id ||
located.episodeNo !== issue.episodeNo ||
located.beatNo !== issue.beatNo ||
located.shotNo !== issue.shotNo ||
!located.shotId ||
!/^[a-f\d]{64}$/.test(located.expectedFingerprint)
)
throw new Error('目标镜头与当前问题不一致,请刷新。')
target.value = located
if (subjectMode.value) {
const result = await preparationApi.beatSubjectPreview(id, located.shotId, issue.subjectRef!, controller.signal)
const result = await preparationApi.beatSubjectPreview(
id,
located.shotId,
issue.subjectRef!,
controller.signal
)
if (current !== version) return
if (result.projectId !== id || result.shotId !== located.shotId || result.subjectRef !== issue.subjectRef || result.written !== false) throw new Error('主体证据与当前问题不一致。')
if (
result.projectId !== id ||
result.shotId !== located.shotId ||
result.subjectRef !== issue.subjectRef ||
result.written !== false
)
throw new Error('主体证据与当前问题不一致。')
beat.value = result
} else {
const result = preview.value ?? await preparationApi.repairPreview(id, located.shotId, controller.signal)
const result = preview.value ?? (await preparationApi.repairPreview(id, located.shotId, controller.signal))
if (current !== version) return
if (result.projectId !== id || result.shotId !== located.shotId || result.expectedFingerprint !== located.expectedFingerprint || !result.requiredActions?.length || !result.durationPlanning?.phases?.length) throw new Error('缺少当前镜头的完整动作规划,不能推测修订。')
preview.value = result; draft.value = actionDraft(result)
if (
result.projectId !== id ||
result.shotId !== located.shotId ||
result.expectedFingerprint !== located.expectedFingerprint ||
!result.requiredActions?.length ||
!result.durationPlanning?.phases?.length
)
throw new Error('缺少当前镜头的完整动作规划,不能推测修订。')
preview.value = result
draft.value = actionDraft(result)
}
} catch (cause) {
if (current === version) error.value = errorMessage(cause)
} finally {
if (current === version) loading.value = false
}
} catch (cause) { if (current === version) error.value = errorMessage(cause) }
finally { if (current === version) loading.value = false }
}
/** 用户选择明确的关联修复建议,仅改变本地草稿。 */
function adopt() {
if (!preview.value?.classification.proposed || props.disabled || writing.value) return
draft.value = actionDraft({ requiredActions: preview.value.requiredActions, durationPlanning: preview.value.classification.proposed })
draft.value = actionDraft({
requiredActions: preview.value.requiredActions,
durationPlanning: preview.value.classification.proposed
})
}
/** 显式预览正式镜头主体追加,不把段落版本当成镜头版本。 */
async function checkSubject() {
if (!target.value || !beat.value || beat.value.status === 'upstream-missing' || props.disabled || writing.value || loading.value) return
const current = version, id = props.projectId, selected = target.value
loading.value = true; error.value = ''; subjectCheck.value = null; acknowledged.value = false
if (
!target.value ||
!beat.value ||
beat.value.status === 'upstream-missing' ||
props.disabled ||
writing.value ||
loading.value
)
return
const current = version,
id = props.projectId,
selected = target.value
loading.value = true
error.value = ''
subjectCheck.value = null
acknowledged.value = false
try {
const result = await preparationApi.subjectPreview(id, { shotId: selected.shotId, subjectRef: props.issue.subjectRef!, expectedFingerprint: selected.expectedFingerprint, confirmed: true }, controller?.signal)
const result = await preparationApi.subjectPreview(
id,
{
shotId: selected.shotId,
subjectRef: props.issue.subjectRef!,
expectedFingerprint: selected.expectedFingerprint,
confirmed: true
},
controller?.signal
)
if (current !== version) return
if (result.projectId !== id || result.shotId !== selected.shotId || result.beforeFingerprint !== selected.expectedFingerprint || result.written !== false) throw new Error('主体修复预览与当前镜头不一致。')
if (
result.projectId !== id ||
result.shotId !== selected.shotId ||
result.beforeFingerprint !== selected.expectedFingerprint ||
result.written !== false
)
throw new Error('主体修复预览与当前镜头不一致。')
subjectCheck.value = result
} catch (cause) { if (current === version) error.value = errorMessage(cause) }
finally { if (current === version) loading.value = false }
} catch (cause) {
if (current === version) error.value = errorMessage(cause)
} finally {
if (current === version) loading.value = false
}
}
/** 费用确认后仅生成模型建议,服务预检未通过或版本变化均不采用。 */
async function generateCandidate() {
if (!target.value || props.disabled || loading.value || writing.value) return
const selected = target.value, current = version, id = props.projectId
writing.value = true; error.value = ''; acknowledged.value = false
const ok = await runOperation(id, '生成动作修复建议', async () => {
const selected = target.value,
current = version,
id = props.projectId
writing.value = true
error.value = ''
acknowledged.value = false
const ok = await runOperation(
id,
'生成动作修复建议',
async () => {
const result = await preparationApi.repairCandidate(id, selected.shotId, selected.expectedFingerprint)
if (current !== version) return
if (result.projectId !== id || result.shotId !== selected.shotId || result.sourceFingerprint !== selected.expectedFingerprint || result.written !== false || result.preflight.written !== false || result.preflight.readyForVersionedWrite !== true || result.preflight.beforeFingerprint !== selected.expectedFingerprint) throw new Error('修复建议未通过当前版本检查,请重新预览。')
draft.value = actionDraft(result.candidate); candidateReason.value = result.candidate.reasoning
}, { type: 'info', content: '修复建议已生成,尚未修改正式镜头,请人工核对。' })
if (current === version) { if (!ok) error.value = getOperation(id).error; writing.value = false }
if (
result.projectId !== id ||
result.shotId !== selected.shotId ||
result.sourceFingerprint !== selected.expectedFingerprint ||
result.written !== false ||
result.preflight.written !== false ||
result.preflight.readyForVersionedWrite !== true ||
result.preflight.beforeFingerprint !== selected.expectedFingerprint
)
throw new Error('修复建议未通过当前版本检查,请重新预览。')
draft.value = actionDraft(result.candidate)
candidateReason.value = result.candidate.reasoning
},
{ type: 'info', content: '修复建议已生成,尚未修改正式镜头,请人工核对。' }
)
if (current === version) {
if (!ok) error.value = getOperation(id).error
writing.value = false
}
}
/** 校验原因、确认及完整动作,保存前再次核对当前正式版本。 */
async function save() {
if (!canSave.value || !target.value) return
issueText.value = !reason.value.trim() ? '请填写修订原因。' : reason.value.trim().length > 500 ? '修订原因最多 500 字。' : !acknowledged.value ? '请先核对并确认修订内容。' : !subjectMode.value && draft.value ? actionDraftIssue(draft.value) : ''
issueText.value = !reason.value.trim()
? '请填写修订原因。'
: reason.value.trim().length > 500
? '修订原因最多 500 字。'
: !acknowledged.value
? '请先核对并确认修订内容。'
: !subjectMode.value && draft.value
? actionDraftIssue(draft.value)
: ''
if (issueText.value) return
const selected = target.value, current = version, id = props.projectId
loading.value = true; error.value = ''
const selected = target.value,
current = version,
id = props.projectId
loading.value = true
error.value = ''
try {
const latest = await preparationApi.repairPreview(id, selected.shotId, controller?.signal)
if (current !== version || props.disabled) return
if (latest.projectId !== id || latest.shotId !== selected.shotId || latest.expectedFingerprint !== selected.expectedFingerprint) {
acknowledged.value = false; throw new Error('镜头内容已变化,请重新读取并核对修订。')
if (
latest.projectId !== id ||
latest.shotId !== selected.shotId ||
latest.expectedFingerprint !== selected.expectedFingerprint
) {
acknowledged.value = false
throw new Error('镜头内容已变化,请重新读取并核对修订。')
}
loading.value = false; writing.value = true
const common = { shotId: selected.shotId, subjectRef: props.issue.subjectRef ?? '', expectedFingerprint: selected.expectedFingerprint, confirmed: true as const, reason: reason.value.trim() }
const ok = await runOperation(id, '保存正式镜头修订', async () => {
loading.value = false
writing.value = true
const common = {
shotId: selected.shotId,
subjectRef: props.issue.subjectRef ?? '',
expectedFingerprint: selected.expectedFingerprint,
confirmed: true as const,
reason: reason.value.trim()
}
const ok = await runOperation(
id,
'保存正式镜头修订',
async () => {
if (subjectMode.value && beat.value?.candidate) {
const fresh = await preparationApi.beatSubjectPreview(id, selected.shotId, common.subjectRef)
if (current !== version) return
if (!fresh.candidate || fresh.projectId !== id || fresh.shotId !== selected.shotId || fresh.subjectRef !== common.subjectRef || fresh.candidate.expectedFingerprint !== beat.value.candidate.expectedFingerprint) throw new Error('剧情段落来源已变化,请重新预览。')
const result = await preparationApi.repairBeatSubject(id, { ...common, expectedFingerprint: fresh.candidate.expectedFingerprint })
if (result.projectId !== id || result.shotId !== selected.shotId || result.beatId !== fresh.beatId || result.written !== true) throw new Error('剧情段落修订结果尚未确认,请刷新。')
if (
!fresh.candidate ||
fresh.projectId !== id ||
fresh.shotId !== selected.shotId ||
fresh.subjectRef !== common.subjectRef ||
fresh.candidate.expectedFingerprint !== beat.value.candidate.expectedFingerprint
)
throw new Error('剧情段落来源已变化,请重新预览。')
const result = await preparationApi.repairBeatSubject(id, {
...common,
expectedFingerprint: fresh.candidate.expectedFingerprint
})
if (
result.projectId !== id ||
result.shotId !== selected.shotId ||
result.beatId !== fresh.beatId ||
result.written !== true
)
throw new Error('剧情段落修订结果尚未确认,请刷新。')
} else if (subjectMode.value) {
const result = await preparationApi.repairSubject(id, common)
if (result.projectId !== id || result.shotId !== selected.shotId || result.beforeFingerprint !== selected.expectedFingerprint || result.written !== true) throw new Error('主体修订结果尚未确认,请刷新。')
if (
result.projectId !== id ||
result.shotId !== selected.shotId ||
result.beforeFingerprint !== selected.expectedFingerprint ||
result.written !== true
)
throw new Error('主体修订结果尚未确认,请刷新。')
} else {
const result = await preparationApi.repair(id, { ...actionDraft(draft.value!), shotId: selected.shotId, expectedFingerprint: selected.expectedFingerprint, confirmed: true, reason: reason.value.trim() })
if (result.projectId !== id || result.shotId !== selected.shotId || result.beforeFingerprint !== selected.expectedFingerprint || result.written !== true) throw new Error('动作修订结果尚未确认,请刷新。')
const result = await preparationApi.repair(id, {
...actionDraft(draft.value!),
shotId: selected.shotId,
expectedFingerprint: selected.expectedFingerprint,
confirmed: true,
reason: reason.value.trim()
})
if (
result.projectId !== id ||
result.shotId !== selected.shotId ||
result.beforeFingerprint !== selected.expectedFingerprint ||
result.written !== true
)
throw new Error('动作修订结果尚未确认,请刷新。')
}
}, { type: 'info', content: '修订已保存,仍需重新检查并完成人工审核。' })
},
{ type: 'info', content: '修订已保存,仍需重新检查并完成人工审核。' }
)
if (current !== version) return
if (ok) { acknowledged.value = false; emit('saved') } else error.value = getOperation(id).error
} catch (cause) { if (current === version) error.value = errorMessage(cause) }
finally { if (current === version) { loading.value = false; writing.value = false } }
if (ok) {
acknowledged.value = false
emit('saved')
} else error.value = getOperation(id).error
} catch (cause) {
if (current === version) error.value = errorMessage(cause)
} finally {
if (current === version) {
loading.value = false
writing.value = false
}
}
}
watch(writing, value => emit('busy', value), { flush: 'sync' })
watch(() => JSON.stringify([props.projectId, props.issue]), () => { reason.value = ''; issueText.value = ''; candidateReason.value = ''; void load() }, { immediate: true })
onScopeDispose(() => { version++; controller?.abort(); emit('busy', false) })
watch(
() => JSON.stringify([props.projectId, props.issue]),
() => {
reason.value = ''
issueText.value = ''
candidateReason.value = ''
void load()
},
{ immediate: true }
)
onScopeDispose(() => {
version++
controller?.abort()
emit('busy', false)
})
/** 父抽屉固定底栏调用同一个保存入口。 */
defineExpose({ save, canSave })
</script>
@@ -166,32 +387,80 @@ defineExpose({ save, canSave })
<template>
<!-- 以下是当前正式镜头问题及可取消的读取状态 -->
<div class="formal-repair-editor space-y-6">
<WorkspaceSectionHeading :title="`第 ${issue.episodeNo} 集 · 剧情段落 ${issue.beatNo} · 镜头 ${issue.shotNo ?? '待核对'}`" :description="userFacingText(issue.message)" />
<WorkspaceSectionHeading
:title="`第 ${issue.episodeNo} 集 · 剧情段落 ${issue.beatNo} · 镜头 ${issue.shotNo ?? '待核对'}`"
:description="userFacingText(issue.message)"
/>
<p v-if="loading" role="status" class="text-sm text-muted">正在核对当前正式镜头…</p>
<div v-if="error" class="problem-surface p-4 space-y-3" role="alert"><p>{{ error }}</p><NButton :disabled="writing || loading" @click="load"><template #icon><RefreshCw :size="15" /></template>重新读取</NButton></div>
<div v-if="error" class="problem-surface p-4 space-y-3" role="alert">
<p>{{ error }}</p>
<NButton :disabled="writing || loading" @click="load"
><template #icon><RefreshCw :size="15" /></template>重新读取</NButton
>
</div>
<!-- 以下是主体遗漏的段落证据,段落修订和镜头修订分开确认 -->
<section v-if="beat" class="space-y-4">
<WorkspaceSectionHeading :title="`补齐主体:${beat.subjectName}`" description="先核对剧情段落是否包含这个主体,再核对镜头引用。每次只保存当前明确的修订,不改写原始剧本。" />
<p class="text-sm leading-6">剧情段落:{{ beat.beat.description }}</p><p class="text-sm leading-6">当前镜头:{{ beat.shot.description }}</p>
<p v-if="beat.candidate" class="text-sm text-muted">本次将把 {{ beat.subjectName }} 加入当前剧情段落;完成后再单独预览镜头引用修复。</p>
<NButton v-else-if="beat.status !== 'upstream-missing'" :disabled="disabled || writing || loading" @click="checkSubject"><template #icon><Lightbulb :size="15" /></template>检查镜头主体引用</NButton>
<WorkspaceSectionHeading
:title="`补齐主体:${beat.subjectName}`"
description="先核对剧情段落是否包含这个主体,再核对镜头引用。每次只保存当前明确的修订,不改写原始剧本。"
/>
<p class="text-sm leading-6">剧情段落:{{ beat.beat.description }}</p>
<p class="text-sm leading-6">当前镜头:{{ beat.shot.description }}</p>
<p v-if="beat.candidate" class="text-sm text-muted">
本次将把 {{ beat.subjectName }} 加入当前剧情段落;完成后再单独预览镜头引用修复。
</p>
<NButton
v-else-if="beat.status !== 'upstream-missing'"
:disabled="disabled || writing || loading"
@click="checkSubject"
><template #icon><Lightbulb :size="15" /></template>检查镜头主体引用</NButton
>
<p v-else class="text-sm text-muted">当前没有符合来源要求的主体补充建议,暂不能保存。</p>
<p v-if="subjectCheck" class="text-sm text-muted">主体引用预览通过,保存时仍会重新核对内容和已有资产。</p>
</section>
<!-- 以下是当前正式动作及显式生成建议模块,读取不会调用模型 -->
<template v-if="preview && draft">
<div class="flex flex-wrap gap-3">
<NButton v-if="preview.classification.proposed" :disabled="disabled || writing" @click="adopt"><template #icon><Lightbulb :size="15" /></template>采用明确的关联修复建议</NButton>
<ConfirmAction v-if="preview.classification.status === 'needs_semantic_repair'" label="生成动作修复建议" description="会调用文字模型并产生费用,只生成当前镜头的修复建议,不保存镜头、不生成图片或视频。建议仍需人工核对。" :disabled="disabled || writing || loading" :loading="writing" @confirm="generateCandidate" />
<NButton v-if="preview.classification.proposed" :disabled="disabled || writing" @click="adopt"
><template #icon><Lightbulb :size="15" /></template>采用明确的关联修复建议</NButton
>
<ConfirmAction
v-if="preview.classification.status === 'needs_semantic_repair'"
label="生成动作修复建议"
description="会调用文字模型并产生费用,只生成当前镜头的修复建议,不保存镜头、不生成图片或视频。建议仍需人工核对。"
:disabled="disabled || writing || loading"
:loading="writing"
@confirm="generateCandidate"
/>
</div>
<p v-if="candidateReason" class="text-sm leading-6 text-muted">建议说明:{{ userFacingText(candidateReason) }}</p>
<p v-if="preview.classification.status === 'unchanged'" class="text-sm text-muted">当前动作规划没有可直接修订的确定性问题,暂不开放保存。可返回诊断列表复查当前镜头。</p>
<ShotActionEditor v-model="draft" :disabled="disabled || writing || loading || preview.classification.status === 'unchanged'" />
<p v-if="candidateReason" class="text-sm leading-6 text-muted">
建议说明:{{ userFacingText(candidateReason) }}
</p>
<p v-if="preview.classification.status === 'unchanged'" class="text-sm text-muted">
当前动作规划没有可直接修订的确定性问题,暂不开放保存。可返回诊断列表复查当前镜头。
</p>
<ShotActionEditor
v-model="draft"
:disabled="disabled || writing || loading || preview.classification.status === 'unchanged'"
/>
</template>
<!-- 以下是明确填写原因与最终核对,打开或添加字段时不自动显示错误 -->
<section v-if="target && (draft || beat)" class="space-y-4">
<NFormItem label="修订原因"><NInput v-model:value="reason" type="textarea" aria-label="修订原因" placeholder="说明如何处理这个问题,以及依据" :autosize="{ minRows: 2, maxRows: 6 }" :disabled="writing" /></NFormItem>
<NCheckbox v-model:checked="acknowledged" aria-label="确认正式镜头修订" :disabled="disabled || writing || loading">我已核对当前镜头及修订内容,保存后重新检查</NCheckbox>
<NFormItem label="修订原因"
><NInput
v-model:value="reason"
type="textarea"
aria-label="修订原因"
placeholder="说明如何处理这个问题,以及依据"
:autosize="{ minRows: 2, maxRows: 6 }"
:disabled="writing"
/></NFormItem>
<NCheckbox
v-model:checked="acknowledged"
aria-label="确认正式镜头修订"
:disabled="disabled || writing || loading"
>我已核对当前镜头及修订内容,保存后重新检查</NCheckbox
>
<p v-if="issueText" role="alert" class="text-sm text-danger">{{ issueText }}</p>
</section>
</div>
@@ -17,14 +17,21 @@ import { useStoryboardPreparation } from './useStoryboardPreparation'
import { currentStoryboardApproval } from './model'
import { preparationApi } from './api'
import type { PreparationIssue } from './types'
import { qualityPolicyConfirmed, qualityPolicySignature, validateQualityPolicyReceipt } from '../projects/quality-policy-confirmation'
import {
qualityPolicyConfirmed,
qualityPolicySignature,
validateQualityPolicyReceipt
} from '../projects/quality-policy-confirmation'
import { userFacingText } from '../../lib/user-facing-text'
/** 制作前检查统一入口,即使后续页面尚未开放也可以补齐审核。 */
const props = withDefaults(defineProps<{
const props = withDefaults(
defineProps<{
/** 当前正式项目。 */ projectId: string
/** 外部项目读取失败或主任务锁。 */ disabled?: boolean
}>(), { disabled: false })
}>(),
{ disabled: false }
)
/** 所有写入或后台终态后让调用方刷新实际导航状态。 */
const emit = defineEmits<{ changed: [] }>()
/** 全屏入口,未打开不读取完整复检。 */
@@ -38,8 +45,16 @@ const directionTask = useWorkflowExecution(watchedProject, 'storyboard-direction
/** 画面状态单独观察,不把 HTTP 受理当作完成。 */
const visualTask = useWorkflowExecution(watchedProject, 'storyboard-visual-state')
/** 活动任务及发现失败时暂停写入,不依赖本次点击的加载状态。 */
const locked = computed(() => props.disabled || getOperation(id.value).pending || hasActiveWorkflowExecution(id.value) ||
directionTask.discovering.value || visualTask.discovering.value || !!directionTask.discoveryError.value || !!visualTask.discoveryError.value)
const locked = computed(
() =>
props.disabled ||
getOperation(id.value).pending ||
hasActiveWorkflowExecution(id.value) ||
directionTask.discovering.value ||
visualTask.discovering.value ||
!!directionTask.discoveryError.value ||
!!visualTask.discoveryError.value
)
/** 复检与独立人工确认流程。 */
const flow = useStoryboardPreparation(id, locked)
/** 当前查看的正式修订目标,在同一抽屉中切换正文。 */
@@ -73,48 +88,89 @@ const checks = computed(() => {
return [
{ label: '项目质量规则已确认', passed: flow.policyConfirmed.value },
{ label: '正式分镜采用的规则来源一致', passed: data.quality.provenance.qualityPolicyConsistent === true },
{ label: '结构与镜头来源检查通过', passed: data.quality.structure.valid === true && data.quality.sourceAudit.valid === true },
{
label: '结构与镜头来源检查通过',
passed: data.quality.structure.valid === true && data.quality.sourceAudit.valid === true
},
{ label: '主体引用与动作问题已处理', passed: data.quality.preflightEligible === true },
{ label: '当前版本已完成人工审核', passed: flow.approved.value },
{ label: '可以进入制作计划', passed: data.entry.ready === true }
]
})
/** 任何规则或镜头证据变化都撤销旧勾选,不清空人工说明。 */
watch(flow.sourceKey, () => { policyAcknowledged.value = false; baselineAcknowledged.value = false; reviewAcknowledged.value = false })
watch(flow.sourceKey, () => {
policyAcknowledged.value = false
baselineAcknowledged.value = false
reviewAcknowledged.value = false
})
/** 打开时读取;关闭立即废弃旧结果及未完成只读请求。 */
watch([open, id], ([shown]) => {
watch(
[open, id],
([shown]) => {
if (shown) watchedProject.value = id.value
else if (watchedProject.value !== id.value) watchedProject.value = ''
repairIssue.value = null; actionError.value = ''
repairIssue.value = null
actionError.value = ''
if (shown) void flow.load()
else flow.cancel()
}, { flush: 'sync' })
},
{ flush: 'sync' }
)
/** 两个独立派生任务终态后重新读取真实准入。 */
for (const task of [directionTask, visualTask]) watch(() => task.query.data.value?.status, (status, before) => {
if (status !== before && ['completed', 'failed'].includes(status ?? '')) { if (open.value) void flow.load(); emit('changed') }
})
for (const task of [directionTask, visualTask])
watch(
() => task.query.data.value?.status,
(status, before) => {
if (status !== before && ['completed', 'failed'].includes(status ?? '')) {
if (open.value) void flow.load()
emit('changed')
}
}
)
/** 明确确认当前项目规则,必要时先 CAS 保存,不调用拆解或模型。 */
async function confirmPolicy() {
if (locked.value || busy.value || flow.reading.value || !policyAcknowledged.value || !flow.data.value) return
const draft = policyEditor.value?.validatedDraft()
if (!draft) return
const projectId = id.value, expected = flow.data.value.policy
actionWriting.value = true; actionError.value = ''
const ok = await runOperation(projectId, '确认项目质量规则', async () => {
const projectId = id.value,
expected = flow.data.value.policy
actionWriting.value = true
actionError.value = ''
const ok = await runOperation(
projectId,
'确认项目质量规则',
async () => {
let current = validateQualityPolicyReceipt(await projectsApi.qualityPolicy(projectId), projectId)
if (id.value !== projectId || !open.value) throw new Error('项目或确认页面已变化,请重新核对。')
if (current.revision !== expected.revision || current.fingerprint !== expected.fingerprint) throw new Error('质量规则已变化,请刷新后重新核对。')
if (qualityPolicySignature(draft) !== qualityPolicySignature(current.policy)) current = validateQualityPolicyReceipt(await projectsApi.saveQualityPolicy(projectId, draft, current.revision), projectId)
if (qualityPolicySignature(current.policy) !== qualityPolicySignature(draft)) throw new Error('规则保存内容尚未确认,请重新核对。')
if (current.revision !== expected.revision || current.fingerprint !== expected.fingerprint)
throw new Error('质量规则已变化,请刷新后重新核对。')
if (qualityPolicySignature(draft) !== qualityPolicySignature(current.policy))
current = validateQualityPolicyReceipt(
await projectsApi.saveQualityPolicy(projectId, draft, current.revision),
projectId
)
if (qualityPolicySignature(current.policy) !== qualityPolicySignature(draft))
throw new Error('规则保存内容尚未确认,请重新核对。')
if (id.value !== projectId || !open.value) throw new Error('项目或确认页面已变化,请重新核对。')
const result = validateQualityPolicyReceipt(await projectsApi.confirmQualityPolicy(projectId, current.revision), projectId)
if (!qualityPolicyConfirmed(result) || result.revision !== current.revision || result.fingerprint !== current.fingerprint) throw new Error('规则确认结果不一致,请刷新。')
}, { type: 'info', content: '项目质量规则已确认,还需核对正式分镜的来源和质量。' })
const result = validateQualityPolicyReceipt(
await projectsApi.confirmQualityPolicy(projectId, current.revision),
projectId
)
if (
!qualityPolicyConfirmed(result) ||
result.revision !== current.revision ||
result.fingerprint !== current.fingerprint
)
throw new Error('规则确认结果不一致,请刷新。')
},
{ type: 'info', content: '项目质量规则已确认,还需核对正式分镜的来源和质量。' }
)
actionWriting.value = false
if (id.value !== projectId) return
if (!ok) actionError.value = getOperation(projectId).error
await flow.load(); emit('changed')
await flow.load()
emit('changed')
}
/**
* 保存用户当前明确选择的审核记录,两种确认不能互相替代。
@@ -130,61 +186,325 @@ async function confirmReview(kind: 'baseline' | 'approval') {
*/
async function generate(kind: 'direction' | 'visual') {
if (locked.value || busy.value || flow.reading.value || !flow.approved.value || !flow.data.value) return
const projectId = id.value, expected = flow.data.value.approval.evidence
actionWriting.value = true; actionError.value = ''
const ok = await runOperation(projectId, kind === 'direction' ? '补齐镜头设计' : '补齐画面状态', async () => {
const projectId = id.value,
expected = flow.data.value.approval.evidence
actionWriting.value = true
actionError.value = ''
const ok = await runOperation(
projectId,
kind === 'direction' ? '补齐镜头设计' : '补齐画面状态',
async () => {
const latest = await preparationApi.approval(projectId)
if (id.value !== projectId || !open.value) return
if (!currentStoryboardApproval(latest, projectId) || latest.evidence.shotFingerprint !== expected.shotFingerprint || latest.evidence.checkpointId !== expected.checkpointId || latest.evidence.qualityPolicyRevision !== expected.qualityPolicyRevision || latest.evidence.qualityPolicyFingerprint !== expected.qualityPolicyFingerprint) throw new Error('正式分镜审核已变化,请重新检查并确认。')
const result = kind === 'direction' ? await storyboardApi.generateDirections(projectId, { concurrency: 2, force: false }) : await storyboardApi.generateVisualStates(projectId, { concurrency: 2, force: false, maxRepairAttempts: 2 })
if (
!currentStoryboardApproval(latest, projectId) ||
latest.evidence.shotFingerprint !== expected.shotFingerprint ||
latest.evidence.checkpointId !== expected.checkpointId ||
latest.evidence.qualityPolicyRevision !== expected.qualityPolicyRevision ||
latest.evidence.qualityPolicyFingerprint !== expected.qualityPolicyFingerprint
)
throw new Error('正式分镜审核已变化,请重新检查并确认。')
const result =
kind === 'direction'
? await storyboardApi.generateDirections(projectId, { concurrency: 2, force: false })
: await storyboardApi.generateVisualStates(projectId, {
concurrency: 2,
force: false,
maxRepairAttempts: 2
})
if (!result.executionId) throw new Error('未取得任务编号,请刷新状态,避免重复提交。')
await (kind === 'direction' ? directionTask : visualTask).track(result.executionId, projectId)
}, { type: 'info', content: '设计任务已受理,请等待实际结果;已有当前有效设计会跳过。' })
},
{ type: 'info', content: '设计任务已受理,请等待实际结果;已有当前有效设计会跳过。' }
)
actionWriting.value = false
if (id.value === projectId && !ok) actionError.value = getOperation(projectId).error
}
/** 正式保存后返回全局复检,不把局部修复当作整体通过。 */
async function repaired() { repairIssue.value = null; repairWriting.value = false; await flow.load(); emit('changed') }
async function repaired() {
repairIssue.value = null
repairWriting.value = false
await flow.load()
emit('changed')
}
</script>
<template>
<!-- 以下是项目顶部始终可到达的制作前检查入口及统一悬浮说明 -->
<WorkspaceActionTooltip label="制作前检查" mobile-only>
<NButton size="small" class="preparation-trigger workspace-action-button" :disabled="disabled || !projectId" aria-label="制作前检查" @click="open = true"><template #icon><ShieldCheck :size="15" aria-hidden="true" /></template><span class="preparation-trigger-label">制作前检查</span></NButton>
<NButton
size="small"
class="preparation-trigger workspace-action-button"
:disabled="disabled || !projectId"
aria-label="制作前检查"
@click="open = true"
><template #icon><ShieldCheck :size="15" aria-hidden="true" /></template
><span class="preparation-trigger-label">制作前检查</span></NButton
>
</WorkspaceActionTooltip>
<AppDrawer v-model:open="open" :title="repairIssue ? '修订正式分镜问题' : '制作前检查'" :busy="busy" description="先核对分镜、处理问题并完成人工审核,再补齐设计和进入镜头制作。">
<AppDrawer
v-model:open="open"
:title="repairIssue ? '修订正式分镜问题' : '制作前检查'"
:busy="busy"
description="先核对分镜、处理问题并完成人工审核,再补齐设计和进入镜头制作。"
>
<!-- 以下是在同一抽屉内查看当前正式镜头的修订模块 -->
<FormalRepairEditor v-if="open && repairIssue" ref="repairEditor" :project-id="projectId" :issue="repairIssue" :disabled="locked" @busy="repairWriting = $event" @saved="repaired" />
<FormalRepairEditor
v-if="open && repairIssue"
ref="repairEditor"
:project-id="projectId"
:issue="repairIssue"
:disabled="locked"
@busy="repairWriting = $event"
@saved="repaired"
/>
<div v-else-if="open" class="preparation-content space-y-6">
<div class="flex flex-wrap items-center justify-between gap-3"><span class="text-sm text-muted">检查只读取已有数据;确认、修订和生成均需单独操作。</span><NButton :loading="flow.reading.value" :disabled="busy" @click="flow.load"><template #icon><RefreshCw :size="15" /></template>刷新检查</NButton></div>
<p v-if="flow.reading.value && !flow.data.value" role="status" class="text-sm text-muted">正在检查当前正式分镜…</p>
<p v-if="flow.error.value || actionError" role="alert" class="problem-surface p-4 text-sm">{{ flow.error.value || actionError }}</p>
<div class="flex flex-wrap items-center justify-between gap-3">
<span class="text-sm text-muted">检查只读取已有数据;确认、修订和生成均需单独操作。</span
><NButton :loading="flow.reading.value" :disabled="busy" @click="flow.load"
><template #icon><RefreshCw :size="15" /></template>刷新检查</NButton
>
</div>
<p v-if="flow.reading.value && !flow.data.value" role="status" class="text-sm text-muted">
正在检查当前正式分镜…
</p>
<p v-if="flow.error.value || actionError" role="alert" class="problem-surface p-4 text-sm">
{{ flow.error.value || actionError }}
</p>
<p v-if="flow.notice.value" role="status" class="text-sm text-muted">{{ flow.notice.value }}</p>
<template v-if="flow.data.value">
<!-- 以下是分项检查,未知或未通过不伪装成成功 -->
<section class="space-y-4"><WorkspaceSectionHeading title="当前准备情况" description="结构通过、局部修订完成和整体审核是不同步骤。" /><div class="preparation-checks"><div v-for="check in checks" :key="check.label" class="flex items-center justify-between gap-4 text-sm"><span>{{ check.label }}</span><NTag :type="check.passed ? 'success' : 'default'" size="small" :bordered="false">{{ check.passed ? '已满足' : '待完成' }}</NTag></div></div></section>
<section class="space-y-4">
<WorkspaceSectionHeading
title="当前准备情况"
description="结构通过、局部修订完成和整体审核是不同步骤。"
/>
<div class="preparation-checks">
<div
v-for="check in checks"
:key="check.label"
class="flex items-center justify-between gap-4 text-sm"
>
<span>{{ check.label }}</span
><NTag :type="check.passed ? 'success' : 'default'" size="small" :bordered="false">{{
check.passed ? '已满足' : '待完成'
}}</NTag>
</div>
</div>
</section>
<!-- 以下是第一次明确确认规则,不显示空白精确例外 -->
<section v-if="!flow.policyConfirmed.value" class="space-y-4"><WorkspaceSectionHeading title="核对项目质量规则" description="确认故事允许哪些动作;已有精确例外会继续保留。" /><QualityPolicySettings ref="policyEditor" :key="flow.data.value.policy.revision" :project-id="projectId" :initial-policy="flow.data.value.policy" :disabled="locked || busy" /><NCheckbox v-model:checked="policyAcknowledged" :disabled="locked || busy">我已核对当前项目质量规则</NCheckbox><NButton type="primary" :disabled="!policyAcknowledged || locked || busy || flow.reading.value" :loading="actionWriting" @click="confirmPolicy"><template #icon><ShieldCheck :size="15" /></template>确认项目质量规则</NButton></section>
<section v-if="!flow.policyConfirmed.value" class="space-y-4">
<WorkspaceSectionHeading
title="核对项目质量规则"
description="确认故事允许哪些动作;已有精确例外会继续保留。"
/><QualityPolicySettings
ref="policyEditor"
:key="flow.data.value.policy.revision"
:project-id="projectId"
:initial-policy="flow.data.value.policy"
:disabled="locked || busy"
/><NCheckbox v-model:checked="policyAcknowledged" :disabled="locked || busy"
>我已核对当前项目质量规则</NCheckbox
><NButton
type="primary"
:disabled="!policyAcknowledged || locked || busy || flow.reading.value"
:loading="actionWriting"
@click="confirmPolicy"
><template #icon><ShieldCheck :size="15" /></template>确认项目质量规则</NButton
>
</section>
<!-- 以下是旧分镜缺少规则记录时的明确重新核对,不重跑拆解 -->
<section v-if="!flow.data.value.quality.provenance.qualityPolicyConsistent" class="space-y-4"><WorkspaceSectionHeading title="核对旧分镜采用的规则" description="旧分镜没有完整规则记录时,由复核人明确采用当前已确认规则重新检查。不会重写历史记录,也不会重新拆解。" /><p v-for="reason in flow.data.value.baseline.reasons" :key="reason" class="text-sm text-muted">{{ userFacingText(reason) }}</p><template v-if="flow.baselineAllowed.value"><NFormItem label="复核人"><NInput aria-label="来源复核人" v-model:value="reviewer" placeholder="填写实际复核人" /></NFormItem><NFormItem label="核对说明"><NInput aria-label="来源核对说明" v-model:value="reviewNote" type="textarea" placeholder="说明核对范围及采用当前规则的依据" /></NFormItem><NCheckbox v-model:checked="baselineAcknowledged" :disabled="locked || busy">我已核对旧分镜,明确采用当前规则继续复检</NCheckbox><NButton type="primary" :disabled="!baselineAcknowledged || locked || busy || flow.reading.value" @click="confirmReview('baseline')">确认规则来源</NButton></template></section>
<section v-if="!flow.data.value.quality.provenance.qualityPolicyConsistent" class="space-y-4">
<WorkspaceSectionHeading
title="核对旧分镜采用的规则"
description="旧分镜没有完整规则记录时,由复核人明确采用当前已确认规则重新检查。不会重写历史记录,也不会重新拆解。"
/>
<p v-for="reason in flow.data.value.baseline.reasons" :key="reason" class="text-sm text-muted">
{{ userFacingText(reason) }}
</p>
<template v-if="flow.baselineAllowed.value"
><NFormItem label="复核人"
><NInput
aria-label="来源复核人"
v-model:value="reviewer"
placeholder="填写实际复核人" /></NFormItem
><NFormItem label="核对说明"
><NInput
aria-label="来源核对说明"
v-model:value="reviewNote"
type="textarea"
placeholder="说明核对范围及采用当前规则的依据" /></NFormItem
><NCheckbox v-model:checked="baselineAcknowledged" :disabled="locked || busy"
>我已核对旧分镜,明确采用当前规则继续复检</NCheckbox
><NButton
type="primary"
:disabled="!baselineAcknowledged || locked || busy || flow.reading.value"
@click="confirmReview('baseline')"
>确认规则来源</NButton
></template
>
</section>
<!-- 以下是正式主体、动作及来源问题,局部修订独立确认 -->
<section class="space-y-4"><WorkspaceSectionHeading title="处理正式分镜问题" description="只修订明确的问题镜头。涉及规则来源或现有素材保护时,先处理对应限制。" /><p v-if="!flow.issues.value.length" class="text-sm text-muted">当前未返回具体镜头问题,请继续核对上面的来源条件和人工审核。</p><article v-for="(item, index) in flow.issues.value" :key="`${item.kind}-${index}`" class="problem-surface p-4 space-y-3"><p class="text-xs text-muted">第 {{ item.episodeNo }} 集 · 剧情段落 {{ item.beatNo }} · 镜头 {{ item.shotNo ?? '待核对' }}</p><p class="text-sm leading-6">{{ userFacingText(item.message) }}</p><NButton class="workspace-action-button" v-if="item.kind !== 'source' && item.shotNo" :disabled="locked || busy || flow.reading.value" @click="repairIssue = item"><template #icon><Wrench :size="15" /></template>查看并修订</NButton></article></section>
<section class="space-y-4">
<WorkspaceSectionHeading
title="处理正式分镜问题"
description="只修订明确的问题镜头。涉及规则来源或现有素材保护时,先处理对应限制。"
/>
<p v-if="!flow.issues.value.length" class="text-sm text-muted">
当前未返回具体镜头问题,请继续核对上面的来源条件和人工审核。
</p>
<article
v-for="(item, index) in flow.issues.value"
:key="`${item.kind}-${index}`"
class="problem-surface p-4 space-y-3"
>
<p class="text-xs text-muted">
第 {{ item.episodeNo }} 集 · 剧情段落 {{ item.beatNo }} · 镜头 {{ item.shotNo ?? '待核对' }}
</p>
<p class="text-sm leading-6">{{ userFacingText(item.message) }}</p>
<NButton
class="workspace-action-button"
v-if="item.kind !== 'source' && item.shotNo"
:disabled="locked || busy || flow.reading.value"
@click="repairIssue = item"
><template #icon><Wrench :size="15" /></template>查看并修订</NButton
>
</article>
</section>
<!-- 以下是正式整体人工审核,不以只读预检或旧记录代替 -->
<section class="space-y-4"><WorkspaceSectionHeading title="人工确认整体分镜" description="检查通过后,由复核人核对动作、主体及镜头衔接。规则或镜头变化后原审核会失效。" /><p v-if="flow.approved.value" class="text-sm text-muted">当前正式分镜已有有效审核记录。</p><p v-else-if="!flow.reviewable.value" class="text-sm text-muted">请先处理规则来源、动作与主体问题,再进行整体审核。</p><template v-else><NFormItem label="审核人"><NInput aria-label="整体审核人" v-model:value="reviewer" placeholder="填写实际审核人" /></NFormItem><NFormItem label="审核说明"><NInput aria-label="整体审核说明" v-model:value="reviewNote" type="textarea" placeholder="说明已核对的动作、主体、画面衔接及结论" /></NFormItem><NCheckbox v-model:checked="reviewAcknowledged" :disabled="locked || busy">我已人工核对当前版本的全部正式分镜</NCheckbox><NButton type="primary" :disabled="!reviewAcknowledged || locked || busy || flow.reading.value" @click="confirmReview('approval')"><template #icon><CheckCheck :size="15" /></template>确认整体审核</NButton></template></section>
<section class="space-y-4">
<WorkspaceSectionHeading
title="人工确认整体分镜"
description="检查通过后,由复核人核对动作、主体及镜头衔接。规则或镜头变化后原审核会失效。"
/>
<p v-if="flow.approved.value" class="text-sm text-muted">当前正式分镜已有有效审核记录。</p>
<p v-else-if="!flow.reviewable.value" class="text-sm text-muted">
请先处理规则来源、动作与主体问题,再进行整体审核。
</p>
<template v-else
><NFormItem label="审核人"
><NInput
aria-label="整体审核人"
v-model:value="reviewer"
placeholder="填写实际审核人" /></NFormItem
><NFormItem label="审核说明"
><NInput
aria-label="整体审核说明"
v-model:value="reviewNote"
type="textarea"
placeholder="说明已核对的动作、主体、画面衔接及结论" /></NFormItem
><NCheckbox v-model:checked="reviewAcknowledged" :disabled="locked || busy"
>我已人工核对当前版本的全部正式分镜</NCheckbox
><NButton
type="primary"
:disabled="!reviewAcknowledged || locked || busy || flow.reading.value"
@click="confirmReview('approval')"
><template #icon><CheckCheck :size="15" /></template>确认整体审核</NButton
></template
>
</section>
<!-- 以下是审核之后的设计补齐与真实生产入口状态 -->
<section class="space-y-4"><WorkspaceSectionHeading title="补齐镜头设计与画面状态" description="先更新镜头设计,再更新画面状态。只补齐缺失或过期结果,生成可能产生模型费用。" /><p class="text-sm text-muted">已保存镜头设计 {{ flow.data.value.entry.derivedAssets.directionCount }} / {{ flow.data.value.entry.derivedAssets.shotCount }} · 画面状态 {{ flow.data.value.entry.derivedAssets.visualStateCount }} / {{ flow.data.value.entry.derivedAssets.shotCount }}</p><div class="flex flex-wrap gap-3"><ConfirmAction label="补齐或更新镜头设计" description="处理整个项目中缺失或过期的镜头设计,已有当前有效结果会跳过。会调用文字模型并产生费用,不生成图片或视频。" :disabled="!flow.approved.value || flow.data.value.entry.ready || locked || busy || flow.reading.value" @confirm="generate('direction')" /><ConfirmAction label="补齐或更新画面状态" description="根据正式镜头和最新镜头设计处理整个项目的画面状态,已有当前有效结果会跳过。会调用文字模型并可能进行最多两次修复,可能产生费用。" :disabled="!flow.approved.value || flow.data.value.entry.ready || locked || busy || flow.reading.value || flow.data.value.entry.derivedAssets.directionCount !== flow.data.value.entry.derivedAssets.shotCount" @confirm="generate('visual')" /></div><p class="text-sm" :class="flow.data.value.entry.ready ? 'text-muted' : 'text-danger'">{{ flow.data.value.entry.ready ? '正式分镜已满足制作入口条件。制作计划还会继续检查主体素材和镜头资产。' : userFacingText(flow.data.value.entry.reason, '制作入口尚未满足条件。') }}</p></section>
<section class="space-y-4">
<WorkspaceSectionHeading
title="补齐镜头设计与画面状态"
description="先更新镜头设计,再更新画面状态。只补齐缺失或过期结果,生成可能产生模型费用。"
/>
<p class="text-sm text-muted">
已保存镜头设计 {{ flow.data.value.entry.derivedAssets.directionCount }} /
{{ flow.data.value.entry.derivedAssets.shotCount }} · 画面状态
{{ flow.data.value.entry.derivedAssets.visualStateCount }} /
{{ flow.data.value.entry.derivedAssets.shotCount }}
</p>
<div class="flex flex-wrap gap-3">
<ConfirmAction
label="补齐或更新镜头设计"
description="处理整个项目中缺失或过期的镜头设计,已有当前有效结果会跳过。会调用文字模型并产生费用,不生成图片或视频。"
:disabled="
!flow.approved.value ||
flow.data.value.entry.ready ||
locked ||
busy ||
flow.reading.value
"
@confirm="generate('direction')"
/><ConfirmAction
label="补齐或更新画面状态"
description="根据正式镜头和最新镜头设计处理整个项目的画面状态,已有当前有效结果会跳过。会调用文字模型并可能进行最多两次修复,可能产生费用。"
:disabled="
!flow.approved.value ||
flow.data.value.entry.ready ||
locked ||
busy ||
flow.reading.value ||
flow.data.value.entry.derivedAssets.directionCount !==
flow.data.value.entry.derivedAssets.shotCount
"
@confirm="generate('visual')"
/>
</div>
<p class="text-sm" :class="flow.data.value.entry.ready ? 'text-muted' : 'text-danger'">
{{
flow.data.value.entry.ready
? '正式分镜已满足制作入口条件。制作计划还会继续检查主体素材和镜头资产。'
: userFacingText(flow.data.value.entry.reason, '制作入口尚未满足条件。')
}}
</p>
</section>
</template>
<!-- 以下是服务持久化的派生任务,关闭抽屉后仍可观察 -->
<WorkflowExecutionPanel v-if="directionTask.executionId.value" title="镜头设计任务" :execution="directionTask.query.data.value ?? null" :loading="directionTask.query.loading.value" :error="directionTask.query.error.value ?? ''" @refresh="directionTask.query.refresh()" @dismiss="directionTask.dismiss()" />
<WorkflowExecutionPanel v-if="visualTask.executionId.value" title="画面状态任务" :execution="visualTask.query.data.value ?? null" :loading="visualTask.query.loading.value" :error="visualTask.query.error.value ?? ''" @refresh="visualTask.query.refresh()" @dismiss="visualTask.dismiss()" />
<WorkflowExecutionPanel
v-if="directionTask.executionId.value"
title="镜头设计任务"
:execution="directionTask.query.data.value ?? null"
:loading="directionTask.query.loading.value"
:error="directionTask.query.error.value ?? ''"
@refresh="directionTask.query.refresh()"
@dismiss="directionTask.dismiss()"
/>
<WorkflowExecutionPanel
v-if="visualTask.executionId.value"
title="画面状态任务"
:execution="visualTask.query.data.value ?? null"
:loading="visualTask.query.loading.value"
:error="visualTask.query.error.value ?? ''"
@refresh="visualTask.query.refresh()"
@dismiss="visualTask.dismiss()"
/>
</div>
<template #footer><NButton :disabled="busy" @click="open = false">关闭</NButton><template v-if="repairIssue"><NButton :disabled="busy" @click="repairIssue = null"><template #icon><ArrowLeft :size="15" /></template>返回检查</NButton><NButton type="primary" :loading="repairWriting" :disabled="!repairEditor?.canSave || busy || locked" @click="repairEditor?.save()"><template #icon><Save :size="15" /></template>保存本次修订</NButton></template></template>
<template #footer
><NButton :disabled="busy" @click="open = false">关闭</NButton
><template v-if="repairIssue"
><NButton :disabled="busy" @click="repairIssue = null"
><template #icon><ArrowLeft :size="15" /></template>返回检查</NButton
><NButton
type="primary"
:loading="repairWriting"
:disabled="!repairEditor?.canSave || busy || locked"
@click="repairEditor?.save()"
><template #icon><Save :size="15" /></template>保存本次修订</NButton
></template
></template
>
</AppDrawer>
</template>
<style scoped>
.preparation-checks { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px 40px; }
.preparation-checks > div { min-width: 0; }
@media (max-width: 760px) { .preparation-checks { grid-template-columns: minmax(0, 1fr); } }
@media (max-width: 639px) { .preparation-trigger-label { display: none; } }
.preparation-checks {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px 40px;
}
.preparation-checks > div {
min-width: 0;
}
@media (max-width: 760px) {
.preparation-checks {
grid-template-columns: minmax(0, 1fr);
}
}
@media (max-width: 639px) {
.preparation-trigger-label {
display: none;
}
}
</style>
+117 -25
View File
@@ -2,14 +2,31 @@ import { storyboardApi } from '../storyboard/api'
import { request } from '../../lib/http'
import type { DiagnosisLocation } from '../breakdown/diagnosis'
import type { StoryboardHandRepairHistory } from '../breakdown/types'
import type { StoryboardRecheck, ReviewBaselinePreview, StoryboardApproval, StoryboardApprovalState, StoryboardReviewInput, ProductionEntryReadiness, LocatedStoryboardShot, FormalShotRepairPreview, FormalRepairCandidate, FormalRepairInput, FormalRepairResult, BeatSubjectPreview, BeatSubjectRepairResult, SubjectRepairInput } from './types'
import type {
StoryboardRecheck,
ReviewBaselinePreview,
StoryboardApproval,
StoryboardApprovalState,
StoryboardReviewInput,
ProductionEntryReadiness,
LocatedStoryboardShot,
FormalShotRepairPreview,
FormalRepairCandidate,
FormalRepairInput,
FormalRepairResult,
BeatSubjectPreview,
BeatSubjectRepairResult,
SubjectRepairInput
} from './types'
/**
* 所有制作前检查都绑定正式项目。
* @param id 正式项目编号
* @returns 编码后的项目路径
*/
function root(id: string): string { return `/projects/${encodeURIComponent(id)}` }
function root(id: string): string {
return `/projects/${encodeURIComponent(id)}`
}
/** 正式分镜审核、版本化修复和制作入口,不使用测试路由。 */
export const preparationApi = {
/**
@@ -18,42 +35,51 @@ export const preparationApi = {
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
recheck: (id: string, signal?: AbortSignal) => request<StoryboardRecheck>(`${root(id)}/breakdown/storyboard-quality-recheck`, { signal }),
recheck: (id: string, signal?: AbortSignal) =>
request<StoryboardRecheck>(`${root(id)}/breakdown/storyboard-quality-recheck`, { signal }),
/**
* 读取旧分镜规则来源的确认条件。
* @param id 当前项目编号
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
baseline: (id: string, signal?: AbortSignal) => request<ReviewBaselinePreview>(`${root(id)}/breakdown/storyboard-review-baseline/preview`, { signal }),
baseline: (id: string, signal?: AbortSignal) =>
request<ReviewBaselinePreview>(`${root(id)}/breakdown/storyboard-review-baseline/preview`, { signal }),
/**
* 明确确认历史规则来源,不改写历史拆解。
* @param id 当前项目编号
* @param input 人工核对内容与原始版本
* @returns 正式接口的实际业务回执
*/
confirmBaseline: (id: string, input: StoryboardReviewInput) => request<StoryboardApproval>(`${root(id)}/breakdown/storyboard-review-baseline/confirm`, { method: 'POST', body: input }),
confirmBaseline: (id: string, input: StoryboardReviewInput) =>
request<StoryboardApproval>(`${root(id)}/breakdown/storyboard-review-baseline/confirm`, {
method: 'POST',
body: input
}),
/**
* 读取人工审核凭据及当前内容证据。
* @param id 当前项目编号
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
approval: (id: string, signal?: AbortSignal) => request<StoryboardApprovalState>(`${root(id)}/storyboard/quality-confirmation`, { signal }),
approval: (id: string, signal?: AbortSignal) =>
request<StoryboardApprovalState>(`${root(id)}/storyboard/quality-confirmation`, { signal }),
/**
* 明确确认当前分镜的整体审核。
* @param id 当前项目编号
* @param input 人工审核内容与原始版本
* @returns 正式接口的实际业务回执
*/
confirmApproval: (id: string, input: StoryboardReviewInput) => request<StoryboardApproval>(`${root(id)}/storyboard/quality-confirmation`, { method: 'POST', body: input }),
confirmApproval: (id: string, input: StoryboardReviewInput) =>
request<StoryboardApproval>(`${root(id)}/storyboard/quality-confirmation`, { method: 'POST', body: input }),
/**
* 只读制作入口结论,必须在制作计划前核对。
* @param id 当前项目编号
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
entry: (id: string, signal?: AbortSignal) => request<ProductionEntryReadiness>(`${root(id)}/production/entry-readiness`, { signal }),
entry: (id: string, signal?: AbortSignal) =>
request<ProductionEntryReadiness>(`${root(id)}/production/entry-readiness`, { signal }),
/**
* 通过精确坐标获得正式镜头和内容版本。
* @param id 当前项目编号
@@ -61,7 +87,11 @@ export const preparationApi = {
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
locate: (id: string, target: Required<DiagnosisLocation>, signal?: AbortSignal) => request<LocatedStoryboardShot>(`${root(id)}/breakdown/storyboard-shots/locate?${new URLSearchParams({ episodeNo: String(target.episodeNo), beatNo: String(target.beatNo), shotNo: String(target.shotNo) })}`, { signal }),
locate: (id: string, target: Required<DiagnosisLocation>, signal?: AbortSignal) =>
request<LocatedStoryboardShot>(
`${root(id)}/breakdown/storyboard-shots/locate?${new URLSearchParams({ episodeNo: String(target.episodeNo), beatNo: String(target.beatNo), shotNo: String(target.shotNo) })}`,
{ signal }
),
/**
* 读取当前正式镜头可编辑动作和确定性建议。
* @param id 当前项目编号
@@ -69,7 +99,11 @@ export const preparationApi = {
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
repairPreview: (id: string, shotId: string, signal?: AbortSignal) => request<FormalShotRepairPreview>(`${root(id)}/breakdown/storyboard-shot-repair/preview/${encodeURIComponent(shotId)}`, { signal }),
repairPreview: (id: string, shotId: string, signal?: AbortSignal) =>
request<FormalShotRepairPreview>(
`${root(id)}/breakdown/storyboard-shot-repair/preview/${encodeURIComponent(shotId)}`,
{ signal }
),
/**
* 用户确认费用后才调用文字模型生成建议,不保存镜头。
* @param id 当前项目编号
@@ -77,14 +111,20 @@ export const preparationApi = {
* @param expectedFingerprint 已核对的原始镜头内容
* @returns 正式接口的实际业务回执
*/
repairCandidate: (id: string, shotId: string, expectedFingerprint: string) => request<FormalRepairCandidate>(`${root(id)}/breakdown/storyboard-shot-repair/candidate`, { method: 'POST', body: { shotId, expectedFingerprint }, timeoutMs: 0 }),
repairCandidate: (id: string, shotId: string, expectedFingerprint: string) =>
request<FormalRepairCandidate>(`${root(id)}/breakdown/storyboard-shot-repair/candidate`, {
method: 'POST',
body: { shotId, expectedFingerprint },
timeoutMs: 0
}),
/**
* 明确保存动作,事务内继续检查来源、资产和任务。
* @param id 当前项目编号
* @param input 明确确认的动作修订与原始版本
* @returns 正式接口的实际业务回执
*/
repair: (id: string, input: FormalRepairInput) => request<FormalRepairResult>(`${root(id)}/breakdown/storyboard-shot-repair`, { method: 'POST', body: input }),
repair: (id: string, input: FormalRepairInput) =>
request<FormalRepairResult>(`${root(id)}/breakdown/storyboard-shot-repair`, { method: 'POST', body: input }),
/**
* 按需读取不可变正式修订历史。
* @param id 当前项目编号
@@ -92,7 +132,11 @@ export const preparationApi = {
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
revisions: (id: string, shotId: string, signal?: AbortSignal) => request<StoryboardHandRepairHistory>(`${root(id)}/breakdown/storyboard-shot-revision-history/${encodeURIComponent(shotId)}`, { signal }),
revisions: (id: string, shotId: string, signal?: AbortSignal) =>
request<StoryboardHandRepairHistory>(
`${root(id)}/breakdown/storyboard-shot-revision-history/${encodeURIComponent(shotId)}`,
{ signal }
),
/**
* 只读核对缺失主体的上游段落和当前镜头证据。
* @param id 当前项目编号
@@ -101,14 +145,23 @@ export const preparationApi = {
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
beatSubjectPreview: (id: string, shotId: string, subjectRef: string, signal?: AbortSignal) => request<BeatSubjectPreview>(`${root(id)}/breakdown/storyboard-beat-subject-repair/preview`, { method: 'POST', body: { shotId, subjectRef }, signal }),
beatSubjectPreview: (id: string, shotId: string, subjectRef: string, signal?: AbortSignal) =>
request<BeatSubjectPreview>(`${root(id)}/breakdown/storyboard-beat-subject-repair/preview`, {
method: 'POST',
body: { shotId, subjectRef },
signal
}),
/**
* 用户确认后按段落内容版本追加主体。
* @param id 当前项目编号
* @param input 明确确认的段落主体修订与段落版本
* @returns 正式接口的实际业务回执
*/
repairBeatSubject: (id: string, input: SubjectRepairInput) => request<BeatSubjectRepairResult>(`${root(id)}/breakdown/storyboard-beat-subject-repair`, { method: 'POST', body: input }),
repairBeatSubject: (id: string, input: SubjectRepairInput) =>
request<BeatSubjectRepairResult>(`${root(id)}/breakdown/storyboard-beat-subject-repair`, {
method: 'POST',
body: input
}),
/**
* 只读核对当前镜头主体追加,前置段落证据须已完整。
* @param id 当前项目编号
@@ -116,14 +169,28 @@ export const preparationApi = {
* @param signal 取消旧查询
* @returns 正式接口的实际业务回执
*/
subjectPreview: (id: string, input: SubjectRepairInput, signal?: AbortSignal) => request<FormalRepairResult>(`${root(id)}/breakdown/storyboard-shot-subject-repair/preview`, { method: 'POST', body: { shotId: input.shotId, subjectRef: input.subjectRef, expectedFingerprint: input.expectedFingerprint, confirmed: true }, signal }),
subjectPreview: (id: string, input: SubjectRepairInput, signal?: AbortSignal) =>
request<FormalRepairResult>(`${root(id)}/breakdown/storyboard-shot-subject-repair/preview`, {
method: 'POST',
body: {
shotId: input.shotId,
subjectRef: input.subjectRef,
expectedFingerprint: input.expectedFingerprint,
confirmed: true
},
signal
}),
/**
* 用户确认后按镜头内容版本追加已有主体。
* @param id 当前项目编号
* @param input 明确确认的镜头主体修订与镜头版本
* @returns 正式接口的实际业务回执
*/
repairSubject: (id: string, input: SubjectRepairInput) => request<FormalRepairResult>(`${root(id)}/breakdown/storyboard-shot-subject-repair`, { method: 'POST', body: input })
repairSubject: (id: string, input: SubjectRepairInput) =>
request<FormalRepairResult>(`${root(id)}/breakdown/storyboard-shot-subject-repair`, {
method: 'POST',
body: input
})
}
/**
@@ -133,15 +200,40 @@ export const preparationApi = {
* @param expectedShotCount 入口统计的正式镜头数
* @returns 当前版本检查完成,缺失或过期时抛出可操作错误
*/
export async function assertCurrentStoryboardDesigns(projectId: string, episodeNos: number[], expectedShotCount: number): Promise<void> {
export async function assertCurrentStoryboardDesigns(
projectId: string,
episodeNos: number[],
expectedShotCount: number
): Promise<void> {
const numbers = [...new Set(episodeNos)]
if (!numbers.length || !Number.isSafeInteger(expectedShotCount) || expectedShotCount <= 0) throw new Error('正式镜头范围尚未确认,请刷新制作前检查。')
const records = await Promise.all(numbers.map(async episodeNo => {
const [direction, visual] = await Promise.all([storyboardApi.directions(projectId, episodeNo), storyboardApi.visualStates(projectId, episodeNo)])
if (direction.projectId !== projectId || visual.projectId !== projectId || direction.episodeNo !== episodeNo || visual.episodeNo !== episodeNo) throw new Error('设计检查结果与当前项目或剧集不一致。')
if (direction.staleCount !== 0 || visual.staleCount !== 0 || direction.shotCount !== direction.directionCount || visual.shotCount !== visual.visualStateCount || direction.coverage !== 1 || visual.coverage !== 1 || direction.shotCount !== visual.shotCount)
if (!numbers.length || !Number.isSafeInteger(expectedShotCount) || expectedShotCount <= 0)
throw new Error('正式镜头范围尚未确认,请刷新制作前检查。')
const records = await Promise.all(
numbers.map(async episodeNo => {
const [direction, visual] = await Promise.all([
storyboardApi.directions(projectId, episodeNo),
storyboardApi.visualStates(projectId, episodeNo)
])
if (
direction.projectId !== projectId ||
visual.projectId !== projectId ||
direction.episodeNo !== episodeNo ||
visual.episodeNo !== episodeNo
)
throw new Error('设计检查结果与当前项目或剧集不一致。')
if (
direction.staleCount !== 0 ||
visual.staleCount !== 0 ||
direction.shotCount !== direction.directionCount ||
visual.shotCount !== visual.visualStateCount ||
direction.coverage !== 1 ||
visual.coverage !== 1 ||
direction.shotCount !== visual.shotCount
)
throw new Error('镜头设计或画面状态已过期、缺失或版本尚未确认,请先补齐或更新设计。')
return direction.shotCount
}))
if (records.reduce((total, count) => total + count, 0) !== expectedShotCount) throw new Error('设计与正式镜头范围不一致,请刷新后核对。')
})
)
if (records.reduce((total, count) => total + count, 0) !== expectedShotCount)
throw new Error('设计与正式镜头范围不一致,请刷新后核对。')
}
+24 -8
View File
@@ -6,12 +6,28 @@ import type { StoryboardApprovalState } from './types'
* @param projectId 当前项目
* @returns 是否具有当前内容对应的有效整体审核
*/
export function currentStoryboardApproval(state: StoryboardApprovalState | null | undefined, projectId: string): boolean {
const record = state?.confirmation, evidence = state?.evidence
return state?.valid === true && !!record && !!evidence && evidence.valid === true &&
record.projectId === projectId && !!evidence.checkpointId && record.checkpointId === evidence.checkpointId &&
Number.isSafeInteger(evidence.qualityPolicyRevision) && evidence.qualityPolicyRevision! >= 0 &&
record.qualityPolicyRevision === evidence.qualityPolicyRevision && record.qualityPolicyFingerprint === evidence.qualityPolicyFingerprint &&
/^[a-f\d]{64}$/.test(evidence.qualityPolicyFingerprint ?? '') && record.shotCount === evidence.shotCount &&
evidence.shotCount > 0 && record.shotFingerprint === evidence.shotFingerprint && /^[a-f\d]{64}$/.test(evidence.shotFingerprint)
export function currentStoryboardApproval(
state: StoryboardApprovalState | null | undefined,
projectId: string
): boolean {
const record = state?.confirmation,
evidence = state?.evidence
return (
state?.valid === true &&
!!record &&
!!evidence &&
evidence.valid === true &&
record.projectId === projectId &&
!!evidence.checkpointId &&
record.checkpointId === evidence.checkpointId &&
Number.isSafeInteger(evidence.qualityPolicyRevision) &&
evidence.qualityPolicyRevision! >= 0 &&
record.qualityPolicyRevision === evidence.qualityPolicyRevision &&
record.qualityPolicyFingerprint === evidence.qualityPolicyFingerprint &&
/^[a-f\d]{64}$/.test(evidence.qualityPolicyFingerprint ?? '') &&
record.shotCount === evidence.shotCount &&
evidence.shotCount > 0 &&
record.shotFingerprint === evidence.shotFingerprint &&
/^[a-f\d]{64}$/.test(evidence.shotFingerprint)
)
}
+53 -9
View File
@@ -21,15 +21,37 @@ export interface StoryboardRecheck {
/** 综合问题状态,当前接口不返回全局通过。 */
status: 'blocked' | 'insufficient_evidence' | 'needs_review'
/** 结构检查。 */
structure: { /** 是否有检查记录。 */ hasValidation: boolean; /** 明确结构结论。 */ valid: boolean | null; /** 原因。 */ reason: string | null }
structure: {
/** 是否有检查记录。 */ hasValidation: boolean
/** 明确结构结论。 */ valid: boolean | null
/** 原因。 */ reason: string | null
}
/** 正式镜头及引用问题统计。 */
coverage: { /** 剧集数。 */ episodeCount: number; /** 剧情段落数。 */ beatCount: number; /** 镜头数。 */ shotCount: number; /** 引用问题数。 */ issueCount: number }
coverage: {
/** 剧集数。 */ episodeCount: number
/** 剧情段落数。 */ beatCount: number
/** 镜头数。 */ shotCount: number
/** 引用问题数。 */ issueCount: number
}
/** 主体遗漏。 */
issues: PreparationIssue[]
/** 动作检查,单独区分阻断与待复核。 */
actionAudit: { /** 所属项目。 */ projectId: string; /** 镜头数。 */ shotCount: number; /** 问题数。 */ issueCount: number; /** 阻断数。 */ blockedCount: number; /** 待复核数。 */ needsReviewCount: number; /** 可定位问题。 */ issues: PreparationIssue[] }
actionAudit: {
/** 所属项目。 */ projectId: string
/** 镜头数。 */ shotCount: number
/** 问题数。 */ issueCount: number
/** 阻断数。 */ blockedCount: number
/** 待复核数。 */ needsReviewCount: number
/** 可定位问题。 */ issues: PreparationIssue[]
}
/** 正式镜头来源检查。 */
sourceAudit: { /** 所属项目。 */ projectId: string; /** 源记录。 */ checkpointId: string | null; /** 镜头数。 */ shotCount: number; /** 来源一致。 */ valid: boolean; /** 来源问题。 */ issues: PreparationIssue[] }
sourceAudit: {
/** 所属项目。 */ projectId: string
/** 源记录。 */ checkpointId: string | null
/** 镜头数。 */ shotCount: number
/** 来源一致。 */ valid: boolean
/** 来源问题。 */ issues: PreparationIssue[]
}
/** 多项来源证据,不能用结构通过替代。 */
provenance: {
/** 最新保存记录。 */ checkpointId: string | null
@@ -93,7 +115,13 @@ export interface ProductionEntryReadiness {
/** 明确结构结论。 */ storyboardValid: boolean | null
/** 当前阻断原因。 */ reason: string | null
/** 已保存的派生设计数量,不能代替新旧版本检查。 */
derivedAssets: { /** 正式镜头数。 */ shotCount: number; /** 镜头设计数。 */ directionCount: number; /** 镜头设计覆盖。 */ directionCoverage: number; /** 画面状态数。 */ visualStateCount: number; /** 画面状态覆盖。 */ visualStateCoverage: number }
derivedAssets: {
/** 正式镜头数。 */ shotCount: number
/** 镜头设计数。 */ directionCount: number
/** 镜头设计覆盖。 */ directionCoverage: number
/** 画面状态数。 */ visualStateCount: number
/** 画面状态覆盖。 */ visualStateCoverage: number
}
}
/** 通过真实坐标查询得到的正式镜头身份。 */
export interface LocatedStoryboardShot extends Required<DiagnosisLocation> {
@@ -111,7 +139,11 @@ export interface FormalShotRepairPreview extends ShotActionDraft {
/** 仅可补齐明确动作;语义问题需人工或模型。 */ status: 'candidate' | 'needs_semantic_repair' | 'unchanged'
/** 候选源版本。 */ beforeFingerprint: string
/** 明确的确定性建议,缺失时不猜测。 */ proposed: ShotDurationPlanning | null
/** 具体语义疑点。 */ semanticIssues: { /** 动作编号。 */ actionId: string; /** 动作描述。 */ description: string; /** 原阶段位置。 */ phaseIndex: number }[]
/** 具体语义疑点。 */ semanticIssues: {
/** 动作编号。 */ actionId: string
/** 动作描述。 */ description: string
/** 原阶段位置。 */ phaseIndex: number
}[]
/** 原始问题。 */ originalIssues: { /** 问题类别。 */ code: string; /** 说明。 */ message: string }[]
}
/** 未写入。 */ written: false
@@ -155,8 +187,17 @@ export interface BeatSubjectPreview {
/** 缺失主体。 */ subjectRef: string
/** 真实主体名称。 */ subjectName: string
/** 主体介绍。 */ subjectDescription: string | null
/** 剧情段落原始内容。 */ beat: { /** 标题。 */ title: string; /** 正文。 */ description: string; /** 重点。 */ visualFocus: string; /** 已有引用。 */ subjectRefs: string[] }
/** 当前镜头内容。 */ shot: { /** 标题。 */ title: string; /** 正文。 */ description: string; /** 重点。 */ visualFocus: string }
/** 剧情段落原始内容。 */ beat: {
/** 标题。 */ title: string
/** 正文。 */ description: string
/** 重点。 */ visualFocus: string
/** 已有引用。 */ subjectRefs: string[]
}
/** 当前镜头内容。 */ shot: {
/** 标题。 */ title: string
/** 正文。 */ description: string
/** 重点。 */ visualFocus: string
}
/** 来源情况。 */ status: 'upstream-present' | 'revision-present' | 'upstream-missing'
/** 不修改数据。 */ written: false
/** 真实可审核候选。 */ candidate: null | {
@@ -164,7 +205,10 @@ export interface BeatSubjectPreview {
/** 所属段落。 */ beatId: string
/** 目标主体。 */ subjectRef: string
/** 段落内容版本,与镜头指纹不可混用。 */ expectedFingerprint: string
/** 明确建议增加的引用。 */ proposed: { /** 来源引用。 */ upstreamRefs: string[]; /** 正式段落引用。 */ persistedRefs: string[] }
/** 明确建议增加的引用。 */ proposed: {
/** 来源引用。 */ upstreamRefs: string[]
/** 正式段落引用。 */ persistedRefs: string[]
}
/** 必须人工核对。 */ requiresHumanReview: true
}
}
@@ -14,20 +14,33 @@ import { errorMessage } from '../../lib/http'
*/
async function read(id: string, signal: AbortSignal) {
const [quality, approval, baseline, entry, policy] = await Promise.all([
preparationApi.recheck(id, signal), preparationApi.approval(id, signal),
preparationApi.baseline(id, signal), preparationApi.entry(id, signal), projectsApi.qualityPolicy(id, signal)
preparationApi.recheck(id, signal),
preparationApi.approval(id, signal),
preparationApi.baseline(id, signal),
preparationApi.entry(id, signal),
projectsApi.qualityPolicy(id, signal)
])
validateQualityPolicyReceipt(policy, id)
if (quality.projectId !== id || quality.actionAudit.projectId !== id || quality.sourceAudit.projectId !== id ||
approval.confirmation && approval.confirmation.projectId !== id)
if (
quality.projectId !== id ||
quality.actionAudit.projectId !== id ||
quality.sourceAudit.projectId !== id ||
(approval.confirmation && approval.confirmation.projectId !== id)
)
throw new Error('检查结果与当前项目不一致,请重新读取。')
let currentEntry = entry
if (entry.ready === true) {
try {
const project = await projectsApi.detail(id, signal)
if (project.id !== id) throw new Error('制作检查项目不一致。')
await assertCurrentStoryboardDesigns(id, project.episodes.map(item => item.episode), entry.derivedAssets.shotCount)
} catch (cause) { currentEntry = { ...entry, ready: false, reason: errorMessage(cause) } }
await assertCurrentStoryboardDesigns(
id,
project.episodes.map(item => item.episode),
entry.derivedAssets.shotCount
)
} catch (cause) {
currentEntry = { ...entry, ready: false, reason: errorMessage(cause) }
}
}
return { quality, approval, baseline, entry: currentEntry, policy }
}
@@ -55,52 +68,95 @@ export function useStoryboardPreparation(projectId: Ref<string>, locked: Ref<boo
let controller: AbortController | undefined
/** 人工确认使用的完整内容身份,规则变化或镜头变化都要求重新核对。 */
const sourceKey = computed(() => JSON.stringify(data.value ? {
projectId: projectId.value, evidence: data.value.approval.evidence, baseline: data.value.baseline,
policyRevision: data.value.policy.revision, policyFingerprint: data.value.policy.fingerprint,
const sourceKey = computed(() =>
JSON.stringify(
data.value
? {
projectId: projectId.value,
evidence: data.value.approval.evidence,
baseline: data.value.baseline,
policyRevision: data.value.policy.revision,
policyFingerprint: data.value.policy.fingerprint,
quality: data.value.quality
} : null))
}
: null
)
)
/** 规则已经由项目独立确认。 */
const policyConfirmed = computed(() => !!data.value && qualityPolicyConfirmed(data.value.policy))
/** 历史来源确认只适用于服务明确允许的旧正式分镜,不改写拆解记录。 */
const baselineAllowed = computed(() => {
const value = data.value
return !!value && policyConfirmed.value && !value.quality.provenance.qualityPolicyConsistent &&
value.baseline.eligible === true && !!value.baseline.checkpointId &&
value.baseline.checkpointId === value.quality.provenance.checkpointId && value.baseline.shotCount > 0 &&
return (
!!value &&
policyConfirmed.value &&
!value.quality.provenance.qualityPolicyConsistent &&
value.baseline.eligible === true &&
!!value.baseline.checkpointId &&
value.baseline.checkpointId === value.quality.provenance.checkpointId &&
value.baseline.shotCount > 0 &&
/^[a-f\d]{64}$/.test(value.baseline.shotFingerprint ?? '')
)
})
/** 只读预检满足后才能人工审核;canConfirm=false 只是查询本身不写入。 */
const reviewable = computed(() => {
if (!data.value || !policyConfirmed.value) return false
const { quality: q, approval: a, policy } = data.value
return q.preflightEligible === true && q.structure.valid === true && q.sourceAudit.valid === true &&
q.provenance.sourceCommitted === true && q.provenance.qualityPolicyConsistent === true &&
q.provenance.shotCountsConsistent === true && q.provenance.checkpointConsistent === true &&
q.coverage.shotCount > 0 && q.issues.length === 0 && q.actionAudit.issueCount === 0 &&
a.evidence.valid === true && a.evidence.checkpointId === q.provenance.checkpointId &&
!!a.evidence.checkpointId && a.evidence.shotCount === q.coverage.shotCount &&
a.evidence.qualityPolicyRevision === policy.revision && a.evidence.qualityPolicyFingerprint === policy.fingerprint &&
return (
q.preflightEligible === true &&
q.structure.valid === true &&
q.sourceAudit.valid === true &&
q.provenance.sourceCommitted === true &&
q.provenance.qualityPolicyConsistent === true &&
q.provenance.shotCountsConsistent === true &&
q.provenance.checkpointConsistent === true &&
q.coverage.shotCount > 0 &&
q.issues.length === 0 &&
q.actionAudit.issueCount === 0 &&
a.evidence.valid === true &&
a.evidence.checkpointId === q.provenance.checkpointId &&
!!a.evidence.checkpointId &&
a.evidence.shotCount === q.coverage.shotCount &&
a.evidence.qualityPolicyRevision === policy.revision &&
a.evidence.qualityPolicyFingerprint === policy.fingerprint &&
/^[a-f\d]{64}$/.test(a.evidence.shotFingerprint)
)
})
/** 当前有效的人工审核,不因存在历史记录而显示通过。 */
const approved = computed(() => reviewable.value && currentStoryboardApproval(data.value?.approval, projectId.value))
const approved = computed(
() => reviewable.value && currentStoryboardApproval(data.value?.approval, projectId.value)
)
/** 所有动作、主体和来源问题按真实位置保留,不合并成虚构镜头。 */
const issues = computed(() => data.value ? [
const issues = computed(() =>
data.value
? [
...data.value.quality.issues.map(item => ({ ...item, kind: 'subject' as const })),
...data.value.quality.actionAudit.issues.map(item => ({ ...item, kind: 'action' as const })),
...data.value.quality.sourceAudit.issues.map(item => ({ ...item, kind: 'source' as const }))
] : [])
]
: []
)
/** 主动刷新时保留旧正文,但取消旧确认资格直到新查询完成。 */
async function load() {
if (writing.value) return
const current = ++version, id = projectId.value
controller?.abort(); controller = new AbortController()
reading.value = true; error.value = ''
try { const result = await read(id, controller.signal); if (current === version) data.value = result }
catch (cause) { if (current === version) { data.value = null; error.value = errorMessage(cause) } }
finally { if (current === version) reading.value = false }
const current = ++version,
id = projectId.value
controller?.abort()
controller = new AbortController()
reading.value = true
error.value = ''
try {
const result = await read(id, controller.signal)
if (current === version) data.value = result
} catch (cause) {
if (current === version) {
data.value = null
error.value = errorMessage(cause)
}
} finally {
if (current === version) reading.value = false
}
}
/**
* 用户明确核对后确认当前版本,确认前重新读取,发生变化时绝不自动改签新版本。
@@ -110,42 +166,109 @@ export function useStoryboardPreparation(projectId: Ref<string>, locked: Ref<boo
* @returns 是否保存了与用户核对一致的记录
*/
async function confirm(kind: 'baseline' | 'approval', reviewer: string, reviewNote: string): Promise<boolean> {
if (locked.value || reading.value || writing.value || !data.value ||
!(kind === 'baseline' ? baselineAllowed.value : reviewable.value && !approved.value)) return false
if (
locked.value ||
reading.value ||
writing.value ||
!data.value ||
!(kind === 'baseline' ? baselineAllowed.value : reviewable.value && !approved.value)
)
return false
if (!reviewer.trim() || reviewer.trim().length > 120 || !reviewNote.trim() || reviewNote.trim().length > 4000) {
error.value = '请填写复核人和核对说明;姓名最多 120 字,说明最多 4000 字。'; return false
error.value = '请填写复核人和核对说明;姓名最多 120 字,说明最多 4000 字。'
return false
}
const id = projectId.value, current = version, expected = sourceKey.value
const id = projectId.value,
current = version,
expected = sourceKey.value
const source = kind === 'baseline' ? data.value.baseline : data.value.approval.evidence
const input = { reviewer: reviewer.trim(), reviewNote: reviewNote.trim(), expectedCheckpointId: source.checkpointId!, expectedShotFingerprint: source.shotFingerprint! }
controller?.abort(); controller = new AbortController(); reading.value = true; error.value = ''; notice.value = ''
const input = {
reviewer: reviewer.trim(),
reviewNote: reviewNote.trim(),
expectedCheckpointId: source.checkpointId!,
expectedShotFingerprint: source.shotFingerprint!
}
controller?.abort()
controller = new AbortController()
reading.value = true
error.value = ''
notice.value = ''
try {
const latest = await read(id, controller.signal)
if (current !== version || locked.value) return false
data.value = latest
if (sourceKey.value !== expected) { error.value = '规则或镜头检查结果已变化,请重新核对并确认。'; return false }
reading.value = false; writing.value = true
const ok = await runOperation(id, kind === 'baseline' ? '确认历史分镜规则来源' : '确认正式分镜审核', async () => {
const record = await (kind === 'baseline' ? preparationApi.confirmBaseline(id, input) : preparationApi.confirmApproval(id, input))
if (record.projectId !== id || record.checkpointId !== input.expectedCheckpointId ||
record.shotFingerprint !== input.expectedShotFingerprint || record.qualityPolicyRevision !== latest.policy.revision ||
record.qualityPolicyFingerprint !== latest.policy.fingerprint)
if (sourceKey.value !== expected) {
error.value = '规则或镜头检查结果已变化,请重新核对并确认。'
return false
}
reading.value = false
writing.value = true
const ok = await runOperation(
id,
kind === 'baseline' ? '确认历史分镜规则来源' : '确认正式分镜审核',
async () => {
const record = await (kind === 'baseline'
? preparationApi.confirmBaseline(id, input)
: preparationApi.confirmApproval(id, input))
if (
record.projectId !== id ||
record.checkpointId !== input.expectedCheckpointId ||
record.shotFingerprint !== input.expectedShotFingerprint ||
record.qualityPolicyRevision !== latest.policy.revision ||
record.qualityPolicyFingerprint !== latest.policy.fingerprint
)
throw new Error('确认回执与核对内容不一致,请刷新后检查。')
}, { type: 'info', content: '审核记录已保存,请以刷新后的检查结果为准。' })
},
{ type: 'info', content: '审核记录已保存,请以刷新后的检查结果为准。' }
)
if (current !== version) return false
const writeError = !ok ? getOperation(id).error : ''
if (!ok) error.value = writeError
else notice.value = kind === 'baseline' ? '已确认旧分镜采用的规则来源,仍需处理问题并完成整体审核。' : '整体审核记录已保存,镜头或规则变化后需要重新审核。'
else
notice.value =
kind === 'baseline'
? '已确认旧分镜采用的规则来源,仍需处理问题并完成整体审核。'
: '整体审核记录已保存,镜头或规则变化后需要重新审核。'
writing.value = false
await load()
if (writeError) error.value = writeError
return ok
} catch (cause) { if (current === version) error.value = errorMessage(cause); return false }
finally { if (current === version) { reading.value = false; writing.value = false } }
} catch (cause) {
if (current === version) error.value = errorMessage(cause)
return false
} finally {
if (current === version) {
reading.value = false
writing.value = false
}
}
}
/** 关闭或离开时只废弃请求;已提交写入不能由迟到回执污染新项目。 */
function cancel() { version++; controller?.abort(); reading.value = false; writing.value = false; data.value = null; error.value = ''; notice.value = '' }
function cancel() {
version++
controller?.abort()
reading.value = false
writing.value = false
data.value = null
error.value = ''
notice.value = ''
}
watch(projectId, cancel, { flush: 'sync' })
onScopeDispose(cancel)
return { data, reading, writing, error, notice, sourceKey, policyConfirmed, baselineAllowed, reviewable, approved, issues, load, confirm, cancel }
return {
data,
reading,
writing,
error,
notice,
sourceKey,
policyConfirmed,
baselineAllowed,
reviewable,
approved,
issues,
load,
confirm,
cancel
}
}
+19 -4
View File
@@ -227,7 +227,20 @@ const rules = { concurrency: integerRule('批量并发'), maxRepairAttempts: int
<WorkspacePage split compact mobile-scroll class="storyboard-workspace-page compact-shot-workspace">
<template #notice>
<!-- 以下是正式分镜审核先于派生生成的明确提示,查看已有设计仍可继续 -->
<ContextNotice v-if="!approved" type="info" :show-icon="false"><p>{{ approval.loading.value ? '正在核对正式分镜审核…' : approval.error.value ? '整体审核记录暂时无法读取,已暂停镜头设计与画面状态生成。' : '当前正式分镜尚未完成整体审核,或规则与镜头版本已变化。请先打开顶部“制作前检查”。' }}</p><NButton v-if="approval.error.value" :loading="approval.loading.value" @click="approval.refresh">重新读取审核记录</NButton></ContextNotice>
<ContextNotice v-if="!approved" type="info" :show-icon="false"
><p>
{{
approval.loading.value
? '正在核对正式分镜审核…'
: approval.error.value
? '整体审核记录暂时无法读取,已暂停镜头设计与画面状态生成。'
: '当前正式分镜尚未完成整体审核,或规则与镜头版本已变化。请先打开顶部“制作前检查”。'
}}
</p>
<NButton v-if="approval.error.value" :loading="approval.loading.value" @click="approval.refresh"
>重新读取审核记录</NButton
></ContextNotice
>
<ContextNotice v-if="episodeSourceUnavailable" type="info" :show-icon="false">
本集镜头已重新生成。新标题和剧情详情尚未提供,当前只显示正式镜头编号;请按实际生成规格核对内容。
</ContextNotice>
@@ -552,9 +565,11 @@ const rules = { concurrency: integerRule('批量并发'), maxRepairAttempts: int
>
<strong>镜头生产前置设计尚未补齐或更新。</strong>
当前导演设计 {{ data.directions.directionCount }}/{{ data.directions.shotCount }},即时视觉状态
{{ data.visualStates.visualStateCount }}/{{
data.visualStates.shotCount
}}。<span v-if="data.directions.staleCount || data.visualStates.staleCount">其中过期镜头设计 {{ data.directions.staleCount }} 条、画面状态 {{ data.visualStates.staleCount }} 条。</span>请先补齐或更新后再进入镜头生产。 </ContextNotice
{{ data.visualStates.visualStateCount }}/{{ data.visualStates.shotCount }}。<span
v-if="data.directions.staleCount || data.visualStates.staleCount"
>其中过期镜头设计 {{ data.directions.staleCount }} 条、画面状态
{{ data.visualStates.staleCount }} 条。</span
>请先补齐或更新后再进入镜头生产。 </ContextNotice
><ContextNotice
v-if="!prerequisites.directionEpisode || !prerequisites.visualEpisode"
type="info"
@@ -48,7 +48,9 @@ function exportReceipt() {
</ContextNotice>
<ul v-else class="mt-3 space-y-2 text-xs text-danger">
<li v-for="(issue, index) in receipt.result.storyboardShotValidation.issues" :key="index">
剧情段落 {{ issue.beatNo ?? '—' }} / 镜头 {{ issue.shotNo ?? '—' }}:{{ userFacingText(issue.message) }}
剧情段落 {{ issue.beatNo ?? '—' }} / 镜头 {{ issue.shotNo ?? '—' }}:{{
userFacingText(issue.message)
}}
</li>
</ul>
</template>
+9 -3
View File
@@ -97,17 +97,23 @@ export function storyboardPrerequisites(checkpoints: Checkpoint[], episodeNo: nu
const latest = workflowCheckpoints(checkpoints, 'breakdown').at(-1)
const state = latest?.state
/** 候选只供阅读和修订,提交前不能充当正式制作输入。 */
const uncommitted = state?.candidateOnly === true && state.storyboardPersisted !== true && state.candidateCommitted !== true
const uncommitted =
state?.candidateOnly === true && state.storyboardPersisted !== true && state.candidateCommitted !== true
const directionEpisodes = state?.breakdownResult?.storyboardEpisodeShots ?? []
const visualEpisodes = state?.storyboardEpisodeShots ?? []
return {
directionEpisode: !uncommitted && directionEpisodes.some(item => item.episodeNo === episodeNo),
directionProject: !uncommitted && directionEpisodes.length > 0,
visualEpisode:
!uncommitted && visualEpisodes.some(item => item.episodeNo === episodeNo) &&
!uncommitted &&
visualEpisodes.some(item => item.episodeNo === episodeNo) &&
!!state?.subjectCandidates?.length &&
!!state?.subjectForms?.length,
visualProject:
!uncommitted &&
visualEpisodes.length > 0 &&
!!state?.subjectCandidates?.length &&
!!state?.subjectForms?.length,
visualProject: !uncommitted && visualEpisodes.length > 0 && !!state?.subjectCandidates?.length && !!state?.subjectForms?.length,
breakdownRunning: state?.workflowExecution?.status === 'running'
}
}
+25 -7
View File
@@ -78,11 +78,18 @@ export function useStoryboard() {
})
const data = query.data
/** 镜头设计与画面状态的新接口要求当前整体审核,独立读取而不影响只读查看。 */
const approval = useQuery(id, (projectId, signal) => projectId ? preparationApi.approval(projectId, signal) : Promise.resolve(null))
const approval = useQuery(id, (projectId, signal) =>
projectId ? preparationApi.approval(projectId, signal) : Promise.resolve(null)
)
/** 有效审核必须绑定正式内容;旧记录或未知状态不放行。 */
const approved = computed(() => !approval.loading.value && !approval.error.value && currentStoryboardApproval(approval.data.value, id.value))
const approved = computed(
() =>
!approval.loading.value && !approval.error.value && currentStoryboardApproval(approval.data.value, id.value)
)
/** 正式修订或审核后随项目数据刷新核对凭据,避免沿用旧权限。 */
watch(context.checkpoints, () => { if (approval.data.value || approval.error.value) void approval.refresh() })
watch(context.checkpoints, () => {
if (approval.data.value || approval.error.value) void approval.refresh()
})
/** 当前工作区的响应式状态或派生业务条件。 */
const session = computed(() => getStoryboardSession(id.value))
/** 单集重生成返回的是最新镜头正文,优先于不会随局部覆盖更新的历史 Breakdown 快照。 */
@@ -126,14 +133,16 @@ export function useStoryboard() {
() =>
!!data.value?.directions.shotCount &&
data.value.directions.directionCount === data.value.directions.shotCount &&
data.value.directions.coverage === 1 && data.value.directions.staleCount === 0
data.value.directions.coverage === 1 &&
data.value.directions.staleCount === 0
)
/** 当前工作区的响应式状态或派生业务条件。 */
const visualStateComplete = computed(
() =>
!!data.value?.visualStates.shotCount &&
data.value.visualStates.visualStateCount === data.value.visualStates.shotCount &&
data.value.visualStates.coverage === 1 && data.value.visualStates.staleCount === 0
data.value.visualStates.coverage === 1 &&
data.value.visualStates.staleCount === 0
)
/** 当前工作区的响应式状态或派生业务条件。 */
const hasCurrentEpisodeShots = computed(
@@ -142,7 +151,12 @@ export function useStoryboard() {
const allowed = computed<Record<StoryboardCommand, boolean>>(() => ({
'shots-current': !blocked.value && episodeNo.value > 0 && hasCurrentEpisodeShots.value,
'direction-all': approved.value && !blocked.value && prerequisites.value.directionProject && batchValid.value,
'visual-all': approved.value && !blocked.value && prerequisites.value.visualProject && batchValid.value && repairsValid.value,
'visual-all':
approved.value &&
!blocked.value &&
prerequisites.value.visualProject &&
batchValid.value &&
repairsValid.value,
prompts: !blocked.value && shots.value.length > 0 && batchValid.value
}))
@@ -213,7 +227,11 @@ export function useStoryboard() {
await runOperation(projectId, `生成${titles[command]}`, async () => {
if (command === 'direction-all' || command === 'visual-all') {
const latest = await preparationApi.approval(projectId)
if (id.value !== projectId || !currentStoryboardApproval(latest, projectId) || JSON.stringify(latest.evidence) !== expectedApproval)
if (
id.value !== projectId ||
!currentStoryboardApproval(latest, projectId) ||
JSON.stringify(latest.evidence) !== expectedApproval
)
throw new Error('正式分镜审核已变化,请重新进行制作前检查并核对费用。')
}
if (command === 'shots-current') {
@@ -209,7 +209,8 @@ const rules = {
@submit="submit"
>
<ContextNotice type="info" :show-icon="false" class="text-xs">
调用 图片模型,每次新增一张图片,可能产生费用。第一张成功的主视图会成为标准参考图;已经有标准参考图时,新主视图只作为候选保留。
调用
图片模型,每次新增一张图片,可能产生费用。第一张成功的主视图会成为标准参考图;已经有标准参考图时,新主视图只作为候选保留。
</ContextNotice>
<!-- 以下是多视角与已有身份图选择模块,单一选项不显示选择器 -->
<NFormItem
@@ -297,7 +298,14 @@ const rules = {
<div v-if="preview" class="text-xs space-y-3">
<p>实际供应方:{{ preview.provider }} · 模型:{{ preview.model }}</p>
<p class="whitespace-pre-wrap">最终提示词:{{ preview.providerPrompt }}</p>
<RawDataDetails :value="{ referenceImages: preview.referenceImages, referencePlan: preview.referencePlan, generationConfig: preview.generationConfig }" title="参考图与生成设置(高级)" />
<RawDataDetails
:value="{
referenceImages: preview.referenceImages,
referencePlan: preview.referencePlan,
generationConfig: preview.generationConfig
}"
title="参考图与生成设置(高级)"
/>
</div>
<NCheckbox
id="identity-image-cost"
@@ -32,8 +32,7 @@ function exportPrompt() {
:description="`${form?.subject.name || ''} · ${form?.name || ''}`"
>
<ContextNotice type="info" :show-icon="false" class="mt-5 text-xs">
结合形态描述与项目视觉风格生成并保存
画面描述。这里只整理文字,不生成图片;重新整理不会修改已有图片或主图。
结合形态描述与项目视觉风格生成并保存 画面描述。这里只整理文字,不生成图片;重新整理不会修改已有图片或主图。
</ContextNotice>
<section class="dialog-section mt-5">
<h3 class="text-sm font-medium">原始外观素材</h3>
@@ -38,7 +38,8 @@ watch(
value => {
if (baseline.value && dirty.value) return
savedConstraints.value = JSON.parse(JSON.stringify(value?.hardConstraints ?? []))
legacyConstraints.value = !Array.isArray(savedConstraints.value) || !savedConstraints.value.every(item => typeof item === 'string')
legacyConstraints.value =
!Array.isArray(savedConstraints.value) || !savedConstraints.value.every(item => typeof item === 'string')
savedConstraintsText = legacyConstraints.value ? '' : (savedConstraints.value as string[]).join('\n')
Object.assign(form, {
name: value?.name ?? '默认视觉风格',
@@ -64,9 +65,13 @@ function save() {
characterPrompt: form.characterPrompt,
scenePrompt: form.scenePrompt,
propPrompt: form.propPrompt,
hardConstraints: legacyConstraints.value || form.constraints === savedConstraintsText
hardConstraints:
legacyConstraints.value || form.constraints === savedConstraintsText
? savedConstraints.value
: form.constraints.split('\n').map(item => item.trim()).filter(Boolean),
: form.constraints
.split('\n')
.map(item => item.trim())
.filter(Boolean),
isLocked: form.isLocked
})
}
@@ -148,7 +153,14 @@ function save() {
</section>
<!-- 以下是要求填写说明;旧格式只读核对,不在普通编辑时丢失内容 -->
<p class="text-xs leading-6 text-muted">每行填写一条画面要求,留空表示没有补充要求。</p>
<NCollapse v-if="legacyConstraints"><NCollapseItem name="legacy-rules" title="查看已有要求(高级)"><p class="text-xs leading-6 text-muted">已有要求使用旧格式,保存风格时会原样保留。</p><pre class="whitespace-pre-wrap break-words text-xs">{{ JSON.stringify(savedConstraints, null, 2) }}</pre></NCollapseItem></NCollapse>
<NCollapse v-if="legacyConstraints"
><NCollapseItem name="legacy-rules" title="查看已有要求(高级)"
><p class="text-xs leading-6 text-muted">已有要求使用旧格式,保存风格时会原样保留。</p>
<pre class="whitespace-pre-wrap break-words text-xs">{{
JSON.stringify(savedConstraints, null, 2)
}}</pre>
</NCollapseItem></NCollapse
>
<NCheckbox
:disabled="disabled"
id="style-lock"
@@ -23,7 +23,10 @@ const search = ref('')
const checkpointMap = computed(() => new Map(props.checkpoints.map(item => [item.checkpointId, item])))
const options = computed(() => [
{ label: '全部制作任务', value: 'all' },
...[...new Set(props.checkpoints.map(item => item.workflowName))].map(value => ({ label: workflowLabel(value), value }))
...[...new Set(props.checkpoints.map(item => item.workflowName))].map(value => ({
label: workflowLabel(value),
value
}))
])
const groups = computed(() =>
(query.data.value?.groups ?? [])
@@ -127,8 +130,9 @@ function exportReport() {
>
</div>
<p class="mt-2 text-xs text-muted">
{{ workflowLabel(checkpointMap.get(node.checkpointId)?.workflowName) }} · {{ userFacingText(node.phase, '其他阶段') }} ·
{{ node.durationText }} · {{ formatDate(node.createdAt) }}
{{ workflowLabel(checkpointMap.get(node.checkpointId)?.workflowName) }} ·
{{ userFacingText(node.phase, '其他阶段') }} · {{ node.durationText }} ·
{{ formatDate(node.createdAt) }}
</p>
<p class="mt-2 break-all font-mono text-[11px] text-muted">{{ node.checkpointId }}</p>
</article>
@@ -32,7 +32,9 @@ const result = computed(() => props.execution?.result ?? {})
/** 动作诊断执行结束仅表示分析完成,不能套用素材生成的通过文案。 */
const diagnosisTask = computed(() => props.execution?.workflowName === 'storyboard-legacy-action-diagnosis')
/** 服务中断后必须由用户核对记录和费用,不根据未匹配数量自动重试。 */
const diagnosisRecovery = computed(() => diagnosisTask.value && result.value.recoveryRequired === true && result.value.retryAutomatically === false)
const diagnosisRecovery = computed(
() => diagnosisTask.value && result.value.recoveryRequired === true && result.value.retryAutomatically === false
)
/**
* 恢复数量缺失时不补零,避免把未知范围描述为没有待核查镜头。
* @param name 服务返回的统计名称
@@ -102,7 +104,12 @@ const staleMotionPlanCount = computed(() => {
})
/** 业务未通过或结果未知时,不把任务执行结束展示为全成功。 */
const statusType = computed(() => {
if (diagnosisTask.value) return props.execution?.status === 'failed' ? 'error' : props.execution?.status === 'completed' ? 'default' : 'warning'
if (diagnosisTask.value)
return props.execution?.status === 'failed'
? 'error'
: props.execution?.status === 'completed'
? 'default'
: 'warning'
if (breakdownTask.value)
return breakdownState.value === 'success'
? 'success'
@@ -283,7 +290,9 @@ function isInputMode(value: unknown, inputMode: string): boolean {
<ContextNotice
v-else-if="execution.status === 'completed' && showStatusHint"
:type="
diagnosisTask ? 'info' : breakdownInvalid
diagnosisTask
? 'info'
: breakdownInvalid
? 'warning'
: keyframeEdit
? result.passed === true
@@ -303,7 +312,9 @@ function isInputMode(value: unknown, inputMode: string): boolean {
>
<p>
{{
diagnosisTask ? '动作诊断已结束,请查看最新结果;执行结束不代表动作全部通过。' : breakdownTask
diagnosisTask
? '动作诊断已结束,请查看最新结果;执行结束不代表动作全部通过。'
: breakdownTask
? '剧本拆解已结束,请查看候选与校验结果。'
: scriptCreation
? '剧本创作任务已结束,可查看最新剧本内容。'
@@ -367,9 +378,21 @@ function isInputMode(value: unknown, inputMode: string): boolean {
<!-- 以下是诊断中断恢复摘要,未知费用与人工核查直接显示 -->
<div v-if="diagnosisTask && finished" class="mt-3 space-y-2 text-xs" aria-label="动作诊断任务统计">
<p v-if="diagnosisRecovery">需要人工核查:中断时的模型请求可能已产生费用,系统不会自动重新诊断。</p>
<p v-if="diagnosisRecovery"><span v-if="diagnosisCount('reusableShotCount') !== null">可复用 {{ diagnosisCount('reusableShotCount') }} 镜 · </span><span v-if="diagnosisCount('manualReviewShotCount') !== null">待核查 {{ diagnosisCount('manualReviewShotCount') }} 镜</span></p>
<p v-if="diagnosisRecovery && result.qualityPolicyVerified !== true">质量规则来源尚未确认,请先核对最新分镜。</p>
<p v-else-if="!diagnosisRecovery">本次处理 {{ diagnosisCount('completed') ?? diagnosisCount('total') ?? '待确认' }} 镜 · 复用 {{ diagnosisCount('skipped') ?? '待确认' }} 镜 · 调用失败 {{ diagnosisCount('failed') ?? '待确认' }} 镜。</p>
<p v-if="diagnosisRecovery">
<span v-if="diagnosisCount('reusableShotCount') !== null"
>可复用 {{ diagnosisCount('reusableShotCount') }} 镜 · </span
><span v-if="diagnosisCount('manualReviewShotCount') !== null"
>待核查 {{ diagnosisCount('manualReviewShotCount') }} 镜</span
>
</p>
<p v-if="diagnosisRecovery && result.qualityPolicyVerified !== true">
质量规则来源尚未确认,请先核对最新分镜。
</p>
<p v-else-if="!diagnosisRecovery">
本次处理 {{ diagnosisCount('completed') ?? diagnosisCount('total') ?? '待确认' }} 镜 · 复用
{{ diagnosisCount('skipped') ?? '待确认' }} 镜 · 调用失败
{{ diagnosisCount('failed') ?? '待确认' }} 镜。
</p>
</div>
<!-- 以下是非拆解任务的 Naive 详情折叠模块 -->
<NCollapse v-if="!breakdownTask" class="mt-3 text-xs text-muted">
+11 -2
View File
@@ -73,7 +73,8 @@ export function getOperation(projectId: string): Operation {
*/
export function operationErrorText(operation: Operation): string {
return operation.cause instanceof Error && errorMessage(operation.cause) === operation.error
? operation.cause.message : operation.error
? operation.cause.message
: operation.error
}
/**
@@ -121,7 +122,15 @@ export async function runOperation<T>(
) {
const operation = getOperation(projectId)
if (operation.pending) return false
Object.assign(operation, { pending: true, label, error: '', cause: null, notice: '', noticeType: null, recovery: null })
Object.assign(operation, {
pending: true,
label,
error: '',
cause: null,
notice: '',
noticeType: null,
recovery: null
})
try {
const result = await action()
const notice = typeof feedback === 'function' ? feedback(result) : feedback
+14 -5
View File
@@ -73,12 +73,21 @@ export function nodeLabel(name?: string): string {
*/
export function workflowLabel(name?: string): string {
const labels: Record<string, string> = {
'create-drama': '剧本创作', breakdown: '剧本拆解', 'visual-style': '视觉风格',
'subject-identity': '主体身份', 'subject-images': '形态图片', storyboard: '分镜设计', production: '镜头制作',
'storyboard-direction': '镜头设计', 'storyboard-visual-state': '画面状态', 'video-prompt': '视频描述',
'keyframe-generation': '首帧生成', 'keyframe-quality': '首帧检查', 'video-quality': '视频检查'
'create-drama': '剧本创作',
breakdown: '剧本拆解',
'visual-style': '视觉风格',
'subject-identity': '主体身份',
'subject-images': '形态图片',
storyboard: '分镜设计',
production: '镜头制作',
'storyboard-direction': '镜头设计',
'storyboard-visual-state': '画面状态',
'video-prompt': '视频描述',
'keyframe-generation': '首帧生成',
'keyframe-quality': '首帧检查',
'video-quality': '视频检查'
}
return name ? labels[name] ?? userFacingText(name, '其他制作任务') : '未标注制作任务'
return name ? (labels[name] ?? userFacingText(name, '其他制作任务')) : '未标注制作任务'
}
/** 下载纯文本或 JSON,不将模型内容作为 HTML 渲染。 */
+10 -2
View File
@@ -102,9 +102,17 @@ export async function optionalResource<T>(promise: Promise<T>): Promise<T | null
export function errorMessage(error: unknown): string {
const fallback = '操作失败,请刷新后重试。'
if (error instanceof ApiError) {
const configurationMessage = configurationErrorText(error.code) ?? configurationErrorText(isRecord(error.details) ? error.details.code : undefined)
const configurationMessage =
configurationErrorText(error.code) ??
configurationErrorText(isRecord(error.details) ? error.details.code : undefined)
if (configurationMessage) return configurationMessage
return [...new Set([userFacingText(error.message, fallback), ...businessErrorMessages(error.details)].filter(Boolean))].join(';') || fallback
return (
[
...new Set(
[userFacingText(error.message, fallback), ...businessErrorMessages(error.details)].filter(Boolean)
)
].join(';') || fallback
)
}
return error instanceof Error ? userFacingText(error.message, fallback) || fallback : fallback
}
+74 -29
View File
@@ -1,9 +1,11 @@
/** 项目配置的确定性业务状态说明,不将配置限制显示为系统故障。 */
const configurationErrorLabels: Record<string, string> = {
CREATIVE_PROFILE_REQUIRED: '请先保存项目生成配置,再重新检查制作计划。',
CANVAS_CHANGE_REQUIRES_REVALIDATION: '已有分镜,暂时不能直接修改作品画幅。需要先重新核对镜头设计和相关素材,当前配置未保存。',
CANVAS_CHANGE_REQUIRES_REVALIDATION:
'已有分镜,暂时不能直接修改作品画幅。需要先重新核对镜头设计和相关素材,当前配置未保存。',
CREATIVE_PROFILE_ACTIVE_WORKFLOW: '项目仍有任务进行中,请等待任务结束后再保存生成配置。',
GENERATION_CONFIG_CHANGE_REQUIRES_REVALIDATION: '已有首帧或视频,暂时不能直接修改相关模型或参数。需要先处理现有素材的更新关系,当前配置未保存。'
GENERATION_CONFIG_CHANGE_REQUIRES_REVALIDATION:
'已有首帧或视频,暂时不能直接修改相关模型或参数。需要先处理现有素材的更新关系,当前配置未保存。'
}
/**
@@ -12,35 +14,66 @@ const configurationErrorLabels: Record<string, string> = {
* @returns 对应中文操作说明,非配置业务码时返回 null
*/
export function configurationErrorText(code: unknown): string | null {
return typeof code === 'string' ? configurationErrorLabels[code] ?? null : null
return typeof code === 'string' ? (configurationErrorLabels[code] ?? null) : null
}
/** 系统说明中允许统一翻译的术语;不处理剧本、提示词正文、文件名或请求字段。 */
const terms: [RegExp, string][] = [
[/\bneeds_review\b/g, '需人工核对'], [/\binsufficient_evidence\b/g, '证据尚不完整'], [/\bblocked\b/g, '存在待处理问题'],
[/由项目 Creative Profile Canvas 决定;单次图片或视频生成不可覆盖。/g, '使用项目配置中的画面比例,单次生成时不能单独更改。'],
[/\bneeds_review\b/g, '需人工核对'],
[/\binsufficient_evidence\b/g, '证据尚不完整'],
[/\bblocked\b/g, '存在待处理问题'],
[
/由项目 Creative Profile Canvas 决定;单次图片或视频生成不可覆盖。/g,
'使用项目配置中的画面比例,单次生成时不能单独更改。'
],
[/业务层必须显式选择,不能依赖 Provider 默认值。/g, '请明确选择是否开启。'],
[/业务默认关闭/g, '默认关闭'], [/业务参考图/g, '参考图'],
[/业务默认关闭/g, '默认关闭'],
[/业务参考图/g, '参考图'],
[/Creative Profile Canvas/gi, '项目画幅设置'],
[/Prompt\s*扩写模式/gi, '画面描述补充方式'], [/Prompt\s*扩写/gi, '自动补充画面描述'],
[/Storyboard Shot/gi, '分镜镜头'], [/Primary Keyframe/gi, '首帧'],
[/\bBreakdown\b/gi, '剧本拆解'], [/\bKeyframe\b/gi, '首帧'],
[/Creative Profile/gi, '项目生成配置'], [/Visual Style/gi, '视觉风格'],
[/GenerationSpec/gi, '镜头生成方案'], [/generationPrompt/gi, '正式生图提示词'],
[/VisualState/gi, '画面即时状态'], [/\bSubjectRefs?\b/gi, '主体引用'],
[/\bSubjectForms?\b/gi, '主体形态'], [/Identity Anchor/gi, '身份母版'],
[/Motion Plan/gi, '动作设计'], [/Video Prompt/gi, '视频提示词'],
[/Negative\s*prompt/gi, '避免出现的内容'], [/Episode Shots?/gi, '单集镜头'],
[/checkpoints?/gi, '保存记录'], [/Storyboard/gi, '分镜'],
[/\bDirection\b/gi, '镜头设计'], [/\bVisual Form\b/gi, '视觉形态'],
[/\bForm\b/g, '形态'], [/\bBeat\b/gi, '剧情段落'], [/\bShot\b/gi, '镜头'],
[/\bProvider\b/gi, '模型服务'], [/\bPrompt\b/gi, '提示词'],
[/\bThinking\b/gi, '深度思考'], [/\bLLM\b/g, '文字生成模型'], [/\bVision\b/g, '画面检查'], [/\bJSON\b/gi, '数据格式'],
[/\bexecutionId\b/g, '任务编号'], [/\bID\b/g, '编号'], [/\bAPI\b/g, '服务'],
[/\bbackend\b|后端/gi, '系统'], [/\bfrontend\b|前端/gi, '页面'],
[/\bcompleted\b/g, '已完成'], [/下游资产/g, '后续制作成果'],
[/后台状态/g, '任务状态'], [/入库/g, '保存'], [/指纹/g, '内容版本'],
[/^auto$/i, '自动'], [/^direct$/i, '直接增强'], [/^agent$/i, '智能补充']
[/Prompt\s*扩写模式/gi, '画面描述补充方式'],
[/Prompt\s*扩写/gi, '自动补充画面描述'],
[/Storyboard Shot/gi, '分镜镜头'],
[/Primary Keyframe/gi, '首帧'],
[/\bBreakdown\b/gi, '剧本拆解'],
[/\bKeyframe\b/gi, '首帧'],
[/Creative Profile/gi, '项目生成配置'],
[/Visual Style/gi, '视觉风格'],
[/GenerationSpec/gi, '镜头生成方案'],
[/generationPrompt/gi, '正式生图提示词'],
[/VisualState/gi, '画面即时状态'],
[/\bSubjectRefs?\b/gi, '主体引用'],
[/\bSubjectForms?\b/gi, '主体形态'],
[/Identity Anchor/gi, '身份母版'],
[/Motion Plan/gi, '动作设计'],
[/Video Prompt/gi, '视频提示词'],
[/Negative\s*prompt/gi, '避免出现的内容'],
[/Episode Shots?/gi, '单集镜头'],
[/checkpoints?/gi, '保存记录'],
[/Storyboard/gi, '分镜'],
[/\bDirection\b/gi, '镜头设计'],
[/\bVisual Form\b/gi, '视觉形态'],
[/\bForm\b/g, '形态'],
[/\bBeat\b/gi, '剧情段落'],
[/\bShot\b/gi, '镜头'],
[/\bProvider\b/gi, '模型服务'],
[/\bPrompt\b/gi, '提示词'],
[/\bThinking\b/gi, '深度思考'],
[/\bLLM\b/g, '文字生成模型'],
[/\bVision\b/g, '画面检查'],
[/\bJSON\b/gi, '数据格式'],
[/\bexecutionId\b/g, '任务编号'],
[/\bID\b/g, '编号'],
[/\bAPI\b/g, '服务'],
[/\bbackend\b|后端/gi, '系统'],
[/\bfrontend\b|前端/gi, '页面'],
[/\bcompleted\b/g, '已完成'],
[/下游资产/g, '后续制作成果'],
[/后台状态/g, '任务状态'],
[/入库/g, '保存'],
[/指纹/g, '内容版本'],
[/^auto$/i, '自动'],
[/^direct$/i, '直接增强'],
[/^agent$/i, '智能补充']
]
/**
@@ -61,13 +94,23 @@ export function userFacingText(value: string | null | undefined, fallback = '暂
QUALITY_POLICY_SNAPSHOT_STALE: '分镜与质量规则版本不一致,请核对最新拆解结果。',
STORYBOARD_SOURCE_MISMATCH: '镜头与已提交分镜不一致,请刷新后核对。'
}
const code = Object.keys(codeLabels).find(key => text === key || text.startsWith(`${key}:`) || text.startsWith(`${key}:`))
if (code) text = text.slice(code.length).replace(/^[::]\s*/, '').trim() || codeLabels[code]!
const code = Object.keys(codeLabels).find(
key => text === key || text.startsWith(`${key}:`) || text.startsWith(`${key}:`)
)
if (code)
text =
text
.slice(code.length)
.replace(/^[::]\s*/, '')
.trim() || codeLabels[code]!
if (!text) return ''
if (/fetch failed|failed to fetch|network error|ECONNREFUSED|ETIMEDOUT/i.test(text))
return '暂时无法连接服务,请检查网络后重试;已提交的任务可能仍在运行。'
if (/PrismaClient|TypeError:|ReferenceError:|SyntaxError:|\bat \S+ \([^)]*:\d+:\d+\)|SELECT\s+.+\s+FROM/i.test(text)) return fallback
if (
/PrismaClient|TypeError:|ReferenceError:|SyntaxError:|\bat \S+ \([^)]*:\d+:\d+\)|SELECT\s+.+\s+FROM/i.test(text)
)
return fallback
for (const [pattern, label] of terms) text = text.replace(pattern, label)
return /[\u4e00-\u9fff]/.test(text) ? text : fallback
}
@@ -88,7 +131,9 @@ export function businessErrorMessages(details: unknown): string[] {
if (Array.isArray(value)) return value.slice(0, 8).flatMap(item => collect(item, depth + 1))
if (!value || typeof value !== 'object') return []
const record = value as Record<string, unknown>
const result = ['message', 'reason', 'issues', 'errors', 'formErrors'].flatMap(key => collect(record[key], depth + 1))
const result = ['message', 'reason', 'issues', 'errors', 'formErrors'].flatMap(key =>
collect(record[key], depth + 1)
)
if (record.fieldErrors && typeof record.fieldErrors === 'object')
result.push(...Object.values(record.fieldErrors).flatMap(item => collect(item, depth + 1)))
return result
+3 -1
View File
@@ -791,4 +791,6 @@ body {
}
/* 项目顶部的相邻辅助入口统一使用中性底色,深浅主题保持一致。 */
.n-button.workspace-action-button { background: var(--app-control); }
.n-button.workspace-action-button {
background: var(--app-control);
}
+6 -2
View File
@@ -67,7 +67,9 @@ describe('精简入口保留功能', () => {
it('未编辑要求时完整保留原有多行条目,不按换行拆开已保存内容', async () => {
const requirements = ['只使用古代服装\n保留角色配饰', '保持人物外观一致']
wrapper = mount(StyleEditor, { props: { visualStyle: styleFixture({ hardConstraints: requirements }), disabled: false } })
wrapper = mount(StyleEditor, {
props: { visualStyle: styleFixture({ hardConstraints: requirements }), disabled: false }
})
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(wrapper.emitted('save')?.[0]?.[0]).toMatchObject({ hardConstraints: requirements })
@@ -75,7 +77,9 @@ describe('精简入口保留功能', () => {
it('旧格式要求只读核对,保存其他设置不会用空白要求覆盖旧内容', async () => {
const legacy = { legacyRules: ['完整保留旧要求'] }
wrapper = mount(StyleEditor, { props: { visualStyle: styleFixture({ hardConstraints: legacy }), disabled: false } })
wrapper = mount(StyleEditor, {
props: { visualStyle: styleFixture({ hardConstraints: legacy }), disabled: false }
})
expect(wrapper.get('#style-constraints').attributes('disabled')).toBeDefined()
await wrapper.get('form').trigger('submit')
await flushPromises()
+4 -1
View File
@@ -138,7 +138,10 @@ describe('统一的 Naive UI 表单校验', () => {
await input('#style-name', '手工风格')
await input('#style-constraints', '真人写实\n\n 只用古代服装 ')
await submit()
expect(wrapper.emitted('save')?.[0]?.[0]).toMatchObject({ name: '手工风格', hardConstraints: ['真人写实', '只用古代服装'] })
expect(wrapper.emitted('save')?.[0]?.[0]).toMatchObject({
name: '手工风格',
hardConstraints: ['真人写实', '只用古代服装']
})
expect(wrapper.get('#style-constraints').isVisible()).toBe(true)
})
+4 -1
View File
@@ -505,7 +505,10 @@ describe('管理后台组件边界', () => {
expect(wrapper.get('.project-view .workspace-page').text()).toBe(path)
}
expect(detail).toHaveBeenCalledOnce()
expect(wrapper.findAll('.project-header .n-button').map(button => button.text())).toEqual(['制作前检查', '项目配置'])
expect(wrapper.findAll('.project-header .n-button').map(button => button.text())).toEqual([
'制作前检查',
'项目配置'
])
expect(wrapper.find('.project-header [aria-label="刷新项目"]').exists()).toBe(false)
expect(wrapper.find('.project-header .n-tag').exists()).toBe(false)
})
+178 -37
View File
@@ -15,7 +15,12 @@ import { effectScope } from 'vue'
import { useWorkflowExecution } from '@/features/workflows/execution'
import { workflowExecutionApi } from '@/features/workflows/execution-api'
import { breakdownApi } from '@/features/breakdown/api'
import { candidateCheckpoint, candidateReview, candidateState, resourceConflictState } from '../../fixtures/breakdown-candidate'
import {
candidateCheckpoint,
candidateReview,
candidateState,
resourceConflictState
} from '../../fixtures/breakdown-candidate'
import { projectsApi } from '@/features/projects/api'
import type { ProjectQualityPolicy } from '@/features/projects/types'
import { getOperation } from '@/features/workflows/operations'
@@ -23,18 +28,38 @@ import { getOperation } from '@/features/workflows/operations'
let wrapper: VueWrapper | undefined
it('首次点击生成先读取并确认质量规则,不直接打开模型启动确认', async () => {
const readPolicy = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('breakdown-scroll-test', { version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] }))
const readPolicy = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(
policyReceipt('breakdown-scroll-test', {
version: 1,
physicsMode: 'realistic',
allowExaggeratedMotion: false,
allowNonPhysicalActions: false,
allowSupernaturalAbilities: false,
customRules: []
})
)
vi.spyOn(breakdownApi, 'preview').mockResolvedValue({
episodeCount: 1, groupCount: 1, estimatedTaskCount: 3, tasks: [], modules: ['character', 'scene', 'prop'], groupSize: 3,
episodeCount: 1,
groupCount: 1,
estimatedTaskCount: 3,
tasks: [],
modules: ['character', 'scene', 'prop'],
groupSize: 3,
groups: [{ groupId: 'preview-group', groupNo: 1, startEpisodeNo: 1, endEpisodeNo: 1, episodes: [] }]
})
const start = vi.spyOn(breakdownApi, 'run')
mountPage()
await wrapper!.get('[data-workspace-tools]').trigger('click')
await flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '预览分组')!.trigger('click')
await drawerPanel()
.findAll('button')
.find(button => button.text() === '预览分组')!
.trigger('click')
await flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '生成拆解候选')!.trigger('click')
await drawerPanel()
.findAll('button')
.find(button => button.text() === '生成拆解候选')!
.trigger('click')
await flushPromises()
expect(readPolicy).toHaveBeenCalledTimes(1)
expect(drawerPanel().text()).toContain('拆解前确认质量规则')
@@ -43,14 +68,26 @@ it('首次点击生成先读取并确认质量规则,不直接打开模型启
})
it('规则确认保留分组预览,隐藏空白例外,确认不调用模型,未变规则不重复打开表单', async () => {
const result = policyReceipt('breakdown-scroll-test', { version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] })
const result = policyReceipt('breakdown-scroll-test', {
version: 1,
physicsMode: 'realistic',
allowExaggeratedMotion: false,
allowNonPhysicalActions: false,
allowSupernaturalAbilities: false,
customRules: []
})
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(result))
vi.spyOn(projectsApi, 'confirmQualityPolicy').mockImplementation(async () => {
Object.assign(result, { confirmed: true, confirmedRevision: 2, confirmedAt: '2026-10-17T15:00:00Z' })
return structuredClone(result)
})
vi.spyOn(breakdownApi, 'preview').mockResolvedValue({
episodeCount: 1, groupCount: 1, estimatedTaskCount: 3, tasks: [], modules: ['character', 'scene', 'prop'], groupSize: 3,
episodeCount: 1,
groupCount: 1,
estimatedTaskCount: 3,
tasks: [],
modules: ['character', 'scene', 'prop'],
groupSize: 3,
groups: [{ groupId: 'preview-group', groupNo: 1, startEpisodeNo: 1, endEpisodeNo: 1, episodes: [] }]
})
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
@@ -58,24 +95,52 @@ it('规则确认保留分组预览,隐藏空白例外,确认不调用模型
mountPage()
await wrapper!.get('[data-workspace-tools]').trigger('click')
await flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '预览分组')!.trigger('click')
await drawerPanel()
.findAll('button')
.find(button => button.text() === '预览分组')!
.trigger('click')
await flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '生成拆解候选')!.trigger('click')
await drawerPanel()
.findAll('button')
.find(button => button.text() === '生成拆解候选')!
.trigger('click')
await flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '取消')!.trigger('click')
await drawerPanel()
.findAll('button')
.find(button => button.text() === '取消')!
.trigger('click')
expect(drawerPanel().text()).toContain('第 1–1 集')
await drawerPanel().findAll('button').find(button => button.text() === '生成拆解候选')!.trigger('click')
await drawerPanel()
.findAll('button')
.find(button => button.text() === '生成拆解候选')!
.trigger('click')
await flushPromises()
expect(drawerPanel().findAll('button').some(button => button.text() === '添加例外')).toBe(false)
await drawerPanel().findAll('[role="checkbox"]').find(box => box.text().includes('我已核对'))!.trigger('click')
await drawerPanel().findAll('button').find(button => button.text() === '确认规则并继续')!.trigger('click')
expect(
drawerPanel()
.findAll('button')
.some(button => button.text() === '添加例外')
).toBe(false)
await drawerPanel()
.findAll('[role="checkbox"]')
.find(box => box.text().includes('我已核对'))!
.trigger('click')
await drawerPanel()
.findAll('button')
.find(button => button.text() === '确认规则并继续')!
.trigger('click')
await flushPromises()
expect(document.querySelector('.app-dialog')?.textContent).toContain('可能产生模型费用')
expect(save).not.toHaveBeenCalled()
expect(start).not.toHaveBeenCalled()
await new DOMWrapper(document.querySelector('.app-dialog')!).findAll('button').find(button => button.text() === '取消')!.trigger('click')
await new DOMWrapper(document.querySelector('.app-dialog')!)
.findAll('button')
.find(button => button.text() === '取消')!
.trigger('click')
await flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '生成拆解候选')!.trigger('click')
await drawerPanel()
.findAll('button')
.find(button => button.text() === '生成拆解候选')!
.trigger('click')
await flushPromises()
expect(drawerPanel().text()).not.toContain('拆解前确认质量规则')
expect(document.querySelector('.app-dialog')?.textContent).toContain('可能产生模型费用')
@@ -83,17 +148,42 @@ it('规则确认保留分组预览,隐藏空白例外,确认不调用模型
})
it('当前动作问题在问题抽屉中提供例外修订,保存期间锁定关闭且保存后仍需审核', async () => {
let policy: ProjectQualityPolicy = { version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] }
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => policyReceipt('breakdown-scroll-test', policy))
let policy: ProjectQualityPolicy = {
version: 1,
physicsMode: 'realistic',
allowExaggeratedMotion: false,
allowNonPhysicalActions: false,
allowSupernaturalAbilities: false,
customRules: []
}
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () =>
policyReceipt('breakdown-scroll-test', policy)
)
let finish!: () => void
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, input) => {
await new Promise<void>(resolve => { finish = resolve })
await new Promise<void>(resolve => {
finish = resolve
})
policy = input
return policyReceipt(id, input)
})
vi.spyOn(breakdownApi, 'revalidateCandidate').mockResolvedValue(candidateReview({
projectId: 'breakdown-scroll-test', actionQualityBlocks: [{ episodeNo: 1, beatNo: 1, shotNo: 1, status: 'blocked', blockingCodes: ['action_resource_conflict'], warningCodes: [], isPendingEpisode: true }], pendingQualityEpisodeNos: [1]
}))
vi.spyOn(breakdownApi, 'revalidateCandidate').mockResolvedValue(
candidateReview({
projectId: 'breakdown-scroll-test',
actionQualityBlocks: [
{
episodeNo: 1,
beatNo: 1,
shotNo: 1,
status: 'blocked',
blockingCodes: ['action_resource_conflict'],
warningCodes: [],
isPendingEpisode: true
}
],
pendingQualityEpisodeNos: [1]
})
)
mountPage([candidateCheckpoint(resourceConflictState({ projectId: 'breakdown-scroll-test' }))])
await flushPromises()
await wrapper!.get('.breakdown-desktop-issues').trigger('click')
@@ -101,17 +191,33 @@ it('当前动作问题在问题抽屉中提供例外修订,保存期间锁定
const drawer = new DOMWrapper(document.querySelector('.breakdown-issues-drawer')!)
const panel = () => drawer.get('[aria-label="动作例外修订"]')
expect(panel().text()).toContain('左手握住铜铃')
await panel().findAll('button').find(button => button.text() === '添加例外')!.trigger('click')
await panel()
.findAll('button')
.find(button => button.text() === '添加例外')!
.trigger('click')
await panel().get('textarea').setValue('剧本中的明确允许设定')
await panel().findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
await panel()
.findAll('button')
.find(button => button.text() === '保存动作例外')!
.trigger('click')
await flushPromises()
expect(drawer.findAll('button').find(button => button.text() === '关闭')!.attributes('disabled')).toBeDefined()
expect(
drawer
.findAll('button')
.find(button => button.text() === '关闭')!
.attributes('disabled')
).toBeDefined()
expect(save).toHaveBeenCalledOnce()
finish()
await flushPromises()
expect(drawer.text()).toContain('动作质量阻断')
expect(panel().text()).toContain('已有例外')
expect(drawer.findAll('button').find(button => button.text() === '关闭')!.attributes('disabled')).toBeUndefined()
expect(
drawer
.findAll('button')
.find(button => button.text() === '关闭')!
.attributes('disabled')
).toBeUndefined()
Object.assign(getOperation('breakdown-scroll-test'), { error: '', notice: '', label: '' })
})
/** 跨组件后台任务观察器,验证结束时释放。 */
@@ -169,8 +275,15 @@ it('后台重新拆解时显示真实运行状态并隐藏所有诊断入口,
it('候选审核通过后只展示候选,修复后的正式结果不再被嵌套历史五个错误污染', async () => {
const old = Array.from({ length: 5 }, (_, index) => ({ episodeNo: 1, message: `历史错误 ${index}` }))
const current = candidateCheckpoint(candidateState({ projectId: 'breakdown-scroll-test', breakdownResult: { storyboardShotValidation: { valid: false, issues: old } } }))
const read = vi.spyOn(breakdownApi, 'revalidateCandidate').mockResolvedValue(candidateReview({ projectId: 'breakdown-scroll-test', previousIssues: old }))
const current = candidateCheckpoint(
candidateState({
projectId: 'breakdown-scroll-test',
breakdownResult: { storyboardShotValidation: { valid: false, issues: old } }
})
)
const read = vi
.spyOn(breakdownApi, 'revalidateCandidate')
.mockResolvedValue(candidateReview({ projectId: 'breakdown-scroll-test', previousIssues: old }))
const provided = mountPage([current])
expect(wrapper!.text()).not.toContain('分镜校验未通过')
await flushPromises()
@@ -180,7 +293,9 @@ it('候选审核通过后只展示候选,修复后的正式结果不再被嵌
await selectTab('分镜')
expect(wrapper!.find('.storyboard-diagnosis-summary').exists()).toBe(false)
expect(read).toHaveBeenCalledTimes(1)
provided.data.value!.checkpoints = [{ ...current, state: { ...current.state, storyboardPersisted: true, candidateCommitted: true } }]
provided.data.value!.checkpoints = [
{ ...current, state: { ...current.state, storyboardPersisted: true, candidateCommitted: true } }
]
await selectTab('人物')
await flushPromises()
expect(wrapper!.text()).toContain('正式拆解结果')
@@ -190,14 +305,26 @@ it('候选审核通过后只展示候选,修复后的正式结果不再被嵌
})
it('历史修复元数据不能掩盖之后新任务的真实失败', async () => {
const current = candidateCheckpoint(candidateState({ projectId: 'breakdown-scroll-test', storyboardPersisted: true, candidateCommitted: true }))
const current = candidateCheckpoint(
candidateState({ projectId: 'breakdown-scroll-test', storyboardPersisted: true, candidateCommitted: true })
)
mountPage([current])
const record = {
id: 'new-failed-breakdown', projectId: 'breakdown-scroll-test', workflowName: 'breakdown',
status: 'failed' as const, stage: 'failed', current: 0, total: 3, currentResourceId: null,
metadata: null, result: null, error: '新任务执行失败',
startedAt: '2026-10-17T10:00:00Z', completedAt: '2026-10-17T10:01:00Z',
createdAt: '2026-10-17T10:00:00Z', updatedAt: '2026-10-17T10:01:00Z'
id: 'new-failed-breakdown',
projectId: 'breakdown-scroll-test',
workflowName: 'breakdown',
status: 'failed' as const,
stage: 'failed',
current: 0,
total: 3,
currentResourceId: null,
metadata: null,
result: null,
error: '新任务执行失败',
startedAt: '2026-10-17T10:00:00Z',
completedAt: '2026-10-17T10:01:00Z',
createdAt: '2026-10-17T10:00:00Z',
updatedAt: '2026-10-17T10:01:00Z'
}
vi.spyOn(workflowExecutionApi, 'get').mockResolvedValue(record)
taskScope = effectScope()
@@ -921,8 +1048,22 @@ describe('拆解页内容滚动', () => {
await flushPromises()
const late = await handDiagnosticsResponse(25).json()
late.data.warningCount = 1
late.data.diagnostics = [{ episodeNo: 1, beatNo: 1, shotNo: 1, phaseNo: 1, characterRef: '@CH0001', actionIds: ['a1', 'a2'], code: 'hand_occupancy_conflict', severity: 'warning', suggestion: '已失效的动作检查问题' }]
resolveFirst!(new Response(JSON.stringify(late), { status: 200, headers: { 'Content-Type': 'application/json' } }))
late.data.diagnostics = [
{
episodeNo: 1,
beatNo: 1,
shotNo: 1,
phaseNo: 1,
characterRef: '@CH0001',
actionIds: ['a1', 'a2'],
code: 'hand_occupancy_conflict',
severity: 'warning',
suggestion: '已失效的动作检查问题'
}
]
resolveFirst!(
new Response(JSON.stringify(late), { status: 200, headers: { 'Content-Type': 'application/json' } })
)
await flushPromises()
await wrapper!.get('.storyboard-diagnosis-summary button').trigger('click')
await flushPromises()
@@ -16,16 +16,35 @@ import { getOperation } from '@/features/workflows/operations'
function conflict() {
const state = resourceConflictState()
const shot = state.storyboardEpisodeShots![0]!.beatShots[0]!.shots[0]!
const review = candidateReview({ actionQualityBlocks: [{ episodeNo: 1, beatNo: 1, shotNo: 1, status: 'blocked', blockingCodes: ['action_resource_conflict'], warningCodes: [], isPendingEpisode: true }], pendingQualityEpisodeNos: [1] })
const review = candidateReview({
actionQualityBlocks: [
{
episodeNo: 1,
beatNo: 1,
shotNo: 1,
status: 'blocked',
blockingCodes: ['action_resource_conflict'],
warningCodes: [],
isPendingEpisode: true
}
],
pendingQualityEpisodeNos: [1]
})
const quality = breakdownQuality(selectBreakdownSource([candidateCheckpoint(state)]), review)
return { state, quality, shot }
}
/** 已有例外与独立全局规则,写入时必须全部保留。 */
const policy: ProjectQualityPolicy = {
version: 1, physicsMode: 'stylized', allowExaggeratedMotion: true, allowNonPhysicalActions: false,
allowSupernaturalAbilities: false, customRules: ['跳跃后正常落地'],
actionExceptions: [{ code: 'action_resource_conflict', ownerRef: '@CH0099', resource: 'right_hand', reason: '旧例外依据' }]
version: 1,
physicsMode: 'stylized',
allowExaggeratedMotion: true,
allowNonPhysicalActions: false,
allowSupernaturalAbilities: false,
customRules: ['跳跃后正常落地'],
actionExceptions: [
{ code: 'action_resource_conflict', ownerRef: '@CH0099', resource: 'right_hand', reason: '旧例外依据' }
]
}
/** 当前真实修订面板实例。 */
let wrapper: VueWrapper<InstanceType<typeof ActionExceptionRepair>> | undefined
@@ -40,10 +59,18 @@ afterEach(() => {
describe('从实际问题建立动作例外', () => {
it('只从当前审核的互斥动作证据带入角色、部位与动作,不从文字猜测', () => {
const { state, quality, shot } = conflict()
expect(actionExceptionTargets(state, quality)).toMatchObject([{
episodeNo: 1, beatNo: 1, shotNo: 1, phaseNo: 1, ownerRef: '@CH0001', ownerName: '人物', resource: 'left_hand',
expect(actionExceptionTargets(state, quality)).toMatchObject([
{
episodeNo: 1,
beatNo: 1,
shotNo: 1,
phaseNo: 1,
ownerRef: '@CH0001',
ownerName: '人物',
resource: 'left_hand',
actions: ['左手握住铜铃', '左手向村民挥动']
}])
}
])
shot.durationPlanning!.phases[0]!.resourceOccupancy = []
expect(actionExceptionTargets(state, quality)).toEqual([])
})
@@ -57,9 +84,14 @@ describe('从实际问题建立动作例外', () => {
phase.actionIds = ['hold']
expect(actionExceptionTargets(state, quality)).toEqual([])
phase.actionIds = ['hold', 'wave']
phase.resourceOccupancy!.forEach(item => { item.shareable = true; item.usage = 'hold' })
phase.resourceOccupancy!.forEach(item => {
item.shareable = true
item.usage = 'hold'
})
expect(actionExceptionTargets(state, quality)).toEqual([])
phase.resourceOccupancy!.forEach(item => { item.shareable = false })
phase.resourceOccupancy!.forEach(item => {
item.shareable = false
})
expect(actionExceptionTargets(state, { ...quality, source: 'history' })).toEqual([])
const resource = phase.resourceOccupancy!.pop()!
shot.durationPlanning!.phases.push({ ...phase, resourceOccupancy: [resource] })
@@ -69,26 +101,59 @@ describe('从实际问题建立动作例外', () => {
it('用户仅填写原因,保存前重读并合并已有例外,不改全局规则或自动放行质量', async () => {
const { state, quality } = conflict()
const latest = { ...policy, customRules: ['其他入口刚保存的新规则'] }
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValueOnce(policyReceipt('candidate-project', policy)).mockResolvedValue(policyReceipt('candidate-project', latest))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, input) => (policyReceipt(id, input)))
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
vi.spyOn(projectsApi, 'qualityPolicy')
.mockResolvedValueOnce(policyReceipt('candidate-project', policy))
.mockResolvedValue(policyReceipt('candidate-project', latest))
const save = vi
.spyOn(projectsApi, 'saveQualityPolicy')
.mockImplementation(async (id, input) => policyReceipt(id, input))
wrapper = mount(ActionExceptionRepair, {
props: {
projectId: 'candidate-project',
checkpointId: 'candidate-current',
state,
quality,
disabled: false
}
})
await flushPromises()
expect(wrapper.text()).toContain('左手握住铜铃')
expect(wrapper.text()).toContain('左手向村民挥动')
await wrapper.findAll('button').find(button => button.text() === '添加例外')!.trigger('click')
await wrapper
.findAll('button')
.find(button => button.text() === '添加例外')!
.trigger('click')
expect(wrapper.find('input').exists()).toBe(false)
expect(wrapper.find('textarea').element.value).toBe('')
expect(wrapper.text()).not.toContain('请填写允许原因')
await wrapper.findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
await wrapper
.findAll('button')
.find(button => button.text() === '保存动作例外')!
.trigger('click')
expect(wrapper.text()).toContain('请填写允许原因')
expect(save).not.toHaveBeenCalled()
await wrapper.get('textarea').setValue('剧本明确允许左手同时挥动持物')
await wrapper.findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
await wrapper
.findAll('button')
.find(button => button.text() === '保存动作例外')!
.trigger('click')
await flushPromises()
expect(save).toHaveBeenCalledExactlyOnceWith('candidate-project', { ...latest, actionExceptions: [
expect(save).toHaveBeenCalledExactlyOnceWith(
'candidate-project',
{
...latest,
actionExceptions: [
policy.actionExceptions![0],
{ code: 'action_resource_conflict', ownerRef: '@CH0001', resource: 'left_hand', reason: '剧本明确允许左手同时挥动持物' }
] }, 2)
{
code: 'action_resource_conflict',
ownerRef: '@CH0001',
resource: 'left_hand',
reason: '剧本明确允许左手同时挥动持物'
}
]
},
2
)
expect(wrapper.emitted('refresh')).toHaveLength(1)
expect(quality.actionStatus).toBe('blocked')
expect(wrapper.find('textarea').exists()).toBe(false)
@@ -97,14 +162,35 @@ describe('从实际问题建立动作例外', () => {
it('保存前出现活动任务或切换检查点时,不提交旧问题的例外', async () => {
const { state, quality } = conflict()
let finish!: (value: ReturnType<typeof policyReceipt>) => void
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('candidate-project', policy))
const read = vi
.spyOn(projectsApi, 'qualityPolicy')
.mockResolvedValue(policyReceipt('candidate-project', policy))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
wrapper = mount(ActionExceptionRepair, {
props: {
projectId: 'candidate-project',
checkpointId: 'candidate-current',
state,
quality,
disabled: false
}
})
await flushPromises()
await wrapper.findAll('button').find(button => button.text() === '添加例外')!.trigger('click')
await wrapper
.findAll('button')
.find(button => button.text() === '添加例外')!
.trigger('click')
await wrapper.get('textarea').setValue('允许原因')
read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
await wrapper.findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
read.mockImplementationOnce(
() =>
new Promise(resolve => {
finish = resolve
})
)
await wrapper
.findAll('button')
.find(button => button.text() === '保存动作例外')!
.trigger('click')
await wrapper.setProps({ disabled: true })
finish(policyReceipt('candidate-project', policy))
await flushPromises()
@@ -117,13 +203,37 @@ describe('从实际问题建立动作例外', () => {
it('已有同一角色部位的例外不重复添加,其他例外保持可见', async () => {
const { state, quality } = conflict()
const existing = { ...policy, actionExceptions: [...policy.actionExceptions!, { code: 'action_resource_conflict' as const, ownerRef: '@CH0001', resource: 'left_hand' as const, reason: '已确认的同类例外' }] }
const existing = {
...policy,
actionExceptions: [
...policy.actionExceptions!,
{
code: 'action_resource_conflict' as const,
ownerRef: '@CH0001',
resource: 'left_hand' as const,
reason: '已确认的同类例外'
}
]
}
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('candidate-project', existing))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
wrapper = mount(ActionExceptionRepair, {
props: {
projectId: 'candidate-project',
checkpointId: 'candidate-current',
state,
quality,
disabled: false
}
})
await flushPromises()
expect(wrapper.text()).toContain('已有动作例外 · 2 项')
expect(wrapper.findAll('button').find(button => button.text() === '已有例外')!.attributes('disabled')).toBeDefined()
expect(
wrapper
.findAll('button')
.find(button => button.text() === '已有例外')!
.attributes('disabled')
).toBeDefined()
expect(wrapper.find('textarea').exists()).toBe(false)
expect(save).not.toHaveBeenCalled()
})
@@ -132,11 +242,25 @@ describe('从实际问题建立动作例外', () => {
const { state, quality } = conflict()
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('candidate-project', policy))
vi.spyOn(projectsApi, 'saveQualityPolicy').mockRejectedValue(new Error('后端拒绝修改'))
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
wrapper = mount(ActionExceptionRepair, {
props: {
projectId: 'candidate-project',
checkpointId: 'candidate-current',
state,
quality,
disabled: false
}
})
await flushPromises()
await wrapper.findAll('button').find(button => button.text() === '添加例外')!.trigger('click')
await wrapper
.findAll('button')
.find(button => button.text() === '添加例外')!
.trigger('click')
await wrapper.get('textarea').setValue('仍需保存的依据')
await wrapper.findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
await wrapper
.findAll('button')
.find(button => button.text() === '保存动作例外')!
.trigger('click')
await flushPromises()
expect(wrapper.get('textarea').element.value).toBe('仍需保存的依据')
expect(wrapper.text()).toContain('系统拒绝修改')
@@ -149,10 +273,23 @@ describe('从实际问题建立动作例外', () => {
const { state, quality } = conflict()
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('other', policy))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
wrapper = mount(ActionExceptionRepair, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, quality, disabled: false } })
wrapper = mount(ActionExceptionRepair, {
props: {
projectId: 'candidate-project',
checkpointId: 'candidate-current',
state,
quality,
disabled: false
}
})
await flushPromises()
expect(wrapper.text()).toContain('规则所属项目不一致')
expect(wrapper.findAll('button').find(button => button.text() === '添加例外')!.attributes('disabled')).toBeDefined()
expect(
wrapper
.findAll('button')
.find(button => button.text() === '添加例外')!
.attributes('disabled')
).toBeDefined()
expect(wrapper.find('textarea').exists()).toBe(false)
expect(save).not.toHaveBeenCalled()
})
@@ -10,21 +10,37 @@ import type { CandidateCommitPreview } from '@/features/breakdown/candidate.type
/** 真实确认弹窗挂载于 body,验证完成后清理。 */
let wrapper: VueWrapper | undefined
beforeEach(() => { vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([candidateCheckpoint()]) })
afterEach(() => { wrapper?.unmount(); wrapper = undefined; document.body.innerHTML = ''; vi.restoreAllMocks() })
beforeEach(() => {
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([candidateCheckpoint()])
})
afterEach(() => {
wrapper?.unmount()
wrapper = undefined
document.body.innerHTML = ''
vi.restoreAllMocks()
})
/** 创建质量已通过但尚未经过安全预检查的面板。 */
function openPanel() {
wrapper = mount(BreakdownCandidatePanel, {
attachTo: document.body,
props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state: candidateState(), quality: breakdownQuality(selectBreakdownSource([candidateCheckpoint()]), candidateReview()), disabled: false }
props: {
projectId: 'candidate-project',
checkpointId: 'candidate-current',
state: candidateState(),
quality: breakdownQuality(selectBreakdownSource([candidateCheckpoint()]), candidateReview()),
disabled: false
}
})
return wrapper
}
/** 点击只读预检查入口,不直接提交。 */
async function checkCandidate() {
await wrapper!.findAll('button').find(button => button.text() === '提交候选为正式结果')!.trigger('click')
await wrapper!
.findAll('button')
.find(button => button.text() === '提交候选为正式结果')!
.trigger('click')
await flushPromises()
}
@@ -32,19 +48,33 @@ async function checkCandidate() {
async function confirmCandidate() {
const dialog = new DOMWrapper(document.querySelector<HTMLElement>('.app-dialog'))
await dialog.get('[role="checkbox"]').trigger('click')
await dialog.findAll('button').find(button => button.text() === '确认提交候选为正式结果')!.trigger('click')
await dialog
.findAll('button')
.find(button => button.text() === '确认提交候选为正式结果')!
.trigger('click')
await flushPromises()
}
describe('候选预检查与最终提交门禁', () => {
it('审核通过不会直接提交;预检查及最终确认均通过后只提交一次并刷新', async () => {
const preview = vi.spyOn(breakdownApi, 'candidateCommitPreview').mockResolvedValue(commitPreview())
const commit = vi.spyOn(breakdownApi, 'commitCandidate').mockResolvedValue({ projectId: 'candidate-project', subjectCount: 2, subjectFormCount: 2, episodeCount: 1, beatCount: 1, shotCount: 2, shotSubjectCount: 2 })
const commit = vi.spyOn(breakdownApi, 'commitCandidate').mockResolvedValue({
projectId: 'candidate-project',
subjectCount: 2,
subjectFormCount: 2,
episodeCount: 1,
beatCount: 1,
shotCount: 2,
shotSubjectCount: 2
})
openPanel()
expect(preview).not.toHaveBeenCalled()
expect(commit).not.toHaveBeenCalled()
expect(wrapper!.findAll('button').some(button => button.text() === '重新检查')).toBe(true)
await wrapper!.findAll('button').find(button => button.text() === '重新检查')!.trigger('click')
await wrapper!
.findAll('button')
.find(button => button.text() === '重新检查')!
.trigger('click')
expect(wrapper!.emitted('refresh')).toHaveLength(1)
await checkCandidate()
expect(commit).not.toHaveBeenCalled()
@@ -55,7 +85,15 @@ describe('候选预检查与最终提交门禁', () => {
expect(wrapper!.emitted('refresh')).toHaveLength(2)
expect(wrapper!.text()).toContain('拆解结果已保存并采用')
expect(wrapper!.findAll('button').some(button => button.text() === '重新检查')).toBe(false)
await wrapper!.setProps({ state: candidateState({ storyboardPersisted: true, candidateCommitted: true }), quality: breakdownQuality(selectBreakdownSource([candidateCheckpoint(candidateState({ storyboardPersisted: true, candidateCommitted: true }))]), null) })
await wrapper!.setProps({
state: candidateState({ storyboardPersisted: true, candidateCommitted: true }),
quality: breakdownQuality(
selectBreakdownSource([
candidateCheckpoint(candidateState({ storyboardPersisted: true, candidateCommitted: true }))
]),
null
)
})
expect(wrapper!.findAll('button').some(button => button.text() === '提交候选为正式结果')).toBe(false)
expect(wrapper!.findAll('button').some(button => button.text() === '重新检查')).toBe(false)
})
@@ -92,7 +130,9 @@ describe('候选预检查与最终提交门禁', () => {
expect(wrapper!.emitted('refresh')).toHaveLength(1)
})
it('最终确认时安全条件改变,原先通过的预检查不能继续使用', async () => {
vi.spyOn(breakdownApi, 'candidateCommitPreview').mockResolvedValueOnce(commitPreview()).mockResolvedValueOnce(commitPreview({ ready: false }))
vi.spyOn(breakdownApi, 'candidateCommitPreview')
.mockResolvedValueOnce(commitPreview())
.mockResolvedValueOnce(commitPreview({ ready: false }))
const commit = vi.spyOn(breakdownApi, 'commitCandidate')
openPanel()
await checkCandidate()
@@ -102,10 +142,18 @@ describe('候选预检查与最终提交门禁', () => {
})
it('版本变化后晚到的预检查响应不会重新打开确认窗口', async () => {
let resolve!: (value: CandidateCommitPreview) => void
const preview = vi.spyOn(breakdownApi, 'candidateCommitPreview').mockImplementation(() => new Promise(done => { resolve = done }))
const preview = vi.spyOn(breakdownApi, 'candidateCommitPreview').mockImplementation(
() =>
new Promise(done => {
resolve = done
})
)
openPanel()
await checkCandidate()
await wrapper!.findAll('button').find(button => button.text() === '提交候选为正式结果')!.trigger('click')
await wrapper!
.findAll('button')
.find(button => button.text() === '提交候选为正式结果')!
.trigger('click')
expect(preview).toHaveBeenCalledTimes(1)
await wrapper!.setProps({ checkpointId: 'new' })
resolve(commitPreview())
@@ -9,7 +9,12 @@ import type { CandidateRevalidation } from '@/features/breakdown/candidate.types
/** 候选修复组件实例,禁止真实写入。 */
let wrapper: VueWrapper | undefined
afterEach(() => { wrapper?.unmount(); wrapper = undefined; vi.restoreAllMocks(); document.body.innerHTML = '' })
afterEach(() => {
wrapper?.unmount()
wrapper = undefined
vi.restoreAllMocks()
document.body.innerHTML = ''
})
/**
* 只将真实阻断镜头的原始动作放入审核响应。
@@ -17,21 +22,63 @@ afterEach(() => { wrapper?.unmount(); wrapper = undefined; vi.restoreAllMocks();
*/
function blockedReview(): CandidateRevalidation {
const state = candidateState()
const blocks = [1, 2].map(shotNo => ({ episodeNo: 1, beatNo: 1, shotNo, status: 'blocked' as const, blockingCodes: ['state_used_as_action_phase'], warningCodes: [], isPendingEpisode: true }))
return candidateReview({ actionQualityBlocks: blocks, actionRepairTargets: blocks.map(block => ({ ...block, shot: { ...state.storyboardEpisodeShots![0]!.beatShots[0]!.shots[block.shotNo - 1]!, requiredActions: state.storyboardEpisodeShots![0]!.beatShots[0]!.shots[block.shotNo - 1]!.requiredActions!, durationPlanning: state.storyboardEpisodeShots![0]!.beatShots[0]!.shots[block.shotNo - 1]!.durationPlanning! } })), pendingQualityEpisodeNos: [1] })
const blocks = [1, 2].map(shotNo => ({
episodeNo: 1,
beatNo: 1,
shotNo,
status: 'blocked' as const,
blockingCodes: ['state_used_as_action_phase'],
warningCodes: [],
isPendingEpisode: true
}))
return candidateReview({
actionQualityBlocks: blocks,
actionRepairTargets: blocks.map(block => ({
...block,
shot: {
...state.storyboardEpisodeShots![0]!.beatShots[0]!.shots[block.shotNo - 1]!,
requiredActions:
state.storyboardEpisodeShots![0]!.beatShots[0]!.shots[block.shotNo - 1]!.requiredActions!,
durationPlanning:
state.storyboardEpisodeShots![0]!.beatShots[0]!.shots[block.shotNo - 1]!.durationPlanning!
}
})),
pendingQualityEpisodeNos: [1]
})
}
describe('人工候选修复', () => {
it('主体和形态只能来自当前候选,错误归属的形态不能提交;成功请求刷新新版本', async () => {
const state = candidateState()
const review = candidateReview({ missingSubjectRefs: [{ episodeNo: 1, beatNo: 1, shotNo: 1, message: '缺少铜铃 @PR0001', shot: state.storyboardEpisodeShots![0]!.beatShots[0]!.shots[0]!, beatSubjectRefs: ['@PR0001'], subject: state.subjectCandidates![1]!, availableForms: [state.subjectForms![1]!] }] })
const repair = vi.spyOn(breakdownApi, 'repairCandidateSubject').mockResolvedValue({ checkpointId: 'repaired', storyboardShotValidation: { valid: true, issues: [] }, candidateValidation: { valid: true, issues: [] } })
wrapper = mount(CandidateRepairs, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, review, disabled: false } })
const review = candidateReview({
missingSubjectRefs: [
{
episodeNo: 1,
beatNo: 1,
shotNo: 1,
message: '缺少铜铃 @PR0001',
shot: state.storyboardEpisodeShots![0]!.beatShots[0]!.shots[0]!,
beatSubjectRefs: ['@PR0001'],
subject: state.subjectCandidates![1]!,
availableForms: [state.subjectForms![1]!]
}
]
})
const repair = vi.spyOn(breakdownApi, 'repairCandidateSubject').mockResolvedValue({
checkpointId: 'repaired',
storyboardShotValidation: { valid: true, issues: [] },
candidateValidation: { valid: true, issues: [] }
})
wrapper = mount(CandidateRepairs, {
props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state, review, disabled: false }
})
wrapper.findAllComponents(NSelect)[0]!.vm.$emit('update:value', '1/1/1')
await flushPromises()
wrapper.findAllComponents(NSelect)[1]!.vm.$emit('update:value', '@PR0001')
await flushPromises()
expect(wrapper.findAllComponents(NSelect)[2]!.props('options')).toEqual([{ label: '铜铃形态', value: 'prop-form' }])
expect(wrapper.findAllComponents(NSelect)[2]!.props('options')).toEqual([
{ label: '铜铃形态', value: 'prop-form' }
])
wrapper.findAllComponents(NSelect)[2]!.vm.$emit('update:value', 'person-form')
await flushPromises()
wrapper.getComponent(ConfirmAction).vm.$emit('confirm')
@@ -41,12 +88,29 @@ describe('人工候选修复', () => {
await flushPromises()
wrapper.getComponent(ConfirmAction).vm.$emit('confirm')
await flushPromises()
expect(repair).toHaveBeenCalledExactlyOnceWith('candidate-project', { expectedCheckpointId: 'candidate-current', episodeNo: 1, beatNo: 1, shotNo: 1, subjectRef: '@PR0001', formId: 'prop-form' })
expect(repair).toHaveBeenCalledExactlyOnceWith('candidate-project', {
expectedCheckpointId: 'candidate-current',
episodeNo: 1,
beatNo: 1,
shotNo: 1,
subjectRef: '@PR0001',
formId: 'prop-form'
})
expect(wrapper.emitted('refresh')).toHaveLength(1)
})
it('多个动作必须经过选择和描述编辑,批量失败保留全部草稿且不发送 kind', async () => {
const repair = vi.spyOn(breakdownApi, 'repairCandidateActions').mockRejectedValue(new Error('目标动作处于并行阶段,不能自动覆盖其他动作描述'))
wrapper = mount(CandidateRepairs, { props: { projectId: 'candidate-project', checkpointId: 'candidate-current', state: candidateState(), review: blockedReview(), disabled: false } })
const repair = vi
.spyOn(breakdownApi, 'repairCandidateActions')
.mockRejectedValue(new Error('目标动作处于并行阶段,不能自动覆盖其他动作描述'))
wrapper = mount(CandidateRepairs, {
props: {
projectId: 'candidate-project',
checkpointId: 'candidate-current',
state: candidateState(),
review: blockedReview(),
disabled: false
}
})
const confirm = () => wrapper!.getComponent(ConfirmAction)
confirm().vm.$emit('confirm')
await flushPromises()
@@ -64,16 +128,30 @@ describe('人工候选修复', () => {
expect(input.expectedCheckpointId).toBe('candidate-current')
expect(input.repairs).toHaveLength(2)
expect(input.repairs.every(item => !('kind' in item))).toBe(true)
expect(wrapper.findAll('textarea').map(field => field.element.value)).toEqual(['人物伸手握住并拿起铜铃 1', '人物伸手握住并拿起铜铃 2'])
expect(wrapper.findAll('textarea').map(field => field.element.value)).toEqual([
'人物伸手握住并拿起铜铃 1',
'人物伸手握住并拿起铜铃 2'
])
expect(wrapper.text()).toContain('并行阶段')
expect(wrapper.emitted('refresh')).toBeUndefined()
})
it('版本过期后旧编辑内容不能提交,正式模式也不能写候选', async () => {
const repair = vi.spyOn(breakdownApi, 'repairCandidateActions')
wrapper = mount(CandidateRepairs, { props: { projectId: 'candidate-project', checkpointId: 'new-version', state: candidateState(), review: blockedReview(), disabled: false } })
wrapper = mount(CandidateRepairs, {
props: {
projectId: 'candidate-project',
checkpointId: 'new-version',
state: candidateState(),
review: blockedReview(),
disabled: false
}
})
expect(wrapper.findAll('textarea')).toHaveLength(0)
expect(repair).not.toHaveBeenCalled()
await wrapper.setProps({ checkpointId: 'candidate-current', state: candidateState({ storyboardPersisted: true }) })
await wrapper.setProps({
checkpointId: 'candidate-current',
state: candidateState({ storyboardPersisted: true })
})
await flushPromises()
expect(wrapper.findAllComponents(NCheckbox).every(item => item.props('disabled'))).toBe(true)
})
+16 -3
View File
@@ -78,8 +78,18 @@ describe('候选提交资格', () => {
vi.stubGlobal('fetch', fetcher)
await breakdownApi.revalidateCandidate('p/id')
await breakdownApi.candidateCommitPreview('p/id')
await breakdownApi.repairCandidateSubject('p/id', { expectedCheckpointId: 'current', episodeNo: 1, beatNo: 2, shotNo: 3, subjectRef: '@PR0001', formId: 'existing-form' })
await breakdownApi.repairCandidateActions('p/id', { expectedCheckpointId: 'current', repairs: [{ episodeNo: 1, beatNo: 2, shotNo: 3, actionId: 'action-1', description: '人物伸手拿起铜铃' }] })
await breakdownApi.repairCandidateSubject('p/id', {
expectedCheckpointId: 'current',
episodeNo: 1,
beatNo: 2,
shotNo: 3,
subjectRef: '@PR0001',
formId: 'existing-form'
})
await breakdownApi.repairCandidateActions('p/id', {
expectedCheckpointId: 'current',
repairs: [{ episodeNo: 1, beatNo: 2, shotNo: 3, actionId: 'action-1', description: '人物伸手拿起铜铃' }]
})
expect(fetcher.mock.calls.map(call => call[0])).toEqual([
'/api/projects/p%2Fid/breakdown/candidate-revalidation',
'/api/projects/p%2Fid/breakdown/candidate-commit-preview',
@@ -89,6 +99,9 @@ describe('候选提交资格', () => {
expect(fetcher.mock.calls.map(call => call[1]?.method)).toEqual(['GET', 'GET', 'POST', 'POST'])
const body = fetcher.mock.calls[3]?.[1]?.body
if (typeof body !== 'string') throw new Error('请求缺少 JSON 正文')
expect(JSON.parse(body)).toEqual({ expectedCheckpointId: 'current', repairs: [{ episodeNo: 1, beatNo: 2, shotNo: 3, actionId: 'action-1', description: '人物伸手拿起铜铃' }] })
expect(JSON.parse(body)).toEqual({
expectedCheckpointId: 'current',
repairs: [{ episodeNo: 1, beatNo: 2, shotNo: 3, actionId: 'action-1', description: '人物伸手拿起铜铃' }]
})
})
})
@@ -7,9 +7,27 @@ import type { LegacyActionDiagnosisResults } from '@/features/breakdown/types'
* @returns 与真实诊断列表一致的最小记录
*/
function repaired(): LegacyActionDiagnosisResults['shots'][number] {
return { shotId: 'repaired-shot', episodeNo: 1, beatNo: 7, shotNo: 1, title: '已修订镜头', diagnosisId: null,
status: 'not_diagnosed', issues: [], createdAt: null, repairStatus: 'repaired', requiresPostRepairDiagnosis: true,
resourceAudit: { status: 'insufficient_evidence', issueCount: 0, evidenceCount: 2, expectedActionCount: 0, coveredActionCount: 0, coverage: null } }
return {
shotId: 'repaired-shot',
episodeNo: 1,
beatNo: 7,
shotNo: 1,
title: '已修订镜头',
diagnosisId: null,
status: 'not_diagnosed',
issues: [],
createdAt: null,
repairStatus: 'repaired',
requiresPostRepairDiagnosis: true,
resourceAudit: {
status: 'insufficient_evidence',
issueCount: 0,
evidenceCount: 2,
expectedActionCount: 0,
coveredActionCount: 0,
coverage: null
}
}
}
describe('实际修复问题与独立 AI 复查分类', () => {
@@ -17,15 +35,43 @@ describe('实际修复问题与独立 AI 复查分类', () => {
expect(diagnosisHasAttention(repaired())).toBe(false)
})
it('过期的冲突或待核对建议不能当成当前动作问题', () => {
expect(diagnosisHasAttention({ ...repaired(), status: 'stale', shotStale: true,
bodyMotionFindings: [{ dimension: 'balance', status: 'conflict', description: '旧冲突', quote: '旧原文' }] })).toBe(false)
expect(
diagnosisHasAttention({
...repaired(),
status: 'stale',
shotStale: true,
bodyMotionFindings: [
{ dimension: 'balance', status: 'conflict', description: '旧冲突', quote: '旧原文' }
]
})
).toBe(false)
expect(diagnosisHasAttention({ ...repaired(), status: 'insufficient_evidence' })).toBe(false)
})
it('当前明确冲突和实时资源问题始终保留,不能因已经修订而隐藏', () => {
expect(diagnosisHasAttention({ ...repaired(), status: 'conflict_found', policyStatus: 'current', shotStale: false })).toBe(true)
expect(diagnosisHasAttention({ ...repaired(), resourceAudit: { ...repaired().resourceAudit!, status: 'conflict_found', issueCount: 1 } })).toBe(true)
expect(diagnosisHasAttention({ ...repaired(), status: 'no_conflict_found', policyStatus: 'current',
bodyMotionFindings: [{ dimension: 'balance', status: 'conflict', description: '当前冲突', quote: '原文' }] })).toBe(true)
expect(
diagnosisHasAttention({
...repaired(),
status: 'conflict_found',
policyStatus: 'current',
shotStale: false
})
).toBe(true)
expect(
diagnosisHasAttention({
...repaired(),
resourceAudit: { ...repaired().resourceAudit!, status: 'conflict_found', issueCount: 1 }
})
).toBe(true)
expect(
diagnosisHasAttention({
...repaired(),
status: 'no_conflict_found',
policyStatus: 'current',
bodyMotionFindings: [
{ dimension: 'balance', status: 'conflict', description: '当前冲突', quote: '原文' }
]
})
).toBe(true)
})
it('可选 AI 复查受限不要求重新拆解或替用户放开模型请求', () => {
for (const code of ['QUALITY_POLICY_SNAPSHOT_UNKNOWN', 'QUALITY_POLICY_SNAPSHOT_INVALID']) {
@@ -9,29 +9,100 @@ import { diagnosisCanStart } from '@/features/breakdown/diagnosis'
import type { DiagnosisPreflight } from '@/features/breakdown/diagnosis.types'
/** 当前正式镜头的免费来源检查。 */
const checked = (): DiagnosisPreflight => ({ projectId: 'diag-p', shotId: 'db-shot', episodeNo: 1, beatNo: 1, shotNo: 1, policyRevision: 3, policyFingerprint: 'a'.repeat(64), existingDiagnosisId: null, existingValid: false, eligibleForFurtherValidation: true, errors: [], requiresExecutionValidation: true, shouldDiagnose: true, willCallModel: false, willModifyAssets: false })
const checked = (): DiagnosisPreflight => ({
projectId: 'diag-p',
shotId: 'db-shot',
episodeNo: 1,
beatNo: 1,
shotNo: 1,
policyRevision: 3,
policyFingerprint: 'a'.repeat(64),
existingDiagnosisId: null,
existingValid: false,
eligibleForFurtherValidation: true,
errors: [],
requiresExecutionValidation: true,
shouldDiagnose: true,
willCallModel: false,
willModifyAssets: false
})
let wrapper: VueWrapper | undefined
/** 最近范围的真实形状,不包含可用于编辑的完整动作字段。 */
const preview = () => ({ projectId: 'diag-p', episodeNo: 1, candidateCount: 1, needsEvidenceCount: 1, invalidSnapshotCount: 0, candidates: [{ shotId: 'db-shot', episodeNo: 1, beatNo: 1, shotNo: 1, title: '当前镜头', description: '原始描述', durationSeconds: 4, requiredActionCount: 2, hasDurationPlanning: true, hasHandOccupancy: true, status: 'has_evidence' as const }], willCallModel: false as const, willModifyAssets: false as const })
const preview = () => ({
projectId: 'diag-p',
episodeNo: 1,
candidateCount: 1,
needsEvidenceCount: 1,
invalidSnapshotCount: 0,
candidates: [
{
shotId: 'db-shot',
episodeNo: 1,
beatNo: 1,
shotNo: 1,
title: '当前镜头',
description: '原始描述',
durationSeconds: 4,
requiredActionCount: 2,
hasDurationPlanning: true,
hasHandOccupancy: true,
status: 'has_evidence' as const
}
],
willCallModel: false as const,
willModifyAssets: false as const
})
/** 只读接口全部隔离,任何未授权模型请求均由测试捕获。 */
function mocks() {
vi.spyOn(workflowExecutionApi, 'latest').mockResolvedValue(null)
vi.spyOn(breakdownApi, 'legacyActionDiagnosisResults').mockResolvedValue({ projectId: 'diag-p', episodeNo: 1, counts: { total: 0, conflict: 0, clear: 0, insufficient: 0, invalid: 0, stale: 0, pending: 0 }, shots: [] })
vi.spyOn(breakdownApi, 'handOccupancyDiagnostics').mockResolvedValue({ projectId: 'diag-p', shotCount: 0, diagnostics: [] } as never)
vi.spyOn(breakdownApi, 'legacyActionDiagnosisResults').mockResolvedValue({
projectId: 'diag-p',
episodeNo: 1,
counts: { total: 0, conflict: 0, clear: 0, insufficient: 0, invalid: 0, stale: 0, pending: 0 },
shots: []
})
vi.spyOn(breakdownApi, 'handOccupancyDiagnostics').mockResolvedValue({
projectId: 'diag-p',
shotCount: 0,
diagnostics: []
} as never)
vi.spyOn(breakdownApi, 'legacyActionDiagnosisPreview').mockImplementation(async () => preview())
return vi.spyOn(breakdownApi, 'startLegacyActionDiagnosis')
}
beforeEach(() => { vi.spyOn(preparationApi, 'revisions').mockResolvedValue({ projectId: 'diag-p', shotId: 'db-shot', count: 0, revisions: [] }) })
afterEach(() => { wrapper?.unmount(); wrapper = undefined; vi.restoreAllMocks(); vi.unstubAllGlobals(); document.body.innerHTML = '' })
beforeEach(() => {
vi.spyOn(preparationApi, 'revisions').mockResolvedValue({
projectId: 'diag-p',
shotId: 'db-shot',
count: 0,
revisions: []
})
})
afterEach(() => {
wrapper?.unmount()
wrapper = undefined
vi.restoreAllMocks()
vi.unstubAllGlobals()
document.body.innerHTML = ''
})
describe('单镜头诊断收费前来源检查', () => {
it('高级检查保留复查记录与范围,隐藏旧手部统计且不改变诊断启动条件', async () => {
const start = mocks()
vi.spyOn(breakdownApi, 'diagnosisPreflight').mockResolvedValue(checked())
vi.mocked(breakdownApi.handOccupancyDiagnostics).mockResolvedValue({ projectId: 'diag-p', shotCount: 61, evidenceShotCount: 42,
warningCount: 0, assessment: 'partial_evidence', diagnostics: [] } as never)
wrapper = mount(StoryboardDiagnosis, { attachTo: document.body, props: { projectId: 'diag-p', episodeNo: 1, episodeNos: [1] } })
wrapper.getComponent(StoryboardDiagnosis).vm.open({ episodeNo: 1, beatNo: 1, shotNo: 1 }); await flushPromises()
vi.mocked(breakdownApi.handOccupancyDiagnostics).mockResolvedValue({
projectId: 'diag-p',
shotCount: 61,
evidenceShotCount: 42,
warningCount: 0,
assessment: 'partial_evidence',
diagnostics: []
} as never)
wrapper = mount(StoryboardDiagnosis, {
attachTo: document.body,
props: { projectId: 'diag-p', episodeNo: 1, episodeNos: [1] }
})
wrapper.getComponent(StoryboardDiagnosis).vm.open({ episodeNo: 1, beatNo: 1, shotNo: 1 })
await flushPromises()
const drawer = new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!)
expect(drawer.text()).toContain('高级检查详情')
expect(drawer.find('.diagnosis-counts').exists()).toBe(false)
@@ -52,11 +123,33 @@ describe('单镜头诊断收费前来源检查', () => {
})
it('确实检出的结构化冲突在普通区域可见,不随高级详情一起隐藏', async () => {
mocks()
vi.mocked(breakdownApi.handOccupancyDiagnostics).mockResolvedValue({ projectId: 'diag-p', shotCount: 1, evidenceShotCount: 1,
warningCount: 1, assessment: 'complete_evidence', diagnostics: [{ episodeNo: 1, beatNo: 1, shotNo: 1, phaseNo: 1,
characterRef: '@CH0001', actionIds: ['a1','a2'], code: 'hand_occupancy_conflict', severity: 'warning', suggestion: '右手同时执行了冲突动作' }] } as never)
wrapper = mount(StoryboardDiagnosis, { attachTo: document.body, props: { projectId: 'diag-p', episodeNo: 1, episodeNos: [1] } })
await flushPromises(); await wrapper.get('button').trigger('click'); await flushPromises()
vi.mocked(breakdownApi.handOccupancyDiagnostics).mockResolvedValue({
projectId: 'diag-p',
shotCount: 1,
evidenceShotCount: 1,
warningCount: 1,
assessment: 'complete_evidence',
diagnostics: [
{
episodeNo: 1,
beatNo: 1,
shotNo: 1,
phaseNo: 1,
characterRef: '@CH0001',
actionIds: ['a1', 'a2'],
code: 'hand_occupancy_conflict',
severity: 'warning',
suggestion: '右手同时执行了冲突动作'
}
]
} as never)
wrapper = mount(StoryboardDiagnosis, {
attachTo: document.body,
props: { projectId: 'diag-p', episodeNo: 1, episodeNos: [1] }
})
await flushPromises()
await wrapper.get('button').trigger('click')
await flushPromises()
const drawer = new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!)
expect(drawer.text()).toContain('右手同时执行了冲突动作')
expect(drawer.find('.diagnosis-evidence-collapse').text()).not.toContain('右手同时执行了冲突动作')
@@ -65,14 +158,32 @@ describe('单镜头诊断收费前来源检查', () => {
it('规则缺失、跨项目、已可复用和不完整检查都不能进入新诊断', () => {
expect(diagnosisCanStart(checked(), 'diag-p', 'db-shot')).toBe(true)
for (const invalid of [{ projectId: 'other' }, { shotId: 'other' }, { existingValid: true }, { shouldDiagnose: false }, { policyRevision: null }, { policyFingerprint: null }, { errors: ['QUALITY_POLICY_SNAPSHOT_UNKNOWN'] }, { eligibleForFurtherValidation: false }])
for (const invalid of [
{ projectId: 'other' },
{ shotId: 'other' },
{ existingValid: true },
{ shouldDiagnose: false },
{ policyRevision: null },
{ policyFingerprint: null },
{ errors: ['QUALITY_POLICY_SNAPSHOT_UNKNOWN'] },
{ eligibleForFurtherValidation: false }
])
expect(diagnosisCanStart({ ...checked(), ...invalid }, 'diag-p', 'db-shot')).toBe(false)
})
it('正式单镜头入口先预检查,缺少规则快照显示中文原因且不发收费请求', async () => {
const start = mocks()
const read = vi.spyOn(breakdownApi, 'diagnosisPreflight').mockResolvedValue({ ...checked(), shouldDiagnose: false, eligibleForFurtherValidation: false, errors: ['QUALITY_POLICY_SNAPSHOT_UNKNOWN'] })
wrapper = mount(StoryboardDiagnosis, { attachTo: document.body, props: { projectId: 'diag-p', episodeNo: 1, episodeNos: [1] } })
wrapper.getComponent(StoryboardDiagnosis).vm.open({ episodeNo: 1, beatNo: 1, shotNo: 1 }); await flushPromises()
const read = vi.spyOn(breakdownApi, 'diagnosisPreflight').mockResolvedValue({
...checked(),
shouldDiagnose: false,
eligibleForFurtherValidation: false,
errors: ['QUALITY_POLICY_SNAPSHOT_UNKNOWN']
})
wrapper = mount(StoryboardDiagnosis, {
attachTo: document.body,
props: { projectId: 'diag-p', episodeNo: 1, episodeNos: [1] }
})
wrapper.getComponent(StoryboardDiagnosis).vm.open({ episodeNo: 1, beatNo: 1, shotNo: 1 })
await flushPromises()
expect(read).toHaveBeenCalledWith('diag-p', 'db-shot')
const drawer = new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!)
expect(drawer.text()).toContain('缺少可信的质量规则记录')
@@ -81,41 +192,135 @@ describe('单镜头诊断收费前来源检查', () => {
})
it('费用确认后再次检查,规则变化时保留只读结果并撤销启动', async () => {
const start = mocks()
vi.spyOn(breakdownApi, 'diagnosisPreflight').mockResolvedValueOnce(checked()).mockResolvedValue({ ...checked(), policyRevision: 4, policyFingerprint: 'b'.repeat(64) })
wrapper = mount(StoryboardDiagnosis, { attachTo: document.body, props: { projectId: 'diag-p', episodeNo: 1, episodeNos: [1] } })
wrapper.getComponent(StoryboardDiagnosis).vm.open({ episodeNo: 1, beatNo: 1, shotNo: 1 }); await flushPromises()
await new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!).get('[aria-label="启动 AI 复查"]').trigger('click')
vi.spyOn(breakdownApi, 'diagnosisPreflight')
.mockResolvedValueOnce(checked())
.mockResolvedValue({ ...checked(), policyRevision: 4, policyFingerprint: 'b'.repeat(64) })
wrapper = mount(StoryboardDiagnosis, {
attachTo: document.body,
props: { projectId: 'diag-p', episodeNo: 1, episodeNos: [1] }
})
wrapper.getComponent(StoryboardDiagnosis).vm.open({ episodeNo: 1, beatNo: 1, shotNo: 1 })
await flushPromises()
await new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!)
.get('[aria-label="启动 AI 复查"]')
.trigger('click')
await flushPromises()
const confirmation = new DOMWrapper(document.querySelector('.app-dialog')!)
await confirmation.findAll('button').find(button => button.text() === '确认启动 AI 复查')!.trigger('click')
await confirmation
.findAll('button')
.find(button => button.text() === '确认启动 AI 复查')!
.trigger('click')
await flushPromises()
expect(start).not.toHaveBeenCalled()
expect(new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!).get('[aria-label="启动 AI 复查"]').attributes('disabled')).toBeDefined()
expect(
new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!)
.get('[aria-label="启动 AI 复查"]')
.attributes('disabled')
).toBeDefined()
})
it('镜头描述在费用确认期间变化时必须重新预览,不能直接诊断新内容', async () => {
const start = mocks()
vi.spyOn(breakdownApi, 'diagnosisPreflight').mockResolvedValue(checked())
vi.mocked(breakdownApi.legacyActionDiagnosisPreview).mockResolvedValueOnce(preview()).mockResolvedValue({ ...preview(), candidates: [{ ...preview().candidates[0]!, description: '已更改的新镜头' }] })
wrapper = mount(StoryboardDiagnosis, { attachTo: document.body, props: { projectId: 'diag-p', episodeNo: 1, episodeNos: [1] } })
wrapper.getComponent(StoryboardDiagnosis).vm.open({ episodeNo: 1, beatNo: 1, shotNo: 1 }); await flushPromises()
await new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!).get('[aria-label="启动 AI 复查"]').trigger('click'); await flushPromises()
await new DOMWrapper(document.querySelector('.app-dialog')!).findAll('button').find(button => button.text() === '确认启动 AI 复查')!.trigger('click'); await flushPromises()
vi.mocked(breakdownApi.legacyActionDiagnosisPreview)
.mockResolvedValueOnce(preview())
.mockResolvedValue({
...preview(),
candidates: [{ ...preview().candidates[0]!, description: '已更改的新镜头' }]
})
wrapper = mount(StoryboardDiagnosis, {
attachTo: document.body,
props: { projectId: 'diag-p', episodeNo: 1, episodeNos: [1] }
})
wrapper.getComponent(StoryboardDiagnosis).vm.open({ episodeNo: 1, beatNo: 1, shotNo: 1 })
await flushPromises()
await new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!)
.get('[aria-label="启动 AI 复查"]')
.trigger('click')
await flushPromises()
await new DOMWrapper(document.querySelector('.app-dialog')!)
.findAll('button')
.find(button => button.text() === '确认启动 AI 复查')!
.trigger('click')
await flushPromises()
expect(start).not.toHaveBeenCalled()
})
it('修订条件与历史按需读取,跨项目响应不显示为可修订', async () => {
const history = vi.spyOn(breakdownApi, 'diagnosisHistory').mockResolvedValue({ projectId: 'other', shotId: 'db-shot', count: 0, revisions: [] })
vi.spyOn(breakdownApi, 'diagnosisRepairReadiness').mockResolvedValue({ projectId: 'other', shotId: 'db-shot', diagnosisId: 'd', eligible: true, repairCandidates: [], blockingReasons: [], requiresManualReview: true, canApplyDirectly: false, willCallModel: false, willModifyAssets: false })
wrapper = mount(DiagnosisShotDetails, { props: { projectId: 'diag-p', shot: { shotId: 'db-shot', episodeNo: 1, beatNo: 1, shotNo: 1, title: '镜头', diagnosisId: 'd', status: 'conflict_found', issues: [], createdAt: null } } })
const history = vi
.spyOn(breakdownApi, 'diagnosisHistory')
.mockResolvedValue({ projectId: 'other', shotId: 'db-shot', count: 0, revisions: [] })
vi.spyOn(breakdownApi, 'diagnosisRepairReadiness').mockResolvedValue({
projectId: 'other',
shotId: 'db-shot',
diagnosisId: 'd',
eligible: true,
repairCandidates: [],
blockingReasons: [],
requiresManualReview: true,
canApplyDirectly: false,
willCallModel: false,
willModifyAssets: false
})
wrapper = mount(DiagnosisShotDetails, {
props: {
projectId: 'diag-p',
shot: {
shotId: 'db-shot',
episodeNo: 1,
beatNo: 1,
shotNo: 1,
title: '镜头',
diagnosisId: 'd',
status: 'conflict_found',
issues: [],
createdAt: null
}
}
})
expect(history).not.toHaveBeenCalled()
await wrapper.get('button').trigger('click'); await flushPromises()
await wrapper.get('button').trigger('click')
await flushPromises()
expect(wrapper.text()).toContain('记录与当前镜头不一致')
expect(wrapper.text()).not.toContain('已满足人工修订')
})
it('旧诊断即使只读资格返回 eligible,也不能显示成当前可修订', async () => {
vi.spyOn(breakdownApi, 'diagnosisHistory').mockResolvedValue({ projectId: 'diag-p', shotId: 'db-shot', count: 0, revisions: [] })
vi.spyOn(breakdownApi, 'diagnosisRepairReadiness').mockResolvedValue({ projectId: 'diag-p', shotId: 'db-shot', diagnosisId: 'd', eligible: true, repairCandidates: [], blockingReasons: [], requiresManualReview: true, canApplyDirectly: false, willCallModel: false, willModifyAssets: false })
wrapper = mount(DiagnosisShotDetails, { props: { projectId: 'diag-p', shot: { shotId: 'db-shot', episodeNo: 1, beatNo: 1, shotNo: 1, title: '镜头', diagnosisId: 'd', status: 'stale', policyStatus: 'stale', shotStale: false, issues: [], createdAt: null } } })
await wrapper.get('button').trigger('click'); await flushPromises()
vi.spyOn(breakdownApi, 'diagnosisHistory').mockResolvedValue({
projectId: 'diag-p',
shotId: 'db-shot',
count: 0,
revisions: []
})
vi.spyOn(breakdownApi, 'diagnosisRepairReadiness').mockResolvedValue({
projectId: 'diag-p',
shotId: 'db-shot',
diagnosisId: 'd',
eligible: true,
repairCandidates: [],
blockingReasons: [],
requiresManualReview: true,
canApplyDirectly: false,
willCallModel: false,
willModifyAssets: false
})
wrapper = mount(DiagnosisShotDetails, {
props: {
projectId: 'diag-p',
shot: {
shotId: 'db-shot',
episodeNo: 1,
beatNo: 1,
shotNo: 1,
title: '镜头',
diagnosisId: 'd',
status: 'stale',
policyStatus: 'stale',
shotStale: false,
issues: [],
createdAt: null
}
}
})
await wrapper.get('button').trigger('click')
await flushPromises()
expect(wrapper.text()).not.toContain('已满足人工修订')
})
})
@@ -10,21 +10,61 @@ import type { LegacyActionDiagnosisResults } from '@/features/breakdown/types'
import type { WorkflowExecution } from '@/features/workflows/execution.types'
/** 页面回执同时包含修订完成、局部证据不足和 AI 待复查。 */
const shot: LegacyActionDiagnosisResults['shots'][number] = { shotId: 'shot-1', episodeNo: 1, beatNo: 1, shotNo: 1, title: '捂耳取铃', diagnosisId: 'diag-1', status: 'stale' as const, issues: [], createdAt: null,
policyStatus: 'stale', shotStale: true, repairStatus: 'repaired', requiresPostRepairDiagnosis: true,
handAudit: { status: 'partial_evidence', evidenceCount: 1, expectedActionCount: 2, coveredActionCount: 1, issueCount: 0, coverage: 0.5 },
bodyMotionFindings: [{ dimension: 'balance', status: 'needs_review', description: '重心需要核对', quote: '单脚站立' }] }
const shot: LegacyActionDiagnosisResults['shots'][number] = {
shotId: 'shot-1',
episodeNo: 1,
beatNo: 1,
shotNo: 1,
title: '捂耳取铃',
diagnosisId: 'diag-1',
status: 'stale' as const,
issues: [],
createdAt: null,
policyStatus: 'stale',
shotStale: true,
repairStatus: 'repaired',
requiresPostRepairDiagnosis: true,
handAudit: {
status: 'partial_evidence',
evidenceCount: 1,
expectedActionCount: 2,
coveredActionCount: 1,
issueCount: 0,
coverage: 0.5
},
bodyMotionFindings: [
{ dimension: 'balance', status: 'needs_review', description: '重心需要核对', quote: '单脚站立' }
]
}
let wrapper: VueWrapper | undefined
afterEach(() => { wrapper?.unmount(); wrapper = undefined; vi.restoreAllMocks(); vi.unstubAllGlobals(); document.body.innerHTML = '' })
afterEach(() => {
wrapper?.unmount()
wrapper = undefined
vi.restoreAllMocks()
vi.unstubAllGlobals()
document.body.innerHTML = ''
})
describe('诊断版本及复查展示', () => {
it('顶部摘要优先表达正式审核通过,不因没有额外 AI 记录提示分镜尚未诊断', async () => {
const current = { ...shot, status: 'not_diagnosed' as const, policyStatus: 'not_diagnosed' as const, shotStale: false, bodyMotionFindings: [] }
vi.spyOn(breakdownApi, 'legacyActionDiagnosisResults').mockResolvedValue({ projectId: 'diag-update', episodeNo: 1,
counts: { total: 1, conflict: 0, clear: 0, insufficient: 0, invalid: 0, stale: 0, pending: 1 }, shots: [current] })
const current = {
...shot,
status: 'not_diagnosed' as const,
policyStatus: 'not_diagnosed' as const,
shotStale: false,
bodyMotionFindings: []
}
vi.spyOn(breakdownApi, 'legacyActionDiagnosisResults').mockResolvedValue({
projectId: 'diag-update',
episodeNo: 1,
counts: { total: 1, conflict: 0, clear: 0, insufficient: 0, invalid: 0, stale: 0, pending: 1 },
shots: [current]
})
const context = testProjectContext('diag-update')
wrapper = mount(StoryboardDiagnosis, { props: { projectId: 'diag-update', episodeNo: 1, episodeNos: [1] },
global: { provide: { [projectContextKey as symbol]: context } } })
wrapper = mount(StoryboardDiagnosis, {
props: { projectId: 'diag-update', episodeNo: 1, episodeNos: [1] },
global: { provide: { [projectContextKey as symbol]: context } }
})
await flushPromises()
expect(wrapper.text()).toContain('分镜校验与审核已通过')
expect(wrapper.text()).not.toContain('尚未诊断')
@@ -38,27 +78,66 @@ describe('诊断版本及复查展示', () => {
expect(wrapper.text()).not.toContain('分镜校验与审核已通过')
})
it('有当前真实问题时摘要仍明确提示处理,不被正式审核状态盖住', async () => {
const current = { ...shot, status: 'conflict_found' as const, policyStatus: 'current' as const, shotStale: false, bodyMotionFindings: [] }
vi.spyOn(breakdownApi, 'legacyActionDiagnosisResults').mockResolvedValue({ projectId: 'diag-update', episodeNo: 1,
counts: { total: 1, conflict: 1, clear: 0, insufficient: 0, invalid: 0, stale: 0, pending: 0 }, shots: [current] })
wrapper = mount(StoryboardDiagnosis, { props: { projectId: 'diag-update', episodeNo: 1, episodeNos: [1] },
global: { provide: { [projectContextKey as symbol]: testProjectContext('diag-update') } } })
const current = {
...shot,
status: 'conflict_found' as const,
policyStatus: 'current' as const,
shotStale: false,
bodyMotionFindings: []
}
vi.spyOn(breakdownApi, 'legacyActionDiagnosisResults').mockResolvedValue({
projectId: 'diag-update',
episodeNo: 1,
counts: { total: 1, conflict: 1, clear: 0, insufficient: 0, invalid: 0, stale: 0, pending: 0 },
shots: [current]
})
wrapper = mount(StoryboardDiagnosis, {
props: { projectId: 'diag-update', episodeNo: 1, episodeNos: [1] },
global: { provide: { [projectContextKey as symbol]: testProjectContext('diag-update') } }
})
await flushPromises()
expect(wrapper.text()).toContain('1 个镜头有实际问题待处理')
expect(wrapper.text()).not.toContain('分镜校验与审核已通过')
})
it('已修订并审核通过默认不列入需处理,可在可选复查中查看且没有修复按钮', async () => {
const current = { ...shot, status: 'not_diagnosed' as const, policyStatus: 'not_diagnosed' as const,
shotStale: false, bodyMotionFindings: [], handAudit: undefined,
resourceAudit: { status: 'insufficient_evidence' as const, issueCount: 0, evidenceCount: 2, expectedActionCount: 0, coveredActionCount: 0, coverage: null } }
vi.spyOn(breakdownApi, 'legacyActionDiagnosisResults').mockResolvedValue({ projectId: 'diag-update', episodeNo: 1,
counts: { total: 1, conflict: 0, clear: 0, insufficient: 0, invalid: 0, stale: 0, pending: 1 }, shots: [current] })
vi.spyOn(breakdownApi, 'handOccupancyDiagnostics').mockResolvedValue({ projectId: 'diag-update', shotCount: 1, evidenceShotCount: 0, diagnostics: [] } as never)
const current = {
...shot,
status: 'not_diagnosed' as const,
policyStatus: 'not_diagnosed' as const,
shotStale: false,
bodyMotionFindings: [],
handAudit: undefined,
resourceAudit: {
status: 'insufficient_evidence' as const,
issueCount: 0,
evidenceCount: 2,
expectedActionCount: 0,
coveredActionCount: 0,
coverage: null
}
}
vi.spyOn(breakdownApi, 'legacyActionDiagnosisResults').mockResolvedValue({
projectId: 'diag-update',
episodeNo: 1,
counts: { total: 1, conflict: 0, clear: 0, insufficient: 0, invalid: 0, stale: 0, pending: 1 },
shots: [current]
})
vi.spyOn(breakdownApi, 'handOccupancyDiagnostics').mockResolvedValue({
projectId: 'diag-update',
shotCount: 1,
evidenceShotCount: 0,
diagnostics: []
} as never)
const start = vi.spyOn(breakdownApi, 'startLegacyActionDiagnosis')
wrapper = mount(StoryboardDiagnosis, { attachTo: document.body, props: { projectId: 'diag-update', episodeNo: 1, episodeNos: [1] },
global: { provide: { [projectContextKey as symbol]: testProjectContext('diag-update') } } })
await flushPromises(); await wrapper.get('button').trigger('click'); await flushPromises()
wrapper = mount(StoryboardDiagnosis, {
attachTo: document.body,
props: { projectId: 'diag-update', episodeNo: 1, episodeNos: [1] },
global: { provide: { [projectContextKey as symbol]: testProjectContext('diag-update') } }
})
await flushPromises()
await wrapper.get('button').trigger('click')
await flushPromises()
const dialog = new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!)
expect(dialog.findAll('.diagnosis-result-item')).toHaveLength(0)
expect(dialog.text()).toContain('当前正式分镜已审核通过')
@@ -73,12 +152,28 @@ describe('诊断版本及复查展示', () => {
})
it('修订完成不显示全部通过,展示规则和镜头过期、手部覆盖及全身疑点', async () => {
vi.spyOn(breakdownApi, 'legacyActionDiagnosisResults').mockResolvedValue({ projectId: 'diag-update', episodeNo: 1, counts: { total: 1, conflict: 0, clear: 0, insufficient: 0, invalid: 0, stale: 1, pending: 0 }, shots: [shot] })
vi.spyOn(breakdownApi, 'handOccupancyDiagnostics').mockResolvedValue({ projectId: 'diag-update', shotCount: 1, evidenceShotCount: 0, diagnostics: [] } as never)
wrapper = mount(StoryboardDiagnosis, { attachTo: document.body, props: { projectId: 'diag-update', episodeNo: 1, episodeNos: [1] } })
await flushPromises(); await wrapper.get('button').trigger('click'); await flushPromises()
vi.spyOn(breakdownApi, 'legacyActionDiagnosisResults').mockResolvedValue({
projectId: 'diag-update',
episodeNo: 1,
counts: { total: 1, conflict: 0, clear: 0, insufficient: 0, invalid: 0, stale: 1, pending: 0 },
shots: [shot]
})
vi.spyOn(breakdownApi, 'handOccupancyDiagnostics').mockResolvedValue({
projectId: 'diag-update',
shotCount: 1,
evidenceShotCount: 0,
diagnostics: []
} as never)
wrapper = mount(StoryboardDiagnosis, {
attachTo: document.body,
props: { projectId: 'diag-update', episodeNo: 1, episodeNos: [1] }
})
await flushPromises()
await wrapper.get('button').trigger('click')
await flushPromises()
const dialog = new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!)
wrapper!.getComponent(NSelect).vm.$emit('update:value', 'review'); await flushPromises()
wrapper!.getComponent(NSelect).vm.$emit('update:value', 'review')
await flushPromises()
expect(dialog.text()).toContain('镜头已修订,可按需进行 AI 复查。')
expect(dialog.text()).toContain('镜头内容已变化')
expect(dialog.text()).toContain('质量规则已变化')
@@ -87,8 +182,32 @@ describe('诊断版本及复查展示', () => {
expect(dialog.text()).not.toContain('全部通过')
})
it('中断诊断显示人工核查与可复用数量,不把未匹配镜头描述为未计费', () => {
const execution = { id: 'task', projectId: 'p', workflowName: 'storyboard-legacy-action-diagnosis', status: 'failed', current: 1, total: 3,
result: { recoveryRequired: true, retryAutomatically: false, requiresManualReview: true, resumeMode: 'manual', reusableShotCount: 1, manualReviewShotCount: 2, scopedShotCount: 3, qualityPolicyVerified: true }, metadata: null, stage: 'interrupted', currentResourceId: null, error: '诊断中断', startedAt: null, completedAt: null, createdAt: '', updatedAt: '' } satisfies WorkflowExecution
const execution = {
id: 'task',
projectId: 'p',
workflowName: 'storyboard-legacy-action-diagnosis',
status: 'failed',
current: 1,
total: 3,
result: {
recoveryRequired: true,
retryAutomatically: false,
requiresManualReview: true,
resumeMode: 'manual',
reusableShotCount: 1,
manualReviewShotCount: 2,
scopedShotCount: 3,
qualityPolicyVerified: true
},
metadata: null,
stage: 'interrupted',
currentResourceId: null,
error: '诊断中断',
startedAt: null,
completedAt: null,
createdAt: '',
updatedAt: ''
} satisfies WorkflowExecution
wrapper = mount(WorkflowExecutionPanel, { props: { execution, loading: false, error: '' } })
expect(wrapper.text()).toContain('需要人工核查')
expect(wrapper.text()).toContain('可复用 1 镜')
+83 -11
View File
@@ -1,7 +1,12 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { effectScope, ref } from 'vue'
import { flushPromises } from '@vue/test-utils'
import { assertCandidateReview, breakdownQuality, normalizeBreakdownState, selectBreakdownSource } from '@/features/breakdown/quality'
import {
assertCandidateReview,
breakdownQuality,
normalizeBreakdownState,
selectBreakdownSource
} from '@/features/breakdown/quality'
import { useBreakdownQuality } from '@/features/breakdown/useBreakdownQuality'
import { breakdownApi } from '@/features/breakdown/api'
import { candidateCheckpoint, candidateReview, candidateState } from '../../fixtures/breakdown-candidate'
@@ -9,7 +14,11 @@ import type { CandidateRevalidation } from '@/features/breakdown/candidate.types
/** 测试后释放自动版本观察,避免跨用例请求。 */
let scope: ReturnType<typeof effectScope> | undefined
afterEach(() => { scope?.stop(); scope = undefined; vi.restoreAllMocks() })
afterEach(() => {
scope?.stop()
scope = undefined
vi.restoreAllMocks()
})
describe('拆解当前质量与来源隔离', () => {
it('新版候选缺少顶层成果时不借用完整的旧嵌套成果充数', () => {
@@ -29,7 +38,9 @@ describe('拆解当前质量与来源隔离', () => {
})
it('最新候选通过时不显示历史五个错误,也不把候选当作正式结果', () => {
const old = Array.from({ length: 5 }, (_, index) => ({ episodeNo: 1, message: `历史错误 ${index}` }))
const record = candidateCheckpoint(candidateState({ breakdownResult: { storyboardShotValidation: { valid: false, issues: old } } }))
const record = candidateCheckpoint(
candidateState({ breakdownResult: { storyboardShotValidation: { valid: false, issues: old } } })
)
const source = selectBreakdownSource([record])
const quality = breakdownQuality(source, candidateReview({ previousIssues: old }))
expect(source.kind).toBe('candidate')
@@ -40,8 +51,42 @@ describe('拆解当前质量与来源隔离', () => {
expect(quality.canRequestCommitPreview).toBe(true)
})
it('真实结构问题与动作阻断分别统计,正常道具检查不会变成错误', () => {
const block = { episodeNo: 1, beatNo: 1, shotNo: 2, status: 'blocked' as const, blockingCodes: ['state_used_as_action_phase'], warningCodes: [], isPendingEpisode: true }
const quality = breakdownQuality(selectBreakdownSource([candidateCheckpoint()]), candidateReview({ currentIssues: [{ episodeNo: 1, beatNo: 1, shotNo: 1, message: '主体引用缺失' }], actionQualityBlocks: [block], pendingQualityEpisodeNos: [1], candidateValidation: { valid: false, issues: ['Storyboard 质量审核未通过', '仍存在待处理的分镜质量问题'] }, propReferenceDiagnostics: [{ episodeNo: 1, beatNo: 1, shotNo: 1, subjectRef: '@PR0001', shotTitle: '', shotDescription: '', beatAllowsSubject: true, shotHasSubject: true, shotHasBinding: true, subjectName: '铜铃', availableForms: [] }] }))
const block = {
episodeNo: 1,
beatNo: 1,
shotNo: 2,
status: 'blocked' as const,
blockingCodes: ['state_used_as_action_phase'],
warningCodes: [],
isPendingEpisode: true
}
const quality = breakdownQuality(
selectBreakdownSource([candidateCheckpoint()]),
candidateReview({
currentIssues: [{ episodeNo: 1, beatNo: 1, shotNo: 1, message: '主体引用缺失' }],
actionQualityBlocks: [block],
pendingQualityEpisodeNos: [1],
candidateValidation: {
valid: false,
issues: ['Storyboard 质量审核未通过', '仍存在待处理的分镜质量问题']
},
propReferenceDiagnostics: [
{
episodeNo: 1,
beatNo: 1,
shotNo: 1,
subjectRef: '@PR0001',
shotTitle: '',
shotDescription: '',
beatAllowsSubject: true,
shotHasSubject: true,
shotHasBinding: true,
subjectName: '铜铃',
availableForms: []
}
]
})
)
expect(quality.structuralIssues).toHaveLength(1)
expect(quality.actionBlocks).toHaveLength(1)
expect(quality.issueCount).toBe(2)
@@ -52,24 +97,43 @@ describe('拆解当前质量与来源隔离', () => {
expect(breakdownQuality(source, candidateReview(), true).structureValid).toBeNull()
expect(breakdownQuality(source, null, false, '读取失败').canRequestCommitPreview).toBe(false)
expect(breakdownQuality(source, candidateReview({ checkpointId: 'old' })).needsRefresh).toBe(true)
expect(() => assertCandidateReview(candidateReview({ checkpointId: 'old' }), 'candidate-project', 'candidate-current')).toThrow('过期')
expect(() =>
assertCandidateReview(candidateReview({ checkpointId: 'old' }), 'candidate-project', 'candidate-current')
).toThrow('过期')
})
it('完整性审核中的 Form 绑定异常计入结构问题,不能标记结构通过', () => {
const quality = breakdownQuality(selectBreakdownSource([candidateCheckpoint()]), candidateReview({ candidateValidation: { valid: false, issues: ['剧集 1 Shot 2 主体 @CH0001 形态绑定无效'] } }))
const quality = breakdownQuality(
selectBreakdownSource([candidateCheckpoint()]),
candidateReview({
candidateValidation: { valid: false, issues: ['剧集 1 Shot 2 主体 @CH0001 形态绑定无效'] }
})
)
expect(quality.structuralCount).toBe(1)
expect(quality.structureValid).toBe(false)
expect(quality.problems[0]?.type).toBe('binding')
expect(quality.canRequestCommitPreview).toBe(false)
})
it('正式提交的持久化标记优先,不继承嵌套旧错误;新候选不覆盖已有正式结果', () => {
const formal = candidateCheckpoint(candidateState({ storyboardPersisted: true, candidateCommitted: true, breakdownResult: { storyboardShotValidation: { valid: false, issues: [{ episodeNo: 1, message: '旧错误' }] } } }), 'formal')
const formal = candidateCheckpoint(
candidateState({
storyboardPersisted: true,
candidateCommitted: true,
breakdownResult: {
storyboardShotValidation: { valid: false, issues: [{ episodeNo: 1, message: '旧错误' }] }
}
}),
'formal'
)
const source = selectBreakdownSource([formal])
expect(breakdownQuality(source, null).source).toBe('formal')
expect(breakdownQuality(source, null).issueCount).toBe(0)
expect(selectBreakdownSource([formal, candidateCheckpoint()]).formal?.checkpointId).toBe('formal')
})
it('只有错误的最新记录可以回看成果,但不能继承候选提交资格或旧错误', () => {
const source = selectBreakdownSource([candidateCheckpoint(), { ...candidateCheckpoint({}, 'failed'), createdAt: '2026-10-17T10:00:00Z' }])
const source = selectBreakdownSource([
candidateCheckpoint(),
{ ...candidateCheckpoint({}, 'failed'), createdAt: '2026-10-17T10:00:00Z' }
])
const quality = breakdownQuality(source, null)
expect(source.kind).toBe('history')
expect(quality.isCandidate).toBe(false)
@@ -81,7 +145,10 @@ describe('拆解当前质量与来源隔离', () => {
const signals: AbortSignal[] = []
const read = vi.spyOn(breakdownApi, 'revalidateCandidate').mockImplementation(async (_id, signal) => {
signals.push(signal!)
if (signals.length === 1) return new Promise(resolve => { resolveOld = resolve })
if (signals.length === 1)
return new Promise(resolve => {
resolveOld = resolve
})
return candidateReview({ checkpointId: 'new' })
})
const records = ref([candidateCheckpoint()])
@@ -114,7 +181,12 @@ describe('拆解当前质量与来源隔离', () => {
it('正式提交后刷新或重新进入,不重新请求候选接口', async () => {
const read = vi.spyOn(breakdownApi, 'revalidateCandidate')
scope = effectScope()
const state = scope.run(() => useBreakdownQuality(ref('candidate-project'), ref([candidateCheckpoint(candidateState({ storyboardPersisted: true, candidateCommitted: true }))])))!
const state = scope.run(() =>
useBreakdownQuality(
ref('candidate-project'),
ref([candidateCheckpoint(candidateState({ storyboardPersisted: true, candidateCommitted: true }))])
)
)!
await state.refresh()
expect(read).not.toHaveBeenCalled()
expect(state.quality.value.committed).toBe(true)
+29 -6
View File
@@ -7,12 +7,25 @@ import { policyReceipt } from '../../fixtures/quality-policy'
import { commitPreview } from '../../fixtures/breakdown-candidate'
/** 当前规则;格式版本不能代替服务修订版本。 */
const policy = { version: 1 as const, physicsMode: 'realistic' as const, allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] }
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); localStorage.clear() })
const policy = {
version: 1 as const,
physicsMode: 'realistic' as const,
allowExaggeratedMotion: false,
allowNonPhysicalActions: false,
allowSupernaturalAbilities: false,
customRules: []
}
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
localStorage.clear()
})
describe('服务端规则确认契约', () => {
it('保存发送规则和期望修订,明确确认使用独立接口', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => new Response(JSON.stringify({ data: policyReceipt('p', policy) })))
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async () => new Response(JSON.stringify({ data: policyReceipt('p', policy) })))
vi.stubGlobal('fetch', fetcher)
await projectsApi.saveQualityPolicy('p', policy, 2)
expect(JSON.parse(String(fetcher.mock.calls[0]?.[1]?.body))).toEqual({ policy, expectedRevision: 2 })
@@ -21,7 +34,9 @@ describe('服务端规则确认契约', () => {
expect(JSON.parse(String(fetcher.mock.calls[1]?.[1]?.body))).toEqual({ expectedRevision: 2 })
})
it('服务已确认的规则跨浏览器直接进入费用确认,启动携带真实修订版本', async () => {
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('p', policy, { confirmed: true, confirmedRevision: 2, confirmedAt: '2026-10-17T15:00:00Z' }))
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(
policyReceipt('p', policy, { confirmed: true, confirmedRevision: 2, confirmedAt: '2026-10-17T15:00:00Z' })
)
const scope = effectScope()
try {
const flow = scope.run(() => useBreakdownStartPolicy(ref('p'), ref('scope'), ref(true)))!
@@ -31,11 +46,19 @@ describe('服务端规则确认契约', () => {
expect(await flow.verifyStart()).toBe(true)
expect(flow.consumePermit()).toEqual({ expectedRevision: 2 })
expect(flow.consumePermit()).toBeNull()
} finally { scope.stop() }
} finally {
scope.stop()
}
})
it('候选安全检查必须包含规则匹配,缺失或 false 均不可提交', () => {
const preview = commitPreview()
expect(candidatePreviewReady({ ...preview, checks: { ...preview.checks, qualityPolicyMatches: false } }, preview.projectId, preview.checkpointId)).toBe(false)
expect(
candidatePreviewReady(
{ ...preview, checks: { ...preview.checks, qualityPolicyMatches: false } },
preview.projectId,
preview.checkpointId
)
).toBe(false)
const missing = structuredClone(preview)
delete (missing.checks as Partial<typeof missing.checks>).qualityPolicyMatches
expect(candidatePreviewReady(missing, preview.projectId, preview.checkpointId)).toBe(false)
+185 -52
View File
@@ -8,16 +8,28 @@ import { qualityPolicySignature } from '@/features/projects/quality-policy-confi
import { policyReceipt } from '../../fixtures/quality-policy'
/** 真实规则回执,旧项目初始修订也必须明确确认。 */
const initial = () => policyReceipt('policy-project', {
version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false,
allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: []
}, { revision: 0 })
const initial = () =>
policyReceipt(
'policy-project',
{
version: 1,
physicsMode: 'realistic',
allowExaggeratedMotion: false,
allowNonPhysicalActions: false,
allowSupernaturalAbilities: false,
customRules: []
},
{ revision: 0 }
)
/** 测试结束释放全部流程观察器。 */
const scopes: EffectScope[] = []
/** 创建独立流程,不访问真实模型。 */
function setup() {
const id = ref('policy-project'), input = ref('preview-1'), allowed = ref(true)
const scope = effectScope(); scopes.push(scope)
const id = ref('policy-project'),
input = ref('preview-1'),
allowed = ref(true)
const scope = effectScope()
scopes.push(scope)
return { id, input, allowed, flow: scope.run(() => useBreakdownStartPolicy(id, input, allowed))! }
}
/** 模拟服务端 CAS 保存及独立明确确认,复制回执避免测试污染。 */
@@ -26,7 +38,10 @@ function server() {
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(saved))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (_id, policy, expected) => {
if (expected !== saved.revision) throw new Error('版本冲突')
saved = policyReceipt(saved.projectId, policyDraft(policy), { revision: saved.revision + 1, fingerprint: 'b'.repeat(64) })
saved = policyReceipt(saved.projectId, policyDraft(policy), {
revision: saved.revision + 1,
fingerprint: 'b'.repeat(64)
})
return structuredClone(saved)
})
const confirm = vi.spyOn(projectsApi, 'confirmQualityPolicy').mockImplementation(async (_id, expected) => {
@@ -34,101 +49,219 @@ function server() {
saved = { ...saved, confirmed: true, confirmedRevision: expected, confirmedAt: '2026-10-17T15:00:00Z' }
return structuredClone(saved)
})
return { read, save, confirm, get: () => saved, change: (value: Partial<ProjectQualityPolicyResult>) => { saved = { ...saved, ...value } } }
return {
read,
save,
confirm,
get: () => saved,
change: (value: Partial<ProjectQualityPolicyResult>) => {
saved = { ...saved, ...value }
}
}
}
afterEach(() => { scopes.splice(0).forEach(scope => scope.stop()); vi.restoreAllMocks(); vi.unstubAllGlobals(); localStorage.clear() })
afterEach(() => {
scopes.splice(0).forEach(scope => scope.stop())
vi.restoreAllMocks()
vi.unstubAllGlobals()
localStorage.clear()
})
describe('规则内容比较与服务端确认', () => {
it('格式版本不代替修订,比较内容时保留许可、规则和例外变化', () => {
const base = initial().policy
expect(qualityPolicySignature({ ...base, actionExceptions: [] })).toBe(qualityPolicySignature(base))
expect(qualityPolicySignature({ ...base, customRules: [' 规则 '] })).toBe(qualityPolicySignature({ ...base, customRules: ['规则'] }))
for (const change of [{ physicsMode: 'fantasy' as const }, { allowExaggeratedMotion: true }, { allowNonPhysicalActions: true }, { allowSupernaturalAbilities: true }, { customRules: ['新规则'] }, { actionExceptions: [{ code: 'action_resource_conflict' as const, ownerRef: '@CH1', resource: 'left_hand' as const, reason: '许可' }] }])
expect(qualityPolicySignature({ ...base, customRules: [' 规则 '] })).toBe(
qualityPolicySignature({ ...base, customRules: ['规则'] })
)
for (const change of [
{ physicsMode: 'fantasy' as const },
{ allowExaggeratedMotion: true },
{ allowNonPhysicalActions: true },
{ allowSupernaturalAbilities: true },
{ customRules: ['新规则'] },
{
actionExceptions: [
{
code: 'action_resource_conflict' as const,
ownerRef: '@CH1',
resource: 'left_hand' as const,
reason: '许可'
}
]
}
])
expect(qualityPolicySignature({ ...base, ...change })).not.toBe(qualityPolicySignature(base))
})
it('旧浏览器确认记录不能跳过服务未确认规则;取消不写入确认', async () => {
const api = server()
localStorage.setItem('short-drama:breakdown-quality-confirmation:v1:policy-project', JSON.stringify({ formatVersion: 1, signature: qualityPolicySignature(initial().policy) }))
const { flow } = setup(); await flow.prepare()
expect(flow.reviewOpen.value).toBe(true); expect(flow.startOpen.value).toBe(false)
flow.cancel(); expect(api.confirm).not.toHaveBeenCalled(); expect(flow.consumePermit()).toBeNull()
localStorage.setItem(
'short-drama:breakdown-quality-confirmation:v1:policy-project',
JSON.stringify({ formatVersion: 1, signature: qualityPolicySignature(initial().policy) })
)
const { flow } = setup()
await flow.prepare()
expect(flow.reviewOpen.value).toBe(true)
expect(flow.startOpen.value).toBe(false)
flow.cancel()
expect(api.confirm).not.toHaveBeenCalled()
expect(flow.consumePermit()).toBeNull()
})
it('未改规则也独立明确确认,修订零可启动,其他页面重进不重复提醒', async () => {
const api = server(); const { flow } = setup()
await flow.prepare(); expect(await flow.confirmRules(initial().policy)).toBe(true)
expect(api.save).not.toHaveBeenCalled(); expect(api.confirm).toHaveBeenCalledExactlyOnceWith('policy-project', 0)
flow.cancel(); const next = setup().flow; await next.prepare()
expect(next.reviewOpen.value).toBe(false); expect(next.startOpen.value).toBe(true)
const api = server()
const { flow } = setup()
await flow.prepare()
expect(await flow.confirmRules(initial().policy)).toBe(true)
expect(api.save).not.toHaveBeenCalled()
expect(api.confirm).toHaveBeenCalledExactlyOnceWith('policy-project', 0)
flow.cancel()
const next = setup().flow
await next.prepare()
expect(next.reviewOpen.value).toBe(false)
expect(next.startOpen.value).toBe(true)
expect(await next.verifyStart()).toBe(true)
expect(next.consumePermit()).toEqual({ expectedRevision: 0 }); expect(next.consumePermit()).toBeNull()
expect(next.consumePermit()).toEqual({ expectedRevision: 0 })
expect(next.consumePermit()).toBeNull()
})
it('修改规则先携带旧修订保存,再确认新修订,最后重读确认', async () => {
const api = server(); const { flow } = setup(); await flow.prepare()
const api = server()
const { flow } = setup()
await flow.prepare()
const draft = { ...initial().policy, allowExaggeratedMotion: true }
expect(await flow.confirmRules(draft)).toBe(true)
expect(api.save).toHaveBeenCalledExactlyOnceWith('policy-project', draft, 0)
expect(api.confirm).toHaveBeenCalledExactlyOnceWith('policy-project', 1)
expect(api.read).toHaveBeenCalledTimes(3)
expect(await flow.verifyStart()).toBe(true); expect(flow.consumePermit()).toEqual({ expectedRevision: 1 })
expect(await flow.verifyStart()).toBe(true)
expect(flow.consumePermit()).toEqual({ expectedRevision: 1 })
})
it('同内容被修改后又恢复但修订增加时仍重新确认,不能覆盖更新', async () => {
const api = server(); const { flow } = setup(); await flow.prepare()
const api = server()
const { flow } = setup()
await flow.prepare()
api.change({ revision: 4 })
expect(await flow.confirmRules(initial().policy)).toBe(false)
expect(flow.policy.value?.revision).toBe(4); expect(api.save).not.toHaveBeenCalled(); expect(api.confirm).not.toHaveBeenCalled()
expect(flow.policy.value?.revision).toBe(4)
expect(api.save).not.toHaveBeenCalled()
expect(api.confirm).not.toHaveBeenCalled()
})
it.each(['读取失败', '项目不符', '元数据缺失', '保存失败', '确认失败', '回执不符', '确认后变化'])('拦截%s且不取得启动许可', async kind => {
const api = server(); const { flow } = setup(); await flow.prepare()
it.each(['读取失败', '项目不符', '元数据缺失', '保存失败', '确认失败', '回执不符', '确认后变化'])(
'拦截%s且不取得启动许可',
async kind => {
const api = server()
const { flow } = setup()
await flow.prepare()
const draft = { ...initial().policy, allowNonPhysicalActions: true }
if (kind === '读取失败') api.read.mockRejectedValueOnce(new Error('读取失败'))
if (kind === '项目不符') api.read.mockResolvedValueOnce({ ...initial(), projectId: 'other' })
if (kind === '元数据缺失') api.read.mockResolvedValueOnce({ ...initial(), revision: undefined } as unknown as ProjectQualityPolicyResult)
if (kind === '元数据缺失')
api.read.mockResolvedValueOnce({
...initial(),
revision: undefined
} as unknown as ProjectQualityPolicyResult)
if (kind === '保存失败') api.save.mockRejectedValueOnce(new Error('保存失败'))
if (kind === '确认失败') api.confirm.mockRejectedValueOnce(new Error('确认失败'))
if (kind === '回执不符') api.confirm.mockResolvedValueOnce(initial())
if (kind === '确认后变化') api.confirm.mockImplementationOnce(async () => {
const confirmed = { ...api.get(), confirmed: true, confirmedRevision: api.get().revision, confirmedAt: '2026-10-17T15:00:00Z' }
api.change({ revision: api.get().revision + 1 }); return confirmed
})
expect(await flow.confirmRules(draft)).toBe(false); expect(flow.startOpen.value).toBe(false); expect(flow.consumePermit()).toBeNull()
if (kind === '确认后变化')
api.confirm.mockImplementationOnce(async () => {
const confirmed = {
...api.get(),
confirmed: true,
confirmedRevision: api.get().revision,
confirmedAt: '2026-10-17T15:00:00Z'
}
api.change({ revision: api.get().revision + 1 })
return confirmed
})
expect(await flow.confirmRules(draft)).toBe(false)
expect(flow.startOpen.value).toBe(false)
expect(flow.consumePermit()).toBeNull()
}
)
it.each(['cancel', 'project', 'scope', 'locked'])('%s 后丢弃迟到读取,重复点击不重复读取', async cause => {
let finish!: (value: ProjectQualityPolicyResult) => void
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(() => new Promise(resolve => { finish = resolve }))
const { flow, id, input, allowed } = setup(); const pending = flow.prepare(); await flow.prepare()
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(
() =>
new Promise(resolve => {
finish = resolve
})
)
const { flow, id, input, allowed } = setup()
const pending = flow.prepare()
await flow.prepare()
expect(read).toHaveBeenCalledTimes(1)
if (cause === 'cancel') flow.cancel()
if (cause === 'project') id.value = 'other'
if (cause === 'scope') input.value = 'new'
if (cause === 'locked') allowed.value = false
finish(initial()); await pending
expect(flow.reviewOpen.value).toBe(false); expect(flow.startOpen.value).toBe(false); expect(flow.consumePermit()).toBeNull()
finish(initial())
await pending
expect(flow.reviewOpen.value).toBe(false)
expect(flow.startOpen.value).toBe(false)
expect(flow.consumePermit()).toBeNull()
})
it('确认写入时锁定取消,写入后的只读回查仍可关闭且迟到响应不启动', async () => {
const api = server(); const { flow } = setup(); await flow.prepare()
const api = server()
const { flow } = setup()
await flow.prepare()
let finish!: (value: ProjectQualityPolicyResult) => void
api.confirm.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
api.confirm.mockImplementationOnce(
() =>
new Promise(resolve => {
finish = resolve
})
)
const pending = flow.confirmRules(initial().policy)
await Promise.resolve(); await Promise.resolve(); expect(flow.saving.value).toBe(true)
flow.cancel(); expect(flow.reviewOpen.value).toBe(true)
await Promise.resolve()
await Promise.resolve()
expect(flow.saving.value).toBe(true)
flow.cancel()
expect(flow.reviewOpen.value).toBe(true)
let finishRead!: (value: ProjectQualityPolicyResult) => void
api.read.mockImplementationOnce(() => new Promise(resolve => { finishRead = resolve }))
api.read.mockImplementationOnce(
() =>
new Promise(resolve => {
finishRead = resolve
})
)
const confirmed = { ...initial(), confirmed: true, confirmedRevision: 0, confirmedAt: '2026-10-17T15:00:00Z' }
finish(confirmed); await Promise.resolve(); await Promise.resolve()
expect(flow.reading.value).toBe(true); expect(flow.saving.value).toBe(false)
flow.cancel(); finishRead(confirmed); expect(await pending).toBe(false); expect(flow.consumePermit()).toBeNull()
finish(confirmed)
await Promise.resolve()
await Promise.resolve()
expect(flow.reading.value).toBe(true)
expect(flow.saving.value).toBe(false)
flow.cancel()
finishRead(confirmed)
expect(await pending).toBe(false)
expect(flow.consumePermit()).toBeNull()
})
it('最终费用确认期间规则更新或确认撤销均返回规则核对', async () => {
const api = server(); const { flow } = setup(); await flow.prepare(); await flow.confirmRules(initial().policy)
const api = server()
const { flow } = setup()
await flow.prepare()
await flow.confirmRules(initial().policy)
api.change({ confirmed: false, confirmedRevision: null, confirmedAt: null })
expect(await flow.verifyStart()).toBe(false); expect(flow.reviewOpen.value).toBe(true); expect(flow.consumePermit()).toBeNull()
expect(await flow.verifyStart()).toBe(false)
expect(flow.reviewOpen.value).toBe(true)
expect(flow.consumePermit()).toBeNull()
})
it('最终重读失败不能启动,取消后迟到成功也不能启动', async () => {
const api = server(); const { flow } = setup(); await flow.prepare(); await flow.confirmRules(initial().policy)
api.read.mockRejectedValueOnce(new Error('重读失败')); expect(await flow.verifyStart()).toBe(false)
const api = server()
const { flow } = setup()
await flow.prepare()
await flow.confirmRules(initial().policy)
api.read.mockRejectedValueOnce(new Error('重读失败'))
expect(await flow.verifyStart()).toBe(false)
let finish!: (value: ProjectQualityPolicyResult) => void
api.read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
const pending = flow.verifyStart(); flow.cancel(); finish(api.get())
expect(await pending).toBe(false); expect(flow.consumePermit()).toBeNull()
api.read.mockImplementationOnce(
() =>
new Promise(resolve => {
finish = resolve
})
)
const pending = flow.verifyStart()
flow.cancel()
finish(api.get())
expect(await pending).toBe(false)
expect(flow.consumePermit()).toBeNull()
})
})
@@ -4,12 +4,54 @@ import StoryboardList from '@/features/breakdown/components/StoryboardList.vue'
import type { EpisodePlan, EpisodeShots } from '@/features/breakdown/types'
/** 一条不涉及实际服务的正式分镜,用于验证定位语义。 */
const plan: EpisodePlan = { episodeNo: 1, episodeTitle: '第一集', storyGoal: '', centralConflict: '', emotionalArc: '', pacing: '', endingHook: '',
beats: [{ beatNo: 1, title: '场景', purpose: 'establish', description: '内容', visualFocus: '', narrativeGoal: '', emotionalTone: '', estimatedDurationSeconds: 5, subjectRefs: [], isKeyBeat: false }] }
const plan: EpisodePlan = {
episodeNo: 1,
episodeTitle: '第一集',
storyGoal: '',
centralConflict: '',
emotionalArc: '',
pacing: '',
endingHook: '',
beats: [
{
beatNo: 1,
title: '场景',
purpose: 'establish',
description: '内容',
visualFocus: '',
narrativeGoal: '',
emotionalTone: '',
estimatedDurationSeconds: 5,
subjectRefs: [],
isKeyBeat: false
}
]
}
/** 当前正式镜头正文。 */
const episode: EpisodeShots = { episodeNo: 1, episodePlan: plan, beatShots: [{ beatNo: 1, shots: [{ shotNo: 1, title: '无问题镜头', description: '正文', visualFocus: '', subjectRefs: [], durationSeconds: 5 }] }] }
const episode: EpisodeShots = {
episodeNo: 1,
episodePlan: plan,
beatShots: [
{
beatNo: 1,
shots: [
{
shotNo: 1,
title: '无问题镜头',
description: '正文',
visualFocus: '',
subjectRefs: [],
durationSeconds: 5
}
]
}
]
}
let wrapper: VueWrapper | undefined
afterEach(() => { wrapper?.unmount(); vi.restoreAllMocks() })
afterEach(() => {
wrapper?.unmount()
vi.restoreAllMocks()
})
describe('分镜定位与问题状态分离', () => {
it('只有从当前实际问题定位时使用错误标记,普通定位会清除旧错误标记', async () => {
@@ -18,8 +18,17 @@ function mountFields(schemas: GenerationOptionSchema[]) {
describe('生成模型参数字段', () => {
it('只有目录声明支持的模型才提供智能时长,不按模型品牌补造 -1', () => {
for (const supported of [false, true]) {
const wrapper = mountFields([{ key: 'durationSeconds', label: '生成时长', type: 'integer', required: true,
min: 4, max: 6, ...(supported ? { specialValues: [{ label: '智能时长', value: -1 }] } : {}) }])
const wrapper = mountFields([
{
key: 'durationSeconds',
label: '生成时长',
type: 'integer',
required: true,
min: 4,
max: 6,
...(supported ? { specialValues: [{ label: '智能时长', value: -1 }] } : {})
}
])
const options = wrapper.getComponent(NSelect).props('options') as { value: number }[]
expect(options.some(item => item.value === -1)).toBe(supported)
wrapper.unmount()
@@ -19,15 +19,37 @@ afterEach(() => wrapper?.unmount())
*/
async function settings() {
const saved = generationProfile('config-contract')
const catalog = { ...imageCatalog, videos: [{ ...imageCatalog.images[0]!, type: 'video' as const, provider: 'seedance', model: 'seedance', generationOptions: [], defaults: {} }] }
const catalog = {
...imageCatalog,
videos: [
{
...imageCatalog.images[0]!,
type: 'video' as const,
provider: 'seedance',
model: 'seedance',
generationOptions: [],
defaults: {}
}
]
}
vi.spyOn(generationConfigApi, 'catalog').mockResolvedValue(catalog)
vi.spyOn(generationConfigApi, 'profile').mockResolvedValue(saved)
const save = vi.spyOn(generationConfigApi, 'saveProfile').mockResolvedValue(saved)
const messages = { success: vi.fn<MessageApi['success']>(), warning: vi.fn<MessageApi['warning']>(), error: vi.fn<MessageApi['error']>(), info: vi.fn<MessageApi['info']>() }
const messages = {
success: vi.fn<MessageApi['success']>(),
warning: vi.fn<MessageApi['warning']>(),
error: vi.fn<MessageApi['error']>(),
info: vi.fn<MessageApi['info']>()
}
const revision = ref(0)
wrapper = mount(CreativeProfileSettings, {
props: { projectId: saved.projectId },
global: { provide: { [actionMessageKey as symbol]: messages as unknown as MessageApi, [projectGenerationRevisionKey as symbol]: revision } }
global: {
provide: {
[actionMessageKey as symbol]: messages as unknown as MessageApi,
[projectGenerationRevisionKey as symbol]: revision
}
}
})
await flushPromises()
return { saved, save, messages, revision }
+44 -6
View File
@@ -150,11 +150,21 @@ function server() {
else if (path.endsWith('/checkpoints')) data = context.checkpoints.value
else if (path.endsWith('/subject-forms')) data = [form]
else if (path.endsWith('/production/entry-readiness')) data = { ready: true, derivedAssets: { shotCount: 1 } }
else if (path.includes('/storyboard-visual-states')) data = { ...directionsResult('capability-test', Number(new URL(String(url), 'http://localhost').searchParams.get('episodeNo') || 1)), shotCount: 1, visualStateCount: 1, staleCount: 0 }
else if (path.includes('/storyboard-visual-states'))
data = {
...directionsResult(
'capability-test',
Number(new URL(String(url), 'http://localhost').searchParams.get('episodeNo') || 1)
),
shotCount: 1,
visualStateCount: 1,
staleCount: 0
}
else if (path.endsWith('/production/plan')) data = plan
else if (path.endsWith('/production/status')) data = status
else if (path.includes('/readiness')) data = readiness
else if (path.includes('/storyboard-directions')) data = { ...directionsResult('capability-test'), shotCount: 1, directionCount: 1 }
else if (path.includes('/storyboard-directions'))
data = { ...directionsResult('capability-test'), shotCount: 1, directionCount: 1 }
else if (path.endsWith('/videos/status'))
data = {
total: 1,
@@ -216,7 +226,9 @@ describe('高级串联生产的安全边界', () => {
const openSettings = vi.fn<() => void>()
wrapper = mount(AdvancedProduction, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context, [projectSettingsOpenKey as symbol]: openSettings } }
global: {
provide: { [projectContextKey as symbol]: context, [projectSettingsOpenKey as symbol]: openSettings }
}
})
await flushPromises()
await expandSections()
@@ -231,7 +243,30 @@ describe('高级串联生产的安全边界', () => {
})
it('配置在预检期间缺失时显示明确阻断,不读取空阶段或允许启动', async () => {
const { service, posts } = await advanced()
vi.spyOn(productionApi, 'plan').mockResolvedValue({ projectId: 'capability-test', canStart: false, canAutoRun: false, hasManualBlockers: true, manualBlocked: 1, configuration: { status: 'blocked', code: 'CREATIVE_PROFILE_REQUIRED', reason: '项目尚未配置 Creative Profile,请先保存项目生成配置' }, entryReadiness: { ready: true }, providers: null, generationConfig: null, completed: false, stage: 'configuration_required', characterIdentity: null, stableIdentityAnchors: null, subjectImages: null, keyframes: null, videoPrompts: null, videos: null, details: null })
vi.spyOn(productionApi, 'plan').mockResolvedValue({
projectId: 'capability-test',
canStart: false,
canAutoRun: false,
hasManualBlockers: true,
manualBlocked: 1,
configuration: {
status: 'blocked',
code: 'CREATIVE_PROFILE_REQUIRED',
reason: '项目尚未配置 Creative Profile,请先保存项目生成配置'
},
entryReadiness: { ready: true },
providers: null,
generationConfig: null,
completed: false,
stage: 'configuration_required',
characterIdentity: null,
stableIdentityAnchors: null,
subjectImages: null,
keyframes: null,
videoPrompts: null,
videos: null,
details: null
})
await service.preflight()
expect(service.check.value).toBeNull()
expect(service.error.value).toContain('请先保存项目生成配置')
@@ -243,8 +278,11 @@ describe('高级串联生产的安全边界', () => {
const { service, fetcher, posts } = await advanced()
const original = fetcher.getMockImplementation()!
let missing = true
fetcher.mockImplementation((url, init) => missing && String(url).endsWith('/creative-profile')
? Promise.resolve(new Response('{"data":null}')) : original(url, init))
fetcher.mockImplementation((url, init) =>
missing && String(url).endsWith('/creative-profile')
? Promise.resolve(new Response('{"data":null}'))
: original(url, init)
)
await service.preflight()
expect(service.configurationRequired.value).toBe(true)
expect(service.check.value).toBeNull()
+12 -4
View File
@@ -55,7 +55,8 @@ describe('全局资产库', () => {
}))
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (input, init) => {
const url = String(input)
if (init?.method === 'PUT') return new Response(JSON.stringify({ data: { ...assets[0], ...JSON.parse(String(init.body)) } }))
if (init?.method === 'PUT')
return new Response(JSON.stringify({ data: { ...assets[0], ...JSON.parse(String(init.body)) } }))
return new Response(JSON.stringify({ data: url.endsWith('/projects') ? projects : assets }))
})
vi.stubGlobal('fetch', fetcher)
@@ -95,17 +96,24 @@ describe('全局资产库', () => {
await flushPromises()
const dialog = document.querySelector('[role="dialog"][aria-label="素材详情与管理"]')!
expect(dialog).not.toBeNull()
expect([...dialog.querySelectorAll('.n-card__footer button')].map(button => button.textContent?.trim())).toEqual(['删除素材', '取消', '保存修改'])
expect(
[...dialog.querySelectorAll('.n-card__footer button')].map(button => button.textContent?.trim())
).toEqual(['删除素材', '取消', '保存修改'])
expect(dialog.querySelector('.asset-management-layout button[type="submit"]')).toBeNull()
expect(dialog.textContent).toContain('rain-street-original.png')
expect(dialog.textContent).toContain('PNG 图片')
expect(dialog.textContent).toContain('4.0 KB')
expect(router.currentRoute.value.path).toBe('/assets')
expect(wrapper.getComponent(AssetCategorySelect).getComponent(NSelect).props('options')).toContainEqual({ label: '视觉风格', value: 'visual-style' })
expect(wrapper.getComponent(AssetCategorySelect).getComponent(NSelect).props('options')).toContainEqual({
label: '视觉风格',
value: 'visual-style'
})
await new DOMWrapper(dialog).get('#library-asset-name').setValue('雨夜街道新版')
wrapper.getComponent(AssetCategorySelect).vm.$emit('update:value', 'visual-style')
await flushPromises()
const save = [...dialog.querySelectorAll<HTMLButtonElement>('.n-card__footer button')].find(button => button.textContent?.trim() === '保存修改')!
const save = [...dialog.querySelectorAll<HTMLButtonElement>('.n-card__footer button')].find(
button => button.textContent?.trim() === '保存修改'
)!
save.click()
await flushPromises()
const update = fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')!
+7 -3
View File
@@ -122,10 +122,14 @@ describe('剧本完成前的下游访问限制', () => {
state.storyboard = { ready: true, reason: null }
vi.mocked(projectsApi.stageReadiness).mockImplementation(async () => structuredClone(state))
vi.spyOn(projectsApi, 'detail').mockResolvedValue(project(id, 'completed'))
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([{
checkpointId: 'old-pending-review', workflowName: 'breakdown', createdAt: '2026-10-01T00:00:00Z',
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([
{
checkpointId: 'old-pending-review',
workflowName: 'breakdown',
createdAt: '2026-10-01T00:00:00Z',
state: { storyboardNeedsManualReview: true, storyboardShotValidation: { valid: true, issues: [] } }
}])
}
])
const { mounted } = await openProject(`/projects/${id}/visual-style`)
expect(mounted).toHaveBeenCalledExactlyOnceWith('visual-style')
expect(wrapper!.find(`.n-menu a[href="/projects/${id}/visual-style"]`).exists()).toBe(true)
+42 -10
View File
@@ -29,7 +29,9 @@ afterEach(() => {
})
describe('项目质量策略', () => {
it('基础规则不再添加空白例外,已有例外只读展示且完整保留在提交草稿中', async () => {
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: policyReceipt('p', saved) } })
const wrapper = mount(QualityPolicySettings, {
props: { projectId: 'p', disabled: false, initialPolicy: policyReceipt('p', saved) }
})
settings = wrapper
await flushPromises()
expect(wrapper.findAll('button').some(button => button.text() === '添加例外')).toBe(false)
@@ -39,9 +41,16 @@ describe('项目质量策略', () => {
})
it('启动入口复用真实回执,保存前重读版本,不把保存当作明确确认', async () => {
let currentPolicy = policyDraft(saved)
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => (policyReceipt('p', policyDraft(currentPolicy))))
vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => { currentPolicy = policyDraft(policy); return policyReceipt(id, policyDraft(policy)) })
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: policyReceipt('p', saved) } })
const read = vi
.spyOn(projectsApi, 'qualityPolicy')
.mockImplementation(async () => policyReceipt('p', policyDraft(currentPolicy)))
vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => {
currentPolicy = policyDraft(policy)
return policyReceipt(id, policyDraft(policy))
})
const wrapper = mount(QualityPolicySettings, {
props: { projectId: 'p', disabled: false, initialPolicy: policyReceipt('p', saved) }
})
settings = wrapper
await flushPromises()
expect(read).not.toHaveBeenCalled()
@@ -53,23 +62,46 @@ describe('项目质量策略', () => {
expect(read).toHaveBeenCalledTimes(2)
})
it('保存基础规则时合并后来新增的例外,不覆盖隐藏的服务端最新例外', async () => {
const latest = { ...saved, actionExceptions: [...saved.actionExceptions!, { code: 'action_resource_conflict' as const, ownerRef: '@CH0002', resource: 'right_hand' as const, reason: '另一处刚添加的例外' }] }
const latest = {
...saved,
actionExceptions: [
...saved.actionExceptions!,
{
code: 'action_resource_conflict' as const,
ownerRef: '@CH0002',
resource: 'right_hand' as const,
reason: '另一处刚添加的例外'
}
]
}
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('p', latest))
const write = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => (policyReceipt(id, policyDraft(policy))))
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: policyReceipt('p', saved) } })
const write = vi
.spyOn(projectsApi, 'saveQualityPolicy')
.mockImplementation(async (id, policy) => policyReceipt(id, policyDraft(policy)))
const wrapper = mount(QualityPolicySettings, {
props: { projectId: 'p', disabled: false, initialPolicy: policyReceipt('p', saved) }
})
settings = wrapper
await flushPromises()
expect(wrapper.find('.text-danger').exists()).toBe(false)
await wrapper.get('#quality-custom-rules').setValue('新的整体规则')
await wrapper.vm.save()
expect(write).toHaveBeenCalledExactlyOnceWith('p', { ...saved, customRules: ['新的整体规则'], actionExceptions: latest.actionExceptions }, 2)
expect(write).toHaveBeenCalledExactlyOnceWith(
'p',
{ ...saved, customRules: ['新的整体规则'], actionExceptions: latest.actionExceptions },
2
)
expect(wrapper.vm.validatedDraft()?.actionExceptions).toEqual(latest.actionExceptions)
expect(wrapper.text()).toContain('已有动作例外 · 2 项')
})
it('基础规则已被其他位置修改时拒绝覆盖,保留用户草稿', async () => {
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(policyReceipt('p', { ...saved, physicsMode: 'fantasy' }))
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(
policyReceipt('p', { ...saved, physicsMode: 'fantasy' })
)
const write = vi.spyOn(projectsApi, 'saveQualityPolicy')
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: policyReceipt('p', saved) } })
const wrapper = mount(QualityPolicySettings, {
props: { projectId: 'p', disabled: false, initialPolicy: policyReceipt('p', saved) }
})
settings = wrapper
await flushPromises()
await wrapper.get('#quality-custom-rules').setValue('不能丢失的用户草稿')
@@ -1,4 +1,10 @@
import type { StoryboardRecheck, ReviewBaselinePreview, StoryboardApprovalState, StoryboardApproval, ProductionEntryReadiness } from '@/features/storyboard-preparation/types'
import type {
StoryboardRecheck,
ReviewBaselinePreview,
StoryboardApprovalState,
StoryboardApproval,
ProductionEntryReadiness
} from '@/features/storyboard-preparation/types'
import { policyReceipt } from '../../fixtures/quality-policy'
/**
@@ -7,11 +13,81 @@ import { policyReceipt } from '../../fixtures/quality-policy'
* @returns 可变化的只读回执与确认记录
*/
export function preparationFixture(projectId = 'p') {
const policy = policyReceipt(projectId, { version: 1, physicsMode: 'stylized', allowExaggeratedMotion: true, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] }, { confirmed: true, confirmedRevision: 2, confirmedAt: '2026-10-19T01:00:00Z' })
const quality: StoryboardRecheck = { projectId, status: 'insufficient_evidence', structure: { hasValidation: true, valid: true, reason: null }, coverage: { episodeCount: 1, beatCount: 1, shotCount: 1, issueCount: 0 }, issues: [], actionAudit: { projectId, shotCount: 1, issueCount: 0, blockedCount: 0, needsReviewCount: 0, issues: [] }, sourceAudit: { projectId, checkpointId: 'cp', shotCount: 1, valid: true, issues: [] }, provenance: { checkpointId: 'cp', sourceCommitted: true, qualityPolicyConsistent: true, qualityPolicyChecks: { projectConfirmed: true, checkpointSnapshotPresent: true }, baselineConsistent: false, shotCountsConsistent: true, checkpointConsistent: true }, preflightEligible: true, canConfirm: false }
const record: StoryboardApproval = { id: 'approval', projectId, checkpointId: 'cp', qualityPolicyRevision: 2, qualityPolicyFingerprint: 'a'.repeat(64), shotCount: 1, shotFingerprint: 'b'.repeat(64), reviewer: '复核人', reviewNote: '已逐镜核对动作与主体', confirmedAt: '2026-10-19T01:00:00Z' }
const approval: StoryboardApprovalState = { valid: false, confirmation: null, evidence: { valid: true, checkpointId: 'cp', qualityPolicyRevision: 2, qualityPolicyFingerprint: 'a'.repeat(64), shotCount: 1, shotFingerprint: 'b'.repeat(64) } }
const baseline: ReviewBaselinePreview = { eligible: false, reasons: ['当前记录已有规则来源'], checkpointId: 'cp', shotCount: 1, shotFingerprint: 'b'.repeat(64) }
const entry: ProductionEntryReadiness = { ready: false, hasStoryboardValidation: true, storyboardValid: true, reason: '请先完成分镜审核', derivedAssets: { shotCount: 1, directionCount: 0, directionCoverage: 0, visualStateCount: 0, visualStateCoverage: 0 } }
const policy = policyReceipt(
projectId,
{
version: 1,
physicsMode: 'stylized',
allowExaggeratedMotion: true,
allowNonPhysicalActions: false,
allowSupernaturalAbilities: false,
customRules: []
},
{ confirmed: true, confirmedRevision: 2, confirmedAt: '2026-10-19T01:00:00Z' }
)
const quality: StoryboardRecheck = {
projectId,
status: 'insufficient_evidence',
structure: { hasValidation: true, valid: true, reason: null },
coverage: { episodeCount: 1, beatCount: 1, shotCount: 1, issueCount: 0 },
issues: [],
actionAudit: { projectId, shotCount: 1, issueCount: 0, blockedCount: 0, needsReviewCount: 0, issues: [] },
sourceAudit: { projectId, checkpointId: 'cp', shotCount: 1, valid: true, issues: [] },
provenance: {
checkpointId: 'cp',
sourceCommitted: true,
qualityPolicyConsistent: true,
qualityPolicyChecks: { projectConfirmed: true, checkpointSnapshotPresent: true },
baselineConsistent: false,
shotCountsConsistent: true,
checkpointConsistent: true
},
preflightEligible: true,
canConfirm: false
}
const record: StoryboardApproval = {
id: 'approval',
projectId,
checkpointId: 'cp',
qualityPolicyRevision: 2,
qualityPolicyFingerprint: 'a'.repeat(64),
shotCount: 1,
shotFingerprint: 'b'.repeat(64),
reviewer: '复核人',
reviewNote: '已逐镜核对动作与主体',
confirmedAt: '2026-10-19T01:00:00Z'
}
const approval: StoryboardApprovalState = {
valid: false,
confirmation: null,
evidence: {
valid: true,
checkpointId: 'cp',
qualityPolicyRevision: 2,
qualityPolicyFingerprint: 'a'.repeat(64),
shotCount: 1,
shotFingerprint: 'b'.repeat(64)
}
}
const baseline: ReviewBaselinePreview = {
eligible: false,
reasons: ['当前记录已有规则来源'],
checkpointId: 'cp',
shotCount: 1,
shotFingerprint: 'b'.repeat(64)
}
const entry: ProductionEntryReadiness = {
ready: false,
hasStoryboardValidation: true,
storyboardValid: true,
reason: '请先完成分镜审核',
derivedAssets: {
shotCount: 1,
directionCount: 0,
directionCoverage: 0,
visualStateCount: 0,
visualStateCoverage: 0
}
}
return { policy, quality, approval, baseline, entry, record }
}
@@ -6,10 +6,35 @@ import { projectsApi } from '@/features/projects/api'
import { subjectImagesApi } from '@/features/subject-images/api'
import { storyboardApi } from '@/features/storyboard/api'
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() })
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
describe('制作计划之前的正式分镜检查', () => {
it('入口未通过时不查询制作计划,也不调用生成接口', async () => {
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockImplementation(async () => new Response(JSON.stringify({ data: { ready: false, reason: '请先完成分镜审核', hasStoryboardValidation: true, storyboardValid: true, derivedAssets: { shotCount: 1, directionCount: 0, directionCoverage: 0, visualStateCount: 0, visualStateCoverage: 0 } } }))))
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>().mockImplementation(
async () =>
new Response(
JSON.stringify({
data: {
ready: false,
reason: '请先完成分镜审核',
hasStoryboardValidation: true,
storyboardValid: true,
derivedAssets: {
shotCount: 1,
directionCount: 0,
directionCoverage: 0,
visualStateCount: 0,
visualStateCoverage: 0
}
}
})
)
)
)
vi.spyOn(generationConfigApi, 'profile').mockResolvedValue(null)
vi.spyOn(projectsApi, 'detail').mockResolvedValue({ id: 'p' } as never)
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
@@ -20,10 +45,33 @@ describe('制作计划之前的正式分镜检查', () => {
expect(plan).not.toHaveBeenCalled()
})
it('设计覆盖完整但已经过期时仍不进入制作计划', async () => {
vi.stubGlobal('fetch', vi.fn<typeof fetch>().mockImplementation(async () => new Response(JSON.stringify({ data: { ready: true, derivedAssets: { shotCount: 1 } } }))))
vi.stubGlobal(
'fetch',
vi
.fn<typeof fetch>()
.mockImplementation(
async () => new Response(JSON.stringify({ data: { ready: true, derivedAssets: { shotCount: 1 } } }))
)
)
vi.spyOn(projectsApi, 'detail').mockResolvedValue({ id: 'p', episodes: [{ episode: 1 }] } as never)
vi.spyOn(storyboardApi, 'directions').mockResolvedValue({ projectId: 'p', episodeNo: 1, shotCount: 1, directionCount: 1, staleCount: 1, coverage: 1, beats: [] })
vi.spyOn(storyboardApi, 'visualStates').mockResolvedValue({ projectId: 'p', episodeNo: 1, shotCount: 1, visualStateCount: 1, staleCount: 0, coverage: 1, beats: [] })
vi.spyOn(storyboardApi, 'directions').mockResolvedValue({
projectId: 'p',
episodeNo: 1,
shotCount: 1,
directionCount: 1,
staleCount: 1,
coverage: 1,
beats: []
})
vi.spyOn(storyboardApi, 'visualStates').mockResolvedValue({
projectId: 'p',
episodeNo: 1,
shotCount: 1,
visualStateCount: 1,
staleCount: 0,
coverage: 1,
beats: []
})
const plan = vi.spyOn(productionApi, 'plan')
await expect(checkPipeline('p')).rejects.toThrow('过期')
expect(plan).not.toHaveBeenCalled()
@@ -5,47 +5,167 @@ import { preparationApi } from '@/features/storyboard-preparation/api'
import type { FormalShotRepairPreview, BeatSubjectPreview } from '@/features/storyboard-preparation/types'
/** 当前正式镜头有明确可补齐的动作关联,全部旧证据必须保留。 */
const preview = (): FormalShotRepairPreview => ({ projectId: 'p', shotId: 's', expectedFingerprint: 'a'.repeat(64), written: false, willCallModel: false, requiredActions: [{ id: 'a', kind: 'action', description: '左手持铃', mustPerformInShot: true }], durationPlanning: { complexity: 'low', phases: [{ action: '持铃', actionIds: ['a'], estimatedSeconds: 4, resourceOccupancy: [{ actionId: 'a', ownerRef: '@CH1', resource: 'left_hand', usage: 'hold', shareable: false, continuityRef: '@PR1' }] }], transitionSeconds: 0, recommendedDurationSeconds: 4, reason: '原动作时长' }, classification: { status: 'candidate', beforeFingerprint: 'a'.repeat(64), proposed: null, semanticIssues: [], originalIssues: [] } })
const preview = (): FormalShotRepairPreview => ({
projectId: 'p',
shotId: 's',
expectedFingerprint: 'a'.repeat(64),
written: false,
willCallModel: false,
requiredActions: [{ id: 'a', kind: 'action', description: '左手持铃', mustPerformInShot: true }],
durationPlanning: {
complexity: 'low',
phases: [
{
action: '持铃',
actionIds: ['a'],
estimatedSeconds: 4,
resourceOccupancy: [
{
actionId: 'a',
ownerRef: '@CH1',
resource: 'left_hand',
usage: 'hold',
shareable: false,
continuityRef: '@PR1'
}
]
}
],
transitionSeconds: 0,
recommendedDurationSeconds: 4,
reason: '原动作时长'
},
classification: {
status: 'candidate',
beforeFingerprint: 'a'.repeat(64),
proposed: null,
semanticIssues: [],
originalIssues: []
}
})
let wrapper: VueWrapper | undefined
afterEach(() => { wrapper?.unmount(); vi.restoreAllMocks() })
afterEach(() => {
wrapper?.unmount()
vi.restoreAllMocks()
})
describe('正式镜头版本化修订', () => {
it('读取当前正式数据,不调用模型;人工确认后保存真实指纹和完整占用证据', async () => {
vi.spyOn(preparationApi, 'repairPreview').mockResolvedValue(preview())
const model = vi.spyOn(preparationApi, 'repairCandidate')
const save = vi.spyOn(preparationApi, 'repair').mockResolvedValue({ projectId: 'p', shotId: 's', written: true, beforeFingerprint: 'a'.repeat(64), afterFingerprint: 'b'.repeat(64) })
wrapper = mount(FormalRepairEditor, { props: { projectId: 'p', issue: { episodeNo: 1, beatNo: 1, shotNo: 1, shotId: 's', message: '关联待修复' }, disabled: false } })
const save = vi.spyOn(preparationApi, 'repair').mockResolvedValue({
projectId: 'p',
shotId: 's',
written: true,
beforeFingerprint: 'a'.repeat(64),
afterFingerprint: 'b'.repeat(64)
})
wrapper = mount(FormalRepairEditor, {
props: {
projectId: 'p',
issue: { episodeNo: 1, beatNo: 1, shotNo: 1, shotId: 's', message: '关联待修复' },
disabled: false
}
})
await flushPromises()
expect(model).not.toHaveBeenCalled(); expect(save).not.toHaveBeenCalled()
expect(model).not.toHaveBeenCalled()
expect(save).not.toHaveBeenCalled()
await wrapper.get('[aria-label="修订原因"] textarea').setValue('逐项核对并调整动作关联')
await wrapper.get('[role="checkbox"][aria-label="确认正式镜头修订"]').trigger('click')
await wrapper.getComponent(FormalRepairEditor).vm.save(); await flushPromises()
expect(save).toHaveBeenCalledWith('p', expect.objectContaining({ shotId: 's', expectedFingerprint: 'a'.repeat(64), confirmed: true, reason: '逐项核对并调整动作关联', durationPlanning: expect.objectContaining({ phases: [expect.objectContaining({ resourceOccupancy: [expect.objectContaining({ continuityRef: '@PR1' })] })] }) }))
await wrapper.getComponent(FormalRepairEditor).vm.save()
await flushPromises()
expect(save).toHaveBeenCalledWith(
'p',
expect.objectContaining({
shotId: 's',
expectedFingerprint: 'a'.repeat(64),
confirmed: true,
reason: '逐项核对并调整动作关联',
durationPlanning: expect.objectContaining({
phases: [
expect.objectContaining({
resourceOccupancy: [expect.objectContaining({ continuityRef: '@PR1' })]
})
]
})
})
)
expect(wrapper.emitted('saved')).toHaveLength(1)
})
it('打开时不校验,保存前版本变化不得覆盖新镜头', async () => {
const read = vi.spyOn(preparationApi, 'repairPreview').mockResolvedValue(preview())
const save = vi.spyOn(preparationApi, 'repair')
wrapper = mount(FormalRepairEditor, { props: { projectId: 'p', issue: { episodeNo: 1, beatNo: 1, shotNo: 1, shotId: 's', message: '关联待修复' }, disabled: false } })
await flushPromises(); expect(wrapper.text()).not.toContain('请填写修订原因')
wrapper = mount(FormalRepairEditor, {
props: {
projectId: 'p',
issue: { episodeNo: 1, beatNo: 1, shotNo: 1, shotId: 's', message: '关联待修复' },
disabled: false
}
})
await flushPromises()
expect(wrapper.text()).not.toContain('请填写修订原因')
await wrapper.get('[aria-label="修订原因"] textarea').setValue('明确原因')
await wrapper.get('[role="checkbox"][aria-label="确认正式镜头修订"]').trigger('click')
read.mockResolvedValue({ ...preview(), expectedFingerprint: 'c'.repeat(64) })
await wrapper.getComponent(FormalRepairEditor).vm.save(); await flushPromises()
expect(save).not.toHaveBeenCalled(); expect(wrapper.text()).toContain('已变化')
await wrapper.getComponent(FormalRepairEditor).vm.save()
await flushPromises()
expect(save).not.toHaveBeenCalled()
expect(wrapper.text()).toContain('已变化')
})
it('主体遗漏先保存段落的真实版本,不把段落指纹当作镜头指纹或自动追加镜头', async () => {
vi.spyOn(preparationApi, 'repairPreview').mockResolvedValue(preview())
const upstream: BeatSubjectPreview = { projectId: 'p', shotId: 's', beatId: 'beat', checkpointId: 'cp', subjectRef: '@PR1', subjectName: '铜铃', subjectDescription: '项目已有铜铃', beat: { title: '取铃', description: '阿皮拿起铜铃', visualFocus: '铜铃', subjectRefs: ['@CH1'] }, shot: { title: '取铃', description: '阿皮拿起铜铃', visualFocus: '铜铃' }, status: 'upstream-missing', written: false, candidate: { checkpointId: 'cp', beatId: 'beat', subjectRef: '@PR1', expectedFingerprint: 'c'.repeat(64), proposed: { upstreamRefs: ['@CH1', '@PR1'], persistedRefs: ['@CH1', '@PR1'] }, requiresHumanReview: true } }
const upstream: BeatSubjectPreview = {
projectId: 'p',
shotId: 's',
beatId: 'beat',
checkpointId: 'cp',
subjectRef: '@PR1',
subjectName: '铜铃',
subjectDescription: '项目已有铜铃',
beat: { title: '取铃', description: '阿皮拿起铜铃', visualFocus: '铜铃', subjectRefs: ['@CH1'] },
shot: { title: '取铃', description: '阿皮拿起铜铃', visualFocus: '铜铃' },
status: 'upstream-missing',
written: false,
candidate: {
checkpointId: 'cp',
beatId: 'beat',
subjectRef: '@PR1',
expectedFingerprint: 'c'.repeat(64),
proposed: { upstreamRefs: ['@CH1', '@PR1'], persistedRefs: ['@CH1', '@PR1'] },
requiresHumanReview: true
}
}
vi.spyOn(preparationApi, 'beatSubjectPreview').mockResolvedValue(upstream)
const beatWrite = vi.spyOn(preparationApi, 'repairBeatSubject').mockResolvedValue({ projectId: 'p', shotId: 's', beatId: 'beat', checkpointId: 'cp', resultFingerprint: 'd'.repeat(64), written: true })
const beatWrite = vi.spyOn(preparationApi, 'repairBeatSubject').mockResolvedValue({
projectId: 'p',
shotId: 's',
beatId: 'beat',
checkpointId: 'cp',
resultFingerprint: 'd'.repeat(64),
written: true
})
const shotWrite = vi.spyOn(preparationApi, 'repairSubject')
wrapper = mount(FormalRepairEditor, { props: { projectId: 'p', issue: { episodeNo: 1, beatNo: 1, shotNo: 1, shotId: 's', subjectRef: '@PR1', message: '缺少铜铃' }, disabled: false } })
wrapper = mount(FormalRepairEditor, {
props: {
projectId: 'p',
issue: { episodeNo: 1, beatNo: 1, shotNo: 1, shotId: 's', subjectRef: '@PR1', message: '缺少铜铃' },
disabled: false
}
})
await flushPromises()
expect(beatWrite).not.toHaveBeenCalled(); expect(wrapper.text()).toContain('剧情段落')
expect(beatWrite).not.toHaveBeenCalled()
expect(wrapper.text()).toContain('剧情段落')
await wrapper.get('[aria-label="修订原因"] textarea').setValue('正文明确出现铜铃,补齐段落来源')
await wrapper.get('[role="checkbox"][aria-label="确认正式镜头修订"]').trigger('click')
await wrapper.getComponent(FormalRepairEditor).vm.save(); await flushPromises()
expect(beatWrite).toHaveBeenCalledExactlyOnceWith('p', { shotId: 's', subjectRef: '@PR1', expectedFingerprint: 'c'.repeat(64), confirmed: true, reason: '正文明确出现铜铃,补齐段落来源' })
expect(shotWrite).not.toHaveBeenCalled(); expect(wrapper.emitted('saved')).toHaveLength(1)
await wrapper.getComponent(FormalRepairEditor).vm.save()
await flushPromises()
expect(beatWrite).toHaveBeenCalledExactlyOnceWith('p', {
shotId: 's',
subjectRef: '@PR1',
expectedFingerprint: 'c'.repeat(64),
confirmed: true,
reason: '正文明确出现铜铃,补齐段落来源'
})
expect(shotWrite).not.toHaveBeenCalled()
expect(wrapper.emitted('saved')).toHaveLength(1)
})
})
@@ -8,7 +8,10 @@ import { preparationFixture } from './fixtures'
/** 当前作用域,避免项目切换测试遗留响应式观察器。 */
const scopes: ReturnType<typeof effectScope>[] = []
afterEach(() => { scopes.splice(0).forEach(scope => scope.stop()); vi.restoreAllMocks() })
afterEach(() => {
scopes.splice(0).forEach(scope => scope.stop())
vi.restoreAllMocks()
})
/** 测试只读回执保留当前已确认规则,所有写入独立模拟。 */
function setup() {
const data = preparationFixture()
@@ -17,8 +20,10 @@ function setup() {
vi.spyOn(preparationApi, 'baseline').mockImplementation(async () => structuredClone(data.baseline))
vi.spyOn(preparationApi, 'entry').mockImplementation(async () => structuredClone(data.entry))
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(data.policy))
const scope = effectScope(); scopes.push(scope)
const id = ref('p'), locked = ref(false)
const scope = effectScope()
scopes.push(scope)
const id = ref('p'),
locked = ref(false)
const flow = scope.run(() => useStoryboardPreparation(id, locked))!
return { data, id, locked, flow }
}
@@ -29,8 +34,15 @@ describe('正式分镜审核绑定当前内容', () => {
expect(currentStoryboardApproval(current, 'p')).toBe(true)
expect(currentStoryboardApproval({ ...current, confirmation: null }, 'p')).toBe(false)
expect(currentStoryboardApproval(current, 'other')).toBe(false)
expect(currentStoryboardApproval({ ...current, evidence: { ...current.evidence, shotFingerprint: 'f'.repeat(64) } }, 'p')).toBe(false)
expect(currentStoryboardApproval({ ...current, evidence: { ...current.evidence, qualityPolicyRevision: 3 } }, 'p')).toBe(false)
expect(
currentStoryboardApproval(
{ ...current, evidence: { ...current.evidence, shotFingerprint: 'f'.repeat(64) } },
'p'
)
).toBe(false)
expect(
currentStoryboardApproval({ ...current, evidence: { ...current.evidence, qualityPolicyRevision: 3 } }, 'p')
).toBe(false)
})
it('只读 canConfirm=false 不代替人工确认;满足实际预检后提交真实版本', async () => {
const { data, flow } = setup()
@@ -39,44 +51,65 @@ describe('正式分镜审核绑定当前内容', () => {
expect(flow.reviewable.value).toBe(true)
expect(confirm).not.toHaveBeenCalled()
expect(await flow.confirm('approval', '复核人', '已逐镜核对动作与主体')).toBe(true)
expect(confirm).toHaveBeenCalledExactlyOnceWith('p', { reviewer: '复核人', reviewNote: '已逐镜核对动作与主体', expectedCheckpointId: 'cp', expectedShotFingerprint: 'b'.repeat(64) })
expect(confirm).toHaveBeenCalledExactlyOnceWith('p', {
reviewer: '复核人',
reviewNote: '已逐镜核对动作与主体',
expectedCheckpointId: 'cp',
expectedShotFingerprint: 'b'.repeat(64)
})
})
it('确认期间镜头版本变化时撤销确认,不自动提交新版本', async () => {
const { data, flow } = setup()
const confirm = vi.spyOn(preparationApi, 'confirmApproval')
await flow.load(); data.approval.evidence.shotFingerprint = 'c'.repeat(64)
await flow.load()
data.approval.evidence.shotFingerprint = 'c'.repeat(64)
expect(await flow.confirm('approval', '复核人', '已核对')).toBe(false)
expect(confirm).not.toHaveBeenCalled()
expect(flow.error.value).toContain('已变化')
})
it('结构通过但动作问题、来源不一致或缺规则确认均不能人工放行', async () => {
const { data, flow } = setup()
data.quality.preflightEligible = false; await flow.load()
data.quality.preflightEligible = false
await flow.load()
expect(flow.reviewable.value).toBe(false)
data.quality.preflightEligible = true; data.quality.actionAudit.issueCount = 1; await flow.load()
data.quality.preflightEligible = true
data.quality.actionAudit.issueCount = 1
await flow.load()
expect(flow.reviewable.value).toBe(false)
data.quality.actionAudit.issueCount = 0; data.policy.confirmed = false; await flow.load()
data.quality.actionAudit.issueCount = 0
data.policy.confirmed = false
await flow.load()
expect(flow.reviewable.value).toBe(false)
})
it('旧分镜来源确认与整体审核分开提交,使用真实镜头内容版本', async () => {
const { data, flow } = setup()
data.quality.provenance.qualityPolicyConsistent = false
data.quality.preflightEligible = false
data.baseline.eligible = true; data.baseline.reasons = []
data.baseline.eligible = true
data.baseline.reasons = []
const baseline = vi.spyOn(preparationApi, 'confirmBaseline').mockResolvedValue(data.record)
const approval = vi.spyOn(preparationApi, 'confirmApproval')
await flow.load(); expect(flow.baselineAllowed.value).toBe(true); expect(flow.reviewable.value).toBe(false)
await flow.load()
expect(flow.baselineAllowed.value).toBe(true)
expect(flow.reviewable.value).toBe(false)
expect(await flow.confirm('baseline', '复核人', '明确采用当前规则重新核对旧分镜')).toBe(true)
expect(baseline).toHaveBeenCalledExactlyOnceWith('p', { reviewer: '复核人', reviewNote: '明确采用当前规则重新核对旧分镜', expectedCheckpointId: 'cp', expectedShotFingerprint: 'b'.repeat(64) })
expect(baseline).toHaveBeenCalledExactlyOnceWith('p', {
reviewer: '复核人',
reviewNote: '明确采用当前规则重新核对旧分镜',
expectedCheckpointId: 'cp',
expectedShotFingerprint: 'b'.repeat(64)
})
expect(approval).not.toHaveBeenCalled()
})
it('确认失败保留可读原因,不能把历史确认存在当作当前有效', async () => {
const { data, flow } = setup()
data.approval.confirmation = data.record
const confirm = vi.spyOn(preparationApi, 'confirmApproval').mockRejectedValue(new Error('版本冲突,请重新核对'))
await flow.load(); expect(flow.approved.value).toBe(false)
await flow.load()
expect(flow.approved.value).toBe(false)
expect(await flow.confirm('approval', '复核人', '已核对')).toBe(false)
expect(confirm).toHaveBeenCalledTimes(1); expect(flow.error.value).toContain('版本冲突')
expect(confirm).toHaveBeenCalledTimes(1)
expect(flow.error.value).toContain('版本冲突')
expect(flow.approved.value).toBe(false)
})
})
+44 -9
View File
@@ -100,7 +100,10 @@ function stubFetch(fetcher: Mock<typeof fetch>) {
let executionCount = 0
fetcher.mockImplementation(async (url, init) => {
const path = String(url)
if (path.endsWith('/storyboard/quality-confirmation')) { const current = preparationFixture(fixture.id); return jsonResponse({ ...current.approval, valid: true, confirmation: current.record }) }
if (path.endsWith('/storyboard/quality-confirmation')) {
const current = preparationFixture(fixture.id)
return jsonResponse({ ...current.approval, valid: true, confirmation: current.record })
}
if (path.endsWith('/generation-models')) return jsonResponse(imageCatalog)
if (path.endsWith('/creative-profile')) return jsonResponse(generationProfile(fixture.id))
if (path.endsWith('/duration-budget'))
@@ -1822,7 +1825,13 @@ describe('工作台页面交互', () => {
expect(drawerPanel().text()).toContain('本集新镜头已保存')
expect(drawerPanel().text()).toContain('2 个镜头')
/** Duration Budget 新增一次只读 GET;镜头重生成不应增加额外写入。 */
expect(fetcher.mock.calls.filter(([url, init]) => (!init?.method || init.method === 'GET') && !String(url).endsWith('/storyboard/quality-confirmation'))).toHaveLength(12)
expect(
fetcher.mock.calls.filter(
([url, init]) =>
(!init?.method || init.method === 'GET') &&
!String(url).endsWith('/storyboard/quality-confirmation')
)
).toHaveLength(12)
expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/duration-budget'))).toHaveLength(2)
expect(fetcher.mock.calls.some(([url]) => String(url) === '/api/workflow-executions/page-execution-1')).toBe(
true
@@ -1919,8 +1928,12 @@ describe('工作台页面交互', () => {
expect(wrapper!.text()).toContain('第2集镜头1')
expect(wrapper!.text()).not.toContain('第1集镜头1')
/** 切换剧集只增加当前集查询,项目时长预算只在挂载时读取一次。 */
expect(fetcher.mock.calls.filter(([url]) => !String(url).endsWith('/storyboard/quality-confirmation'))).toHaveLength(6)
expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard/quality-confirmation'))).toHaveLength(1)
expect(
fetcher.mock.calls.filter(([url]) => !String(url).endsWith('/storyboard/quality-confirmation'))
).toHaveLength(6)
expect(
fetcher.mock.calls.filter(([url]) => String(url).endsWith('/storyboard/quality-confirmation'))
).toHaveLength(1)
expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/duration-budget'))).toHaveLength(1)
expect(fetcher.mock.calls.every(([, init]) => !init?.method || init.method === 'GET')).toBe(true)
})
@@ -2090,9 +2103,27 @@ describe('工作台页面交互', () => {
'{"data":{"episodeCount":1,"groupCount":1,"estimatedTaskCount":3,"groups":[],"tasks":[],"modules":["character","scene","prop"],"groupSize":2}}'
)
if (String(url).endsWith('quality-policy/confirm')) rulesConfirmed = true
if (String(url).includes('quality-policy')) return new Response(JSON.stringify({ data: { projectId: 'page-test-project', revision: 3, fingerprint: 'a'.repeat(64), confirmed: rulesConfirmed, confirmedRevision: rulesConfirmed ? 3 : null, confirmedAt: rulesConfirmed ? '2026-10-17T15:00:00Z' : null, policy: {
version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: []
} } }))
if (String(url).includes('quality-policy'))
return new Response(
JSON.stringify({
data: {
projectId: 'page-test-project',
revision: 3,
fingerprint: 'a'.repeat(64),
confirmed: rulesConfirmed,
confirmedRevision: rulesConfirmed ? 3 : null,
confirmedAt: rulesConfirmed ? '2026-10-17T15:00:00Z' : null,
policy: {
version: 1,
physicsMode: 'realistic',
allowExaggeratedMotion: false,
allowNonPhysicalActions: false,
allowSupernaturalAbilities: false,
customRules: []
}
}
})
)
return new Response('{"data":{"workflowExecution":{"status":"completed"}}}')
})
stubFetch(fetcher)
@@ -2111,14 +2142,18 @@ describe('工作台页面交互', () => {
await flushPromises()
button('生成拆解候选').click()
await flushPromises()
const acknowledgement = Array.from(document.querySelectorAll<HTMLElement>('[role="checkbox"]')).find(input => input.textContent?.includes('我已核对'))!
const acknowledgement = Array.from(document.querySelectorAll<HTMLElement>('[role="checkbox"]')).find(input =>
input.textContent?.includes('我已核对')
)!
acknowledgement.click()
await flushPromises()
button('确认规则并继续').click()
await flushPromises()
button('确认生成拆解候选').click()
await flushPromises()
const post = fetcher.mock.calls.find(call => call[1]?.method === 'POST' && String(call[0]).endsWith('/breakdown/start'))
const post = fetcher.mock.calls.find(
call => call[1]?.method === 'POST' && String(call[0]).endsWith('/breakdown/start')
)
expect(post?.[0]).toBe('/api/projects/page-test-project/breakdown/start')
expect(JSON.parse(post![1]!.body as string)).toEqual({
expectedRevision: 3,
+20 -5
View File
@@ -1,5 +1,10 @@
import { describe, expect, it } from 'vitest'
import { breakdownSnapshot, formalBreakdownSnapshot, recoveryOptions, workflowCheckpoints } from '@/features/workflows/selectors'
import {
breakdownSnapshot,
formalBreakdownSnapshot,
recoveryOptions,
workflowCheckpoints
} from '@/features/workflows/selectors'
import type { Checkpoint } from '@/features/workflows/types'
import type { BreakdownState } from '@/features/breakdown/types'
@@ -12,17 +17,27 @@ describe('Checkpoint 选择与恢复', () => {
it('正式工作区不会读取未提交候选,已有正式成果也不会被新候选覆盖', () => {
const candidate = checkpoint(2, { candidateOnly: true, subjectCandidates: [] })
expect(formalBreakdownSnapshot([candidate])).toBeNull()
const formal = checkpoint(1, { candidateOnly: true, candidateCommitted: true, storyboardPersisted: true, subjectCandidates: [], storyboardShotValidation: { valid: true, issues: [] } })
const formal = checkpoint(1, {
candidateOnly: true,
candidateCommitted: true,
storyboardPersisted: true,
subjectCandidates: [],
storyboardShotValidation: { valid: true, issues: [] }
})
expect(formalBreakdownSnapshot([formal, candidate])?.candidateCommitted).toBe(true)
})
it('顶层修复和正式提交结果覆盖同一检查点内的旧嵌套质量状态', () => {
const result = breakdownSnapshot([checkpoint(1, {
const result = breakdownSnapshot([
checkpoint(1, {
candidateOnly: true,
candidateCommitted: true,
storyboardPersisted: true,
storyboardShotValidation: { valid: true, issues: [] },
breakdownResult: { storyboardShotValidation: { valid: false, issues: [{ episodeNo: 1, message: '旧错误' }] } }
})])
breakdownResult: {
storyboardShotValidation: { valid: false, issues: [{ episodeNo: 1, message: '旧错误' }] }
}
})
])
expect(result?.breakdownResult?.storyboardShotValidation).toEqual({ valid: true, issues: [] })
})
it('按 graph 隔离并保持输入不可变', () => {
+160 -20
View File
@@ -9,29 +9,118 @@ import type { Checkpoint } from '@/features/workflows/types'
*/
export function candidateState(overrides: Partial<BreakdownState> = {}): BreakdownState {
const plan: EpisodePlan = {
episodeNo: 1, episodeTitle: '第一集', storyGoal: '', centralConflict: '', emotionalArc: '', pacing: '', endingHook: '',
beats: [{ beatNo: 1, title: '取物', purpose: 'action', description: '', visualFocus: '', narrativeGoal: '', emotionalTone: '', estimatedDurationSeconds: 8, subjectRefs: ['@CH0001', '@PR0001'], isKeyBeat: false }]
episodeNo: 1,
episodeTitle: '第一集',
storyGoal: '',
centralConflict: '',
emotionalArc: '',
pacing: '',
endingHook: '',
beats: [
{
beatNo: 1,
title: '取物',
purpose: 'action',
description: '',
visualFocus: '',
narrativeGoal: '',
emotionalTone: '',
estimatedDurationSeconds: 8,
subjectRefs: ['@CH0001', '@PR0001'],
isKeyBeat: false
}
]
}
return {
projectId: 'candidate-project', candidateOnly: true, storyboardPersisted: false,
projectId: 'candidate-project',
candidateOnly: true,
storyboardPersisted: false,
expectedEpisodeFingerprints: { 1: 'fingerprint' },
runConfig: { groupSize: 3, modules: ['character', 'prop'], episodeGroups: [], sourceEpisodes: [{ episodeNo: 1 }] },
runConfig: {
groupSize: 3,
modules: ['character', 'prop'],
episodeGroups: [],
sourceEpisodes: [{ episodeNo: 1 }]
},
subjectCandidates: [
{ profileId: 'person', name: '人物', ref: '@CH0001', module: 'character', description: '', appearance_prompt: '' },
{
profileId: 'person',
name: '人物',
ref: '@CH0001',
module: 'character',
description: '',
appearance_prompt: ''
},
{ profileId: 'prop', name: '铜铃', ref: '@PR0001', module: 'prop', description: '', appearance_prompt: '' }
],
subjectForms: [
{ formId: 'person-form', profileId: 'person', type: 'character', name: '人物形态', isDefault: true, description: '', appearancePrompt: '' },
{ formId: 'prop-form', profileId: 'prop', type: 'prop', name: '铜铃形态', isDefault: true, description: '', appearancePrompt: '' }
{
formId: 'person-form',
profileId: 'person',
type: 'character',
name: '人物形态',
isDefault: true,
description: '',
appearancePrompt: ''
},
{
formId: 'prop-form',
profileId: 'prop',
type: 'prop',
name: '铜铃形态',
isDefault: true,
description: '',
appearancePrompt: ''
}
],
storyboardPlans: [plan],
storyboardEpisodeShots: [{ episodeNo: 1, episodePlan: plan, beatShots: [{ beatNo: 1, shots: [1, 2].map(shotNo => ({
shotNo, title: `动作镜头 ${shotNo}`, description: '人物拿起铜铃', visualFocus: '', durationSeconds: 4,
subjectRefs: ['@CH0001'], subjectBindings: [{ subjectRef: '@CH0001', profileId: 'person', formId: 'person-form', formName: '人物形态' }],
requiredActions: [{ id: `action-${shotNo}`, description: '铜铃已经在手中', kind: 'state', mustPerformInShot: false }],
durationPlanning: { complexity: 'low', phases: [{ action: '铜铃已经在手中', actionIds: [`action-${shotNo}`], estimatedSeconds: 4 }], transitionSeconds: 0, recommendedDurationSeconds: 4, reason: '测试' }
})) }] }],
storyboardShotValidation: { valid: true, issues: [] }, storyboardPendingQualityEpisodeNos: [], ...overrides
storyboardEpisodeShots: [
{
episodeNo: 1,
episodePlan: plan,
beatShots: [
{
beatNo: 1,
shots: [1, 2].map(shotNo => ({
shotNo,
title: `动作镜头 ${shotNo}`,
description: '人物拿起铜铃',
visualFocus: '',
durationSeconds: 4,
subjectRefs: ['@CH0001'],
subjectBindings: [
{
subjectRef: '@CH0001',
profileId: 'person',
formId: 'person-form',
formName: '人物形态'
}
],
requiredActions: [
{
id: `action-${shotNo}`,
description: '铜铃已经在手中',
kind: 'state',
mustPerformInShot: false
}
],
durationPlanning: {
complexity: 'low',
phases: [
{ action: '铜铃已经在手中', actionIds: [`action-${shotNo}`], estimatedSeconds: 4 }
],
transitionSeconds: 0,
recommendedDurationSeconds: 4,
reason: '测试'
}
}))
}
]
}
],
storyboardShotValidation: { valid: true, issues: [] },
storyboardPendingQualityEpisodeNos: [],
...overrides
}
}
@@ -47,13 +136,17 @@ export function resourceConflictState(overrides: Partial<BreakdownState> = {}):
{ id: 'hold', description: '左手握住铜铃', kind: 'action', mustPerformInShot: true },
{ id: 'wave', description: '左手向村民挥动', kind: 'action', mustPerformInShot: true }
]
shot.durationPlanning!.phases = [{
action: '握铃时挥手', actionIds: ['hold', 'wave'], estimatedSeconds: 4,
shot.durationPlanning!.phases = [
{
action: '握铃时挥手',
actionIds: ['hold', 'wave'],
estimatedSeconds: 4,
resourceOccupancy: [
{ ownerRef: '@CH0001', resource: 'left_hand', actionId: 'hold', usage: 'hold', shareable: false },
{ ownerRef: '@CH0001', resource: 'left_hand', actionId: 'wave', usage: 'move', shareable: false }
]
}]
}
]
return state
}
@@ -64,7 +157,13 @@ export function resourceConflictState(overrides: Partial<BreakdownState> = {}):
* @returns 检查点记录
*/
export function candidateCheckpoint(state = candidateState(), checkpointId = 'candidate-current'): Checkpoint {
return { checkpointId, createdAt: '2026-10-17T09:28:59Z', workflowName: 'breakdown', metadata: { nodeName: 'candidate_action_batch_repair', sourceCheckpointId: 'old' }, state }
return {
checkpointId,
createdAt: '2026-10-17T09:28:59Z',
workflowName: 'breakdown',
metadata: { nodeName: 'candidate_action_batch_repair', sourceCheckpointId: 'old' },
state
}
}
/**
@@ -73,7 +172,23 @@ export function candidateCheckpoint(state = candidateState(), checkpointId = 'ca
* @returns 候选重新审核响应
*/
export function candidateReview(overrides: Partial<CandidateRevalidation> = {}): CandidateRevalidation {
return { projectId: 'candidate-project', checkpointId: 'candidate-current', episodeCount: 1, shotCount: 2, previousIssues: [], currentIssues: [], missingSubjectRefs: [], pendingQualityEpisodeNos: [], actionQualityBlocks: [], actionRepairTargets: [], propReferenceDiagnostics: [], pendingWithoutActionBlocks: [], candidateValidation: { valid: true, issues: [] }, canCommit: false, ...overrides }
return {
projectId: 'candidate-project',
checkpointId: 'candidate-current',
episodeCount: 1,
shotCount: 2,
previousIssues: [],
currentIssues: [],
missingSubjectRefs: [],
pendingQualityEpisodeNos: [],
actionQualityBlocks: [],
actionRepairTargets: [],
propReferenceDiagnostics: [],
pendingWithoutActionBlocks: [],
candidateValidation: { valid: true, issues: [] },
canCommit: false,
...overrides
}
}
/**
@@ -82,5 +197,30 @@ export function candidateReview(overrides: Partial<CandidateRevalidation> = {}):
* @returns 只读安全检查
*/
export function commitPreview(overrides: Partial<CandidateCommitPreview> = {}): CandidateCommitPreview {
return { projectId: 'candidate-project', checkpointId: 'candidate-current', ready: true, readOnly: true, checks: { qualityPolicyMatches: true, episodeNumbersMatch: true, episodeFingerprintsMatch: true, noActiveExecutions: true, noActiveVideos: true, noSubjectIdentities: true, noSubjectImages: true, noProtectedShots: true }, counts: { episodes: 1, existingStoryboards: 0, activeExecutions: 0, activeVideos: 0, subjectIdentities: 0, subjectImages: 0, protectedShots: 0 }, ...overrides }
return {
projectId: 'candidate-project',
checkpointId: 'candidate-current',
ready: true,
readOnly: true,
checks: {
qualityPolicyMatches: true,
episodeNumbersMatch: true,
episodeFingerprintsMatch: true,
noActiveExecutions: true,
noActiveVideos: true,
noSubjectIdentities: true,
noSubjectImages: true,
noProtectedShots: true
},
counts: {
episodes: 1,
existingStoryboards: 0,
activeExecutions: 0,
activeVideos: 0,
subjectIdentities: 0,
subjectImages: 0,
protectedShots: 0
},
...overrides
}
}
+15 -2
View File
@@ -7,6 +7,19 @@ import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from '@/feature
* @param overrides 修订和确认状态差异
* @returns 独立的接口回执
*/
export function policyReceipt(projectId: string, policy: ProjectQualityPolicy, overrides: Partial<ProjectQualityPolicyResult> = {}): ProjectQualityPolicyResult {
return { projectId, policy, revision: 2, fingerprint: 'a'.repeat(64), confirmed: false, confirmedRevision: null, confirmedAt: null, ...overrides }
export function policyReceipt(
projectId: string,
policy: ProjectQualityPolicy,
overrides: Partial<ProjectQualityPolicyResult> = {}
): ProjectQualityPolicyResult {
return {
projectId,
policy,
revision: 2,
fingerprint: 'a'.repeat(64),
confirmed: false,
confirmedRevision: null,
confirmedAt: null,
...overrides
}
}
+22 -5
View File
@@ -4,12 +4,20 @@ import { getOperation, operationErrorText, runOperation } from '@/features/workf
describe('面向普通用户的系统提示', () => {
it('规则版本冲突显示操作指引,保留原始错误码供流程恢复', () => {
const cause = new ApiError('QUALITY_POLICY_VERSION_CONFLICT: 质量规则已更新', 409, undefined, 'QUALITY_POLICY_VERSION_CONFLICT')
const cause = new ApiError(
'QUALITY_POLICY_VERSION_CONFLICT: 质量规则已更新',
409,
undefined,
'QUALITY_POLICY_VERSION_CONFLICT'
)
expect(errorMessage(cause)).not.toContain('QUALITY_POLICY_VERSION_CONFLICT')
expect(cause.code).toBe('QUALITY_POLICY_VERSION_CONFLICT')
})
it('错误展示使用中文说明,不把技术字段和调试对象直接输出给用户', () => {
const details = { issues: [{ message: 'Shot 主体引用缺失:@CH0001' }], debug: { executionId: 'internal-id', sql: 'SELECT secret' } }
const details = {
issues: [{ message: 'Shot 主体引用缺失:@CH0001' }],
debug: { executionId: 'internal-id', sql: 'SELECT secret' }
}
const error = new ApiError('后端 Storyboard 校验失败', 400, details)
const text = errorMessage(error)
expect(text).toContain('分镜')
@@ -24,7 +32,9 @@ describe('面向普通用户的系统提示', () => {
})
it('中文展示不改变恢复流程读取的原始错误,手动更新后的提示也不会沿用旧原因', async () => {
const original = new ApiError('Shot 缺少 Primary Keyframe', 400)
await runOperation('copy-recovery-test', '生成视频描述', async () => { throw original })
await runOperation('copy-recovery-test', '生成视频描述', async () => {
throw original
})
const operation = getOperation('copy-recovery-test')
expect(operation.error).toContain('首帧')
expect(operation.error).not.toContain('Primary Keyframe')
@@ -34,8 +44,15 @@ describe('面向普通用户的系统提示', () => {
})
})
it.each(['CANVAS_CHANGE_REQUIRES_REVALIDATION', 'CREATIVE_PROFILE_ACTIVE_WORKFLOW', 'GENERATION_CONFIG_CHANGE_REQUIRES_REVALIDATION'])('配置冲突 %s 从真实 details.code 或顶层 code 转成中文原因', code => {
for (const cause of [new ApiError('请求失败(409)', 409, { code }), new ApiError('服务器内部错误', 409, undefined, code)]) {
it.each([
'CANVAS_CHANGE_REQUIRES_REVALIDATION',
'CREATIVE_PROFILE_ACTIVE_WORKFLOW',
'GENERATION_CONFIG_CHANGE_REQUIRES_REVALIDATION'
])('配置冲突 %s 从真实 details.code 或顶层 code 转成中文原因', code => {
for (const cause of [
new ApiError('请求失败(409)', 409, { code }),
new ApiError('服务器内部错误', 409, undefined, code)
]) {
expect(errorMessage(cause)).not.toMatch(/请求失败|服务器内部错误|REQUIRES|WORKFLOW/)
expect(errorMessage(cause)).toMatch(/画幅|任务|模型/)
expect(cause.status).toBe(409)