feat(short-drama-agent-front): 完善质量规则确认与中文交互

This commit is contained in:
GJ committed 2026-10-17 22:09:28 +08:00
1 parent 190333d4f9
commit c4b43b9725
85 files changed
+2059 -480

No files matched your search

+98 -1
View File
@@ -14,9 +14,106 @@ 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 } 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'
let wrapper: VueWrapper | undefined
it('首次点击生成先读取并确认质量规则,不直接打开模型启动确认', async () => {
const readPolicy = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({
projectId: 'breakdown-scroll-test',
policy: { 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,
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 flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '生成拆解候选')!.trigger('click')
await flushPromises()
expect(readPolicy).toHaveBeenCalledTimes(1)
expect(drawerPanel().text()).toContain('拆解前确认质量规则')
expect(document.querySelector('.app-dialog')).toBeNull()
expect(start).not.toHaveBeenCalled()
})
it('规则确认保留分组预览,隐藏空白例外,确认不调用模型,未变规则不重复打开表单', async () => {
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({
projectId: 'breakdown-scroll-test',
policy: { 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,
groups: [{ groupId: 'preview-group', groupNo: 1, startEpisodeNo: 1, endEpisodeNo: 1, episodes: [] }]
})
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
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 flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '生成拆解候选')!.trigger('click')
await flushPromises()
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 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')
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 flushPromises()
await drawerPanel().findAll('button').find(button => button.text() === '生成拆解候选')!.trigger('click')
await flushPromises()
expect(drawerPanel().text()).not.toContain('拆解前确认质量规则')
expect(document.querySelector('.app-dialog')?.textContent).toContain('可能产生模型费用')
expect(start).not.toHaveBeenCalled()
})
it('当前动作问题在问题抽屉中提供例外修订,保存期间锁定关闭且保存后仍需审核', async () => {
let policy: ProjectQualityPolicy = { version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: [] }
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => ({ projectId: 'breakdown-scroll-test', policy }))
let finish!: () => void
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, input) => {
await new Promise<void>(resolve => { finish = resolve })
policy = input
return { projectId: id, policy: 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]
}))
mountPage([candidateCheckpoint(resourceConflictState({ projectId: 'breakdown-scroll-test' }))])
await flushPromises()
await wrapper!.get('.breakdown-desktop-issues').trigger('click')
await flushPromises()
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().get('textarea').setValue('剧本中的明确允许设定')
await panel().findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
await flushPromises()
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()
Object.assign(getOperation('breakdown-scroll-test'), { error: '', notice: '', label: '' })
})
/** 跨组件后台任务观察器,验证结束时释放。 */
let taskScope: ReturnType<typeof effectScope> | undefined
afterEach(() => {
@@ -0,0 +1,158 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { actionExceptionTargets } from '@/features/breakdown/action-exceptions'
import ActionExceptionRepair from '@/features/breakdown/components/ActionExceptionRepair.vue'
import { breakdownQuality, selectBreakdownSource } from '@/features/breakdown/quality'
import { projectsApi } from '@/features/projects/api'
import type { ProjectQualityPolicy } from '@/features/projects/types'
import { candidateCheckpoint, candidateReview, resourceConflictState } from '../../fixtures/breakdown-candidate'
import { getOperation } from '@/features/workflows/operations'
/**
* 同阶段同一角色左手执行两个互斥动作,坐标与后端审核一致。
* @returns 独立的真实契约形状的候选与审核
*/
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 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: '旧例外依据' }]
}
/** 当前真实修订面板实例。 */
let wrapper: VueWrapper<InstanceType<typeof ActionExceptionRepair>> | undefined
afterEach(() => {
wrapper?.unmount()
wrapper = undefined
vi.restoreAllMocks()
localStorage.clear()
Object.assign(getOperation('candidate-project'), { pending: false, error: '', label: '', notice: '' })
})
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: ['左手握住铜铃', '左手向村民挥动']
}])
shot.durationPlanning!.phases[0]!.resourceOccupancy = []
expect(actionExceptionTargets(state, quality)).toEqual([])
})
it('不同阶段、可共享证据、未知角色或动作及历史审核都不能生成例外目标', () => {
const { state, quality, shot } = conflict()
const phase = shot.durationPlanning!.phases[0]!
phase.resourceOccupancy![1]!.ownerRef = '@CH9999'
expect(actionExceptionTargets(state, quality)).toEqual([])
phase.resourceOccupancy![1]!.ownerRef = '@CH0001'
phase.actionIds = ['hold']
expect(actionExceptionTargets(state, quality)).toEqual([])
phase.actionIds = ['hold', 'wave']
phase.resourceOccupancy!.forEach(item => { item.shareable = true; item.usage = 'hold' })
expect(actionExceptionTargets(state, quality)).toEqual([])
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] })
expect(actionExceptionTargets(state, quality)).toEqual([])
})
it('用户仅填写原因,保存前重读并合并已有例外,不改全局规则或自动放行质量', async () => {
const { state, quality } = conflict()
const latest = { ...policy, customRules: ['其他入口刚保存的新规则'] }
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValueOnce({ projectId: 'candidate-project', policy }).mockResolvedValue({ projectId: 'candidate-project', policy: latest })
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, input) => ({ projectId: id, policy: 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')
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')
expect(wrapper.text()).toContain('请填写允许原因')
expect(save).not.toHaveBeenCalled()
await wrapper.get('textarea').setValue('剧本明确允许左手同时挥动持物')
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: '剧本明确允许左手同时挥动持物' }
] })
expect(wrapper.emitted('refresh')).toHaveLength(1)
expect(quality.actionStatus).toBe('blocked')
expect(wrapper.find('textarea').exists()).toBe(false)
})
it('保存前出现活动任务或切换检查点时,不提交旧问题的例外', async () => {
const { state, quality } = conflict()
let finish!: (value: { projectId: string; policy: ProjectQualityPolicy }) => void
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'candidate-project', policy })
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
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.get('textarea').setValue('允许原因')
read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
await wrapper.findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
await wrapper.setProps({ disabled: true })
finish({ projectId: 'candidate-project', policy })
await flushPromises()
expect(save).not.toHaveBeenCalled()
expect(wrapper.find('textarea').element.value).toBe('允许原因')
await wrapper.setProps({ checkpointId: 'new-checkpoint' })
expect(wrapper.find('textarea').exists()).toBe(false)
expect(wrapper.emitted('refresh')).toBeUndefined()
})
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: '已确认的同类例外' }] }
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'candidate-project', policy: existing })
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
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.find('textarea').exists()).toBe(false)
expect(save).not.toHaveBeenCalled()
})
it('保存失败保留原因供修正,不增加本地例外或宣称已通过', async () => {
const { state, quality } = conflict()
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'candidate-project', policy })
vi.spyOn(projectsApi, 'saveQualityPolicy').mockRejectedValue(new Error('后端拒绝修改'))
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.get('textarea').setValue('仍需保存的依据')
await wrapper.findAll('button').find(button => button.text() === '保存动作例外')!.trigger('click')
await flushPromises()
expect(wrapper.get('textarea').element.value).toBe('仍需保存的依据')
expect(wrapper.text()).toContain('系统拒绝修改')
expect(wrapper.text()).toContain('已有动作例外 · 1 项')
expect(wrapper.emitted('refresh')).toBeUndefined()
expect(wrapper.emitted('busy')?.map(event => event[0])).toEqual([true, false])
})
it('读取失败或项目不符时不使用默认规则、不开放添加', async () => {
const { state, quality } = conflict()
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'other', policy })
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
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.find('textarea').exists()).toBe(false)
expect(save).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,261 @@
import { effectScope, ref, type EffectScope } from 'vue'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { projectsApi } from '@/features/projects/api'
import type { ProjectQualityPolicy, ProjectQualityPolicyResult } from '@/features/projects/types'
import { policyDraft } from '@/features/projects/quality-policy'
import { useBreakdownStartPolicy } from '@/features/breakdown/useBreakdownStartPolicy'
import {
invalidateQualityPolicyConfirmation, qualityPolicySignature,
readQualityPolicyConfirmation, rememberQualityPolicyConfirmation
} from '@/features/projects/quality-policy-confirmation'
/**
* 使用真实接口形状的独立规则,不连接服务或调用模型。
* @returns 独立项目规则回执
*/
function receipt(): ProjectQualityPolicyResult {
return { projectId: 'policy-project', policy: {
version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false,
allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: []
} }
}
/** 每个测试释放组合函数观察器。 */
let scope: EffectScope | undefined
/**
* 创建可切换项目、预览和活动锁的测试观察器。
* @returns 流程及其响应式输入
*/
function setup() {
const id = ref('policy-project')
const input = ref('preview-1')
const allowed = ref(true)
scope = effectScope()
const flow = scope.run(() => useBreakdownStartPolicy(id, input, allowed))!
return { id, input, allowed, flow }
}
afterEach(() => {
scope?.stop()
vi.unstubAllGlobals()
localStorage.clear()
vi.restoreAllMocks()
})
describe('拆解质量规则内容与当前浏览器确认', () => {
it('忽略属性顺序、首尾空格和空例外表示,但识别许可、规则和例外的实际变化', () => {
const base = receipt().policy
expect(qualityPolicySignature({ ...base, actionExceptions: [] })).toBe(qualityPolicySignature(base))
const reversed = Object.fromEntries(Object.entries({ ...base, customRules: ['规则'] }).toReversed()) as unknown as ProjectQualityPolicy
expect(qualityPolicySignature({ ...base, customRules: [' 规则 '] })).toBe(qualityPolicySignature(reversed))
for (const changed of [
{ ...base, physicsMode: 'fantasy' as const },
{ ...base, allowExaggeratedMotion: true },
{ ...base, allowNonPhysicalActions: true },
{ ...base, allowSupernaturalAbilities: true },
{ ...base, customRules: ['新规则'] },
{ ...base, actionExceptions: [{ code: 'action_resource_conflict' as const, ownerRef: '@CH1', resource: 'left_hand' as const, reason: '剧本许可' }] }
]) expect(qualityPolicySignature(changed)).not.toBe(qualityPolicySignature(base))
expect(() => qualityPolicySignature({ ...base, customRules: null } as unknown as ProjectQualityPolicy)).toThrow('质量规则响应不完整')
})
it('确认按项目隔离,损坏存储或存储权限失败不会被当作已确认', () => {
expect(readQualityPolicyConfirmation('policy-project')).toBeNull()
rememberQualityPolicyConfirmation('policy-project', 'signature')
expect(readQualityPolicyConfirmation('other')).toBeNull()
localStorage.setItem('short-drama:breakdown-quality-confirmation:v1:policy-project', '{')
expect(readQualityPolicyConfirmation('policy-project')).toBeNull()
vi.stubGlobal('localStorage', { getItem: () => null, setItem: () => { throw new Error('storage blocked') } })
expect(rememberQualityPolicyConfirmation('policy-project', 'new')).toBe(false)
})
})
describe('拆解前规则确认流程', () => {
it('首次读取失败不展示默认规则,重试后才能进入确认', async () => {
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockRejectedValueOnce(new Error('读取不可用')).mockResolvedValue(receipt())
const { flow } = setup()
await flow.prepare()
expect(flow.policy.value).toBeNull()
expect(flow.reviewOpen.value).toBe(false)
expect(flow.startOpen.value).toBe(false)
expect(flow.error.value).toBe('读取不可用')
expect(flow.consumePermit()).toBe(false)
await flow.prepare()
expect(read).toHaveBeenCalledTimes(2)
expect(flow.reviewOpen.value).toBe(true)
expect(flow.error.value).toBe('')
})
it('首次读取真实规则,取消不记录确认,也不允许绕过确认直接启动', async () => {
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(receipt())
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
const { flow } = setup()
expect(read).not.toHaveBeenCalled()
await flow.prepare()
expect(flow.reviewOpen.value).toBe(true)
expect(flow.startOpen.value).toBe(false)
expect(await flow.verifyStart()).toBe(false)
expect(flow.consumePermit()).toBe(false)
flow.cancel()
expect(readQualityPolicyConfirmation('policy-project')).toBeNull()
expect(save).not.toHaveBeenCalled()
})
it('明确确认未改规则不重复保存,刷新会话后直接进入普通启动确认', async () => {
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(receipt())
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
const { flow } = setup()
await flow.prepare()
expect(await flow.confirmRules(receipt().policy)).toBe(true)
expect(flow.startOpen.value).toBe(true)
expect(save).not.toHaveBeenCalled()
expect(flow.consumePermit()).toBe(false)
flow.cancel()
scope!.stop()
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()).toBe(true)
expect(next.consumePermit()).toBe(false)
})
it('编辑的完整草稿先保存并重读,保存后的内容才记作已确认', async () => {
const saved = receipt()
const draft = { ...saved.policy, allowExaggeratedMotion: true }
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(saved))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => {
saved.policy = policyDraft(policy)
return { projectId: id, policy: policyDraft(policy) }
})
const { flow } = setup()
await flow.prepare()
expect(await flow.confirmRules(draft)).toBe(true)
expect(save).toHaveBeenCalledWith('policy-project', draft)
expect(read).toHaveBeenCalledTimes(3)
expect(readQualityPolicyConfirmation('policy-project')).toBe(qualityPolicySignature(draft))
})
it('规则在其他位置更新后重新确认,不覆盖服务端较新规则', async () => {
let saved = receipt()
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(saved))
const save = vi.spyOn(projectsApi, 'saveQualityPolicy')
const { flow } = setup()
await flow.prepare()
saved = { ...saved, policy: { ...saved.policy, allowNonPhysicalActions: true } }
expect(await flow.confirmRules(receipt().policy)).toBe(false)
expect(flow.policy.value?.policy.allowNonPhysicalActions).toBe(true)
expect(flow.reviewOpen.value).toBe(true)
expect(flow.startOpen.value).toBe(false)
expect(save).not.toHaveBeenCalled()
expect(readQualityPolicyConfirmation('policy-project')).toBeNull()
})
it('真实保存期间锁定取消,保存后的只读回查可取消,迟到回查不记录确认', async () => {
const initial = receipt()
const draft = { ...initial.policy, allowNonPhysicalActions: true }
let finishSave!: (value: ProjectQualityPolicyResult) => void
let finishRead!: (value: ProjectQualityPolicyResult) => void
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(initial)
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(() => new Promise(resolve => { finishSave = resolve }))
const { flow } = setup()
await flow.prepare()
const pending = flow.confirmRules(draft)
await Promise.resolve()
await Promise.resolve()
expect(save).toHaveBeenCalledOnce()
expect(flow.saving.value).toBe(true)
flow.cancel()
expect(flow.reviewOpen.value).toBe(true)
read.mockImplementationOnce(() => new Promise(resolve => { finishRead = resolve }))
finishSave({ ...initial, policy: draft })
await Promise.resolve()
await Promise.resolve()
expect(flow.saving.value).toBe(false)
expect(flow.reading.value).toBe(true)
flow.cancel()
finishRead({ ...initial, policy: draft })
expect(await pending).toBe(false)
expect(flow.reviewOpen.value).toBe(false)
expect(flow.startOpen.value).toBe(false)
expect(readQualityPolicyConfirmation(initial.projectId)).toBeNull()
})
it('最终启动确认期间规则变化,返回规则界面并撤销启动许可', async () => {
const saved = receipt()
vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => structuredClone(saved))
rememberQualityPolicyConfirmation(saved.projectId, qualityPolicySignature(saved.policy))
const { flow } = setup()
await flow.prepare()
saved.policy.customRules = ['新规则']
expect(await flow.verifyStart()).toBe(false)
expect(flow.reviewOpen.value).toBe(true)
expect(flow.startOpen.value).toBe(false)
expect(flow.consumePermit()).toBe(false)
})
it.each(['读取失败', '项目不符', '保存失败', '回执不符', '保存后变化'])('安全拦截%s,不记住确认', async kind => {
const initial = receipt()
const changed = { ...initial.policy, allowNonPhysicalActions: true }
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(initial)
const save = vi.spyOn(projectsApi, 'saveQualityPolicy').mockResolvedValue({ ...initial, policy: changed })
const { flow } = setup()
await flow.prepare()
if (kind === '读取失败') read.mockRejectedValueOnce(new Error('读取失败'))
if (kind === '项目不符') read.mockResolvedValueOnce({ ...initial, projectId: 'other' })
if (kind === '保存失败') save.mockRejectedValueOnce(new Error('保存失败'))
if (kind === '回执不符') save.mockResolvedValueOnce(initial)
expect(await flow.confirmRules(changed)).toBe(false)
expect(flow.reviewOpen.value).toBe(true)
expect(flow.startOpen.value).toBe(false)
expect(flow.consumePermit()).toBe(false)
expect(readQualityPolicyConfirmation(initial.projectId)).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()
expect(read).toHaveBeenCalledTimes(1)
if (cause === 'cancel') flow.cancel()
if (cause === 'project') id.value = 'other'
if (cause === 'scope') input.value = 'preview-2'
if (cause === 'locked') allowed.value = false
finish(receipt())
await pending
expect(flow.reviewOpen.value).toBe(false)
expect(flow.startOpen.value).toBe(false)
expect(flow.consumePermit()).toBe(false)
})
it('最终重读失败不能启动,取消后迟到成功也不能启动', async () => {
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(receipt())
rememberQualityPolicyConfirmation('policy-project', qualityPolicySignature(receipt().policy))
const { flow } = setup()
await flow.prepare()
read.mockRejectedValueOnce(new Error('重读失败'))
expect(await flow.verifyStart()).toBe(false)
expect(flow.consumePermit()).toBe(false)
let finish!: (value: ProjectQualityPolicyResult) => void
read.mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
const pending = flow.verifyStart()
flow.cancel()
finish(receipt())
expect(await pending).toBe(false)
expect(flow.consumePermit()).toBe(false)
})
it('存储受限时仅在本次会话跳过确认,实际规则保存会撤销临时确认', async () => {
vi.stubGlobal('localStorage', { getItem: () => null, removeItem: () => {}, setItem: () => { throw new Error('blocked') } })
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue(receipt())
const { flow } = setup()
await flow.prepare()
expect(await flow.confirmRules(receipt().policy)).toBe(true)
flow.cancel()
await flow.prepare()
expect(flow.startOpen.value).toBe(true)
invalidateQualityPolicyConfirmation('policy-project')
expect(await flow.verifyStart()).toBe(false)
expect(flow.reviewOpen.value).toBe(true)
})
})
@@ -31,7 +31,7 @@ describe('生成模型参数字段', () => {
expect(select.props('clearable')).toBe(false)
expect(select.props('options')).toEqual([
{ label: '目录支持尺寸', value: '2048*2048' },
{ label: 'auto', value: 'auto' },
{ label: '自动', value: 'auto' },
{ label: '2K', value: '2K' }
])
expect(wrapper.findComponent(NInputNumber).exists()).toBe(false)
+1 -1
View File
@@ -602,7 +602,7 @@ describe('视频修复候选与复检晋升', () => {
expect(data.fetcher.mock.calls.some(([, options]) => options?.method === 'PUT')).toBe(false)
wrapper!.unmount()
wrapper = mount(QualityResult, { props: { receipt } })
expect(wrapper.text()).toContain('后端已将其设为主视频')
expect(wrapper.text()).toContain('修复后的视频已通过检查,并设为主视频')
})
it('视频修复面板明确一次一任务及复检后替换,不展示生图次数', async () => {
+18 -4
View File
@@ -1,8 +1,9 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { createMemoryHistory, createRouter } from 'vue-router'
import { NTooltip } from 'naive-ui'
import { NSelect, NTooltip } from 'naive-ui'
import AssetLibraryPage from '@/features/project-assets/AssetLibraryPage.vue'
import AssetCategorySelect from '@/features/project-assets/components/AssetCategorySelect.vue'
let wrapper: VueWrapper | undefined
afterEach(() => {
@@ -52,8 +53,9 @@ describe('全局资产库', () => {
createdAt: '',
updatedAt: ''
}))
const fetcher = vi.fn<typeof fetch>().mockImplementation(async input => {
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)) } }))
return new Response(JSON.stringify({ data: url.endsWith('/projects') ? projects : assets }))
})
vi.stubGlobal('fetch', fetcher)
@@ -93,10 +95,22 @@ 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.querySelector('.asset-management-layout button[type="submit"]')).toBeNull()
expect(dialog.textContent).toContain('rain-street-original.png')
expect(dialog.textContent).toContain('image/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' })
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() === '保存修改')!
save.click()
await flushPromises()
const update = fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')!
expect(update[0]).toBe('/api/projects/project-one/assets/asset-scene')
expect(JSON.parse(String(update[1]?.body))).toEqual({ name: '雨夜街道新版', category: 'visual-style' })
await wrapper.get('input[aria-label="搜索资产图片"]').setValue('天降甘霖')
expect(wrapper.findAll('.asset-library-card')).toHaveLength(1)
+49 -53
View File
@@ -4,6 +4,7 @@ import { policyDraft, policyIssue } from '@/features/projects/quality-policy'
import { projectsApi } from '@/features/projects/api'
import type { ProjectQualityPolicy } from '@/features/projects/types'
import QualityPolicySettings from '@/features/generation-config/components/QualityPolicySettings.vue'
import { qualityPolicySignature, readQualityPolicyConfirmation, rememberQualityPolicyConfirmation } from '@/features/projects/quality-policy-confirmation'
/** 保留已有精确例外的服务端完整策略。 */
const saved: ProjectQualityPolicy = {
@@ -23,66 +24,61 @@ afterEach(() => {
settings?.unmount()
settings = undefined
vi.unstubAllGlobals()
vi.restoreAllMocks()
localStorage.clear()
})
describe('项目质量策略', () => {
it('进入和新增例外不立即报错,保存时拦截缺失字段,修正后才写入', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(
async (_url, init) =>
new Response(
JSON.stringify({
data: {
projectId: 'p',
policy:
init?.method === 'PUT'
? JSON.parse(String(init.body))
: { ...saved, actionExceptions: [] }
}
})
)
)
vi.stubGlobal('fetch', fetcher)
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false } })
it('基础规则不再添加空白例外,已有例外只读展示且完整保留在提交草稿中', async () => {
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: { projectId: 'p', policy: saved } } })
settings = wrapper
await flushPromises()
expect(wrapper.findAll('button').some(button => button.text() === '添加例外')).toBe(false)
expect(wrapper.find('[aria-label="例外 1 主体引用"]').exists()).toBe(false)
expect(wrapper.text()).toContain('已有动作例外 · 1 项')
expect(wrapper.vm.validatedDraft()?.actionExceptions).toEqual(saved.actionExceptions)
})
it('启动入口复用真实回执,不重复读取,无变化保存保留确认,修改后撤销确认', async () => {
let currentPolicy = policyDraft(saved)
const read = vi.spyOn(projectsApi, 'qualityPolicy').mockImplementation(async () => ({ projectId: 'p', policy: policyDraft(currentPolicy) }))
vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => { currentPolicy = policyDraft(policy); return { projectId: id, policy: policyDraft(policy) } })
const signature = qualityPolicySignature(saved)
rememberQualityPolicyConfirmation('p', signature)
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: { projectId: 'p', policy: saved } } })
settings = wrapper
await flushPromises()
expect(read).not.toHaveBeenCalled()
expect(wrapper.vm.validatedDraft()).toEqual(saved)
await wrapper.vm.save()
expect(readQualityPolicyConfirmation('p')).toBe(signature)
await wrapper.get('#quality-custom-rules').setValue('新规则')
await wrapper.vm.save()
expect(readQualityPolicyConfirmation('p')).toBeNull()
})
it('保存基础规则时合并后来新增的例外,不覆盖隐藏的服务端最新例外', async () => {
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({ projectId: 'p', policy: latest })
const write = vi.spyOn(projectsApi, 'saveQualityPolicy').mockImplementation(async (id, policy) => ({ projectId: id, policy: policyDraft(policy) }))
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: { projectId: 'p', policy: saved } } })
settings = wrapper
await flushPromises()
expect(wrapper.find('.text-danger').exists()).toBe(false)
await wrapper
.findAll('button')
.find(button => button.text() === '添加例外')!
.trigger('click')
expect(wrapper.text()).not.toContain('精确例外需填写')
expect(wrapper.vm.canSave).toBe(true)
await wrapper.vm.save()
expect(wrapper.text()).toContain('精确例外需填写')
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'PUT')).toHaveLength(0)
await wrapper.get('[aria-label="例外 1 主体引用"] input').setValue('@CH0001')
expect(wrapper.text()).not.toContain('精确例外需填写')
await wrapper.vm.save()
expect(wrapper.text()).toContain('精确例外需填写')
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'PUT')).toHaveLength(0)
await wrapper.get('[aria-label="例外 1 确认依据"] input').setValue('剧本明确的动作许可')
await wrapper.get('#quality-custom-rules').setValue('新的整体规则')
await wrapper.vm.save()
expect(write).toHaveBeenCalledExactlyOnceWith('p', { ...saved, customRules: ['新的整体规则'], actionExceptions: latest.actionExceptions })
expect(wrapper.vm.validatedDraft()?.actionExceptions).toEqual(latest.actionExceptions)
expect(wrapper.text()).toContain('已有动作例外 · 2 项')
})
it('基础规则已被其他位置修改时拒绝覆盖,保留用户草稿', async () => {
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'p', policy: { ...saved, physicsMode: 'fantasy' } })
const write = vi.spyOn(projectsApi, 'saveQualityPolicy')
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: { projectId: 'p', policy: saved } } })
settings = wrapper
await flushPromises()
const writes = fetcher.mock.calls.filter(([, init]) => init?.method === 'PUT')
expect(writes).toHaveLength(1)
expect(JSON.parse(String(writes[0]?.[1]?.body))).toEqual({
version: 1,
physicsMode: 'realistic',
allowExaggeratedMotion: false,
allowNonPhysicalActions: false,
allowSupernaturalAbilities: false,
customRules: ['规则'],
actionExceptions: [
{
code: 'action_resource_conflict',
ownerRef: '@CH0001',
resource: 'left_hand',
reason: '剧本明确的动作许可'
}
]
})
expect(wrapper.text()).toContain('质量策略已保存')
await wrapper.get('#quality-custom-rules').setValue('不能丢失的用户草稿')
await wrapper.vm.save()
expect(write).not.toHaveBeenCalled()
expect(wrapper.text()).toContain('质量规则已在其他位置更新')
expect(wrapper.vm.validatedDraft()?.customRules).toEqual(['不能丢失的用户草稿'])
})
it('草稿编辑不污染已保存策略,完整保留精确例外', () => {
const draft = policyDraft(saved)
@@ -448,7 +448,7 @@ describe('过期首帧到具体素材定位', () => {
it('警告列出具体集数与镜头,可定位关联素材或打开对应生产镜头', async () => {
const { router, fetcher } = await gallery()
const warning = wrapper!.get('[data-keyframe-impact]')
expect(warning.text()).toContain('第 2 集 · BEAT 2 / 镜头 1')
expect(warning.text()).toContain('第 2 集 · 剧情段落 2 / 镜头 1')
const shotLink = warning.get('a[data-impact-shot-link]')
const location = new URL(shotLink.attributes('href')!, 'http://localhost')
expect(location.pathname).toBe('/projects/capability-test/production')
+2 -2
View File
@@ -75,9 +75,9 @@ describe('WorkflowExecution 前端契约', () => {
expect(wrapper.text()).toContain('更新时间')
wrapper.unmount()
})
it('保留未知阶段并限制真实进度范围', () => {
it('未知阶段以待确认展示且不影响真实进度范围', () => {
expect(executionStageLabel('repairing')).toBe('自动修复')
expect(executionStageLabel('new_backend_stage')).toBe('new_backend_stage')
expect(executionStageLabel('new_backend_stage')).toBe('状态待确认')
expect(executionPercentage(1, 2)).toBe(50)
expect(executionPercentage(4, 2)).toBe(100)
expect(executionPercentage(1, 0)).toBe(0)
+18 -12
View File
@@ -37,6 +37,7 @@ import { identityFixture, identityImageFixture } from '@/features/subject-identi
import { getIdentitySession } from '@/features/subject-identity/model'
import { drawerPanel, expandSections, selectControl } from '@/testing/naive'
import ProductionPage from '@/features/production/ProductionPage.vue'
import RawDataDetails from '@/components/ui/RawDataDetails.vue'
import { getProductionSession } from '@/features/production/model'
/**
@@ -353,7 +354,7 @@ describe('内容级滚动下的生产反馈', () => {
expect(wrapper.find('.workspace-tools-drawer').exists()).toBe(false)
const alert = wrapper.get('.workspace-split [role="alert"]')
expect(alert.element.closest('.workspace-tools-drawer')).toBeNull()
expect(alert.text()).toContain('无法连接后端')
expect(alert.text()).toContain('暂时无法连接服务')
})
it('回执返回时自动展开总览,部分失败诊断不会留在折叠区内', async () => {
@@ -827,7 +828,7 @@ describe('视觉风格与主体身份工作区', () => {
await new DOMWrapper(document.body).get('[aria-label="风格图片地址"]').setValue('javascript:alert(1)')
button('添加参考图').click()
await flushPromises()
expect(document.querySelector('.n-form-item-feedback--error')?.textContent).toContain('请填写有效的')
expect(document.querySelector('.n-form-item-feedback--error')?.textContent).toContain('请填写可访问的图片链接')
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
await new DOMWrapper(document.body).get('[aria-label="风格图片地址"]').setValue('/storage/style.png')
button('添加参考图').click()
@@ -894,7 +895,7 @@ describe('视觉风格与主体身份工作区', () => {
expect(button('确认AI 重新生成风格').disabled).toBe(true)
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
})
it('视觉风格首次查询为空时可人工保存,JSON 校验和锁定字段准确传递', async () => {
it('视觉风格首次查询为空时可人工保存,画面要求与锁定字段准确传递', async () => {
let style: ReturnType<typeof styleFixture> | null = null
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (_url, init) => {
if (init?.method === 'PUT') style = styleFixture(JSON.parse(init.body as string))
@@ -906,12 +907,7 @@ describe('视觉风格与主体身份工作区', () => {
await expandSections()
expect(wrapper!.text()).toContain('默认采用中国人物选角基线')
expect(wrapper!.text()).toContain('人物风格与选角背景')
await wrapper!.get('#style-constraints').setValue('{"不应静默丢弃":true}')
button('保存视觉风格').click()
await flushPromises()
expect(document.querySelector('.n-form-item-feedback--error')?.textContent).toContain('JSON 字符串数组')
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'PUT')).toBe(false)
await wrapper!.get('#style-constraints').setValue('["真人写实"]')
await wrapper!.get('#style-constraints').setValue('真人写实')
await wrapper!.get('#style-lock').trigger('click')
await wrapper!.get('#style-name').setValue('雨夜风格')
button('保存视觉风格').click()
@@ -1347,7 +1343,7 @@ describe('视觉风格与主体身份工作区', () => {
button('AI 生成主体身份').click()
await flushPromises()
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1)
expect(getOperation(fixture.id).error).toContain('无法连接后端')
expect(getOperation(fixture.id).error).toContain('暂时无法连接服务')
provided.data.value!.project = { ...fixture, status: 'generating' }
await flushPromises()
expect(new DOMWrapper(document.body).get('#identity-description').attributes('disabled')).toBeDefined()
@@ -1669,8 +1665,10 @@ describe('工作台页面交互', () => {
expect(wrapper.text()).toContain('图片不可用')
expect(wrapper.find('.reference-card a').exists()).toBe(false)
expect(wrapper.find('.reference-card img').exists()).toBe(false)
button('读取生成规格').click()
button('整理生成方案').click()
await flushPromises()
expect(wrapper.find('pre').exists()).toBe(false)
await wrapper.getComponent(RawDataDetails).get('.n-collapse-item__header-main').trigger('click')
expect(wrapper.get('pre').text()).toContain('form-db')
expect(wrapper.get('pre').text()).toContain('地面积水')
expect(fetcher.mock.calls[2]?.[0]).toBe('/api/storyboard-shots/shot-db-1-1/generation-spec')
@@ -1971,7 +1969,7 @@ describe('工作台页面交互', () => {
)
await flushPromises()
expect(wrapper.text()).not.toContain('旧镜头人物')
expect(button('读取生成规格').disabled).toBe(true)
expect(button('整理生成方案').disabled).toBe(true)
})
it('提示词必须确认才 POST,使用正式 Shot ID,返回内容以纯文本显示', async () => {
@@ -2083,6 +2081,9 @@ describe('工作台页面交互', () => {
return new Response(
'{"data":{"episodeCount":1,"groupCount":1,"estimatedTaskCount":3,"groups":[],"tasks":[],"modules":["character","scene","prop"],"groupSize":2}}'
)
if (String(url).includes('quality-policy')) return new Response(JSON.stringify({ data: { projectId: 'page-test-project', policy: {
version: 1, physicsMode: 'realistic', allowExaggeratedMotion: false, allowNonPhysicalActions: false, allowSupernaturalAbilities: false, customRules: []
} } }))
return new Response('{"data":{"workflowExecution":{"status":"completed"}}}')
})
stubFetch(fetcher)
@@ -2101,6 +2102,11 @@ describe('工作台页面交互', () => {
await flushPromises()
button('生成拆解候选').click()
await flushPromises()
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')