import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' import { afterEach, describe, expect, it, vi } from 'vitest' import { readFileSync } from 'node:fs' import { mediaAssetUrl } from '@/lib/assets' import KeyframeDialog from '@/features/production/components/KeyframeDialog.vue' import { productionApi } from '@/features/production/api' import { isActiveVideo, issueLabel, primaryKeyframe, primaryVideo, productionStatusLabel, validOptionalSize } from '@/features/production/model' import { keyframeFixture, videoFixture } from '@/features/production/testing/fixtures' let wrapper: VueWrapper | undefined afterEach(() => { wrapper?.unmount() wrapper = undefined document.body.innerHTML = '' vi.unstubAllGlobals() }) /** 从 Naive 弹窗中查找精确按钮。 */ function button(label: string): HTMLButtonElement { const item = [...document.querySelectorAll('button')].find(element => element.textContent?.trim() === label) if (!item) throw new Error(`缺少按钮 ${label}`) return item } describe('镜头生产数据契约', () => { it('三个生产阶段使用统一的块级操作区,保证卡片、按钮和下一阶段之间有稳定间距', () => { const source = readFileSync('src/features/production/components/ShotProductionAssets.vue', 'utf8') expect(source.match(/class="production-stage-actions"/g)).toHaveLength(3) expect(source).toMatch(/\.production-stage-actions\s*\{[^}]*mt-4[^}]*min-h-\[34px\][^}]*items-center[^}]*gap-3/) }) it('本次视频生成设置限制内容宽度,并统一标题、字段和说明文字间距', () => { const source = readFileSync('src/features/production/components/ShotProductionAssets.vue', 'utf8') expect(source).toContain('class="generation-settings-panel surface-inset mt-4"') expect(source).toContain('class="generation-settings-content"') expect(source).toContain('class="generation-input-mode"') expect(source).toMatch(/\.generation-settings-panel\s*\{[^}]*p-5/) expect(source).toMatch(/\.generation-settings-content\s*\{[^}]*max-w-\[1120px\]/) expect(source).toMatch(/\.generation-input-mode-label\s*\{[^}]*mb-\[7px\][^}]*text-xs/) }) it('素材外层铺满,单行保持紧凑方图,换行后按可用宽度等分', () => { const source = readFileSync('src/features/production/components/ShotProductionAssets.vue', 'utf8') expect(source).toContain('v-if="currentVideo" class="video-grid mt-4"') expect(source).toMatch(/\.keyframe-grid,\s*\.video-grid\s*\{[^}]*max-w-\[260px\][^}]*grid-cols-1/) expect(source).toMatch( /\.video-input-grid\s*\{[^}]*grid-template-columns:\s*repeat\(auto-fit, minmax\(min\(220px, 100%\), 1fr\)\)/ ) expect(source).toContain("'--video-input-count': (currentVideoInput?.references.length ?? 0) + 1") expect(source).toMatch(/\.video-input-section\s*\{\s*width:\s*100%;\s*\}/) expect(source).toMatch( /\.video-input-grid\s*\{[^}]*max-width:\s*calc\(var\(--video-input-count\) \* 220px \+ \(var\(--video-input-count\) - 1\) \* 12px\)/ ) expect(source).toMatch(/\.keyframe-card \.asset-image\s*\{[^}]*aspect-square/) const videoCard = readFileSync('src/features/production/components/VideoCard.vue', 'utf8') expect(videoCard).toContain('class="block aspect-square w-full bg-[#080808] object-contain"') expect(source).toMatch(/\.video-input-card\s*\{[^}]*bg-\(--app-control\)/) expect(source).toMatch(/\.video-input-image\s*\{[^}]*aspect-square/) expect(source).toContain('object-fit="cover"') expect(source).not.toContain('class="video-input-ref"') expect(source).not.toContain('{{ reference.subjectFormName }} · {{ reference.subjectRef }}') expect(source).toMatch( /@media \(max-width: 760px\)[\s\S]*?\.video-input-grid\s*\{[^}]*grid-template-columns:\s*repeat\(auto-fit, minmax\(min\(120px, 100%\), 1fr\)\)/ ) }) it('可选尺寸必须成对留空或填写正整数', () => { expect(validOptionalSize('', '')).toBe(true) expect(validOptionalSize(1920, 1080)).toBe(true) expect(validOptionalSize(1920, '')).toBe(false) expect(validOptionalSize('', 1080)).toBe(false) expect(validOptionalSize(0, 1080)).toBe(false) expect(validOptionalSize(10.5, 1080)).toBe(false) }) it('主资产只接受已完成且具有地址的记录,活动视频覆盖三种状态', () => { expect(primaryKeyframe([keyframeFixture()])?.id).toBe('keyframe-1') expect(primaryKeyframe([keyframeFixture({ status: 'failed' })])).toBeUndefined() expect(primaryVideo([videoFixture()])?.id).toBe('video-1') expect(primaryVideo([videoFixture({ videoUrl: null })])).toBeUndefined() for (const status of ['pending', 'queued', 'running'] as const) expect(isActiveVideo(videoFixture({ status }))).toBe(true) expect(isActiveVideo(videoFixture())).toBe(false) }) it('就绪问题和异步任务状态提供中文标签', () => { expect(issueLabel('missing_keyframe')).toBe('缺少主首帧') expect(issueLabel('stale_prompt')).toBe('视频提示词需要更新') expect(issueLabel('provider_input_recovery')).toBe('视频模型输入需要处理') expect(issueLabel('invalid_generation_spec')).toBe('生成规格不完整') expect(issueLabel('missing_identity_anchor')).toBe('缺少演员母版') expect(issueLabel('identity_unlocked')).toBe('演员身份未锁定') expect(productionStatusLabel('in_progress')).toBe('任务进行中') expect(productionStatusLabel('unknown')).toBe('unknown') }) it('视频地址与图片使用相同的安全协议限制', () => { expect(mediaAssetUrl('/storage/videos/a.mp4')).toContain('/storage/videos/a.mp4') expect(mediaAssetUrl('https://cdn.example.com/a.mp4')).toBe('https://cdn.example.com/a.mp4') expect(mediaAssetUrl('javascript:alert(1)')).toBeNull() expect(mediaAssetUrl('/storage/../admin')).toBeNull() }) it('项目接口传递 force、Provider 与并发,视频创建不冒充同步完成', async () => { const fetcher = vi.fn().mockImplementation(async url => { const path = String(url) if (path.includes('/readiness')) return new Response( JSON.stringify({ data: { total: 1, ready: 1, skipped: 0, inProgress: 0, blocked: 0, missingPrompt: 0, missingKeyframe: 0, missingReference: 0, items: [] } }) ) return new Response( JSON.stringify({ data: { total: 1, targetCount: 1, created: 1, skipped: 0, readiness: {}, failed: 0, failures: [] } }) ) }) vi.stubGlobal('fetch', fetcher) await productionApi.videoReadiness('project/1', true) await productionApi.startQualityVideoExecution('project/1', { concurrency: 3, force: true, episodeNo: 2, limit: 2, inputMode: 'omni_reference', maxRepairAttempts: 2 }) expect(fetcher.mock.calls[0]?.[0]).toBe('/api/projects/project%2F1/videos/readiness?force=true') expect(fetcher.mock.calls[1]?.[0]).toBe('/api/projects/project%2F1/videos/generate-quality/start') expect(JSON.parse(String(fetcher.mock.calls[1]?.[1]?.body))).toEqual({ concurrency: 3, force: true, episodeNo: 2, limit: 2, inputMode: 'omni_reference', maxRepairAttempts: 2 }) }) it('视频输入规划支持当前集预览和单镜头预览', async () => { const fetcher = vi.fn().mockImplementation(async url => { const path = String(url) const shotId = path.includes('/storyboard-shots/') ? 'shot-1' : undefined return new Response( JSON.stringify({ data: shotId ? { shotId, inputMode: 'first_frame', reasons: ['主体关系简单'], metrics: {} } : { projectId: 'project/1', episodeNo: 3, readyCount: 1, firstFrameCount: 1, omniReferenceCount: 0, plans: [] } }) ) }) vi.stubGlobal('fetch', fetcher) await productionApi.videoInputPlans('project/1', 3) await productionApi.videoInputPlan('shot-1') expect(fetcher.mock.calls[0]?.[0]).toBe('/api/projects/project%2F1/video-input-plans?episodeNo=3') expect(fetcher.mock.calls[1]?.[0]).toBe('/api/storyboard-shots/shot-1/video-input-plan') expect(fetcher.mock.calls[0]?.[1]?.method).toBe('GET') expect(fetcher.mock.calls[1]?.[1]?.method).toBe('GET') }) it('所有首帧生成都先成为候选,并要求费用确认', async () => { wrapper = mount(KeyframeDialog, { attachTo: document.body, props: { open: true, shotId: 'shot-1', shotTitle: '开场', projectId: 'project-1', disabled: false } }) await flushPromises() expect(button('确认生成首帧').disabled).toBe(true) document.querySelector('#confirm-keyframe-cost')!.click() await flushPromises() button('确认生成首帧').click() await flushPromises() expect(wrapper.emitted('generate')).toEqual([ [{ provider: undefined, generationOptions: {}, setPrimary: false }] ]) await wrapper.setProps({ open: false }) await flushPromises() await wrapper.setProps({ open: true, shotId: 'shot-2', replacePrimary: true }) await flushPromises() expect(document.body.textContent).toContain('生成替代候选') document.querySelector('#confirm-keyframe-cost')!.click() await flushPromises() button('确认生成首帧').click() await flushPromises() expect(wrapper.emitted('generate')?.at(-1)).toEqual([ { provider: undefined, generationOptions: {}, setPrimary: false } ]) }) it('首帧生成前可预览后端最终选图规划和 Prompt', async () => { const fetcher = vi.fn().mockImplementation(async url => { const path = String(url) if (path.endsWith('/generation-models')) return new Response( JSON.stringify({ data: { defaults: { imageProvider: 'seedream', videoProvider: 'seedance' }, images: [ { type: 'image', provider: 'seedream', providerLabel: 'Seedream', model: 'image-model', modelLabel: 'Image Model', supported: true, enabled: true, isDefault: true, capabilities: {}, generationOptions: [], defaults: {}, projectConstraints: [] } ], videos: [] } }) ) if (path.includes('/creative-profile')) return new Response(JSON.stringify({ data: null })) return new Response( JSON.stringify({ data: { shotId: 'shot-1', episodeNo: 1, beatNo: 1, shotNo: 1, provider: 'seedream', model: 'image-model', generationConfig: {}, references: [], referencePlan: { provider: 'seedream', maxReferenceImages: 4, totalCandidates: 2, strategy: 'subject-coverage', selected: [ { subjectRef: '@CH0001', module: 'character', role: 'identity-anchor', imageId: 'anchor-1' } ], omitted: [ { subjectRef: '@SC0001', module: 'scene', role: 'form-primary', imageId: 'scene-1' } ] }, providerPrompt: '最终首帧 Prompt' } }) ) }) vi.stubGlobal('fetch', fetcher) wrapper = mount(KeyframeDialog, { attachTo: document.body, props: { open: true, shotId: 'shot-1', shotTitle: '开场', projectId: 'project-1', disabled: false } }) await flushPromises() button('预览实际生成输入').click() await flushPromises() const previewCall = fetcher.mock.calls.find(([url]) => String(url).includes('/keyframe/preview')) expect(previewCall?.[0]).toBe('/api/storyboard-shots/shot-1/keyframe/preview') expect(JSON.parse(String(previewCall?.[1]?.body))).toMatchObject({ provider: 'seedream', generationOptions: {} }) expect(document.body.textContent).toContain('已选 1 / 2 张') expect(document.body.textContent).toContain('省略 1 张') expect(document.body.textContent).toContain('最终首帧 Prompt') expect(wrapper.emitted('generate')).toBeUndefined() }) })