feat(short-drama-agent-front): 接入素材预览审核并完善创作流程

This commit is contained in:
GJ committed 2026-11-02 10:16:10 +08:00
1 parent f8b0fbb8ca
commit dc8bb17a23
66 files changed
+2864 -632

No files matched your search

@@ -203,7 +203,7 @@ describe('过期首帧到具体素材定位', () => {
})
const card = wrapper!.findAll('.form-image-card').find(item => item.attributes('data-form-id') === first.id)!
expect(card.get('.asset-image').classes()).not.toContain('form-image-has-source')
expect(card.get('.asset-image-empty').text()).toContain('确认并锁定身份母版后自动复用')
expect(card.get('.asset-image-empty').text()).toContain('请先确认并锁定身份母版')
expect(card.find('img').exists()).toBe(false)
})
@@ -224,7 +224,7 @@ describe('过期首帧到具体素材定位', () => {
.get('.gallery-layout-switch')
.findAll('button')
.map(button => button.attributes('aria-label'))
).toEqual(['网格布局', '瀑布流布局', '批量生图'])
).toEqual(['图片准备检查', '网格布局', '瀑布流布局', '批量生图'])
await wrapper!.get('[aria-label="网格布局"]').trigger('click')
expect(wrapper!.find('.form-image-masonry').exists()).toBe(false)
expect(wrapper!.get('[aria-label="网格布局"]').attributes('aria-pressed')).toBe('true')
@@ -0,0 +1,147 @@
import { defineComponent, ref } from 'vue'
import { mount, flushPromises, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { ApiError } from '@/lib/http'
import { useImageGenerationPreview, type ImageGenerationSubmission } from '@/features/subject-images/generation-preview'
import { imagePreviewFixture } from '../../fixtures/image-preview'
/** 仅挂载实际状态逻辑,所有请求均为无费用替身。 */
let wrapper: VueWrapper | undefined
/** 每个用例释放监听与未完成预览。 */
afterEach(() => wrapper?.unmount())
/**
* 建立受控表单,测试确认、版本和异步边界。
* @param generate 生成请求的确定性替身
* @param load 只读预览的确定性替身
* @returns 表单状态及真实共用逻辑
*/
function setup(
generate = vi.fn<() => Promise<ImageGenerationSubmission>>(
async (): Promise<ImageGenerationSubmission> => ({ accepted: true })
),
load = vi.fn<() => Promise<ReturnType<typeof imagePreviewFixture>>>(async () => imagePreviewFixture())
) {
const open = ref(true),
prompt = ref('初始描述')
let flow!: ReturnType<typeof useImageGenerationPreview<{ prompt: string }, ReturnType<typeof imagePreviewFixture>>>
wrapper = mount(
defineComponent({
setup() {
flow = useImageGenerationPreview({
open,
target: () => 'form-1',
input: () => ({ prompt: prompt.value }),
disabled: () => false,
load,
generate
})
return () => null
}
})
)
return { flow, open, prompt, generate, load }
}
describe('生图预览与版本确认', () => {
it('预览成功且确认后才携带版本提交,修改描述立即清除旧确认', async () => {
const { flow, prompt, generate } = setup()
flow.acknowledged.value = true
await flow.submit()
expect(generate).not.toHaveBeenCalled()
await flow.loadPreview()
flow.acknowledged.value = true
prompt.value = '新描述'
expect(flow.preview.value).toBeNull()
expect(flow.acknowledged.value).toBe(false)
await flow.loadPreview()
flow.acknowledged.value = true
await flow.submit()
expect(generate).toHaveBeenCalledExactlyOnceWith({
prompt: '新描述',
expectedPreviewFingerprint: 'a'.repeat(64)
})
})
it('明确的预览过期 409 只重新预览,不自动重复收费请求', async () => {
const generate = vi.fn<() => Promise<ImageGenerationSubmission>>(async () => ({
accepted: false,
cause: new ApiError('过期', 409, undefined, 'IMAGE_PREVIEW_STALE')
}))
const { flow, open, load } = setup(generate)
await flow.loadPreview()
flow.acknowledged.value = true
await flow.submit()
expect(open.value).toBe(true)
expect(load).toHaveBeenCalledTimes(2)
expect(generate).toHaveBeenCalledOnce()
expect(flow.acknowledged.value).toBe(false)
expect(flow.canSubmit.value).toBe(false)
expect(flow.staleNotice.value).toContain('重新确认')
})
it('普通 409 和未知网络结果均不自动预览或重新提交', async () => {
const { flow, load, generate } = setup(
vi.fn<() => Promise<ImageGenerationSubmission>>(async () => ({
accepted: false,
cause: new ApiError('活动任务冲突', 409)
}))
)
await flow.loadPreview()
flow.acknowledged.value = true
await flow.submit()
expect(load).toHaveBeenCalledOnce()
expect(generate).toHaveBeenCalledOnce()
expect(flow.error.value).toContain('活动任务')
expect(flow.acknowledged.value).toBe(false)
})
it('关闭再打开相同参数后,旧预览响应不得回填', async () => {
let resolve!: (value: ReturnType<typeof imagePreviewFixture>) => void
const { flow, open } = setup(
undefined,
vi.fn<() => Promise<ReturnType<typeof imagePreviewFixture>>>(
() =>
new Promise(done => {
resolve = done
})
)
)
const request = flow.loadPreview()
open.value = false
open.value = true
resolve(imagePreviewFixture())
await request
expect(flow.preview.value).toBeNull()
expect(flow.loading.value).toBe(false)
})
it('提交期间重复点击不会重复创建任务,参数变化后不关闭新表单', async () => {
let resolve!: (value: ImageGenerationSubmission) => void
const generate = vi.fn<() => Promise<ImageGenerationSubmission>>(
() =>
new Promise<ImageGenerationSubmission>(done => {
resolve = done
})
)
const { flow, prompt, open } = setup(generate)
await flow.loadPreview()
flow.acknowledged.value = true
const request = flow.submit()
await flow.submit()
expect(generate).toHaveBeenCalledOnce()
prompt.value = '另一个目标的草稿'
resolve({ accepted: true })
await request
expect(open.value).toBe(true)
})
it('缺失预览版本不能被确认成有效输入', async () => {
const { flow } = setup(
undefined,
vi.fn<() => Promise<ReturnType<typeof imagePreviewFixture>>>(async () => ({
...imagePreviewFixture(),
previewFingerprint: ''
}))
)
await flow.loadPreview()
await flushPromises()
expect(flow.preview.value).toBeNull()
expect(flow.error.value).toContain('不完整')
})
})
+77 -12
View File
@@ -1,6 +1,7 @@
import { imagePreviewFixture } from '../../fixtures/image-preview'
import { imageCatalog, generationProfile } from '../../fixtures/generation'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { AssetImage } from '@/components/ui'
import { getOperation } from '@/features/workflows/operations'
import GenerateImageDialog from '@/features/subject-images/components/GenerateImageDialog.vue'
@@ -11,6 +12,8 @@ import { expandSections } from '@/testing/naive'
/** 当前测试使用真实目录契约构造项目模型配置。 */
const creativeProfile = generationProfile('gallery-test')
/** 生成提交由测试替身接收,绝不调用真实模型。 */
const submitGeneration = vi.fn<() => Promise<{ accepted: boolean }>>(async () => ({ accepted: true }))
let wrapper: VueWrapper | undefined
/** Naive 将弹窗挂载到 body,需要从实际弹窗找到按钮。 */
function button(label: string): HTMLButtonElement {
@@ -18,7 +21,18 @@ function button(label: string): HTMLButtonElement {
if (!element) throw new Error('找不到按钮:' + label)
return element
}
/** 每次生成用例只返回无副作用的预览夹具。 */
beforeEach(() =>
vi.stubGlobal(
'fetch',
vi.fn<typeof fetch>().mockImplementation(async url => {
const formId = String(url).match(/subject-forms\/([^/]+)/)?.[1] ?? 'form-db-1'
return new Response(JSON.stringify({ data: imagePreviewFixture(formId) }))
})
)
)
afterEach(() => {
submitGeneration.mockClear()
wrapper?.unmount()
wrapper = undefined
document.body.innerHTML = ''
@@ -70,10 +84,17 @@ describe('形态图片选择与操作', () => {
form.subject.module = module
wrapper = mount(GenerateImageDialog, {
attachTo: document.body,
props: { open: true, form, disabled: false, catalog: imageCatalog, profile: creativeProfile }
props: {
submitGeneration,
open: true,
form,
disabled: false,
catalog: imageCatalog,
profile: creativeProfile
}
})
await flushPromises()
expect(document.body.textContent).toContain('母版')
expect(document.body.textContent).toContain('质量审核')
expect(document.body.textContent).not.toContain('道具形态生图暂不自动引用')
})
it('按需预览正式形态的实际参考图和 Provider Prompt,不触发生图事件', async () => {
@@ -81,6 +102,7 @@ describe('形态图片选择与操作', () => {
new Response(
JSON.stringify({
data: {
...imagePreviewFixture(),
subjectFormId: 'form-db-1',
provider: 'seedream',
model: 'image-model',
@@ -101,7 +123,14 @@ describe('形态图片选择与操作', () => {
vi.stubGlobal('fetch', fetcher)
wrapper = mount(GenerateImageDialog, {
attachTo: document.body,
props: { open: true, form: formFixture(), disabled: false, catalog: imageCatalog, profile: creativeProfile }
props: {
submitGeneration,
open: true,
form: formFixture(),
disabled: false,
catalog: imageCatalog,
profile: creativeProfile
}
})
await flushPromises()
button('预览实际生成输入').click()
@@ -142,30 +171,56 @@ describe('形态图片选择与操作', () => {
it('生图确认发送正式形态 ID 和项目模型参数,默认不替换已有主图', async () => {
wrapper = mount(GenerateImageDialog, {
attachTo: document.body,
props: { open: true, form: formFixture(), disabled: false, catalog: imageCatalog, profile: creativeProfile }
props: {
submitGeneration,
open: true,
form: formFixture(),
disabled: false,
catalog: imageCatalog,
profile: creativeProfile
}
})
await flushPromises()
expect(button('确认生成图片').disabled).toBe(true)
button('预览实际生成输入').click()
await flushPromises()
document.querySelector<HTMLInputElement>('#confirm-image-cost')!.click()
await flushPromises()
button('确认生成图片').click()
await flushPromises()
expect(wrapper.emitted('generate')).toEqual([
['form-db-1', { setPrimary: false, provider: 'qwen-image', generationOptions: { size: '2048*2048' } }]
expect(submitGeneration.mock.calls).toEqual([
[
'form-db-1',
{
setPrimary: false,
expectedPreviewFingerprint: 'a'.repeat(64),
provider: 'qwen-image',
generationOptions: { size: '2048*2048' }
}
]
])
})
it('新形态默认设主图并继承目录尺寸,切换形态清空提示词和费用确认', async () => {
it('新形态默认保留候选并继承目录尺寸,切换形态清空提示词和确认', async () => {
const form = formFixture()
form.images = []
wrapper = mount(GenerateImageDialog, {
attachTo: document.body,
props: { open: true, form, disabled: false, catalog: imageCatalog, profile: creativeProfile }
props: {
submitGeneration,
open: true,
form,
disabled: false,
catalog: imageCatalog,
profile: creativeProfile
}
})
await flushPromises()
const prompt = document.querySelector<HTMLTextAreaElement>('#image-prompt')!
prompt.value = '上一形态自定义提示词'
prompt.dispatchEvent(new Event('input', { bubbles: true }))
button('预览实际生成输入').click()
await flushPromises()
document.querySelector<HTMLInputElement>('#confirm-image-cost')!.click()
await flushPromises()
expect(button('确认生成图片').disabled).toBe(false)
@@ -176,12 +231,22 @@ describe('形态图片选择与操作', () => {
expect(document.querySelector('#image-width')).toBeNull()
expect(document.querySelector('#image-height')).toBeNull()
expect(document.querySelector('#confirm-image-cost')!.getAttribute('aria-checked')).toBe('false')
button('预览实际生成输入').click()
await flushPromises()
document.querySelector<HTMLInputElement>('#confirm-image-cost')!.click()
await flushPromises()
button('确认生成图片').click()
await flushPromises()
expect(wrapper.emitted('generate')).toEqual([
['form-db-2', { setPrimary: true, provider: 'qwen-image', generationOptions: { size: '2048*2048' } }]
expect(submitGeneration.mock.calls).toEqual([
[
'form-db-2',
{
setPrimary: false,
expectedPreviewFingerprint: 'a'.repeat(64),
provider: 'qwen-image',
generationOptions: { size: '2048*2048' }
}
]
])
})
@@ -223,7 +288,7 @@ describe('形态图片选择与操作', () => {
button('设为主参考图').click()
await flushPromises()
expect(fetcher.mock.calls).toHaveLength(1)
button('确认切换主图').click()
button('确认费用并设为主图').click()
await flushPromises()
expect(fetcher.mock.calls.find(([, init]) => init?.method === 'PUT')?.[0]).toBe(
'/api/subject-forms/form-db-1/images/image-db-1/primary'
+14 -6
View File
@@ -13,6 +13,8 @@ import GenerateImageDialog from '@/features/subject-images/components/GenerateIm
/** 当前测试使用真实目录契约构造项目模型配置。 */
const creativeProfile = generationProfile('gallery-test')
/** 生成提交由测试替身接收,绝不调用真实模型。 */
const submitGeneration = vi.fn<() => Promise<{ accepted: boolean }>>(async () => ({ accepted: true }))
let wrapper: VueWrapper | undefined
const projectId = 'capability-test'
/** 从实际挂载的确认弹窗查找操作按钮。 */
@@ -20,6 +22,7 @@ function find(label: string) {
return [...document.querySelectorAll('button')].find(item => item.textContent?.trim() === label)!
}
afterEach(() => {
submitGeneration.mockClear()
wrapper?.unmount()
wrapper = undefined
document.body.innerHTML = ''
@@ -180,13 +183,20 @@ describe('形态正式提示词与批量配置', () => {
await flushPromises()
expect(wrapper.emitted('generate')).toEqual([['form-db-1', false]])
})
it('缺少正式和原始提示词仍可确认生图,由后端补齐而非前端编造', async () => {
it('未取得有效预览时不允许直接生图,不代为补齐资料', async () => {
const form = formFixture()
form.appearancePrompt = null
form.generationPrompt = null
wrapper = mount(GenerateImageDialog, {
attachTo: document.body,
props: { open: true, disabled: false, form, catalog: imageCatalog, profile: creativeProfile }
props: {
submitGeneration,
open: true,
disabled: false,
form,
catalog: imageCatalog,
profile: creativeProfile
}
})
await flushPromises()
document.querySelector<HTMLElement>('#confirm-image-cost')!.click()
@@ -194,11 +204,9 @@ describe('形态正式提示词与批量配置', () => {
const submit = [...document.querySelectorAll('button')].find(
item => item.textContent?.trim() === '确认生成图片'
)!
expect(submit.disabled).toBe(false)
expect(submit.disabled).toBe(true)
submit.click()
await flushPromises()
expect(wrapper.emitted('generate')).toEqual([
['form-db-1', { setPrimary: false, provider: 'qwen-image', generationOptions: { size: '2048*2048' } }]
])
expect(submitGeneration).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,160 @@
import { mount, flushPromises, type VueWrapper } from '@vue/test-utils'
import { afterEach, describe, expect, it, vi } from 'vitest'
import ImageGalleryDialog from '@/features/subject-images/components/ImageGalleryDialog.vue'
import { getOperation } from '@/features/workflows/operations'
import { formFixture, imageFixture } from '@/features/subject-images/testing/fixtures'
import { subjectImagesApi } from '@/features/subject-images/api'
/** 当前测试挂载的图库。 */
let wrapper: VueWrapper | undefined
/** 清理测试请求、活动锁和弹层。 */
afterEach(() => {
wrapper?.unmount()
document.body.innerHTML = ''
vi.unstubAllGlobals()
Object.assign(getOperation('quality-flow'), { pending: false, cause: null, error: '', notice: '' })
})
/**
* 根据中文名称选择真实确认按钮。
* @param label 完整按钮文本
* @returns 原生按钮
*/
function button(label: string) {
const value = [...document.querySelectorAll('button')].find(item => item.textContent?.trim() === label)
if (!value) throw new Error(`缺少按钮 ${label}`)
return value
}
describe('候选质量与主图门禁', () => {
it('completed 但质量失败的候选保留,GET 不切主图,审核不自动采纳', async () => {
const original = imageFixture({ id: 'old' })
const candidate = imageFixture({
id: 'candidate',
isPrimary: false,
qualityPassed: false,
qualityIssues: [{ type: 'form_mismatch', severity: 'error', description: '原始数量不一致' }]
})
const fetcher = vi.fn<typeof fetch>().mockImplementation(
async (_url, init) =>
new Response(
JSON.stringify({
data:
init?.method === 'POST'
? {
subjectId: 'subject-db-1',
subjectFormId: 'form-db-1',
imageId: 'candidate',
passed: false,
sourceRequirementsPassed: false,
sourceVisualRequirements: [],
summary: '需核对数量',
issues: []
}
: [candidate, original]
})
)
)
vi.stubGlobal('fetch', fetcher)
wrapper = mount(ImageGalleryDialog, {
attachTo: document.body,
props: { projectId: 'quality-flow', form: formFixture(), disabled: false, open: true }
})
await flushPromises()
document.querySelector<HTMLButtonElement>('[aria-label="查看图片 candidate"]')!.click()
await flushPromises()
expect(button('设为主参考图').disabled).toBe(true)
expect(document.body.textContent).toContain('质量未通过')
expect(fetcher.mock.calls.every(([, init]) => init?.method === 'GET')).toBe(true)
button('审核此图片').click()
await flushPromises()
expect(fetcher).toHaveBeenCalledOnce()
button('确认费用并审核').click()
await flushPromises()
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')).toHaveLength(1)
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'PUT')).toBe(false)
expect(original.isPrimary).toBe(true)
expect(document.body.textContent).toContain('需核对数量')
})
it('主图晋升 409 保留原主图,不乐观切换或自动重试', async () => {
const original = imageFixture({ id: 'old' })
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (_url, init) =>
init?.method === 'PUT'
? new Response(JSON.stringify({ message: '审核证据已过期,请明确重新审核' }), { status: 409 })
: new Response(
JSON.stringify({
data: [imageFixture({ id: 'candidate', isPrimary: false, qualityPassed: true }), original]
})
)
)
vi.stubGlobal('fetch', fetcher)
wrapper = mount(ImageGalleryDialog, {
attachTo: document.body,
props: { projectId: 'quality-flow', form: formFixture(), disabled: false, open: true }
})
await flushPromises()
document.querySelector<HTMLButtonElement>('[aria-label="查看图片 candidate"]')!.click()
await flushPromises()
button('设为主参考图').click()
await flushPromises()
button('确认费用并设为主图').click()
await flushPromises()
expect(fetcher.mock.calls.filter(([, init]) => init?.method === 'PUT')).toHaveLength(1)
expect(document.body.textContent).toContain('审核证据已过期')
expect(wrapper.emitted('changed')).toBeUndefined()
expect(original.isPrimary).toBe(true)
})
it('质量处理默认预算为零,只有明确确认后发出一次请求', async () => {
const image = imageFixture({ isPrimary: false })
const fetcher = vi.fn<typeof fetch>().mockImplementation(
async (_url, init) =>
new Response(
JSON.stringify({
data:
init?.method === 'POST'
? {
subjectFormId: 'form-db-1',
initialImageId: image.id,
finalImageId: image.id,
passed: false,
repaired: false,
repairAttempts: 0,
maxRepairAttempts: 0,
primaryChanged: false,
attempts: []
}
: [image]
})
)
)
vi.stubGlobal('fetch', fetcher)
wrapper = mount(ImageGalleryDialog, {
attachTo: document.body,
props: { projectId: 'quality-flow', form: formFixture(), disabled: false, open: true }
})
await flushPromises()
button('审核与修复').click()
await flushPromises()
expect(fetcher.mock.calls.some(([, init]) => init?.method === 'POST')).toBe(false)
expect(document.querySelector<HTMLInputElement>('#quality-repair-budget')?.value).toBe('0')
button('确认费用并执行').click()
await flushPromises()
const calls = fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')
expect(calls).toHaveLength(1)
expect(JSON.parse(calls[0]![1]!.body as string)).toEqual({
imageId: image.id,
provider: image.provider,
maxRepairAttempts: 0
})
expect(document.body.textContent).toContain('主图未切换')
})
it('预览携带尺寸与负面描述,结构准备只调用正式文字入口', async () => {
const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => new Response(JSON.stringify({ data: {} })))
vi.stubGlobal('fetch', fetcher)
const input = { width: 1024, height: 1024, negativePrompt: '不要额外配件', prompt: '原始要求' }
await subjectImagesApi.preview('form/1', input)
await subjectImagesApi.prepareStructure('form/1')
expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual(input)
expect(fetcher.mock.calls[1]![0]).toBe('/api/subject-forms/form%2F1/prop-structure-spec/generate')
expect(fetcher).toHaveBeenCalledTimes(2)
})
})
@@ -0,0 +1,70 @@
import { describe, expect, it } from 'vitest'
import {
imageValidationPassed,
sourceRequirementRows,
type ImageValidationResult
} from '@/features/subject-images/validation'
/**
* 原始定义与实际计数使用不同题材的确定性样例。
* @returns 当前主体审核记录
*/
function result(): ImageValidationResult {
return {
subjectId: 'subject',
imageId: 'image',
passed: true,
summary: '审核结束',
issues: [],
sourceRequirementsPassed: true,
sourceVisualRequirements: [
{
id: 'requirement',
subjectId: 'subject',
subjectName: '控制台',
sourceQuote: '控制台上有三个圆形按键',
quantities: [{ id: 'quantity', sourcePhrase: '三个圆形按键', expectedCount: 3 }]
}
],
sourceVisualRequirementResults: [
{
requirementId: 'requirement',
status: 'passed',
evidence: '图中可辨认三个按键',
quantities: [{ quantityId: 'quantity', observedCount: 3 }]
}
]
}
}
describe('原始定义与数量审核', () => {
it('只有原文、唯一审核结果与数量全部一致才显示通过', () => {
expect(imageValidationPassed(result())).toBe(true)
expect(sourceRequirementRows(result())[0]).toMatchObject({
sourceQuote: '控制台上有三个圆形按键',
label: '通过'
})
})
it.each(['missing', 'duplicate', 'unobservable', 'count', 'missing_quantity', 'duplicate_quantity'] as const)(
'%s 证据不完整时不信任顶层 passed',
kind => {
const value = result()
const item = value.sourceVisualRequirementResults![0]!
if (kind === 'missing') value.sourceVisualRequirementResults = []
if (kind === 'duplicate') value.sourceVisualRequirementResults!.push({ ...item })
if (kind === 'unobservable') item.status = 'unobservable'
if (kind === 'count') item.quantities![0]!.observedCount = 2
if (kind === 'missing_quantity') item.quantities = []
if (kind === 'duplicate_quantity') item.quantities!.push({ ...item.quantities![0]! })
expect(imageValidationPassed(value)).toBe(false)
}
)
it('无原始数量要求时不编造数量;旧审核缺少证据不标通过', () => {
const value = result()
value.sourceVisualRequirements = []
value.sourceVisualRequirementResults = []
expect(imageValidationPassed(value)).toBe(true)
delete value.sourceRequirementsPassed
expect(imageValidationPassed(value)).toBe(false)
})
})