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
87 files changed
+5714 -1436

No files matched your search

+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',
actions: ['左手握住铜铃', '左手向村民挥动']
}])
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: [
policy.actionExceptions![0],
{ code: 'action_resource_conflict', ownerRef: '@CH0001', resource: 'left_hand', reason: '剧本明确允许左手同时挥动持物' }
] }, 2)
expect(save).toHaveBeenCalledExactlyOnceWith(
'candidate-project',
{
...latest,
actionExceptions: [
policy.actionExceptions![0],
{
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)
+192 -59
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()
})
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.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()
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()
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.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()
}
)
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')!
+8 -4
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',
state: { storyboardNeedsManualReview: true, storyboardShotValidation: { valid: true, issues: [] } }
}])
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,
+24 -9
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: [] } })
expect(formalBreakdownSnapshot([formal, candidate])?.candidateCommitted).toBe(true)
})
it('顶层修复和正式提交结果覆盖同一检查点内的旧嵌套质量状态', () => {
const result = breakdownSnapshot([checkpoint(1, {
const formal = checkpoint(1, {
candidateOnly: true,
candidateCommitted: true,
storyboardPersisted: true,
storyboardShotValidation: { valid: true, issues: [] },
breakdownResult: { storyboardShotValidation: { valid: false, issues: [{ episodeNo: 1, message: '旧错误' }] } }
})])
subjectCandidates: [],
storyboardShotValidation: { valid: true, issues: [] }
})
expect(formalBreakdownSnapshot([formal, candidate])?.candidateCommitted).toBe(true)
})
it('顶层修复和正式提交结果覆盖同一检查点内的旧嵌套质量状态', () => {
const result = breakdownSnapshot([
checkpoint(1, {
candidateOnly: true,
candidateCommitted: true,
storyboardPersisted: true,
storyboardShotValidation: { valid: true, issues: [] },
breakdownResult: {
storyboardShotValidation: { valid: false, issues: [{ episodeNo: 1, message: '旧错误' }] }
}
})
])
expect(result?.breakdownResult?.storyboardShotValidation).toEqual({ valid: true, issues: [] })
})
it('按 graph 隔离并保持输入不可变', () => {