feat(short-drama-agent-front): 完善分镜审核与制作准备流程

This commit is contained in:
GJ committed 2026-10-19 21:59:22 +08:00
1 parent c4b43b9725
commit 1da56e0d46
72 files changed
+2801 -528

No files matched your search

+19 -19
View File
@@ -1,3 +1,4 @@
import { policyReceipt } from '../../fixtures/quality-policy'
import { computed, ref } from 'vue'
import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -22,10 +23,7 @@ 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: [] }
})
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,
groups: [{ groupId: 'preview-group', groupNo: 1, startEpisodeNo: 1, endEpisodeNo: 1, episodes: [] }]
@@ -45,9 +43,11 @@ it('首次点击生成先读取并确认质量规则,不直接打开模型启
})
it('规则确认保留分组预览,隐藏空白例外,确认不调用模型,未变规则不重复打开表单', async () => {
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({
projectId: 'breakdown-scroll-test',
policy: { 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,
@@ -84,12 +84,12 @@ it('规则确认保留分组预览,隐藏空白例外,确认不调用模型
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 }))
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 })
policy = input
return { projectId: id, 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]
@@ -400,7 +400,7 @@ function handDiagnosticsResponse(evidenceShotCount: number) {
* @returns 当前动作诊断弹窗
*/
function qualityDialog() {
const panel = document.querySelector<HTMLElement>('.app-dialog[aria-label="动作诊断"]')
const panel = document.querySelector<HTMLElement>('.app-drawer[aria-label="动作诊断"]')
if (!panel) throw new Error('动作诊断弹窗未打开')
return new DOMWrapper(panel)
}
@@ -751,7 +751,7 @@ describe('拆解页内容滚动', () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async input => {
const url = String(input)
if (url.includes('storyboard-legacy-action-diagnosis-results')) return diagnosisResultsResponse()
if (url.endsWith('storyboard-hand-occupancy-diagnostics')) return handDiagnosticsResponse(0)
if (url.endsWith('storyboard-action-resource-diagnostics')) return handDiagnosticsResponse(0)
throw new Error(`未预期的诊断请求:${url}`)
})
vi.stubGlobal('fetch', fetcher)
@@ -765,7 +765,7 @@ describe('拆解页内容滚动', () => {
const panel = qualityDialog()
expect(panel.findAll('button').some(button => button.text() === '刷新校验')).toBe(false)
expect(panel.get('.storyboard-diagnosis-dialog').attributes('aria-busy')).toBe('false')
const footer = panel.get('.n-card__footer')
const footer = panel.get('.n-drawer-footer')
expect(footer.text()).toContain('预览诊断范围')
expect(footer.text()).toContain('启动 AI 诊断')
expect(footer.text()).toContain('关闭')
@@ -778,7 +778,7 @@ describe('拆解页内容滚动', () => {
await flushPromises()
expect(panel.findAll('button').some(button => button.text() === '刷新校验')).toBe(false)
expect(
fetcher.mock.calls.filter(([input]) => String(input).endsWith('storyboard-hand-occupancy-diagnostics'))
fetcher.mock.calls.filter(([input]) => String(input).endsWith('storyboard-action-resource-diagnostics'))
).toHaveLength(1)
})
@@ -795,7 +795,7 @@ describe('拆解页内容滚动', () => {
})
return diagnosisResultsResponse()
}
if (url.endsWith('storyboard-hand-occupancy-diagnostics')) return handDiagnosticsResponse(0)
if (url.endsWith('storyboard-action-resource-diagnostics')) return handDiagnosticsResponse(0)
throw new Error(`未预期的诊断请求:${url}`)
})
vi.stubGlobal('fetch', fetcher)
@@ -807,7 +807,7 @@ describe('拆解页内容滚动', () => {
await panel.findAll('.n-collapse-item__header-main')[1]!.trigger('click')
await flushPromises()
const content = panel.get('.diagnosis-dialog-content').element
const scroll = panel.get<HTMLElement>('.dialog-body-scroll .n-scrollbar-container').element
const scroll = panel.get<HTMLElement>('.n-drawer-body .n-scrollbar-container').element
scroll.scrollTop = 80
const refreshButton = panel.findAll('button').find(button => button.text() === '刷新结果')!
const refreshIcon = refreshButton.get('.n-button__icon').element
@@ -838,7 +838,7 @@ describe('拆解页内容滚动', () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async input => {
const url = String(input)
if (url.includes('storyboard-legacy-action-diagnosis-results')) return diagnosisResultsResponse()
if (url.endsWith('storyboard-hand-occupancy-diagnostics')) {
if (url.endsWith('storyboard-action-resource-diagnostics')) {
handRequests++
if (handRequests > 1)
return new Promise<Response>(resolve => {
@@ -886,7 +886,7 @@ describe('拆解页内容滚动', () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async input => {
const url = String(input)
if (url.includes('storyboard-legacy-action-diagnosis-results')) return diagnosisResultsResponse()
if (url.endsWith('storyboard-hand-occupancy-diagnostics')) {
if (url.endsWith('storyboard-action-resource-diagnostics')) {
handRequests++
if (handRequests === 1)
return new Promise<Response>(resolve => {
@@ -906,13 +906,13 @@ describe('拆解页内容滚动', () => {
expect(qualityDialog().text()).not.toContain('诊断结果')
expect(
qualityDialog()
.get('.n-card__footer')
.get('.n-drawer-footer')
.findAll('button')
.filter(button => button.text() !== '关闭')
.every(button => (button.element as HTMLButtonElement).disabled)
).toBe(true)
const close = qualityDialog()
.get('.n-card__footer')
.get('.n-drawer-footer')
.findAll('button')
.find(button => button.text() === '关闭')!
expect((close.element as HTMLButtonElement).disabled).toBe(false)
@@ -1,3 +1,4 @@
import { policyReceipt } from '../../fixtures/quality-policy'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { actionExceptionTargets } from '@/features/breakdown/action-exceptions'
@@ -68,8 +69,8 @@ describe('从实际问题建立动作例外', () => {
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 }))
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('左手握住铜铃')
@@ -87,7 +88,7 @@ describe('从实际问题建立动作例外', () => {
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)
@@ -95,8 +96,8 @@ describe('从实际问题建立动作例外', () => {
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 })
let finish!: (value: ReturnType<typeof policyReceipt>) => void
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 } })
await flushPromises()
@@ -105,7 +106,7 @@ describe('从实际问题建立动作例外', () => {
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 })
finish(policyReceipt('candidate-project', policy))
await flushPromises()
expect(save).not.toHaveBeenCalled()
expect(wrapper.find('textarea').element.value).toBe('允许原因')
@@ -117,7 +118,7 @@ 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: '已确认的同类例外' }] }
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'candidate-project', policy: existing })
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 } })
await flushPromises()
@@ -129,7 +130,7 @@ describe('从实际问题建立动作例外', () => {
it('保存失败保留原因供修正,不增加本地例外或宣称已通过', async () => {
const { state, quality } = conflict()
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'candidate-project', policy })
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 } })
await flushPromises()
@@ -146,7 +147,7 @@ describe('从实际问题建立动作例外', () => {
it('读取失败或项目不符时不使用默认规则、不开放添加', async () => {
const { state, quality } = conflict()
vi.spyOn(projectsApi, 'qualityPolicy').mockResolvedValue({ projectId: 'other', policy })
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 } })
await flushPromises()
@@ -0,0 +1,83 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, DOMWrapper, type VueWrapper } from '@vue/test-utils'
import StoryboardDiagnosis from '@/features/breakdown/components/StoryboardDiagnosis.vue'
import DiagnosisShotDetails from '@/features/breakdown/components/DiagnosisShotDetails.vue'
import { preparationApi } from '@/features/storyboard-preparation/api'
import { breakdownApi } from '@/features/breakdown/api'
import { workflowExecutionApi } from '@/features/workflows/execution-api'
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 })
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 })
/** 只读接口全部隔离,任何未授权模型请求均由测试捕获。 */
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, '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 = '' })
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 }])
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()
expect(read).toHaveBeenCalledWith('diag-p', 'db-shot')
const drawer = new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!)
expect(drawer.text()).toContain('缺少可信的质量规则记录')
expect(drawer.get('[aria-label="启动 AI 诊断"]').attributes('disabled')).toBeDefined()
expect(start).not.toHaveBeenCalled()
})
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')
await flushPromises()
const confirmation = new DOMWrapper(document.querySelector('.app-dialog')!)
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()
})
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()
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 } } })
expect(history).not.toHaveBeenCalled()
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()
expect(wrapper.text()).not.toContain('已满足人工修订')
})
})
@@ -0,0 +1,41 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, DOMWrapper, type VueWrapper } from '@vue/test-utils'
import StoryboardDiagnosis from '@/features/breakdown/components/StoryboardDiagnosis.vue'
import WorkflowExecutionPanel from '@/features/workflows/WorkflowExecutionPanel.vue'
import { breakdownApi } from '@/features/breakdown/api'
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: '单脚站立' }] }
let wrapper: VueWrapper | undefined
afterEach(() => { wrapper?.unmount(); wrapper = undefined; vi.restoreAllMocks(); vi.unstubAllGlobals(); document.body.innerHTML = '' })
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()
const dialog = new DOMWrapper(document.querySelector('[aria-label="动作诊断"]')!)
expect(dialog.text()).toContain('镜头已修订,AI 待复查')
expect(dialog.text()).toContain('镜头内容已变化')
expect(dialog.text()).toContain('质量规则已变化')
expect(dialog.text()).toContain('手部动作证据 1 / 2')
expect(dialog.text()).toContain('重心需要核对')
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
wrapper = mount(WorkflowExecutionPanel, { props: { execution, loading: false, error: '' } })
expect(wrapper.text()).toContain('需要人工核查')
expect(wrapper.text()).toContain('可复用 1 镜')
expect(wrapper.text()).toContain('待核查 2 镜')
expect(wrapper.text()).toContain('可能已产生费用')
expect(wrapper.text()).not.toContain('未计费')
})
})
@@ -0,0 +1,43 @@
import { effectScope, ref } from 'vue'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { projectsApi } from '@/features/projects/api'
import { useBreakdownStartPolicy } from '@/features/breakdown/useBreakdownStartPolicy'
import { candidatePreviewReady } from '@/features/breakdown/candidate'
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() })
describe('服务端规则确认契约', () => {
it('保存发送规则和期望修订,明确确认使用独立接口', async () => {
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 })
await projectsApi.confirmQualityPolicy('p', 2)
expect(fetcher.mock.calls[1]?.[0]).toBe('/api/projects/p/quality-policy/confirm')
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' }))
const scope = effectScope()
try {
const flow = scope.run(() => useBreakdownStartPolicy(ref('p'), ref('scope'), ref(true)))!
await flow.prepare()
expect(flow.reviewOpen.value).toBe(false)
expect(flow.startOpen.value).toBe(true)
expect(await flow.verifyStart()).toBe(true)
expect(flow.consumePermit()).toEqual({ expectedRevision: 2 })
expect(flow.consumePermit()).toBeNull()
} finally { scope.stop() }
})
it('候选安全检查必须包含规则匹配,缺失或 false 均不可提交', () => {
const preview = commitPreview()
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)
})
})
+105 -232
View File
@@ -1,261 +1,134 @@
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 type { 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'
import { qualityPolicySignature } from '@/features/projects/quality-policy-confirmation'
import { policyReceipt } from '../../fixtures/quality-policy'
/**
* 使用真实接口形状的独立规则,不连接服务或调用模型。
* @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 流程及其响应式输入
*/
/** 真实规则回执,旧项目初始修订也必须明确确认。 */
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')
const input = ref('preview-1')
const allowed = ref(true)
scope = effectScope()
const flow = scope.run(() => useBreakdownStartPolicy(id, input, allowed))!
return { id, input, allowed, flow }
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))! }
}
afterEach(() => {
scope?.stop()
vi.unstubAllGlobals()
localStorage.clear()
vi.restoreAllMocks()
})
/** 模拟服务端 CAS 保存及独立明确确认,复制回执避免测试污染。 */
function server() {
let saved = initial()
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) })
return structuredClone(saved)
})
const confirm = vi.spyOn(projectsApi, 'confirmQualityPolicy').mockImplementation(async (_id, expected) => {
if (expected !== saved.revision) throw new Error('版本冲突')
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 } } }
}
afterEach(() => { scopes.splice(0).forEach(scope => scope.stop()); vi.restoreAllMocks(); vi.unstubAllGlobals(); localStorage.clear() })
describe('拆解质量规则内容与当前浏览器确认', () => {
it('忽略属性顺序、首尾空格和空例外表示,但识别许可、规则和例外的实际变化', () => {
const base = receipt().policy
describe('规则内容比较与服务端确认', () => {
it('格式版本不代替修订,比较内容时保留许可、规则和例外变化', () => {
const base = initial().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('质量规则响应不完整')
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('确认按项目隔离,损坏存储或存储权限失败不会被当作已确认', () => {
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)
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()
})
})
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)
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)
expect(await next.verifyStart()).toBe(true)
expect(next.consumePermit()).toBe(true)
expect(next.consumePermit()).toBe(false)
expect(next.consumePermit()).toEqual({ expectedRevision: 0 }); expect(next.consumePermit()).toBeNull()
})
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()
it('修改规则先携带旧修订保存,再确认新修订,最后重读确认', async () => {
const api = server(); const { flow } = setup(); await flow.prepare()
const draft = { ...initial().policy, allowExaggeratedMotion: true }
expect(await flow.confirmRules(draft)).toBe(true)
expect(save).toHaveBeenCalledWith('policy-project', draft)
expect(read).toHaveBeenCalledTimes(3)
expect(readQualityPolicyConfirmation('policy-project')).toBe(qualityPolicySignature(draft))
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 })
})
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 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('真实保存期间锁定取消,保存后的只读回查可取消,迟到回查不记录确认', 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.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('最终启动确认期间规则变化,返回规则界面并撤销启动许可', 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 => {
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 { 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 === 'scope') input.value = 'new'
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)
finish(initial()); await pending
expect(flow.reviewOpen.value).toBe(false); expect(flow.startOpen.value).toBe(false); expect(flow.consumePermit()).toBeNull()
})
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)
it('确认写入时锁定取消,写入后的只读回查仍可关闭且迟到响应不启动', async () => {
const api = server(); const { flow } = setup(); await flow.prepare()
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)
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)
let finishRead!: (value: ProjectQualityPolicyResult) => void
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()
})
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)
it('最终费用确认期间规则更新或确认撤销均返回规则核对', async () => {
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()
})
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)
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()
})
})
@@ -32,7 +32,10 @@ afterEach(() => {
vi.unstubAllGlobals()
})
/** happy-dom 不计算排版;注入明确的容器几何,但保持真实 NScrollbar 和原生 scroll 事件路径。 */
/**
* 注入容器几何与浏览器滚动取整规则,保持真实 NScrollbar 和原生 scroll 事件路径。
* @returns 正文与目录容器、章节原始位置及滚动调用记录
*/
async function mountReader() {
wrapper = mount(EpisodeReader, { props: { episodes } })
const reader = wrapper.get<HTMLElement>('.reader-scroll .n-scrollbar-container').element
@@ -45,7 +48,9 @@ async function mountReader() {
if (this === reader) return new DOMRect(0, 100, 600, reader.clientHeight)
if (this === directory) return new DOMRect(0, 50, 200, directory.clientHeight)
if (this.matches('.reader-chapter')) {
return new DOMRect(0, 100 + tops[Number(this.dataset.episode)]! - reader.scrollTop, 600, 600)
// 模拟章节平移后的可见位置,保留真实组件负责的像素对齐行为。
const translation = parseFloat(this.style.getPropertyValue('--reader-chapter-offset')) || 0
return new DOMRect(0, 100 + tops[Number(this.dataset.episode)]! + translation - reader.scrollTop, 600, 600)
}
if (this.matches('.reader-episode-link')) {
return new DOMRect(0, 58 + (Number(this.dataset.episode) - 1) * 72 - directory.scrollTop, 180, 64)
@@ -55,7 +60,7 @@ async function mountReader() {
const readerScroll = vi.spyOn(reader, 'scrollTo').mockImplementation((options?: ScrollToOptions | number) => {
if (typeof options !== 'object') return
// 模拟浏览器边界:末集最小高度及上下留白让其标题能抵达阅读线。
reader.scrollTop = Math.max(0, Math.min(options.top ?? 0, Math.max(...Object.values(tops)) - 32))
reader.scrollTop = Math.round(Math.max(0, Math.min(options.top ?? 0, Math.max(...Object.values(tops)) - 32)))
reader.dispatchEvent(new Event('scroll'))
})
const directoryScroll = vi.spyOn(directory, 'scrollTo').mockImplementation((options?: ScrollToOptions | number) => {
@@ -131,6 +136,18 @@ describe('连续剧本阅读器', () => {
expect(pageScroll).not.toHaveBeenCalled()
})
it('章节高度含小数时,反复切换各集仍与首集顶部精确对齐', async () => {
const { reader, tops } = await mountReader()
tops[2] = 700.625
tops[3] = 1480.84375
for (const episode of [1, 2, 3, 2, 1, 3, 2]) {
await wrapper!.get(`.reader-episode-link[data-episode="${episode}"]`).trigger('click')
const chapter = wrapper!.get(`.reader-chapter[data-episode="${episode}"]`).element
expect(chapter.getBoundingClientRect().top - reader.getBoundingClientRect().top).toBe(32)
expect(currentEpisode()).toBe(episode)
}
})
it('手机上下集按目录顺序切换,跳过缺号并禁用首尾边界', async () => {
const { reader } = await mountReader()
await wrapper!.setProps({ episodes: [episodes[0]!, episodes[2]!] })
@@ -16,6 +16,15 @@ 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 options = wrapper.getComponent(NSelect).props('options') as { value: number }[]
expect(options.some(item => item.value === -1)).toBe(supported)
wrapper.unmount()
}
})
it('图片尺寸只保留当前 Provider 枚举、默认值与当前值', () => {
const wrapper = mountFields([
{
@@ -86,6 +86,14 @@ const catalog: GenerationModelCatalog = {
}
describe('项目配置保存前校验', () => {
it('项目竖屏画布允许目录支持的方形参考图尺寸,不把两者强制绑定', () => {
const draft = creativeProfileDraft(saved)
const squareCatalog = structuredClone(catalog)
squareCatalog.images[0]!.generationOptions[0]!.options = [{ label: '方形参考图', value: '2048*2048' }]
draft.imageOptions.size = '2048*2048'
expect(draft.aspectRatio).toBe('9:16')
expect(creativeProfileIssues(draft, squareCatalog)).toEqual([])
})
it('保留但提示不再支持的历史尺寸,选择有效尺寸后可保存', () => {
const draft = creativeProfileDraft(saved)
expect(creativeProfileIssues(draft, catalog)).toHaveLength(1)
@@ -0,0 +1,67 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { NSelect, type MessageApi } from 'naive-ui'
import { ref } from 'vue'
import CreativeProfileSettings from '@/features/generation-config/components/CreativeProfileSettings.vue'
import { generationConfigApi } from '@/features/generation-config/api'
import { projectGenerationRevisionKey } from '@/features/generation-config/context'
import { actionMessageKey } from '@/components/ui/useActionMessage'
import { ApiError } from '@/lib/http'
import { generationProfile, imageCatalog } from '../../fixtures/generation'
/** 当前配置表单实例,测试后释放观察器。 */
let wrapper: VueWrapper | undefined
afterEach(() => wrapper?.unmount())
/**
* 使用真实表单和隔离消息层,不请求真实服务或保存项目数据。
* @returns 草稿原值、保存接口、消息及配置修订号
*/
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: {} }] }
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 revision = ref(0)
wrapper = mount(CreativeProfileSettings, {
props: { projectId: saved.projectId },
global: { provide: { [actionMessageKey as symbol]: messages as unknown as MessageApi, [projectGenerationRevisionKey as symbol]: revision } }
})
await flushPromises()
return { saved, save, messages, revision }
}
describe('项目配置的业务冲突反馈', () => {
it.each([
['CANVAS_CHANGE_REQUIRES_REVALIDATION', '画幅'],
['CREATIVE_PROFILE_ACTIVE_WORKFLOW', '任务'],
['GENERATION_CONFIG_CHANGE_REQUIRES_REVALIDATION', '模型']
])('保存遇到 %s 时只提示业务原因、保留草稿且不重试', async (code, label) => {
const { saved, save, messages, revision } = await settings()
await wrapper!.findAllComponents(NSelect)[0]!.vm.$emit('update:value', '9:16')
save.mockRejectedValue(new ApiError('请求失败(409)', 409, { code, keyframeCount: 1 }))
await wrapper!.find('button').trigger('click')
await flushPromises()
expect(save).toHaveBeenCalledTimes(1)
expect(messages.warning).toHaveBeenCalledWith(expect.stringContaining(label), expect.any(Object))
expect(messages.error).not.toHaveBeenCalled()
expect(messages.success).not.toHaveBeenCalled()
expect(wrapper!.findAllComponents(NSelect)[0]!.props('value')).toBe('9:16')
expect(wrapper!.emitted('saved')).toBeUndefined()
expect(revision.value).toBe(0)
expect(saved.aspectRatio).toBe('1:1')
expect(wrapper!.text()).not.toContain('请求失败')
})
it('保存成功使用统一消息,不遗留重复的常驻成功提示', async () => {
const { save, messages, revision } = await settings()
await wrapper!.find('button').trigger('click')
await flushPromises()
expect(save).toHaveBeenCalledTimes(1)
expect(messages.success).toHaveBeenCalledTimes(1)
expect(wrapper!.find('.context-notice-success').exists()).toBe(false)
expect(revision.value).toBe(1)
})
})
@@ -6,7 +6,7 @@ import type { ProductionStartInput } from '@/features/production/types'
afterEach(() => vi.unstubAllGlobals())
describe('生产后端真实请求契约', () => {
it('计划使用 POST JSON 并将图片参数与启动保持同源', async () => {
it('计划保持 POST 且只发送支持的模型参数,启动另外携带执行范围和视频参数', async () => {
const fetchMock = vi
.fn<typeof fetch>()
.mockImplementation(async () => new Response(JSON.stringify({ data: { projectId: 'p' } })))
@@ -15,6 +15,7 @@ describe('生产后端真实请求契约', () => {
imageProvider: 'qwen-image',
imageGenerationOptions: { size: '1024*1024', seed: 3 },
videoProvider: 'wan',
videoGenerationOptions: { duration: -1, resolution: '720p' },
startFrom: 'subjectImages',
stopAfter: 'videoPrompts',
stableIdentityAnchorLimit: 1,
@@ -27,10 +28,13 @@ describe('生产后端真实请求契约', () => {
await productionApi.startPipeline('p', input)
expect(fetchMock.mock.calls[0]?.[0]).toBe('/api/projects/p/production/plan')
expect(fetchMock.mock.calls[1]?.[0]).toBe('/api/projects/p/production/start')
for (const [, request] of fetchMock.mock.calls) {
expect(request?.method).toBe('POST')
expect(JSON.parse(String(request?.body))).toEqual(input)
}
expect(fetchMock.mock.calls.every(([, request]) => request?.method === 'POST')).toBe(true)
expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({
imageProvider: input.imageProvider,
imageGenerationOptions: input.imageGenerationOptions,
videoProvider: input.videoProvider
})
expect(JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body))).toEqual(input)
expect(fetchMock.mock.calls[0]?.[1]?.signal).toBeInstanceOf(AbortSignal)
})
+51 -1
View File
@@ -8,6 +8,9 @@ import { getOperation } from '@/features/workflows/operations'
import { formFixture } from '@/features/subject-images/testing/fixtures'
import { directionsResult } from '@/features/storyboard/testing/fixtures'
import { checkPipeline, useAdvancedProduction } from '@/features/production/useAdvancedProduction'
import { productionApi } from '@/features/production/api'
import { generationConfigApi } from '@/features/generation-config/api'
import { projectSettingsOpenKey } from '@/features/generation-config/context'
import { useProduction } from '@/features/production/useProduction'
import { getProductionSession } from '@/features/production/model'
import AdvancedProduction from '@/features/production/components/AdvancedProduction.vue'
@@ -146,10 +149,12 @@ 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.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')
else if (path.includes('/storyboard-directions')) data = { ...directionsResult('capability-test'), shotCount: 1, directionCount: 1 }
else if (path.endsWith('/videos/status'))
data = {
total: 1,
@@ -205,6 +210,51 @@ async function advanced() {
}
describe('高级串联生产的安全边界', () => {
it('缺少配置时在计划位置提供已有配置入口,不创建配置或允许启动', async () => {
const { context, posts } = server()
vi.spyOn(generationConfigApi, 'profile').mockResolvedValue(null)
const openSettings = vi.fn<() => void>()
wrapper = mount(AdvancedProduction, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context, [projectSettingsOpenKey as symbol]: openSettings } }
})
await flushPromises()
await expandSections()
button('检查串联生产条件').click()
await flushPromises()
const configure = wrapper.findAll('button').find(item => item.text() === '前往项目配置')
expect(configure?.exists()).toBe(true)
await configure!.trigger('click')
expect(openSettings).toHaveBeenCalledTimes(1)
expect(button('启动串联生产').disabled).toBe(true)
expect(posts()).toHaveLength(0)
})
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 })
await service.preflight()
expect(service.check.value).toBeNull()
expect(service.error.value).toContain('请先保存项目生成配置')
expect(service.error.value).not.toContain('TypeError')
expect(service.configurationRequired.value).toBe(true)
expect(posts()).toHaveLength(0)
})
it('尚无配置时不请求阶段计划,保存配置后重新预检恢复正常流程', async () => {
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))
await service.preflight()
expect(service.configurationRequired.value).toBe(true)
expect(service.check.value).toBeNull()
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/production/plan'))).toBe(false)
missing = false
await service.preflight()
expect(service.configurationRequired.value).toBe(false)
expect(service.check.value?.issues).toEqual([])
expect(posts()).toHaveLength(0)
})
it('挂载不查询或生成,通过预检仍需显式启动,再次预检后提交安全范围与项目模型参数', async () => {
const { service, fetcher, posts } = await advanced()
expect(fetcher).not.toHaveBeenCalled()
+23
View File
@@ -114,6 +114,29 @@ async function openProject(initialPath: string) {
}
describe('剧本完成前的下游访问限制', () => {
it('导航使用当前阶段结果,旧待审标记不盖过已审核状态,下游素材仍独立限制', async () => {
const id = 'current-review-navigation'
const state = readiness(id, false)
state.script = { ready: true, reason: null }
state.breakdown = { ready: true, reason: null }
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: [] } }
}])
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)
expect(wrapper!.find(`.n-menu a[href="/projects/${id}/subject-identity"]`).exists()).toBe(false)
expect(wrapper!.find(`.n-menu a[href="/projects/${id}/production"]`).exists()).toBe(false)
state.breakdown = { ready: false, reason: '当前分镜审核已失效,请重新核对。' }
await wrapper!.get('.probe-refresh').trigger('click')
await flushPromises()
expect(wrapper!.find('.workspace-probe').exists()).toBe(false)
expect(wrapper!.get('.project-access-gate').text()).toContain('当前分镜审核已失效')
})
it('身份请求不使用全局加载消息,完成和失败使用临时消息且不遗留横幅', async () => {
vi.useFakeTimers()
const id = 'identity-message-test'
+17 -19
View File
@@ -1,10 +1,10 @@
import { policyReceipt } from '../../fixtures/quality-policy'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
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 = {
@@ -29,7 +29,7 @@ afterEach(() => {
})
describe('项目质量策略', () => {
it('基础规则不再添加空白例外,已有例外只读展示且完整保留在提交草稿中', async () => {
const wrapper = mount(QualityPolicySettings, { props: { projectId: 'p', disabled: false, initialPolicy: { projectId: 'p', policy: 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)
@@ -37,41 +37,39 @@ describe('项目质量策略', () => {
expect(wrapper.text()).toContain('已有动作例外 · 1 项')
expect(wrapper.vm.validatedDraft()?.actionExceptions).toEqual(saved.actionExceptions)
})
it('启动入口复用真实回执,不重复读取,无变化保存保留确认,修改后撤销确认', async () => {
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 } } })
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()
expect(wrapper.vm.validatedDraft()).toEqual(saved)
await wrapper.vm.save()
expect(readQualityPolicyConfirmation('p')).toBe(signature)
expect(read).toHaveBeenCalledTimes(1)
await wrapper.get('#quality-custom-rules').setValue('新规则')
await wrapper.vm.save()
expect(readQualityPolicyConfirmation('p')).toBeNull()
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: '另一处刚添加的例外' }] }
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 } } })
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) } })
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 })
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({ projectId: 'p', policy: { ...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: { projectId: 'p', policy: 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('不能丢失的用户草稿')
@@ -98,11 +96,11 @@ describe('项目质量策略', () => {
it('完整提交正式质量策略接口,保留用户明确的权限选择', async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async () => new Response(JSON.stringify({ data: { projectId: 'p', policy: saved } })))
.mockImplementation(async () => new Response(JSON.stringify({ data: policyReceipt('p', saved) })))
vi.stubGlobal('fetch', fetcher)
await projectsApi.saveQualityPolicy('p', saved)
await projectsApi.saveQualityPolicy('p', saved, 2)
expect(fetcher.mock.calls[0]![0]).toContain('/projects/p/quality-policy')
expect(fetcher.mock.calls[0]![1]!.method).toBe('PUT')
expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual(saved)
expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual({ policy: saved, expectedRevision: 2 })
})
})
@@ -0,0 +1,17 @@
import type { StoryboardRecheck, ReviewBaselinePreview, StoryboardApprovalState, StoryboardApproval, ProductionEntryReadiness } from '@/features/storyboard-preparation/types'
import { policyReceipt } from '../../fixtures/quality-policy'
/**
* 创建符合真实路由形状的独立复检数据,canConfirm 始终为 false。
* @param projectId 当前测试项目
* @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 } }
return { policy, quality, approval, baseline, entry, record }
}
@@ -0,0 +1,31 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { checkPipeline } from '@/features/production/useAdvancedProduction'
import { productionApi } from '@/features/production/api'
import { generationConfigApi } from '@/features/generation-config/api'
import { projectsApi } from '@/features/projects/api'
import { subjectImagesApi } from '@/features/subject-images/api'
import { storyboardApi } from '@/features/storyboard/api'
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.spyOn(generationConfigApi, 'profile').mockResolvedValue(null)
vi.spyOn(projectsApi, 'detail').mockResolvedValue({ id: 'p' } as never)
vi.spyOn(projectsApi, 'checkpoints').mockResolvedValue([])
vi.spyOn(subjectImagesApi, 'listForms').mockResolvedValue([])
vi.spyOn(productionApi, 'status').mockResolvedValue({ projectId: 'p' } as never)
const plan = vi.spyOn(productionApi, 'plan').mockRejectedValue(new Error('不应该进入制作计划'))
await expect(checkPipeline('p')).rejects.toThrow('请先完成分镜审核')
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.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: [] })
const plan = vi.spyOn(productionApi, 'plan')
await expect(checkPipeline('p')).rejects.toThrow('过期')
expect(plan).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,51 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import FormalRepairEditor from '@/features/storyboard-preparation/FormalRepairEditor.vue'
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: [] } })
let wrapper: VueWrapper | undefined
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 } })
await flushPromises()
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' })] })] }) }))
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('请填写修订原因')
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('已变化')
})
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 } }
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 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 } })
await flushPromises()
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)
})
})
@@ -0,0 +1,82 @@
import { effectScope, ref } from 'vue'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { preparationApi } from '@/features/storyboard-preparation/api'
import { projectsApi } from '@/features/projects/api'
import { useStoryboardPreparation } from '@/features/storyboard-preparation/useStoryboardPreparation'
import { currentStoryboardApproval } from '@/features/storyboard-preparation/model'
import { preparationFixture } from './fixtures'
/** 当前作用域,避免项目切换测试遗留响应式观察器。 */
const scopes: ReturnType<typeof effectScope>[] = []
afterEach(() => { scopes.splice(0).forEach(scope => scope.stop()); vi.restoreAllMocks() })
/** 测试只读回执保留当前已确认规则,所有写入独立模拟。 */
function setup() {
const data = preparationFixture()
vi.spyOn(preparationApi, 'recheck').mockImplementation(async () => structuredClone(data.quality))
vi.spyOn(preparationApi, 'approval').mockImplementation(async () => structuredClone(data.approval))
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 flow = scope.run(() => useStoryboardPreparation(id, locked))!
return { data, id, locked, flow }
}
describe('正式分镜审核绑定当前内容', () => {
it('有效标志也必须有同项目同版本的实际审核凭据', () => {
const data = preparationFixture()
const current = { ...data.approval, valid: true, confirmation: data.record }
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)
})
it('只读 canConfirm=false 不代替人工确认;满足实际预检后提交真实版本', async () => {
const { data, flow } = setup()
const confirm = vi.spyOn(preparationApi, 'confirmApproval').mockResolvedValue(data.record)
await flow.load()
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) })
})
it('确认期间镜头版本变化时撤销确认,不自动提交新版本', async () => {
const { data, flow } = setup()
const confirm = vi.spyOn(preparationApi, 'confirmApproval')
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()
expect(flow.reviewable.value).toBe(false)
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()
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 = []
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)
expect(await flow.confirm('baseline', '复核人', '明确采用当前规则重新核对旧分镜')).toBe(true)
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)
expect(await flow.confirm('approval', '复核人', '已核对')).toBe(false)
expect(confirm).toHaveBeenCalledTimes(1); expect(flow.error.value).toContain('版本冲突')
expect(flow.approved.value).toBe(false)
})
})
+10 -4
View File
@@ -1,3 +1,4 @@
import { preparationFixture } from '../storyboard-preparation/fixtures'
import { generationProfile, imageCatalog } from '../../fixtures/generation'
import { routerLinkStubs } from '../../fixtures/router'
import { computed, ref } from 'vue'
@@ -99,6 +100,7 @@ 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('/generation-models')) return jsonResponse(imageCatalog)
if (path.endsWith('/creative-profile')) return jsonResponse(generationProfile(fixture.id))
if (path.endsWith('/duration-budget'))
@@ -1816,7 +1818,7 @@ describe('工作台页面交互', () => {
expect(drawerPanel().text()).toContain('本集新镜头已保存')
expect(drawerPanel().text()).toContain('2 个镜头')
/** Duration Budget 新增一次只读 GET;镜头重生成不应增加额外写入。 */
expect(fetcher.mock.calls.filter(([, init]) => !init?.method || init.method === 'GET')).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
@@ -1913,7 +1915,8 @@ describe('工作台页面交互', () => {
expect(wrapper!.text()).toContain('第2集镜头1')
expect(wrapper!.text()).not.toContain('第1集镜头1')
/** 切换剧集只增加当前集查询,项目时长预算只在挂载时读取一次。 */
expect(fetcher.mock.calls).toHaveLength(6)
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)
})
@@ -2076,12 +2079,14 @@ describe('工作台页面交互', () => {
})
it('修改每组集数会废弃预览,重新预览并确认后才能启动', async () => {
let rulesConfirmed = false
const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => {
if (String(url).includes('breakdown-preview'))
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: {
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: []
} } }))
return new Response('{"data":{"workflowExecution":{"status":"completed"}}}')
@@ -2109,9 +2114,10 @@ describe('工作台页面交互', () => {
await flushPromises()
button('确认生成拆解候选').click()
await flushPromises()
const post = fetcher.mock.calls.find(call => call[1]?.method === 'POST')
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,
groupSize: 2,
modules: ['character', 'scene', 'prop'],
candidateOnly: true