import { imageCatalog, generationProfile } from '../../fixtures/generation' import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' import { afterEach, describe, expect, it, vi } from 'vitest' import { NButton, NImage } from 'naive-ui' import { AppDialog } from '@/components/ui' import IdentityImageDialog from '@/features/subject-identity/components/IdentityImageDialog.vue' import IdentityGallery from '@/features/subject-identity/components/IdentityGallery.vue' import IdentityImageCard from '@/features/subject-identity/components/IdentityImageCard.vue' import CastingCandidateDialog from '@/features/subject-identity/components/CastingCandidateDialog.vue' import { subjectIdentityApi } from '@/features/subject-identity/api' import { canBeAnchor, castingStatusLabel, currentAnchor, groupIdentitySubjects, mergeCastingSubjects } from '@/features/subject-identity/model' import { identityImageFixture } from '@/features/subject-identity/testing/fixtures' import { formFixture } from '@/features/subject-images/testing/fixtures' import { selectControl } from '@/testing/naive' let wrapper: VueWrapper | undefined afterEach(() => { wrapper?.unmount() wrapper = undefined document.body.innerHTML = '' vi.unstubAllGlobals() }) /** * 按可见文本或无障碍名称查找真实弹窗与标签操作按钮。 * @param label 按钮文本或无障碍名称 * @returns 对应的原生按钮 */ function button(label: string) { const item = [...document.querySelectorAll('button')].find( element => element.textContent?.trim() === label || element.getAttribute('aria-label') === label ) if (!item) throw new Error(`缺少按钮 ${label}`) return item } /** * 在指定图片卡片中获取操作按钮,避免不同候选的同名按钮混用。 * @param card 当前图片卡片 * @param label 目标操作文本 * @returns 当前卡片的按钮包装器 */ function cardButton(card: VueWrapper, label: string) { return card.findAllComponents(NButton).find(item => item.text() === label)! } /** 修改 Portal 表单控件并触发 Vue 绑定。 */ function input(selector: string, value: string) { if (selector === '#identity-view' || selector === '#identity-reference') { selectControl(wrapper!, 'id', selector.slice(1)).vm.$emit('update:value', value) return } const item = document.querySelector(selector)! item.value = value item.dispatchEvent(new Event(item.tagName === 'SELECT' ? 'change' : 'input', { bubbles: true })) } /** 当前测试使用真实目录契约构造项目模型配置。 */ const creativeProfile = generationProfile('project-1') describe('身份图与母版契约', () => { it('主页面只显示权威母版,所有候选与辅助、失败和进行中记录在管理弹窗中浏览', async () => { const images = [ identityImageFixture({ id: 'candidate', isAnchor: false }), identityImageFixture({ id: 'failed', status: 'failed', imageUrl: null, isAnchor: false, error: '模型超时' }), identityImageFixture({ id: 'anchor', imageUrl: '/storage/anchor.png', provider: 'qwen-image', model: 'qwen-image-3.0-pro' }), identityImageFixture({ id: 'front', viewType: 'front', isAnchor: false }), identityImageFixture({ id: 'pending', status: 'pending', imageUrl: null, isAnchor: false }), identityImageFixture({ id: 'generating', status: 'generating', imageUrl: null, isAnchor: false }) ] wrapper = mount(IdentityGallery, { attachTo: document.body, props: { subjectName: '林夏', module: 'character', identityLocked: true, disabled: false, images } }) expect(wrapper.findAll('.identity-anchor-grid .identity-image-card')).toHaveLength(1) expect(wrapper.getComponent(NImage).props()).toMatchObject({ objectFit: 'cover', previewDisabled: false }) expect(wrapper.getComponent(NImage).props('src')).toContain('/storage/anchor.png') expect(wrapper.text()).not.toContain('qwen-image') expect(wrapper.find('.image-history').exists()).toBe(false) expect(document.querySelector('.identity-candidate-grid')).toBeNull() button('管理候选(5)').click() await flushPromises() const dialog = document.querySelector('[role="dialog"][aria-label="身份候选管理"]')! expect(dialog.querySelectorAll('.identity-image-card')).toHaveLength(5) expect(dialog.querySelector('[aria-label="身份图片 anchor"]')).toBeNull() for (const id of ['candidate', 'failed', 'front', 'pending', 'generating']) { expect(dialog.querySelector(`[aria-label="身份图片 ${id}"]`)).not.toBeNull() } expect(dialog.textContent).toContain('排队中') expect(dialog.textContent).toContain('生成中') expect(wrapper.emitted('anchor')).toBeUndefined() expect(wrapper.emitted('validate')).toBeUndefined() expect(wrapper.emitted('regenerate')).toBeUndefined() }) it('单张候选直接显示且保持未确认,无图片时不提供管理入口', async () => { wrapper = mount(IdentityGallery, { attachTo: document.body, props: { subjectName: '林夏', module: 'character', identityLocked: false, disabled: false, images: [identityImageFixture({ id: 'candidate', isAnchor: false })] } }) expect(wrapper.text()).toContain('母版候选 · 未确认') expect(wrapper.find('.identity-anchor-grid').exists()).toBe(true) expect(wrapper.findAll('button').some(item => item.text().includes('管理候选'))).toBe(false) expect(document.querySelector('[aria-label="身份图片 candidate"]')).not.toBeNull() expect(wrapper.emitted('anchor')).toBeUndefined() await wrapper.setProps({ images: [] }) expect(wrapper.text()).toContain('尚无身份图片') expect(wrapper.find('.identity-anchor-grid').exists()).toBe(false) expect(wrapper.findAll('button').some(item => item.text().includes('管理候选'))).toBe(false) }) it('失败详情按需在浮层显示,关闭管理同步收起详情,重试仅发出原记录 ID', async () => { wrapper = mount(IdentityGallery, { attachTo: document.body, props: { subjectName: '林夏', module: 'character', identityLocked: true, disabled: false, images: [ identityImageFixture({ id: 'anchor' }), identityImageFixture({ id: 'interrupted', status: 'failed', imageUrl: null, isAnchor: false, error: '服务重启时图片 Provider 请求状态不可恢复,请人工确认后重新生成' }) ] } }) expect(wrapper.find('.identity-image-failure').exists()).toBe(false) button('管理候选(1)').click() await flushPromises() const card = document.querySelector('[aria-label="身份图片 interrupted"]')! expect(card.textContent).not.toContain('核对原任务结果') expect(document.querySelector('.identity-image-failure')).toBeNull() expect(button('生成失败,查看失败原因').getAttribute('aria-expanded')).toBe('false') button('生成失败,查看失败原因').click() await flushPromises() const failure = document.querySelector('.identity-image-failure')! expect(failure.closest('.identity-failure-scroll.n-scrollbar')).not.toBeNull() expect(failure.closest('.identity-image-card')).toBeNull() expect(failure.closest('.app-dialog')).toBeNull() expect(button('生成失败,查看失败原因').getAttribute('aria-expanded')).toBe('true') expect(failure.textContent).toContain('图片生成中断,结果未确认') expect(failure.textContent).toContain('核对原任务结果') expect(failure.textContent).toContain('重复生成和计费') expect(failure.textContent).not.toContain('Provider') expect(failure.querySelector('button')).toBeNull() expect(failure.textContent).not.toContain('查看当前母版') document.querySelector('[aria-label="身份候选管理"] .n-card-header__close')!.click() await flushPromises() expect( wrapper .findAllComponents(AppDialog) .find(item => item.props('title') === '身份候选管理')! .props('open') ).toBe(false) button('管理候选(1)').click() await flushPromises() expect(button('生成失败,查看失败原因').getAttribute('aria-expanded')).toBe('false') button('生成失败,查看失败原因').click() await flushPromises() button('生成失败,查看失败原因').dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })) await flushPromises() expect(button('生成失败,查看失败原因').getAttribute('aria-expanded')).toBe('false') button('重新生成角色候选图').click() await flushPromises() expect(wrapper.emitted('regenerate')).toEqual([['interrupted']]) expect(wrapper.emitted('anchor')).toBeUndefined() expect( wrapper .findAllComponents(AppDialog) .find(item => item.props('title') === '身份候选管理')! .props('open') ).toBe(false) }) it('辅助图失败保留真实原因,草稿阻塞时说明恢复方向并禁止重试', async () => { wrapper = mount(IdentityGallery, { attachTo: document.body, props: { subjectName: '林夏', module: 'character', identityLocked: false, disabled: false, retryDisabledReason: '请先保存身份文本修改,再重新生成图片。', images: [ identityImageFixture({ id: 'failed-front', viewType: 'front', status: 'failed', imageUrl: null, isAnchor: false, error: '图片模型超时' }) ] } }) expect(wrapper.findAll('button').some(item => item.text().includes('管理候选'))).toBe(false) await flushPromises() expect(document.querySelector('[aria-label="身份图片 failed-front"]')!.textContent).not.toContain( '图片模型超时' ) button('生成失败,查看失败原因').click() await flushPromises() const notice = document.querySelector('.identity-image-failure')! expect(notice.textContent).toContain('图片模型超时') expect(notice.textContent).not.toContain('后台服务重启') expect(notice.textContent).toContain('请先保存身份文本修改') expect(button('重新生成辅助参考图').disabled).toBe(true) button('重新生成辅助参考图').click() await flushPromises() expect(wrapper.emitted('regenerate')).toBeUndefined() await wrapper.setProps({ retryDisabledReason: '' }) button('重新生成辅助参考图').click() await flushPromises() expect(wrapper.emitted('regenerate')).toEqual([['failed-front']]) }) it('明确确认目标后才提交指定候选,刷新同一母版保持管理弹窗,新母版返回后关闭弹窗', async () => { const anchor = identityImageFixture({ id: 'anchor' }) const candidate = identityImageFixture({ id: 'candidate', isAnchor: false }) wrapper = mount(IdentityGallery, { attachTo: document.body, props: { subjectName: '林夏', module: 'character', identityLocked: true, disabled: false, images: [anchor, candidate] } }) button('管理候选(1)').click() await flushPromises() const management = wrapper.findAllComponents(AppDialog).find(item => item.props('title') === '身份候选管理')! button('确认选角并锁定').click() await flushPromises() expect(wrapper.emitted('anchor')).toBeUndefined() button('取消').click() await flushPromises() expect(wrapper.emitted('anchor')).toBeUndefined() button('确认选角并锁定').click() await flushPromises() button('确认演员选择').click() await flushPromises() expect(wrapper.emitted('anchor')).toEqual([['candidate']]) expect(management.props('open')).toBe(true) await wrapper.setProps({ images: [anchor, { ...candidate }, identityImageFixture({ id: 'new', isAnchor: false })] }) expect(management.props('open')).toBe(true) expect(wrapper.get('.identity-anchor-grid .identity-image-card').attributes('aria-label')).toBe( '身份图片 anchor' ) await wrapper.setProps({ images: [ { ...anchor, isAnchor: false }, { ...candidate, isAnchor: true } ] }) expect(management.props('open')).toBe(false) expect(wrapper.get('.identity-anchor-grid .identity-image-card').attributes('aria-label')).toBe( '身份图片 candidate' ) }) it('启用的辅助视角不是母版,primary 候选停用时仍可选为母版', () => { const front = identityImageFixture({ id: 'front', viewType: 'front', isAnchor: false }) const candidate = identityImageFixture({ id: 'candidate', isAnchor: false }) expect(canBeAnchor(front)).toBe(false) expect(canBeAnchor(candidate)).toBe(true) expect(currentAnchor([front, candidate])).toBeUndefined() expect(canBeAnchor(identityImageFixture({ status: 'failed' }))).toBe(false) expect(canBeAnchor(identityImageFixture({ imageUrl: null }))).toBe(false) }) it('正式主体关联校验不接受不同主体的 form', () => { expect(() => groupIdentitySubjects([{ ...formFixture(), subjectId: 'wrong' }])).toThrow('不匹配') }) it('选角就绪结果可以补入尚无形态的角色目录', () => { const rows = mergeCastingSubjects( groupIdentitySubjects([formFixture()]), [ { subjectId: 'character-without-form', subjectRef: '@CH0002', subjectName: '陆川', status: 'missing_identity', isLocked: false } ], 'project-1' ) expect(rows).toHaveLength(2) expect(rows.find(item => item.id === 'character-without-form')).toMatchObject({ projectId: 'project-1', module: 'character', forms: [] }) expect(castingStatusLabel('candidate_pending')).toBe('待确认选角') }) it('辅助视角传递明确参考图、目录尺寸和本次 Prompt,不传旧宽高字段', async () => { wrapper = mount(IdentityImageDialog, { attachTo: document.body, props: { open: true, subjectId: 's1', subjectName: '林夏', module: 'character', images: [identityImageFixture()], disabled: false, catalog: imageCatalog, profile: creativeProfile } }) await flushPromises() input('#identity-view', 'three-quarter') input('#identity-reference', 'identity-image-1') await flushPromises() expect(document.querySelector('#identity-width')).toBeNull() expect(document.querySelector('#identity-height')).toBeNull() expect(button('确认生成身份图').disabled).toBe(true) input('#identity-image-prompt', ' 自定义身份提示词 ') await flushPromises() document.querySelector('#identity-image-cost')!.click() await flushPromises() button('确认生成身份图').click() await flushPromises() expect(wrapper.emitted('generate')).toEqual([ [ { viewType: 'three-quarter', referenceImageId: 'identity-image-1', provider: 'qwen-image', generationOptions: { size: '2048*2048', promptExtendMode: 'direct' }, prompt: '自定义身份提示词' } ] ]) }) it('切换主体清空生图配置和费用确认,失效参考图不能提交', async () => { wrapper = mount(IdentityImageDialog, { attachTo: document.body, props: { open: true, subjectId: 's1', subjectName: '林夏', module: 'character', images: [identityImageFixture()], disabled: false, catalog: imageCatalog, profile: creativeProfile } }) await flushPromises() input('#identity-reference', 'identity-image-1') document.querySelector('#identity-image-cost')!.click() await flushPromises() await wrapper.setProps({ images: [] }) expect(button('确认生成身份图').disabled).toBe(true) await wrapper.setProps({ subjectId: 's2', subjectName: '陆川' }) expect(document.querySelector('#identity-reference')).toBeNull() expect(document.querySelector('#identity-image-cost')!.getAttribute('aria-checked')).toBe('false') }) it('Character 普通身份图入口只提供辅助视角,primary 必须走选角候选接口', async () => { wrapper = mount(IdentityImageDialog, { attachTo: document.body, props: { open: true, subjectId: 's1', subjectName: '林夏', module: 'character', images: [identityImageFixture()], disabled: false, catalog: imageCatalog, profile: creativeProfile } }) await flushPromises() const select = selectControl(wrapper!, 'id', 'identity-view') expect(select.props('options')!.map(item => item.value)).toEqual(['front', 'three-quarter', 'full-body']) expect(select.props('value')).toBe('front') }) it('辅助图只有校验入口,不能通过候选弹窗切换母版', async () => { wrapper = mount(IdentityGallery, { attachTo: document.body, props: { subjectName: '林夏', module: 'character', identityLocked: false, disabled: false, images: [identityImageFixture({ viewType: 'front', isAnchor: false })] } }) expect(wrapper.findAll('button').some(item => item.text().includes('管理候选'))).toBe(false) await flushPromises() const card = wrapper.findAllComponents(IdentityImageCard)[0]! expect(card.findAllComponents(NButton).some(item => item.text() === '确认选角并锁定')).toBe(false) expect(card.text()).toContain('不能直接设为身份母版') expect(card.text()).not.toContain('本次实际提示词') expect(wrapper.emitted('anchor')).toBeUndefined() }) it('角色已有母版但未锁定时仍可确认选角,确认文案不冒充普通母版切换', async () => { wrapper = mount(IdentityGallery, { attachTo: document.body, props: { subjectName: '林夏', module: 'character', identityLocked: false, disabled: false, images: [identityImageFixture({ isAnchor: true })] } }) button('确认选角并锁定').click() await flushPromises() expect(document.body.textContent).toContain('作为 林夏 的角色母版并锁定身份') button('确认演员选择').click() expect(wrapper.emitted('anchor')).toEqual([['identity-image-1']]) }) it('多张候选同时可见时加载只绑定提交目标,操作期间所有重复提交均禁用', async () => { wrapper = mount(IdentityGallery, { attachTo: document.body, props: { subjectName: '林夏', module: 'character', identityLocked: false, disabled: false, images: ['first', 'second'].map(id => identityImageFixture({ id, isAnchor: false })) } }) button('管理候选(1)').click() await flushPromises() const cards = wrapper.findAllComponents(IdentityImageCard) const first = cards.find(item => item.props('image').id === 'first')! const second = cards.find(item => item.props('image').id === 'second')! await wrapper.setProps({ pendingOperation: { projectId: 'project-1', subjectId: 'subject-1', imageId: 'first', kind: 'confirm' } }) expect(cardButton(first, '确认选角并锁定').props('loading')).toBe(true) expect(cardButton(second, '确认选角并锁定').props('loading')).toBe(false) expect(cardButton(first, '确认选角并锁定').props('disabled')).toBe(true) expect(cardButton(second, '确认选角并锁定').props('disabled')).toBe(true) await cardButton(second, '确认选角并锁定').trigger('click') expect(wrapper.emitted('anchor')).toBeUndefined() await wrapper.setProps({ pendingOperation: { projectId: 'project-1', subjectId: 'subject-1', imageId: 'second', kind: 'validate' } }) expect(cardButton(first, '校验此身份图片').props('loading')).toBe(false) expect(cardButton(second, '校验此身份图片').props('loading')).toBe(true) expect(cardButton(second, '校验此身份图片').props('disabled')).toBe(true) await wrapper.setProps({ pendingOperation: null }) expect(cardButton(second, '校验此身份图片').props('loading')).toBe(false) }) it('选角候选发送当前图片 Provider 与动态参数,不携带旧宽高字段', async () => { wrapper = mount(CastingCandidateDialog, { attachTo: document.body, props: { open: true, subjectId: 'subject-1', subjectName: '林夏', disabled: false, catalog: { defaults: { imageProvider: 'qwen-image', videoProvider: 'seedance' }, images: [ { type: 'image', provider: 'qwen-image', providerLabel: 'Qwen', model: 'qwen-image-3.0-pro', modelLabel: 'Qwen Image', supported: true, enabled: true, isDefault: true, capabilities: {}, generationOptions: [], defaults: { size: '1536*2688' }, projectConstraints: [] } ], videos: [] }, profile: { projectId: 'project-1', aspectRatio: '9:16', imageProvider: 'qwen-image', imageModel: 'qwen-image-3.0-pro', imageOptions: { size: '1536*2688' }, videoProvider: 'seedance', videoModel: 'seedance', videoOptions: {} } } }) await flushPromises() expect(document.body.textContent).toContain('不会复用当前身份母版') document.querySelector('#casting-candidate-cost')!.click() await flushPromises() button('AI 生成角色候选图').click() await flushPromises() expect(wrapper.emitted('generate')).toEqual([ [{ provider: 'qwen-image', generationOptions: { size: '1536*2688' } }] ]) }) it('角色选角接口区分批量身份、候选生图与确认事务', async () => { const fetcher = vi.fn().mockImplementation( async () => new Response( JSON.stringify({ data: { total: 0, targetCount: 0, generated: 0, skipped: 0, skippedLocked: 0, failed: 0, failures: [] } }) ) ) vi.stubGlobal('fetch', fetcher) await subjectIdentityApi.generateCharacters('project/1', { force: false, concurrency: 2 }) await subjectIdentityApi.generateCastingCandidate('subject/1', {}) await subjectIdentityApi.confirmCasting('subject/1', 'image/1') expect(fetcher.mock.calls.map(([url]) => url)).toEqual([ '/api/projects/project%2F1/character-identities/generate', '/api/subjects/subject%2F1/identity/casting-candidates', '/api/subjects/subject%2F1/identity/images/image%2F1/casting' ]) expect(fetcher.mock.calls.map(([, init]) => init?.method)).toEqual(['POST', 'POST', 'PUT']) }) })