Files
short-drama-agent-front/tests/features/workflows/pages.test.ts
T

2062 lines
103 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { generationProfile, imageCatalog } from '../../fixtures/generation'
import { computed, ref } from 'vue'
import { NImage, NRadioGroup, NScrollbar } from 'naive-ui'
import { createMemoryHistory, createRouter } from 'vue-router'
import { DOMWrapper, flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi, type Mock } from 'vitest'
import CreateProjectDialog from '@/features/projects/components/CreateProjectDialog.vue'
import BreakdownPage from '@/features/breakdown/BreakdownPage.vue'
import CreateDramaPage from '@/features/create-drama/CreateDramaPage.vue'
import ProjectsPage from '@/features/projects/ProjectsPage.vue'
import { projectContextKey, type useProjectData } from '@/features/projects/context'
import type { ProjectDetail } from '@/features/projects/types'
import type { Checkpoint } from '@/features/workflows/types'
import StoryboardPage from '@/features/storyboard/StoryboardPage.vue'
import ShotTools from '@/features/storyboard/components/ShotTools.vue'
import ShotDesign from '@/features/storyboard/components/ShotDesign.vue'
import {
designedShot,
directionsResult,
storyboardCheckpoint,
visualStatesResult
} from '@/features/storyboard/testing/fixtures'
import { getStoryboardSession } from '@/features/storyboard/model'
import { getOperation } from '@/features/workflows/operations'
import SubjectImagesPage from '@/features/subject-images/SubjectImagesPage.vue'
import { formFixture, imageFixture } from '@/features/subject-images/testing/fixtures'
import { getImageSession } from '@/features/subject-images/model'
import VisualStylePage from '@/features/visual-style/VisualStylePage.vue'
import { visualStyleApi } from '@/features/visual-style/api'
import SubjectIdentityPage from '@/features/subject-identity/SubjectIdentityPage.vue'
import IdentityGallery from '@/features/subject-identity/components/IdentityGallery.vue'
import { subjectIdentityApi } from '@/features/subject-identity/api'
import { subjectImagesApi } from '@/features/subject-images/api'
import { styleFixture, styleImageFixture } from '@/features/visual-style/testing/fixtures'
import { identityFixture, identityImageFixture } from '@/features/subject-identity/testing/fixtures'
import { getIdentitySession } from '@/features/subject-identity/model'
import { drawerPanel, expandSections, selectControl } from '@/testing/naive'
import ProductionPage from '@/features/production/ProductionPage.vue'
import { getProductionSession } from '@/features/production/model'
/** 新资产页面复用已有项目上下文和内存路由,不接入真实模型。 */
async function mountAssets(page: 'style' | 'identity', query = '') {
const component = page === 'style' ? VisualStylePage : SubjectIdentityPage
const router = createRouter({ history: createMemoryHistory(), routes: [{ path: '/assets', component }] })
await router.push('/assets' + query)
const provided = context()
wrapper = mount(component, {
attachTo: document.body,
global: { plugins: [router], provide: { [projectContextKey as symbol]: provided } }
})
await flushPromises()
if (page === 'identity') await expandSections()
return provided
}
/** 统一构造独立响应,避免复用已消费的 Response body。 */
function jsonResponse(data: unknown) {
return new Response(JSON.stringify({ data }))
}
/**
* 为页面模拟请求补齐正式模型目录和配置,后台启动返回 202 句柄,结果只从任务 GET 读取;响应逐次复制避免消费同一正文。
* @param fetcher 业务 API 模拟请求
*/
function stubFetch(fetcher: Mock<typeof fetch>) {
const implementation = fetcher.getMockImplementation()!
const executions = new Map<string, object>()
let executionCount = 0
fetcher.mockImplementation(async (url, init) => {
const path = String(url)
if (path.endsWith('/generation-models')) return jsonResponse(imageCatalog)
if (path.endsWith('/creative-profile')) return jsonResponse(generationProfile(fixture.id))
if (path.includes('/workflow-executions/')) return jsonResponse(executions.get(path.split('/').at(-1)!))
const response = await implementation(url, init)
const workflowName = path.endsWith('/storyboard-directions/generate')
? 'storyboard-direction'
: path.endsWith('/storyboard-visual-states/generate')
? 'storyboard-visual-state'
: path.endsWith('/storyboard-shots/regenerate')
? 'breakdown'
: ''
if (init?.method === 'POST' && workflowName && response.ok) {
const result = (await response.clone().json()).data
const executionId = `page-execution-${++executionCount}`
const body = JSON.parse(String(init.body))
executions.set(executionId, {
id: executionId,
projectId: fixture.id,
workflowName,
status: 'completed',
stage: 'finalize',
current: 1,
total: 1,
currentResourceId: null,
metadata:
workflowName === 'breakdown'
? { action: 'regenerate-storyboard-episode', episodeNo: body.episodeNo }
: null,
result,
error: null,
startedAt: '2026-10-08T00:00:00Z',
completedAt: '2026-10-08T00:00:01Z',
createdAt: '2026-10-08T00:00:00Z',
updatedAt: '2026-10-08T00:00:01Z'
})
return new Response(JSON.stringify({ data: { executionId, status: 'pending' } }), { status: 202 })
}
return response.clone()
})
vi.stubGlobal('fetch', fetcher)
}
/** 模拟 API 响应仅用于测试,不会打包进生产页面。 */
const fixture: ProjectDetail = {
id: 'page-test-project',
title: '雨夜来信',
topic: '一封信改变了两个人的命运',
style: '都市悬疑',
status: 'completed',
createdAt: '2026-08-27T00:00:00Z',
updatedAt: '2026-08-27T00:00:00Z',
episodes: [{ episode: 1, title: '来信', content: '<script>不要执行模型内容</script>\n第一场:旧书店。' }],
characters: [{ id: 'character', name: '林知夏' }],
world: { era: '当代' }
}
let wrapper: VueWrapper | undefined
/** 使用真实上下文形状,不绕过页面内的异步操作与按钮守卫。 */
function context(): ReturnType<typeof useProjectData> {
const data = ref({
project: fixture,
checkpoints: [] as Checkpoint[],
stageReadiness: {
projectId: fixture.id,
script: { ready: true, reason: null },
breakdown: { ready: true, reason: null },
visualStyle: { ready: true, reason: null },
identity: { ready: true, reason: null },
subjectAssets: { ready: true, reason: null },
storyboard: { ready: true, reason: null }
}
})
return {
data,
project: computed(() => data.value.project),
checkpoints: computed(() => data.value.checkpoints),
stageReadiness: computed(() => data.value.stageReadiness),
loading: ref(false),
error: ref(''),
updatedAt: ref(''),
refresh: vi.fn<() => Promise<void>>().mockResolvedValue(),
refreshStageReadiness: vi.fn<() => Promise<void>>().mockResolvedValue()
}
}
/** 找到挂载到 body 的 Naive 弹窗按钮。 */
function button(label: string): HTMLButtonElement {
const element = [...document.querySelectorAll('button')].find(
item => item.textContent?.trim() === label || item.getAttribute('aria-label') === label
)
if (!element) throw new Error('找不到按钮:' + label)
return element
}
/** 走真实确认弹窗,包括后端任务停止的显式确认。 */
async function confirmGeneration(label: string) {
button(label).click()
await flushPromises()
const acknowledgement = button('确认' + label)
.closest('.app-dialog')!
.querySelector<HTMLElement>('[role="checkbox"]')
expect(button('确认' + label).disabled).toBe(true)
acknowledgement!.click()
await flushPromises()
button('确认' + label).click()
await flushPromises()
}
/** 挂载分镜页面并复用项目上下文 fixture。 */
async function mountStoryboard() {
const provided = context()
provided.data.value!.checkpoints = [storyboardCheckpoint()]
wrapper = mount(StoryboardPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: provided }, stubs: { RouterLink: true } }
})
await flushPromises()
await expandSections()
return provided
}
/** 形态图库使用真实路由解析来自主体列表的筛选参数。 */
async function mountSubjectImages() {
const router = createRouter({
history: createMemoryHistory(),
routes: [{ path: '/projects/:projectId/:workspace', component: SubjectImagesPage }]
})
await router.push(`/projects/${fixture.id}/subject-images`)
wrapper = mount(SubjectImagesPage, {
attachTo: document.body,
global: { plugins: [router], provide: { [projectContextKey as symbol]: context() } }
})
await flushPromises()
await expandSections()
}
afterEach(() => {
getProductionSession(fixture.id).receipt = null
getProductionSession(fixture.id).pipelineReceipt = null
getIdentitySession(fixture.id).receipt = null
wrapper?.unmount()
wrapper = undefined
document.body.innerHTML = ''
vi.unstubAllGlobals()
localStorage.clear()
Object.assign(getStoryboardSession(fixture.id), { receipt: null, prompts: {}, regeneratedEpisodes: {} })
getImageSession(fixture.id).receipt = null
getImageSession(fixture.id).promptReceipt = null
Object.assign(getOperation(fixture.id), { pending: false, label: '', error: '', notice: '', noticeType: null })
})
describe('内容级滚动下的生产反馈', () => {
it('生产目录和资产详情由两个独立 NScrollbar 接管,切镜头不会新增生产请求', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => {
const path = String(url)
if (path.includes('/storyboard-directions')) return jsonResponse(directionsResult(fixture.id))
if (path.includes('/readiness') || path.endsWith('/videos/status'))
return jsonResponse({
total: 2,
ready: 0,
skipped: 0,
blocked: 0,
completed: 0,
queued: 0,
pending: 0,
running: 0,
failed: 0,
cancelled: 0,
notStarted: 2,
items: []
})
return jsonResponse([])
})
stubFetch(fetcher)
wrapper = mount(ProductionPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context() }, stubs: { RouterLink: true } }
})
await flushPromises()
const directory = wrapper.get('.production-shot-list')
const detail = wrapper.get('.production-detail')
expect(directory.getComponent(NScrollbar).props('xScrollable')).toBe(true)
expect(detail.get('.panel-scroll').classes()).toContain('n-scrollbar')
expect(directory.get('.n-scrollbar-container').element).not.toBe(detail.get('.n-scrollbar-container').element)
const items = directory.findAll('.production-shot-link')
expect(items).toHaveLength(2)
expect(directory.findAll('.beat-directory-group')).toHaveLength(2)
expect(directory.findAll('.directory-group-count').map(item => item.text())).toEqual(['1 镜', '1 镜'])
expect(items[0]!.get('.directory-shot-number').text()).toBe('镜头 01')
expect(directory.get('.directory-heading').text()).toContain('生产镜头')
expect(directory.get('.directory-heading').element.closest('.n-scrollbar-container')).toBeNull()
expect(items[0]!.find('.directory-item-title').exists()).toBe(true)
expect(items[0]!.find('.directory-item-meta .directory-status').exists()).toBe(true)
await items[1]!.trigger('click')
await flushPromises()
expect(items[1]!.attributes('aria-current')).toBe('true')
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
})
it('默认折叠总览时查询错误仍显示在内容区外层', async () => {
stubFetch(vi.fn<typeof fetch>().mockRejectedValue(new Error('生产连接中断')))
wrapper = mount(ProductionPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context() }, stubs: { RouterLink: true } }
})
await flushPromises()
expect(wrapper.get('[data-workspace-tools]').attributes('aria-expanded')).toBe('false')
expect(wrapper.find('.workspace-tools-drawer').exists()).toBe(false)
const alert = wrapper.get('.workspace-split [role="alert"]')
expect(alert.element.closest('.workspace-tools-drawer')).toBeNull()
expect(alert.text()).toContain('无法连接后端')
})
it('回执返回时自动展开总览,部分失败诊断不会留在折叠区内', async () => {
stubFetch(vi.fn<typeof fetch>().mockRejectedValue(new Error('离线测试')))
wrapper = mount(ProductionPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context() }, stubs: { RouterLink: true } }
})
await flushPromises()
getProductionSession(fixture.id).receipt = {
kind: 'retry',
title: '重试失败视频任务',
result: {
totalFailed: 1,
retryable: 1,
skipped: 0,
retried: 0,
failed: 1,
failures: [{ shotId: 'shot-1', error: '供应商不可用' }]
}
}
await flushPromises()
expect(wrapper.get('[data-workspace-tools]').attributes('aria-expanded')).toBe('true')
expect(drawerPanel().find('.n-collapse-item--active').exists()).toBe(true)
expect(drawerPanel().text()).toContain('供应商不可用')
})
})
describe('视觉风格与主体身份工作区', () => {
it('当前主体已确认但其它角色未完成时,隐藏形态入口;保存后按新阶段状态开放', async () => {
/** 当前主体已锁定,其它角色仍未确认,用真实项目准入规则约束页面入口。 */
const saved = identityFixture({ isLocked: true })
vi.spyOn(subjectIdentityApi, 'get').mockResolvedValue(saved)
vi.spyOn(subjectIdentityApi, 'save').mockImplementation(async (_id, input) => ({ ...saved, ...input }))
vi.spyOn(subjectIdentityApi, 'listImages').mockResolvedValue([identityImageFixture()])
vi.spyOn(subjectIdentityApi, 'castingReadiness').mockResolvedValue({
total: 0,
ready: 0,
missingIdentity: 0,
missingAnchor: 0,
candidatePending: 0,
unlocked: 0,
locked: 0,
items: []
})
stubFetch(
vi
.fn<typeof fetch>()
.mockImplementation(async url =>
jsonResponse(String(url).endsWith('/subject-forms') ? [formFixture()] : styleFixture())
)
)
const provided = await mountAssets('identity')
provided.data.value!.stageReadiness.identity = { ready: false, reason: '还有角色身份需要确认' }
await flushPromises()
expect(wrapper!.get('.identity-next-action').text()).toContain('还有角色身份需要确认')
expect(wrapper!.get('.identity-next-action').find('button').exists()).toBe(false)
expect(wrapper!.get('.identity-subject-forms').text()).not.toContain('查看此主体形态图片')
expect(wrapper!.find('a[href*="/subject-images"]').exists()).toBe(false)
vi.mocked(provided.refreshStageReadiness).mockImplementation(async () => {
provided.data.value!.stageReadiness.identity = { ready: true, reason: null }
})
await wrapper!.get('#identity-description').setValue('保存后仍保留已确认母版')
button('保存主体身份').click()
await flushPromises()
expect(provided.refreshStageReadiness).toHaveBeenCalledOnce()
expect(button('查看形态图片').disabled).toBe(false)
expect(wrapper!.get('.identity-detail a[href*="/subject-images"]').attributes('href')).toContain(
'subjectRef=@CH0001'
)
})
it('生成进度保留全栏提示,失败详情按需在浮层显示,切换后不串主体状态', async () => {
/** 两个主体分别处于生成中与失败状态,所有查询均使用隔离的测试响应。 */
const first = formFixture()
const second = { ...formFixture(), id: 'second-form', subjectId: 'second-subject', images: [] }
second.subject = { ...second.subject, id: second.subjectId, name: '第二个主体', ref: '@CH0002' }
vi.spyOn(subjectIdentityApi, 'get').mockImplementation(async id =>
identityFixture({ id: `identity-${id}`, subjectId: id })
)
vi.spyOn(subjectIdentityApi, 'listImages').mockImplementation(async id => [
identityImageFixture({
identityId: `identity-${id}`,
status: id === first.subjectId ? 'generating' : 'failed',
isAnchor: false,
imageUrl: null,
error: id === first.subjectId ? null : '模型暂时不可用'
})
])
vi.spyOn(subjectIdentityApi, 'castingReadiness').mockResolvedValue({
total: 0,
ready: 0,
missingIdentity: 0,
missingAnchor: 0,
candidatePending: 0,
unlocked: 0,
locked: 0,
items: []
})
stubFetch(
vi
.fn<typeof fetch>()
.mockImplementation(async url =>
jsonResponse(String(url).endsWith('/subject-forms') ? [first, second] : styleFixture())
)
)
await mountAssets('identity')
const feedback = wrapper!.get('.identity-generation-feedback')
const workspace = wrapper!.get('.identity-workspace')
expect(feedback.element.closest('.identity-workspace-region')).toBe(
wrapper!.get('.identity-workspace-region').element
)
expect(feedback.element.closest('.identity-detail')).toBeNull()
expect(feedback.element.compareDocumentPosition(workspace.element) & 4).toBe(4)
expect(feedback.text()).toContain('林知夏 的身份图片正在生成')
await wrapper!
.findAll('.identity-subject-item')
.find(item => item.text().includes('第二个主体'))!
.trigger('click')
await flushPromises()
expect(wrapper!.find('.identity-generation-feedback').exists()).toBe(false)
expect(wrapper!.find('.identity-image-failure').exists()).toBe(false)
button('管理候选(1)').click()
await flushPromises()
expect(document.querySelector('.identity-candidate-grid')?.textContent).not.toContain('模型暂时不可用')
expect(document.querySelector('.identity-image-failure')).toBeNull()
button('生成失败,查看失败原因').click()
await flushPromises()
expect(document.querySelector('.identity-image-failure')?.textContent).toContain('模型暂时不可用')
expect(document.querySelectorAll('.identity-image-failure')).toHaveLength(1)
vi.mocked(subjectIdentityApi.listImages).mockResolvedValue([
identityImageFixture({ identityId: `identity-${second.subjectId}`, status: 'completed' })
])
await wrapper!
.get('.identity-detail')
.findAll('button')
.find(item => item.text() === '刷新身份')!
.trigger('click')
await flushPromises()
expect(wrapper!.find('.identity-generation-feedback').exists()).toBe(false)
expect(document.querySelector('.identity-image-failure')).toBeNull()
})
it('主体目录与详情分别显示骨架,查询失败结束占位并可重试恢复', async () => {
/** 分别阻塞目录与详情,避免将未完成查询误显示为空身份。 */
let rejectCatalog!: (error: Error) => void
let rejectDetail!: (error: Error) => void
vi.spyOn(subjectImagesApi, 'listForms')
.mockImplementationOnce(
() =>
new Promise((_resolve, reject) => {
rejectCatalog = reject
})
)
.mockResolvedValue([formFixture()])
vi.spyOn(subjectIdentityApi, 'get')
.mockImplementationOnce(
() =>
new Promise((_resolve, reject) => {
rejectDetail = reject
})
)
.mockResolvedValue(null)
vi.spyOn(subjectIdentityApi, 'castingReadiness').mockResolvedValue({
total: 0,
ready: 0,
missingIdentity: 0,
missingAnchor: 0,
candidatePending: 0,
unlocked: 0,
locked: 0,
items: []
})
stubFetch(vi.fn<typeof fetch>().mockImplementation(async () => jsonResponse(styleFixture())))
await mountAssets('identity')
expect(wrapper!.get('.subject-identity-skeleton').attributes('aria-busy')).toBe('true')
expect(wrapper!.get('.subject-identity-skeleton').text()).toBe('')
expect(wrapper!.find('#identity-description').exists()).toBe(false)
expect(wrapper!.text()).not.toContain('尚无身份母版')
rejectCatalog(new Error('主体目录读取失败'))
await flushPromises()
expect(wrapper!.find('.subject-identity-skeleton').exists()).toBe(false)
expect(wrapper!.get('.workspace-feedback [role="alert"]').text()).toContain('主体目录读取失败')
button('重试读取目录').click()
await flushPromises()
expect(wrapper!.find('.subject-identity-skeleton').exists()).toBe(false)
expect(wrapper!.findAll('.identity-subject-item')).toHaveLength(1)
expect(wrapper!.get('.identity-detail').text()).toContain('林知夏')
expect(wrapper!.get('.identity-detail-skeleton').attributes('aria-busy')).toBe('true')
rejectDetail(new Error('身份读取失败'))
await flushPromises()
expect(wrapper!.find('.identity-detail-skeleton').exists()).toBe(false)
expect(wrapper!.get('.identity-detail [role="alert"]').text()).toContain('身份读取失败')
expect(wrapper!.find('#identity-description').exists()).toBe(false)
button('刷新身份').click()
await flushPromises()
expect(wrapper!.get<HTMLInputElement>('#identity-description').element.value).toBe('')
expect(wrapper!.text()).toContain('尚无身份母版')
})
it('已有身份刷新保留草稿与图库,图片操作归属图库并遵守未保存限制', async () => {
/** 刷新返回前后均保持编辑器实例,防止骨架导致草稿丢失。 */
let finishRefresh!: (value: ReturnType<typeof identityFixture>) => void
vi.spyOn(subjectIdentityApi, 'get')
.mockResolvedValueOnce(identityFixture())
.mockImplementationOnce(
() =>
new Promise(resolve => {
finishRefresh = resolve
})
)
vi.spyOn(subjectIdentityApi, 'listImages').mockResolvedValue([identityImageFixture()])
vi.spyOn(subjectIdentityApi, 'castingReadiness').mockResolvedValue({
total: 0,
ready: 0,
missingIdentity: 0,
missingAnchor: 0,
candidatePending: 0,
unlocked: 0,
locked: 0,
items: []
})
stubFetch(
vi
.fn<typeof fetch>()
.mockImplementation(async url =>
jsonResponse(String(url).endsWith('/subject-forms') ? [formFixture()] : styleFixture())
)
)
await mountAssets('identity')
const editor = wrapper!.get('#identity-description').element
const gallery = wrapper!.get('[aria-label="身份参考图库"]')
expect(gallery.get('.identity-gallery-actions').text()).toContain('生成辅助参考图')
expect(wrapper!.get('.page-form-actions').text()).not.toContain('生成辅助参考图')
expect(button('生成辅助参考图').disabled).toBe(false)
await wrapper!.get('#identity-description').setValue('保留人工身份草稿')
expect(button('生成辅助参考图').disabled).toBe(true)
button('刷新身份').click()
await flushPromises()
expect(wrapper!.find('.identity-detail-skeleton').exists()).toBe(false)
expect(wrapper!.get('#identity-description').element).toBe(editor)
expect(gallery.find('img').exists()).toBe(true)
finishRefresh(identityFixture({ description: '服务器刷新结果' }))
await flushPromises()
expect(wrapper!.get<HTMLTextAreaElement>('#identity-description').element.value).toBe('保留人工身份草稿')
expect(button('生成辅助参考图').disabled).toBe(true)
})
it('风格首读显示骨架,失败后展示重试,恢复后分类与规则始终可见', async () => {
/** 延迟首次响应,确认骨架不会混入尚未创建或空参考图提示。 */
let rejectStyle!: (error: Error) => void
vi.spyOn(visualStyleApi, 'get')
.mockImplementationOnce(
() =>
new Promise((_resolve, reject) => {
rejectStyle = reject
})
)
.mockResolvedValue(styleFixture())
await mountAssets('style')
expect(wrapper!.get('.visual-style-skeleton').attributes('aria-busy')).toBe('true')
expect(wrapper!.find('#style-prompt').exists()).toBe(false)
expect(wrapper!.text()).not.toContain('尚无风格参考图')
rejectStyle(new Error('风格读取失败'))
await flushPromises()
expect(wrapper!.find('.visual-style-skeleton').exists()).toBe(false)
expect(wrapper!.get('[role="alert"]').text()).toContain('风格读取失败')
expect(wrapper!.text()).not.toContain('视觉风格已准备好')
expect(wrapper!.find('.style-images-panel').exists()).toBe(false)
button('重试读取').click()
await flushPromises()
expect(wrapper!.find('#style-prompt').exists()).toBe(true)
expect(wrapper!.get('.visual-style-rules').text()).toContain('中国人物选角基线')
expect(wrapper!.find('.n-collapse').exists()).toBe(false)
expect(wrapper!.findAll('.style-category-fields textarea')).toHaveLength(3)
})
it('刷新已有风格时保留编辑器、参考图和未保存的分类草稿', async () => {
const image = styleImageFixture()
/** 图片启停后的刷新延迟返回,保护现有内容与人工草稿。 */
let resolveStyle!: (value: ReturnType<typeof styleFixture>) => void
vi.spyOn(visualStyleApi, 'get')
.mockResolvedValueOnce(styleFixture({ images: [image] }))
.mockImplementationOnce(
() =>
new Promise(resolve => {
resolveStyle = resolve
})
)
vi.spyOn(visualStyleApi, 'setImageEnabled').mockResolvedValue({ ...image, enabled: false })
await mountAssets('style')
const editor = wrapper!.get('.style-category-section').element
await wrapper!.get('textarea[aria-label="人物风格与选角背景"]').setValue('人物风格人工草稿')
button('停用').click()
await flushPromises()
expect(wrapper!.find('.visual-style-skeleton').exists()).toBe(false)
expect(wrapper!.get('.style-category-section').element).toBe(editor)
resolveStyle(styleFixture({ images: [{ ...image, enabled: false }] }))
await flushPromises()
expect((wrapper!.get('textarea[aria-label="人物风格与选角背景"]').element as HTMLTextAreaElement).value).toBe(
'人物风格人工草稿'
)
expect(button('AI 重新生成风格').disabled).toBe(true)
expect(button('启用').disabled).toBe(false)
})
it.each([
{ locked: null, label: '尚未创建', action: 'AI 生成风格', disabled: false },
{ locked: false, label: '未锁定', action: 'AI 重新生成风格', disabled: false },
{ locked: true, label: '已锁定', action: 'AI 重新生成风格', disabled: true }
])('视觉风格 $label 使用独立状态说明与等高操作按钮,保留锁定限制', async ({ locked, label, action, disabled }) => {
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async () => jsonResponse(locked === null ? null : styleFixture({ isLocked: locked })))
stubFetch(fetcher)
await mountAssets('style')
const status = wrapper!.get('.visual-style-status')
expect(status.attributes('role')).toBe('status')
expect(status.get('strong').text()).toBe(label)
expect(status.find('button').exists()).toBe(false)
expect(wrapper!.find('.visual-style-toolbar .n-tag').exists()).toBe(false)
expect(wrapper!.get('.visual-style-actions').findAll('button')).toHaveLength(1)
expect(button(action).disabled).toBe(disabled)
expect(button(action).style.getPropertyValue('--n-height')).toBe('34px')
expect(fetcher.mock.calls.every(([, options]) => !options?.method || options.method === 'GET')).toBe(true)
})
it('主体目录显示已确认母版和默认占位,点缩略图只切换主体,不重复读取所有角色图库', async () => {
const first = formFixture()
const forms = [
first,
...[2, 3].map(index => ({
...first,
id: `form-${index}`,
subjectId: `subject-${index}`,
images: [],
subject: { ...first.subject, id: `subject-${index}`, ref: `@CH000${index}`, name: `角色${index}` }
}))
]
const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => {
const path = String(url)
if (path.endsWith('/subject-forms')) return jsonResponse(forms)
if (path.endsWith('/visual-style')) return jsonResponse(styleFixture())
if (path.endsWith('/character-casting/readiness'))
return jsonResponse({
total: 3,
ready: 2,
missingIdentity: 0,
missingAnchor: 1,
candidatePending: 0,
unlocked: 0,
locked: 2,
items: forms.map((form, index) => ({
subjectId: form.subjectId,
subjectRef: form.subject.ref,
subjectName: form.subject.name,
status: index === 2 ? 'missing_anchor' : 'ready',
isLocked: index !== 2,
anchorImageId: index === 2 ? undefined : `anchor-${index}`,
anchorImageUrl: index === 2 ? undefined : `/storage/anchor-${index}.png`,
candidateImages: [{ id: 'candidate', imageUrl: '/storage/candidate.png' }]
}))
})
const second = path.includes('/subject-2/')
if (path.endsWith('/identity/images'))
return jsonResponse([
identityImageFixture({
identityId: second ? 'identity-2' : 'identity-db-1',
imageUrl: `/storage/anchor-${second ? 1 : 0}.png`
})
])
return jsonResponse(
identityFixture({
subjectId: second ? 'subject-2' : first.subjectId,
id: second ? 'identity-2' : 'identity-db-1'
})
)
})
stubFetch(fetcher)
await mountAssets('identity')
await drawerPanel().get('.n-card-header__close').trigger('click')
await flushPromises()
const items = wrapper!.findAll('.identity-subject-item')
expect(items).toHaveLength(3)
expect(items[0]!.get('.identity-thumbnail img').attributes('src')).toContain('/storage/anchor-0.png')
expect(items[1]!.get('.identity-thumbnail img').attributes('src')).toContain('/storage/anchor-1.png')
expect(items[2]!.get('.identity-thumbnail [role="img"]').attributes('aria-label')).toContain('暂无母版')
expect(fetcher.mock.calls.filter(([url]) => String(url).endsWith('/identity/images'))).toHaveLength(1)
await items[1]!.get('.identity-thumbnail img').trigger('click')
await flushPromises()
expect(items[1]!.attributes('aria-pressed')).toBe('true')
expect(document.querySelector('.n-image-preview-container')).toBeNull()
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
})
it('从形态深链接进入后,手动选择其它主体保持当前选择', async () => {
const form = formFixture()
const second = {
...form,
id: 'form-2',
subjectId: 'subject-2',
images: [],
subject: { ...form.subject, id: 'subject-2', name: '陆川', ref: '@CH0002' }
}
stubFetch(
vi.fn<typeof fetch>().mockImplementation(async url => {
if (String(url).endsWith('/subject-forms')) return jsonResponse([form, second])
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture())
return jsonResponse(null)
})
)
await mountAssets('identity', '?subjectId=subject-db-1')
const sidebar = wrapper!.get('.identity-directory')
expect(sidebar.get('.directory-filters').element.closest('.n-scrollbar-container')).toBeNull()
expect(sidebar.get('.identity-subject-list').findAll('.directory-item')).toHaveLength(2)
await wrapper!.findAll('.identity-subject-item')[1]!.trigger('click')
await flushPromises()
expect(wrapper!.findAll('.identity-subject-item')[1]!.attributes('aria-pressed')).toBe('true')
})
it('身份文本保存发送正式主体 ID 与锁定状态,草稿切换需确认', async () => {
let identity = identityFixture()
const form = formFixture()
const second = {
...form,
id: 'form-2',
subjectId: 'subject-2',
images: [],
subject: { ...form.subject, id: 'subject-2', name: '陆川', ref: '@CH0002' }
}
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (String(url).endsWith('/subject-forms')) return jsonResponse([form, second])
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture())
if (String(url).endsWith('/identity/images')) return jsonResponse([])
if (String(url).includes('/subject-2/')) return jsonResponse(null)
if (init?.method === 'PUT') identity = { ...identity, ...JSON.parse(init.body as string) }
return jsonResponse(identity)
})
stubFetch(fetcher)
await mountAssets('identity')
await new DOMWrapper(document.body).get('#identity-description').setValue('人工稳定身份')
await new DOMWrapper(document.body).get('#identity-lock').trigger('click')
button('保存主体身份').click()
await flushPromises()
const put = fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')!
expect(put[0]).toBe('/api/subjects/subject-db-1/identity')
expect(JSON.parse(put[1]!.body as string)).toMatchObject({ description: '人工稳定身份', isLocked: true })
expect(wrapper!.get('.page-form-actions').text()).not.toContain('当前内容已保存到项目')
expect(wrapper!.get('.page-form-actions button[type="submit"]').text()).toBe('已保存')
expect(button('AI 生成角色候选图').disabled).toBe(false)
await new DOMWrapper(document.body).get('#identity-description').setValue('新的未保存草稿')
await wrapper!.findAll('.identity-subject-item')[1]!.trigger('click')
expect(document.body.textContent).toContain('切换会丢弃草稿')
expect((new DOMWrapper(document.body).get('#identity-description').element as HTMLTextAreaElement).value).toBe(
'新的未保存草稿'
)
button('放弃草稿并切换').click()
await flushPromises()
expect((new DOMWrapper(document.body).get('#identity-description').element as HTMLTextAreaElement).value).toBe(
''
)
expect(wrapper!.get('.page-form-actions button[type="submit"]').text()).toBe('保存主体身份')
expect(wrapper!.get('.page-form-actions').text()).not.toContain('已保存')
})
it('链接添加拒绝危险 URL,只传已有地址及分类排序,成功后关闭并清空弹窗', async () => {
const image = styleImageFixture()
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async (_url, init) => jsonResponse(init?.method === 'POST' ? image : styleFixture()))
stubFetch(fetcher)
await mountAssets('style')
expect(wrapper!.find('[aria-label="风格图片地址"]').exists()).toBe(false)
button('通过链接添加').click()
await flushPromises()
await new DOMWrapper(document.body).get('[aria-label="风格图片地址"]').setValue('javascript:alert(1)')
button('添加参考图').click()
await flushPromises()
expect(document.querySelector('.n-form-item-feedback--error')?.textContent).toContain('请填写有效的')
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
await new DOMWrapper(document.body).get('[aria-label="风格图片地址"]').setValue('/storage/style.png')
button('添加参考图').click()
await flushPromises()
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(post[0]).toBe('/api/projects/page-test-project/visual-style/images')
expect(JSON.parse(post[1]!.body as string)).toEqual({
imageUrl: '/storage/style.png',
category: 'overall',
source: 'upload',
enabled: true,
sortOrder: 0
})
expect(document.querySelector('.app-dialog')).toBeNull()
button('通过链接添加').click()
await flushPromises()
expect(document.querySelector<HTMLInputElement>('[aria-label="风格图片地址"]')!.value).toBe('')
})
it('参考图添加失败保留弹窗、来源与设置,显式重试成功才关闭', async () => {
let rejectAdd = true
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (_url, init) => {
if (init?.method === 'POST')
return rejectAdd
? new Response('{"message":"参考图保存失败"}', { status: 500 })
: jsonResponse(styleImageFixture())
return jsonResponse(styleFixture())
})
stubFetch(fetcher)
await mountAssets('style')
button('通过链接添加').click()
await flushPromises()
const body = new DOMWrapper(document.body)
await body.get('[aria-label="风格图片地址"]').setValue('/storage/draft.png')
await body.get('[aria-label="风格图片排序"]').setValue('-2')
button('添加参考图').click()
await flushPromises()
expect(document.querySelector('.app-dialog')?.textContent).toContain('参考图保存失败')
expect(document.querySelector<HTMLInputElement>('[aria-label="风格图片地址"]')!.value).toBe(
'/storage/draft.png'
)
expect(document.querySelector<HTMLInputElement>('[aria-label="风格图片排序"]')!.value).toBe('-2')
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1)
rejectAdd = false
button('添加参考图').click()
await flushPromises()
expect(document.querySelector('.app-dialog')).toBeNull()
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(2)
})
it('AI 确认取消后重新打开必须再次确认,不能复用上次勾选', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => jsonResponse(styleFixture()))
stubFetch(fetcher)
await mountAssets('style')
button('AI 重新生成风格').click()
await flushPromises()
document.querySelector<HTMLElement>('.app-dialog [role="checkbox"]')!.click()
await flushPromises()
expect(button('确认AI 重新生成风格').disabled).toBe(false)
button('取消').click()
await flushPromises()
button('AI 重新生成风格').click()
await flushPromises()
expect(button('确认AI 重新生成风格').disabled).toBe(true)
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
})
it('视觉风格首次查询为空时可人工保存,JSON 校验和锁定字段准确传递', async () => {
let style: ReturnType<typeof styleFixture> | null = null
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (_url, init) => {
if (init?.method === 'PUT') style = styleFixture(JSON.parse(init.body as string))
return jsonResponse(style)
})
stubFetch(fetcher)
await mountAssets('style')
expect(wrapper!.text()).toContain('尚未创建')
await expandSections()
expect(wrapper!.text()).toContain('默认采用中国人物选角基线')
expect(wrapper!.text()).toContain('人物风格与选角背景')
await wrapper!.get('#style-constraints').setValue('{"不应静默丢弃":true}')
button('保存视觉风格').click()
await flushPromises()
expect(document.querySelector('.n-form-item-feedback--error')?.textContent).toContain('JSON 字符串数组')
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'PUT')).toBe(false)
await wrapper!.get('#style-constraints').setValue('["真人写实"]')
await wrapper!.get('#style-lock').trigger('click')
await wrapper!.get('#style-name').setValue('雨夜风格')
button('保存视觉风格').click()
await flushPromises()
const put = fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')!
expect(put[0]).toBe('/api/projects/page-test-project/visual-style')
expect(JSON.parse(put[1]!.body as string)).toMatchObject({
name: '雨夜风格',
isLocked: true,
hardConstraints: ['真人写实']
})
expect(button('AI 重新生成风格').disabled).toBe(true)
expect(button('保存视觉风格').disabled).toBe(false)
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
})
it('未保存风格草稿保持人工输入并禁止 AI 重生成', async () => {
let style = styleFixture()
stubFetch(vi.fn<typeof fetch>().mockImplementation(async () => jsonResponse(style)))
await mountAssets('style')
await wrapper!.get('#style-prompt').setValue('人工草稿')
style = styleFixture({ prompt: '后台新内容' })
await flushPromises()
expect((wrapper!.get('#style-prompt').element as HTMLTextAreaElement).value).toBe('人工草稿')
expect(button('AI 重新生成风格').disabled).toBe(true)
})
it('风格接口 404 显示错误而不是当作空风格,禁止写入', async () => {
stubFetch(vi.fn<typeof fetch>().mockResolvedValue(new Response('{"message":"路由不存在"}', { status: 404 })))
await mountAssets('style')
expect(wrapper!.text()).toContain('路由不存在')
expect(button('AI 生成风格').disabled).toBe(true)
expect(wrapper!.find('#style-prompt').exists()).toBe(false)
})
it('风格图启停用 PUT,移除经确认用 DELETE,均不调用生图接口', async () => {
let image = styleImageFixture()
let removed = false
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (init?.method === 'PUT') {
image = { ...image, enabled: false }
return jsonResponse(image)
}
if (init?.method === 'DELETE') {
removed = true
return jsonResponse(image)
}
expect(String(url)).toContain('/visual-style')
return jsonResponse(styleFixture({ images: removed ? [] : [image] }))
})
stubFetch(fetcher)
await mountAssets('style')
button('停用').click()
await flushPromises()
const put = fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')!
expect(put[0]).toBe('/api/projects/page-test-project/visual-style/images/style-image-1/enabled')
expect(JSON.parse(put[1]!.body as string)).toEqual({ enabled: false })
button('移除').click()
await flushPromises()
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'DELETE')).toBe(false)
button('确认移除').click()
await flushPromises()
expect(fetcher.mock.calls.find(([, init]) => init?.method === 'DELETE')?.[0]).toBe(
'/api/projects/page-test-project/visual-style/images/style-image-1'
)
expect(wrapper!.text()).toContain('尚无风格参考图')
})
it('主体目录按正式 Subject ID 去重,无 Identity 时不请求会报错的图片接口', async () => {
const form = formFixture()
const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => {
if (String(url).endsWith('/subject-forms'))
return jsonResponse([form, { ...form, id: 'form-db-2', images: [], name: '雨夜造型' }])
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture())
return jsonResponse(null)
})
stubFetch(fetcher)
await mountAssets('identity')
expect(wrapper!.findAll('.identity-subject-item')).toHaveLength(1)
expect(wrapper!.text()).toContain('2 个形态')
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/subjects/subject-db-1/identity'))).toBe(true)
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/identity/images'))).toBe(false)
expect(button('AI 生成主体身份').disabled).toBe(false)
})
it('AI 主体身份生成在表单底部保留唯一入口,覆盖已保存文本需要确认', async () => {
let identity = identityFixture()
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (String(url).endsWith('/subject-forms')) return jsonResponse([formFixture()])
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture())
if (String(url).endsWith('/identity/images')) return jsonResponse([])
if (init?.method === 'POST') identity = identityFixture({ description: 'AI 重新生成的身份描述' })
return jsonResponse(identity)
})
stubFetch(fetcher)
await mountAssets('identity')
const actions = wrapper!.get('.page-form-actions')
expect(actions.text()).toContain('AI 生成主体身份')
expect(actions.findAll('button').map(item => item.text())).toEqual(['已保存', 'AI 生成主体身份'])
expect(actions.text()).not.toContain('当前内容已保存到项目')
expect(wrapper!.findAll('button').filter(item => item.text() === 'AI 生成主体身份')).toHaveLength(1)
button('AI 生成主体身份').click()
await flushPromises()
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
button('确认AI 生成主体身份').click()
await flushPromises()
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(post[0]).toBe('/api/subjects/subject-db-1/identity/generate')
expect(JSON.parse(post[1]!.body as string)).toEqual({ force: true })
expect(wrapper!.get<HTMLTextAreaElement>('#identity-description').element.value).toBe('AI 重新生成的身份描述')
})
it('锁定阻止身份 AI 覆盖但不阻止人工编辑,并按步骤进入后续操作', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (String(url).endsWith('/subject-forms')) return jsonResponse([formFixture()])
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture({ isLocked: true }))
if (init?.method === 'POST') return jsonResponse(identityImageFixture())
if (String(url).endsWith('/identity/images')) return jsonResponse([identityImageFixture()])
return jsonResponse(identityFixture({ isLocked: true }))
})
stubFetch(fetcher)
await mountAssets('identity')
expect(wrapper!.text()).toContain('主体身份已完成')
expect(button('AI 生成主体身份').disabled).toBe(true)
await new DOMWrapper(document.body).get('#identity-description').setValue('人工稳定身份草稿')
expect(button('保存主体身份').disabled).toBe(false)
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
})
it('无项目风格时禁止生成身份和图片,但仍可人工保存身份', async () => {
stubFetch(
vi.fn<typeof fetch>().mockImplementation(async url => {
if (String(url).endsWith('/subject-forms')) return jsonResponse([formFixture()])
if (String(url).endsWith('/visual-style')) return jsonResponse(null)
if (String(url).endsWith('/identity/images')) return jsonResponse([])
return jsonResponse(identityFixture())
})
)
await mountAssets('identity')
expect(button('设置视觉风格').disabled).toBe(false)
expect(button('AI 生成主体身份').disabled).toBe(true)
await new DOMWrapper(document.body).get('#identity-description').setValue('人工稳定身份草稿')
expect(button('保存主体身份').disabled).toBe(false)
})
it('身份批量生成区分锁定跳过和部分失败,不将 HTTP 200 当作全部成功', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (init?.method === 'POST')
return jsonResponse({
total: 3,
targetCount: 2,
generated: 1,
skipped: 1,
skippedLocked: 1,
failed: 1,
failures: [{ subjectId: 'failed-db', subjectRef: '@CH0003', error: '文本模型超时' }]
})
if (String(url).endsWith('/subject-forms')) return jsonResponse([formFixture()])
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture())
return jsonResponse(null)
})
stubFetch(fetcher)
await mountAssets('identity')
await confirmGeneration('补齐全部主体身份文本')
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(post[0]).toBe('/api/projects/page-test-project/subject-identities/generate')
expect(JSON.parse(post[1]!.body as string)).toEqual({ force: false, concurrency: 3 })
expect(drawerPanel().text()).toContain('本次存在部分失败')
expect(drawerPanel().text()).toContain('含锁定 1')
expect(drawerPanel().text()).toContain('文本模型超时')
})
it.each([true, false])(
'身份图片校验按真实 passed=%s 反馈,等待时显示目标按钮加载,结果不驻留页面',
async passed => {
/** 延迟校验回执以覆盖请求期间的真实按钮状态。 */
let finish!: (response: Response) => void
const response = new Promise<Response>(resolve => {
finish = resolve
})
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
const path = String(url)
if (path.endsWith('/subject-forms')) return jsonResponse([formFixture()])
if (path.endsWith('/visual-style')) return jsonResponse(styleFixture())
if (init?.method === 'POST' && path.endsWith('/validate')) return response
if (path.endsWith('/identity/images')) return jsonResponse([identityImageFixture()])
return jsonResponse(identityFixture())
})
stubFetch(fetcher)
await mountAssets('identity')
const gallery = wrapper!.findComponent(IdentityGallery)
gallery.vm.$emit('validate', 'identity-image-1')
await flushPromises()
expect(gallery.props('pendingOperation')).toMatchObject({ imageId: 'identity-image-1', kind: 'validate' })
expect(button('校验此身份图片').disabled).toBe(true)
expect(getOperation(fixture.id).pending).toBe(true)
finish(
jsonResponse({
subjectId: 'subject-db-1',
imageId: 'identity-image-1',
passed,
summary: '本次视觉检查结果',
issues: []
})
)
await flushPromises()
expect(getOperation(fixture.id)).toMatchObject({
pending: false,
noticeType: passed ? 'success' : 'warning',
notice: `林知夏 的身份图片校验${passed ? '通过' : '未通过'}:本次视觉检查结果`
})
expect(gallery.props('pendingOperation')).toBeNull()
expect(wrapper!.text()).not.toContain('本次视觉检查结果')
}
)
it('身份候选母版切换需确认,只发送正确 Subject ID 的 anchor PUT', async () => {
let selected = false
const form = formFixture()
form.subject.module = 'scene'
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (String(url).endsWith('/subject-forms')) return jsonResponse([form])
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture())
if (init?.method === 'PUT') {
selected = true
return jsonResponse({
identityId: 'identity-db-1',
subjectId: 'subject-db-1',
isLocked: true,
anchor: identityImageFixture({ id: 'candidate', isAnchor: true })
})
}
if (String(url).endsWith('/identity/images'))
return jsonResponse([identityImageFixture({ id: 'candidate', isAnchor: selected })])
return jsonResponse(identityFixture())
})
stubFetch(fetcher)
await mountAssets('identity')
button('管理候选(1)').click()
await flushPromises()
button('设为身份母版').click()
await flushPromises()
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'PUT')).toBe(false)
button('确认切换身份母版').click()
await flushPromises()
expect(fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')?.[0]).toBe(
'/api/subjects/subject-db-1/identity/images/candidate/stable-anchor'
)
expect(wrapper!.text()).toContain('身份母版')
expect(getOperation(fixture.id)).toMatchObject({
noticeType: 'success',
notice: '林知夏 的身份母版已确认并锁定。'
})
// 仅检查正文母版预览,目录缩略图使用相同身份标识但不提供原图预览。
const anchorImage = wrapper!.get('.identity-anchor-grid').getComponent(NImage)
expect(anchorImage.props()).toMatchObject({ objectFit: 'cover', previewDisabled: false })
})
it('选角进度卡片分层显示长姓名、编号和状态,点击仍按正式 ID 切换主体', async () => {
const longName = '来自记忆当铺的另一条时间线中尚未丢失记忆的林默'
const items = [
{
subjectId: 'subject-db-1',
subjectRef: '@CH0001',
subjectName: longName,
status: 'ready',
isLocked: true
},
{
subjectId: 'subject-db-2',
subjectRef: '@CH0002',
subjectName: '老周',
status: 'candidate_pending',
isLocked: false
}
]
const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => {
const path = String(url)
if (path.endsWith('/subject-forms')) return jsonResponse([formFixture()])
if (path.endsWith('/visual-style')) return jsonResponse(styleFixture())
if (path.endsWith('/character-casting/readiness'))
return jsonResponse({
total: 2,
ready: 1,
missingIdentity: 0,
missingAnchor: 0,
candidatePending: 1,
unlocked: 0,
locked: 1,
items
})
if (path.endsWith('/identity/images')) return jsonResponse([])
const second = path.includes('/subject-db-2/')
return jsonResponse(
identityFixture({
subjectId: second ? 'subject-db-2' : 'subject-db-1',
description: second ? '老周的稳定身份' : '林默的稳定身份'
})
)
})
stubFetch(fetcher)
await mountAssets('identity')
expect(drawerPanel().get('.identity-tools-intro').text()).toContain('为同一个人物、场景或道具固定稳定特征')
const cards = drawerPanel().get('[aria-label="角色选角进度"]').findAll('.casting-item')
expect(cards).toHaveLength(2)
expect(cards[0]!.get('.casting-item-name').text()).toBe(longName)
expect(cards[0]!.get('.casting-item-ref').text()).toBe('@CH0001')
expect(cards[0]!.get('.casting-item-status').text()).toBe('选角已完成')
expect(cards[0]!.find('.truncate').exists()).toBe(false)
expect(cards[0]!.attributes('aria-pressed')).toBe('true')
expect(cards[1]!.get('.casting-item-status').text()).toBe('等待确认演员')
await cards[1]!.trigger('click')
await flushPromises()
expect(cards[0]!.attributes('aria-pressed')).toBe('false')
expect(cards[1]!.attributes('aria-pressed')).toBe('true')
expect(cards[1]!.classes()).toContain('selected')
expect(new DOMWrapper(document.body).get<HTMLTextAreaElement>('#identity-description').element.value).toBe(
'老周的稳定身份'
)
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/subjects/subject-db-2/identity'))).toBe(true)
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
})
it('Character 确认选角原子切换 Anchor 并锁定 Identity,不调用普通母版接口', async () => {
let locked = false
let selected = false
const candidate = identityImageFixture({ id: 'casting-1', isAnchor: false })
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
const path = String(url)
if (path.endsWith('/subject-forms')) return jsonResponse([formFixture()])
if (path.endsWith('/visual-style')) return jsonResponse(styleFixture())
if (path.endsWith('/character-casting/readiness'))
return jsonResponse({
total: 1,
ready: locked ? 1 : 0,
missingIdentity: 0,
missingAnchor: 0,
candidatePending: locked ? 0 : 1,
unlocked: 0,
locked: locked ? 1 : 0,
items: [
{
subjectId: 'subject-db-1',
subjectRef: '@CH0001',
subjectName: '林知夏',
status: locked ? 'ready' : 'candidate_pending',
identityId: 'identity-db-1',
candidateImages: locked ? undefined : [{ id: 'casting-1', imageUrl: candidate.imageUrl }],
anchorImageId: locked ? 'casting-1' : undefined,
anchorImageUrl: locked ? candidate.imageUrl : undefined,
isLocked: locked
}
]
})
if (path.endsWith('/identity/images')) return jsonResponse([{ ...candidate, isAnchor: selected }])
if (init?.method === 'PUT' && path.endsWith('/casting')) {
locked = true
selected = true
return jsonResponse({
identityId: candidate.identityId,
subjectId: 'subject-db-1',
isLocked: true,
anchor: { ...candidate, isAnchor: true }
})
}
return jsonResponse(identityFixture({ isLocked: locked }))
})
stubFetch(fetcher)
await mountAssets('identity')
expect(wrapper!.text()).toContain('等待确认演员')
button('管理候选并确认').click()
await flushPromises()
button('确认选角并锁定').click()
await flushPromises()
button('确认演员选择').click()
await flushPromises()
const put = fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')!
expect(put[0]).toBe('/api/subjects/subject-db-1/identity/images/casting-1/casting')
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/anchor'))).toBe(false)
expect(wrapper!.text()).toContain('主体身份已完成')
expect(wrapper!.get('.identity-gallery').text()).toContain('已确认并锁定')
})
it('切换主体会取消旧查询,迟到的身份结果不覆盖当前主体', async () => {
let finish!: (value: Response) => void
const form = formFixture()
const second = {
...form,
id: 'form-2',
subjectId: 'subject-2',
images: [],
subject: { ...form.subject, id: 'subject-2', name: '陆川', ref: '@CH0002' }
}
const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => {
const path = String(url)
if (path.endsWith('/subject-forms')) return jsonResponse([form, second])
if (path.endsWith('/visual-style')) return jsonResponse(styleFixture())
if (path.endsWith('/subject-db-1/identity'))
return new Promise(resolve => {
finish = resolve
})
if (path.endsWith('/identity/images')) return jsonResponse([])
return jsonResponse(
identityFixture({ id: 'identity-2', subjectId: 'subject-2', description: '陆川的稳定身份' })
)
})
stubFetch(fetcher)
await mountAssets('identity')
expect(wrapper!.find('.subject-identity-skeleton').exists()).toBe(false)
expect(wrapper!.find('.identity-detail-skeleton').exists()).toBe(true)
await wrapper!.findAll('.identity-subject-item')[1]!.trigger('click')
await flushPromises()
expect(wrapper!.find('.identity-detail-skeleton').exists()).toBe(false)
expect(
fetcher.mock.calls.find(([url]) => String(url).endsWith('/subject-db-1/identity'))?.[1]?.signal?.aborted
).toBe(true)
finish(jsonResponse(identityFixture()))
await flushPromises()
expect((new DOMWrapper(document.body).get('#identity-description').element as HTMLTextAreaElement).value).toBe(
'陆川的稳定身份'
)
})
it('生成失败不自动重发,后端正在拆解时禁止身份写操作', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (String(url).endsWith('/subject-forms')) return jsonResponse([formFixture()])
if (String(url).endsWith('/visual-style')) return jsonResponse(styleFixture())
if (String(url).endsWith('/identity/images')) return jsonResponse([])
if (init?.method === 'POST') throw new Error('connection lost')
if (String(url).endsWith('/identity')) return jsonResponse(null)
return jsonResponse(identityFixture())
})
stubFetch(fetcher)
const provided = await mountAssets('identity')
button('AI 生成主体身份').click()
await flushPromises()
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1)
expect(getOperation(fixture.id).error).toContain('无法连接后端')
provided.data.value!.project = { ...fixture, status: 'generating' }
await flushPromises()
expect(new DOMWrapper(document.body).get('#identity-description').attributes('disabled')).toBeDefined()
expect(button('AI 生成主体身份').disabled).toBe(true)
})
})
describe('工作台页面交互', () => {
it('形态筛选搜索、类型和图片状态仍只过滤本地显示,控件与结果数处于同一工具栏', async () => {
const person = formFixture()
const scene = {
...formFixture(),
id: 'scene-form',
images: [],
subject: { ...person.subject, id: 'scene-subject', ref: '@SC0001', name: '旧书店', module: 'scene' }
}
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => jsonResponse([person, scene]))
stubFetch(fetcher)
await mountSubjectImages()
const filters = wrapper!.get('.form-image-filters')
expect(wrapper!.get('.form-image-toolbar').classes()).not.toContain('has-impact-picker')
expect(filters.element.parentElement).toBe(wrapper!.get('.form-image-toolbar').element)
expect(wrapper!.findAll('.form-image-filters')).toHaveLength(1)
expect(filters.get('.filter-result-count').text()).toBe('2 个形态')
expect(filters.find('input[aria-label="搜索形态图片"]').exists()).toBe(true)
selectControl(wrapper!, 'aria-label', '筛选图片状态').vm.$emit('update:value', 'missing')
await flushPromises()
expect(wrapper!.findAll('.form-image-card')).toHaveLength(1)
expect(wrapper!.get('.form-image-card').text()).toContain('旧书店')
selectControl(wrapper!, 'aria-label', '筛选主体类型').vm.$emit('update:value', 'character')
await flushPromises()
expect(filters.get('.filter-result-count').text()).toBe('0 个形态')
selectControl(wrapper!, 'aria-label', '筛选主体类型').vm.$emit('update:value', 'all')
await filters.get('input[aria-label="搜索形态图片"]').setValue('旧书店')
expect(filters.get('.filter-result-count').text()).toBe('1 个形态')
expect(selectControl(wrapper!, 'aria-label', '筛选图片状态').props('options')).not.toContainEqual({
label: '身份过期',
value: 'stale'
})
expect(filters.get('.filter-result-count').text()).toBe('1 个形态')
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
})
it('拆解导出图标位于 Tabs suffix,空快照时禁用且不再提供执行记录', async () => {
wrapper = mount(BreakdownPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context() }, stubs: { RouterLink: true } }
})
const toolbar = wrapper.get('.result-toolbar')
expect(toolbar.find('[aria-label="拆解结果"]').exists()).toBe(true)
expect(toolbar.find(':scope > button').exists()).toBe(false)
const exportButton = toolbar.get<HTMLButtonElement>('.n-tabs-nav__suffix [aria-label="导出拆解结果"]')
expect(exportButton.element.disabled).toBe(true)
expect(exportButton.text()).toBe('')
expect(exportButton.get('svg').attributes('width')).toBe('18')
expect(toolbar.find('[aria-label="拆解更多操作"]').exists()).toBe(false)
expect(wrapper.find('.history-panel').exists()).toBe(false)
expect(wrapper.text()).not.toContain('执行记录')
})
it('形态图库自动显示后端已有图片,不需要再次生图;筛选只改变显示', async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async () => new Response(JSON.stringify({ data: [formFixture()] })))
stubFetch(fetcher)
await mountSubjectImages()
expect(wrapper!.get('.form-image-card img').attributes('src')).toContain(
'/storage/subjects/project/form/image.png'
)
expect(wrapper!.text()).toContain('林知夏')
expect(wrapper!.text()).toContain('主参考图')
expect(fetcher.mock.calls.map(([url, init]) => [url, init?.method])).toEqual(
expect.arrayContaining([
['/api/projects/page-test-project/subject-forms', 'GET'],
['/api/generation-models', 'GET'],
['/api/projects/page-test-project/creative-profile', 'GET'],
['/api/projects/page-test-project/keyframes/readiness?force=false', 'GET'],
['/api/projects/page-test-project/videos/readiness?force=false', 'GET']
])
)
expect(fetcher).toHaveBeenCalledTimes(5)
await wrapper!.get('[aria-label="搜索形态图片"]').setValue('不存在的形态')
expect(wrapper!.text()).toContain('没有匹配的形态')
button('清除筛选').click()
await flushPromises()
expect(wrapper!.findAll('.form-image-card')).toHaveLength(1)
})
it('瀑布流形态卡片完整展示并打开原生图片预览,历史管理仍从独立按钮进入', async () => {
const form = formFixture()
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async url =>
jsonResponse(String(url).endsWith('/subject-forms') ? [form] : form.images)
)
stubFetch(fetcher)
await mountSubjectImages()
await drawerPanel().get('.n-card-header__close').trigger('click')
const card = wrapper!.get('.form-image-card')
expect(card.getComponent(NImage).props()).toMatchObject({ objectFit: 'contain', previewDisabled: false })
await card.get('img').trigger('click')
await flushPromises()
expect(document.querySelector('.n-image-preview')?.getAttribute('src')).toContain(
'/storage/subjects/project/form/image.png'
)
expect(document.querySelector('.image-history')).toBeNull()
expect(fetcher).toHaveBeenCalledTimes(5)
document.querySelector<HTMLElement>('.n-image-preview-overlay')!.click()
await flushPromises()
button('查看图片与记录').click()
await flushPromises()
expect(document.querySelector('.image-history')).not.toBeNull()
expect(fetcher.mock.calls.some(([url]) => String(url).endsWith('/subject-forms/form-db-1/images'))).toBe(true)
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
})
it('形态单图确认后发送正式 ID 并刷新候选图,不会调用 production/start', async () => {
const form = formFixture()
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (_url, init) => {
if (init?.method === 'POST') {
const candidate = imageFixture({
id: 'new-candidate',
isPrimary: false,
status: 'pending',
imageUrl: null
})
form.images.unshift(candidate)
return new Response(JSON.stringify({ data: candidate }))
}
return new Response(JSON.stringify({ data: [form] }))
})
stubFetch(fetcher)
await mountSubjectImages()
button('再生成一张').click()
await flushPromises()
document.querySelector<HTMLInputElement>('#confirm-image-cost')!.click()
await flushPromises()
button('确认生成图片').click()
await flushPromises()
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(post[0]).toBe('/api/subject-forms/form-db-1/images')
expect(JSON.parse(post[1]!.body as string)).toEqual({
setPrimary: false,
provider: 'qwen-image',
generationOptions: { size: '2048*2048' }
})
expect(wrapper!.text()).toContain('2 条记录')
expect(wrapper!.get('.form-image-card img').attributes('src')).not.toContain('/storage/new.png')
expect(fetcher.mock.calls.some(([url]) => String(url).includes('production/start'))).toBe(false)
})
it('批量生图保留部分失败回执,默认跳过有主图项,筛选不会成为批量参数', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(
async (_url, init) =>
new Response(
JSON.stringify({
data:
init?.method === 'POST'
? {
total: 2,
targetCount: 1,
generated: 0,
skipped: 1,
failed: 1,
failures: [{ subjectFormId: 'form-db-2', error: '服务暂不可用' }]
}
: [formFixture()]
})
)
)
stubFetch(fetcher)
await mountSubjectImages()
await wrapper!.get('[aria-label="搜索形态图片"]').setValue('@CH0001')
await confirmGeneration('补齐项目主参考图')
expect(drawerPanel().get('[aria-label="生图批量回执"]').text()).toContain('部分形态生图失败')
expect(drawerPanel().text()).toContain('服务暂不可用')
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(JSON.parse(post[1]!.body as string)).toEqual({ concurrency: 2, force: false })
await drawerPanel()
.findAll('[role="checkbox"]')
.find(item => item.text().includes('已有主图也新增候选图'))!
.trigger('click')
await confirmGeneration('为全项目新增候选图')
const lastPost = fetcher.mock.calls.filter(([, init]) => init?.method === 'POST').at(-1)!
expect(JSON.parse(lastPost[1]!.body as string).force).toBe(true)
})
it('后端持久化生成中或查询失败时暂停生图,旧图库仍可查看', async () => {
let fail = false
const form = formFixture()
form.images.unshift(imageFixture({ id: 'running', isPrimary: false, status: 'generating', imageUrl: null }))
const fetcher = vi
.fn<typeof fetch>()
.mockImplementation(async () =>
fail
? new Response('{"message":"数据库异常"}', { status: 500 })
: new Response(JSON.stringify({ data: [form] }))
)
stubFetch(fetcher)
await mountSubjectImages()
expect(button('再生成一张').disabled).toBe(true)
expect(wrapper!.text()).toContain('数据库中有形态图片正在后台生成')
fail = true
button('查看图片与记录').click()
await flushPromises()
expect(document.body.textContent).toContain('数据库异常')
expect(wrapper!.find('.form-image-card img').exists()).toBe(true)
await new DOMWrapper(button('刷新图片').closest('.app-dialog')!).get('.n-card-header__close').trigger('click')
await flushPromises()
expect(button('补齐项目主参考图').disabled).toBe(true)
})
it('分镜参考图使用 cover 和原生预览,查看图片不触发生成功能', async () => {
const shot = designedShot()
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(
jsonResponse({
shotId: shot.shotId,
references: [
{
shotSubjectId: 'binding-db',
subjectId: 'subject-db',
subjectRef: '@CH0001',
subjectName: '林知夏',
module: 'character',
subjectFormId: 'form-db',
subjectFormName: '日常',
imageId: 'image-db',
imageUrl: '/storage/reference.png'
}
],
missing: []
})
)
stubFetch(fetcher)
wrapper = mount(ShotTools, { attachTo: document.body, props: { projectId: fixture.id, shot, disabled: false } })
await flushPromises()
expect(wrapper.getComponent(NImage).props()).toMatchObject({ objectFit: 'cover', previewDisabled: false })
const image = wrapper.get('.reference-card img')
expect(image.element.parentElement?.closest('a')).toBeNull()
await image.trigger('click')
await flushPromises()
expect(document.querySelector('.n-image-preview')?.getAttribute('src')).toBe(image.attributes('src'))
expect(fetcher.mock.calls).toHaveLength(1)
expect(fetcher.mock.calls.every(([, init]) => !init?.method || init.method === 'GET')).toBe(true)
})
it('参考图拦截危险地址,生成规格只通过 GET 读取正式形态和状态', async () => {
const shot = designedShot()
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValueOnce(
new Response(
JSON.stringify({
data: {
shotId: shot.shotId,
references: [
{
shotSubjectId: 'binding-db',
subjectId: 'subject-db',
subjectRef: '@CH0001',
subjectName: '林知夏',
module: 'character',
subjectFormId: 'form-db',
subjectFormName: '日常',
imageId: 'image-db',
imageUrl: 'javascript:alert(1)'
}
],
missing: []
}
})
)
)
.mockResolvedValueOnce(
new Response(
JSON.stringify({
data: {
projectId: fixture.id,
episodeNo: 1,
beatNo: 1,
shotId: shot.shotId,
shotNo: 1,
title: '来信',
description: '真实镜头',
visualFocus: '信封',
durationSeconds: 5,
subjects: [{ subjectId: 'subject-db', subjectFormId: 'form-db' }],
direction: shot.direction,
environment: {
timeOfDay: '夜晚',
weather: '小雨',
atmosphere: '安静',
transientState: '地面积水'
},
continuityNote: '信封在右手'
}
})
)
)
stubFetch(fetcher)
wrapper = mount(ShotTools, { attachTo: document.body, props: { projectId: fixture.id, shot, disabled: false } })
await flushPromises()
expect(wrapper.text()).toContain('图片不可用')
expect(wrapper.find('.reference-card a').exists()).toBe(false)
expect(wrapper.find('.reference-card img').exists()).toBe(false)
button('读取生成规格').click()
await flushPromises()
expect(wrapper.get('pre').text()).toContain('form-db')
expect(wrapper.get('pre').text()).toContain('地面积水')
expect(fetcher.mock.calls[1]?.[0]).toBe('/api/storyboard-shots/shot-db-1-1/generation-spec')
expect(fetcher.mock.calls.every(([, init]) => init?.method !== 'POST')).toBe(true)
})
it('生成途中切换剧集并离开页面,不改变提交目标,也不丢失项目回执', async () => {
let finish!: (response: Response) => void
const fetcher = vi.fn<typeof fetch>().mockImplementation((url, init) => {
if (init?.method === 'POST')
return new Promise(resolve => {
finish = resolve
})
const episodeNo = Number(new URL(String(url), 'http://localhost').searchParams.get('episodeNo'))
return Promise.resolve(
new Response(
JSON.stringify({
data: String(url).includes('storyboard-directions')
? directionsResult(fixture.id, episodeNo)
: visualStatesResult(fixture.id, episodeNo)
})
)
)
})
stubFetch(fetcher)
await mountStoryboard()
await flushPromises()
await confirmGeneration('补齐项目导演设计')
expect(button('补齐项目导演设计').disabled).toBe(true)
await drawerPanel().get('.n-card-header__close').trigger('click')
await flushPromises()
expect(wrapper!.get('[data-workspace-tools]').attributes('aria-expanded')).toBe('false')
expect(getOperation(fixture.id).pending).toBe(true)
selectControl(wrapper!, 'aria-label', '选择分镜剧集').vm.$emit('update:value', 2)
await flushPromises()
wrapper!.unmount()
wrapper = undefined
finish(
new Response(
`{"data":{"projectId":"${fixture.id}","episodeCount":2,"completedEpisodes":1,"skippedEpisodes":1,"failedEpisodes":0,"shotCount":4,"directionCount":4,"coverage":1,"episodes":[]}}`
)
)
await flushPromises()
expect(getStoryboardSession(fixture.id).receipt).toBeNull()
expect(localStorage.getItem('short-drama:workflow-execution:page-test-project:storyboard-direction')).toBe(
'page-execution-1'
)
await mountStoryboard()
await flushPromises()
expect(getStoryboardSession(fixture.id).receipt).toMatchObject({
kind: 'batch',
title: '项目导演设计'
})
expect(getOperation(fixture.id).pending).toBe(false)
const posts = fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')
expect(posts).toHaveLength(1)
expect(JSON.parse(posts[0]![1]!.body as string)).toEqual({ concurrency: 2, force: false })
})
it('分镜只提供正式项目生成,逐集失败回执保留零次修复参数', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (init?.method === 'POST')
return new Response(
JSON.stringify({
data: {
projectId: fixture.id,
episodeCount: 1,
completedEpisodes: 0,
skippedEpisodes: 0,
failedEpisodes: 1,
shotCount: 2,
visualStateCount: 0,
coverage: 0,
episodes: [
{
episodeNo: 1,
status: 'failed',
shotCount: 2,
visualStateCount: 0,
repairAttempts: 0,
error: '缺少主体状态'
}
]
}
})
)
const result = String(url).includes('storyboard-directions')
? directionsResult(fixture.id, 1, true)
: visualStatesResult(fixture.id)
return new Response(JSON.stringify({ data: result }))
})
stubFetch(fetcher)
await mountStoryboard()
await flushPromises()
expect(wrapper!.text()).not.toContain('生成本集导演设计')
expect(wrapper!.text()).not.toContain('生成本集即时状态')
expect(button('补齐项目导演设计').disabled).toBe(false)
expect(button('补齐项目即时状态').disabled).toBe(false)
expect(fetcher.mock.calls.every(([, init]) => init?.method !== 'POST')).toBe(true)
await drawerPanel().get('#storyboard-repairs').setValue('0')
await confirmGeneration('补齐项目即时状态')
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(JSON.parse(post[1]!.body as string)).toEqual({
concurrency: 2,
force: false,
maxRepairAttempts: 0
})
expect(drawerPanel().text()).toContain('本次存在失败')
expect(drawerPanel().text()).toContain('缺少主体状态')
})
it('重生成当前集镜头后读取后台终态,并废弃过期 Breakdown 文本', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (init?.method === 'POST')
return jsonResponse({
projectId: fixture.id,
episodeNo: 1,
storyboardShotSummary: {
episodeCount: 1,
beatCount: 2,
shotCount: 2,
totalDurationSeconds: 10,
subjectRefCount: 2,
subjectBindingCount: 2,
bindingCoverage: 1
},
storyboardShotValidation: { valid: true, issues: [] }
})
return jsonResponse(
String(url).includes('storyboard-directions')
? directionsResult(fixture.id, 1, false)
: visualStatesResult(fixture.id)
)
})
stubFetch(fetcher)
await mountStoryboard()
await confirmGeneration('重生成第 1 集镜头')
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(post[0]).toBe('/api/projects/page-test-project/storyboard-shots/regenerate')
expect(JSON.parse(post[1]!.body as string)).toEqual({ episodeNo: 1 })
expect(wrapper!.text()).not.toContain('第1集镜头1')
expect(wrapper!.text()).not.toContain('门口收到一封信')
expect(getStoryboardSession(fixture.id).invalidatedEpisodeSources[1]).toBe(true)
expect(wrapper!.text()).toContain('新标题和剧情详情尚未提供')
expect(drawerPanel().text()).toContain('本集新镜头已保存')
expect(drawerPanel().text()).toContain('2 个镜头')
expect(fetcher.mock.calls.filter(([, init]) => !init?.method || init.method === 'GET')).toHaveLength(8)
expect(fetcher.mock.calls.some(([url]) => String(url) === '/api/workflow-executions/page-execution-1')).toBe(
true
)
})
it('后台终态部分失败不显示全成功,默认补齐与显式覆盖参数独立', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, init) => {
if (init?.method === 'POST')
return new Response(
JSON.stringify({
data: {
projectId: fixture.id,
episodeCount: 2,
completedEpisodes: 0,
skippedEpisodes: 1,
failedEpisodes: 1,
shotCount: 4,
directionCount: 2,
coverage: 0.5,
episodes: [
{ episodeNo: 1, status: 'skipped', shotCount: 2, directionCount: 2 },
{
episodeNo: 2,
status: 'failed',
shotCount: 2,
directionCount: 0,
error: '模型校验失败'
}
]
}
})
)
return new Response(
JSON.stringify({
data: String(url).includes('storyboard-directions')
? directionsResult(fixture.id)
: visualStatesResult(fixture.id)
})
)
})
stubFetch(fetcher)
await mountStoryboard()
await flushPromises()
await confirmGeneration('补齐项目导演设计')
expect(drawerPanel().get('[aria-label="生成回执"] [role="alert"]').text()).toContain('存在失败')
expect(drawerPanel().text()).toContain('模型校验失败')
await drawerPanel().get('[role="checkbox"]').trigger('click')
await confirmGeneration('重生成全部导演设计')
const posts = fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')
expect(posts.map(([, init]) => JSON.parse(init!.body as string))).toEqual([
{ concurrency: 2, force: false },
{ concurrency: 2, force: true }
])
})
it('切换剧集取消旧查询,迟到响应不会覆盖新剧集,也不自动提交生成', async () => {
const oldRequests: { finish: (response: Response) => void; url: string; signal: AbortSignal }[] = []
const fetcher = vi.fn<typeof fetch>().mockImplementation((url, init) => {
const address = String(url)
if (address.endsWith('episodeNo=1'))
return new Promise(resolve =>
oldRequests.push({ finish: resolve, url: address, signal: init!.signal as AbortSignal })
)
return Promise.resolve(
new Response(
JSON.stringify({
data: address.includes('storyboard-directions')
? directionsResult(fixture.id, 2)
: visualStatesResult(fixture.id, 2)
})
)
)
})
stubFetch(fetcher)
await mountStoryboard()
await flushPromises()
selectControl(wrapper!, 'aria-label', '选择分镜剧集').vm.$emit('update:value', 2)
await flushPromises()
expect(oldRequests.every(request => request.signal.aborted)).toBe(true)
for (const request of oldRequests)
request.finish(
new Response(
JSON.stringify({
data: request.url.includes('storyboard-directions')
? directionsResult(fixture.id)
: visualStatesResult(fixture.id)
})
)
)
await flushPromises()
/** 用当前设计组件的正式镜头验证迟到响应隔离,不依赖已隐藏的内部编号文案。 */
expect(wrapper!.getComponent(ShotDesign).props('shot').shotId).toBe('shot-db-2-1')
expect(wrapper!.text()).toContain('第2集镜头1')
expect(wrapper!.text()).not.toContain('第1集镜头1')
expect(fetcher.mock.calls).toHaveLength(4)
})
it('首次分镜读取失败时禁用生成,重试恢复后才允许操作', async () => {
let fail = true
const fetcher = vi.fn<typeof fetch>().mockImplementation(async url => {
if (fail) return new Response('{"message":"数据库暂不可用"}', { status: 503 })
return new Response(
JSON.stringify({
data: String(url).includes('storyboard-directions')
? directionsResult(fixture.id)
: visualStatesResult(fixture.id)
})
)
})
stubFetch(fetcher)
await mountStoryboard()
await flushPromises()
expect(wrapper!.text()).toContain('数据库暂不可用')
expect(button('补齐项目导演设计').disabled).toBe(true)
fail = false
button('重试查询').click()
await flushPromises()
expect(button('补齐项目导演设计').disabled).toBe(false)
/** 重试恢复正式镜头数据,内部编号仍用于业务选择。 */
expect(wrapper!.getComponent(ShotDesign).props('shot').shotId).toBe('shot-db-1-1')
})
it('镜头工具按需 GET,切换镜头会废弃旧参考图,未完成设计不能编译规格', async () => {
let finish!: (response: Response) => void
const fetcher = vi.fn<typeof fetch>().mockImplementation(
() =>
new Promise(resolve => {
finish = resolve
})
)
stubFetch(fetcher)
wrapper = mount(ShotTools, {
attachTo: document.body,
props: { projectId: fixture.id, shot: designedShot(), disabled: false }
})
expect(fetcher).toHaveBeenCalledTimes(1)
await flushPromises()
expect(fetcher.mock.calls[0]?.[0]).toBe('/api/storyboard-shots/shot-db-1-1/references')
await wrapper.setProps({ shot: { ...designedShot('shot-db-1-2'), visualState: null } })
expect(fetcher.mock.calls[0]?.[1]?.signal?.aborted).toBe(true)
finish(
new Response(
'{"data":{"shotId":"shot-db-1-1","references":[],"missing":[{"subjectId":"x","subjectName":"旧镜头人物","reason":"缺图"}]}}'
)
)
await flushPromises()
expect(wrapper.text()).not.toContain('旧镜头人物')
expect(button('读取生成规格').disabled).toBe(true)
})
it('提示词必须确认才 POST,使用正式 Shot ID,返回内容以纯文本显示', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (_url, init) =>
init?.method !== 'POST'
? jsonResponse({ shotId: 'shot-db-1-1', references: [], missing: [] })
: new Response(
JSON.stringify({
data: {
shotId: 'shot-db-1-1',
updatedAt: '2026-09-10T00:00:00Z',
videoPrompt: '<script>模型内容</script>',
negativePrompt: '模糊',
status: 'prompt_ready'
}
})
)
)
stubFetch(fetcher)
wrapper = mount(ShotTools, {
attachTo: document.body,
props: { projectId: fixture.id, shot: designedShot(), disabled: false }
})
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
await confirmGeneration('读取/生成提示词')
const post = fetcher.mock.calls.find(([, init]) => init?.method === 'POST')!
expect(post[0]).toBe('/api/storyboard-shots/shot-db-1-1/video-prompt')
expect(JSON.parse(post[1]!.body as string)).toEqual({ force: false })
expect(wrapper.text()).toContain('<script>模型内容</script>')
expect(wrapper.find('script').exists()).toBe(false)
})
it('提示词生成缺少主首帧时保存当前剧集和镜头作为恢复位置', async () => {
stubFetch(
vi.fn<typeof fetch>().mockResolvedValue(
new Response(
JSON.stringify({
message: '服务器内部错误 Shot 缺少可用于视频 0 秒起点校验的 Primary Keyframe: shot-db-1-1'
}),
{ status: 500 }
)
)
)
wrapper = mount(ShotTools, {
attachTo: document.body,
props: { projectId: fixture.id, episodeNo: 1, shot: designedShot(), disabled: false }
})
await confirmGeneration('读取/生成提示词')
expect(getOperation(fixture.id).recovery).toEqual({
target: 'keyframe',
shotId: 'shot-db-1-1',
episodeNo: 1
})
})
it('项目筛选无结果时可清除条件并返回真实列表', async () => {
stubFetch(
vi.fn<typeof fetch>().mockImplementation(async () => new Response(JSON.stringify({ data: [fixture] })))
)
const router = createRouter({
history: createMemoryHistory(),
routes: [{ path: '/', component: ProjectsPage }]
})
await router.push('/')
wrapper = mount(ProjectsPage, { attachTo: document.body, global: { plugins: [router] } })
await flushPromises()
expect(wrapper.getComponent(NRadioGroup).props('size')).toBe('medium')
expect(wrapper.text()).toContain('雨夜来信')
await wrapper.get('input[aria-label="搜索项目"]').setValue('不存在的关键词')
expect(wrapper.text()).toContain('没有匹配的剧本')
button('清除筛选').click()
await flushPromises()
expect(wrapper.findAll('tbody tr')).toHaveLength(1)
})
it('新建弹窗提交真实参数并返回 202 的项目 ID', async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValue(
new Response('{"projectId":"created","executionId":"create-1","status":"pending"}', { status: 202 })
)
stubFetch(fetcher)
wrapper = mount(CreateProjectDialog, { attachTo: document.body })
button('新建剧本').click()
await flushPromises()
const title = document.querySelector<HTMLInputElement>('#title')!
title.value = ' 雨夜来信标题 '
title.dispatchEvent(new Event('input', { bubbles: true }))
const topic = document.querySelector<HTMLTextAreaElement>('#topic')!
topic.value = ' 雨夜来信 '
topic.dispatchEvent(new Event('input', { bubbles: true }))
const count = document.querySelector<HTMLInputElement>('#episode-count')!
count.value = '6'
count.dispatchEvent(new Event('input', { bubbles: true }))
document.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))
await flushPromises()
expect(wrapper.emitted('created')).toEqual([['created', 'create-1']])
expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual({
title: '雨夜来信标题',
topic: '雨夜来信',
style: '',
episodeCount: 6
})
})
it('修改每组集数会废弃预览,重新预览并确认后才能启动', async () => {
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}}'
)
return new Response('{"data":{"workflowExecution":{"status":"completed"}}}')
})
stubFetch(fetcher)
const provided = context()
wrapper = mount(BreakdownPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: provided } }
})
await expandSections()
button('预览分组').click()
await flushPromises()
expect(button('开始拆解').disabled).toBe(false)
await drawerPanel().get('#group-size').setValue('2')
expect(document.body.textContent).not.toContain('开始拆解')
button('预览分组').click()
await flushPromises()
button('开始拆解').click()
await flushPromises()
button('确认开始拆解').click()
await flushPromises()
const post = fetcher.mock.calls.find(call => call[1]?.method === 'POST')
expect(post?.[0]).toBe('/api/projects/page-test-project/breakdown/start')
expect(JSON.parse(post![1]!.body as string)).toEqual({ groupSize: 2, modules: ['character', 'scene', 'prop'] })
expect(provided.refresh).toHaveBeenCalledOnce()
})
it('切换剧本标签保留阅读容器和位置,右侧只保留直接导出', async () => {
wrapper = mount(CreateDramaPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context() }, stubs: { RouterLink: true } }
})
const suffix = wrapper.get('.script-section .n-tabs-nav__suffix')
expect(suffix.findAll('button').map(item => item.text())).toEqual([''])
expect(suffix.get('button').attributes('aria-label')).toBe('导出剧本')
expect(suffix.get('button').classes()).toContain('icon-button')
expect(suffix.findAll('svg')).toHaveLength(1)
expect(suffix.get('svg').attributes('width')).toBe('18')
expect(suffix.find('router-link-stub').exists()).toBe(false)
expect(suffix.text()).not.toContain('进入拆解')
const reader = wrapper.get<HTMLElement>('.reader-scroll .n-scrollbar-container').element
reader.scrollTop = 120
expect(wrapper.find('.history-panel').exists()).toBe(false)
await wrapper
.findAll('.n-tabs-tab')
.find(item => item.text() === '角色设定')!
.trigger('click')
expect(wrapper.get('.episode-reader').isVisible()).toBe(false)
await wrapper
.findAll('.n-tabs-tab')
.find(item => item.text().includes('剧集正文'))!
.trigger('click')
expect(wrapper.get('.episode-reader').isVisible()).toBe(true)
expect(wrapper.get('.reader-scroll .n-scrollbar-container').element).toBe(reader)
expect(reader.scrollTop).toBe(120)
expect(wrapper.find('.history-panel').exists()).toBe(false)
expect(wrapper.text()).not.toContain('执行记录')
})
it('剧本文本按纯文本显示,不执行模型输出的 HTML', () => {
wrapper = mount(CreateDramaPage, {
attachTo: document.body,
global: { provide: { [projectContextKey as symbol]: context() }, stubs: { RouterLink: true } }
})
expect(wrapper.find('.script-body').text()).toContain('<script>不要执行模型内容</script>')
expect(wrapper.find('.script-body script').exists()).toBe(false)
})
})