feat(short-drama-agent-front): 补齐后端生产与质量功能

This commit is contained in:
GJ committed 2026-10-08 18:28:35 +08:00
1 parent 967c4ebea1
commit 470b52e26d
52 files changed
+3754 -1075

No files matched your search

@@ -0,0 +1,60 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { productionApi } from '@/features/production/api'
import { validateProductionScope } from '@/features/production/useAdvancedProduction'
import type { ProductionStartInput } from '@/features/production/types'
afterEach(() => vi.unstubAllGlobals())
describe('生产后端真实请求契约', () => {
it('计划使用 POST JSON 并将图片参数与启动保持同源', async () => {
const fetchMock = vi
.fn<typeof fetch>()
.mockImplementation(async () => new Response(JSON.stringify({ data: { projectId: 'p' } })))
vi.stubGlobal('fetch', fetchMock)
const input: ProductionStartInput = {
imageProvider: 'qwen-image',
imageGenerationOptions: { size: '1024*1024', seed: 3 },
videoProvider: 'wan',
startFrom: 'subjectImages',
stopAfter: 'videoPrompts',
stableIdentityAnchorLimit: 1,
subjectImageLimit: 2,
keyframeLimit: 3,
videoPromptLimit: 4
}
const controller = new AbortController()
await productionApi.plan('p', controller.signal, input)
await productionApi.startPipeline('p', input)
expect(fetchMock.mock.calls[0]?.[0]).toBe('/api/projects/p/production/plan')
expect(fetchMock.mock.calls[1]?.[0]).toBe('/api/projects/p/production/start')
for (const [, request] of fetchMock.mock.calls) {
expect(request?.method).toBe('POST')
expect(JSON.parse(String(request?.body))).toEqual(input)
}
expect(fetchMock.mock.calls[0]?.[1]?.signal).toBeInstanceOf(AbortSignal)
})
it('409 携带现有 executionId 且封装不重试', async () => {
const fetchMock = vi.fn<typeof fetch>().mockImplementation(
async () =>
new Response(JSON.stringify({ message: '已有任务', details: { executionId: 'existing' } }), {
status: 409
})
)
vi.stubGlobal('fetch', fetchMock)
await expect(productionApi.startPipeline('p')).rejects.toMatchObject({
status: 409,
details: { executionId: 'existing' }
})
expect(fetchMock).toHaveBeenCalledTimes(1)
})
it('拒绝反向阶段、零值和非整数,支持主体图片结束阶段', () => {
expect(validateProductionScope({ startFrom: 'videoPrompts', stopAfter: 'subjectImages' })).toContain('结束阶段')
expect(validateProductionScope({ subjectImageLimit: 0 })).toContain('整数')
expect(validateProductionScope({ stableIdentityAnchorLimit: 1.5 })).toContain('整数')
expect(
validateProductionScope({ startFrom: 'subjectImages', stopAfter: 'subjectImages', videoPromptLimit: 1 })
).toBe('')
})
})
@@ -28,7 +28,7 @@ afterEach(() => {
}
})
/** 所有预检均是模拟 GET;生成接口只记录契约,不调用真实 Provider。 */
/** 预检支持正式 POST plan;付费启动单独计数,不调用真实 Provider。 */
function stageFixture() {
return { total: 1, planned: 1, skipped: 0, upstreamResolvable: 0, manualBlocked: 0 }
}
@@ -147,7 +147,10 @@ function server() {
plan,
status,
fetcher,
posts: () => fetcher.mock.calls.filter(([, init]) => init?.method === 'POST')
posts: () =>
fetcher.mock.calls.filter(
([url, init]) => init?.method === 'POST' && !String(url).endsWith('/production/plan')
)
}
}
@@ -0,0 +1,85 @@
import { describe, expect, it, vi, afterEach } from 'vitest'
import { qualityApi } from '@/features/production/quality-api'
import {
qualityTargets,
parseKeyframeValidationOutput,
isQualityBatchResult,
qualityKey
} from '@/features/production/quality'
import type { KeyframeReadiness } from '@/features/production/types'
/** 契约测试仅使用本地模拟数据,不调用生成服务。 */
afterEach(() => vi.unstubAllGlobals())
describe('首帧质量正式后端契约', () => {
it('202 只表示后台开始且保留单镜头模型参数', async () => {
const fetcher = vi
.fn<typeof fetch>()
.mockResolvedValue(
new Response(
JSON.stringify({ data: { executionId: 'exec', projectId: 'p', status: 'running', total: 1 } }),
{ status: 202 }
)
)
vi.stubGlobal('fetch', fetcher)
const result = await qualityApi.generate('p', {
concurrency: 1,
maxRepairAttempts: 2,
force: true,
episodeNo: 2,
limit: 1,
shotId: 's',
provider: 'image-provider',
generationOptions: { quality: 'high' }
})
expect(result.executionId).toBe('exec')
expect(isQualityBatchResult(result)).toBe(false)
expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toMatchObject({
shotId: 's',
limit: 1,
provider: 'image-provider',
generationOptions: { quality: 'high' }
})
})
it('就绪项按集和镜头筛选,不因其他集过期漏掉缺失项', () => {
const readiness = {
stalePrimaryKeyframe: 1,
items: [
{ shotId: 's', episodeNo: 2, status: 'ready' },
{ shotId: 'other', episodeNo: 1, status: 'ready', primaryKeyframeStale: true }
]
} as KeyframeReadiness
expect(
qualityTargets(readiness, {
concurrency: 1,
maxRepairAttempts: 1,
force: false,
episodeNo: 2,
limit: 1,
shotId: 's'
}).map(item => item.shotId)
).toEqual(['s'])
expect(qualityKey('p', { kind: 'batch', episodeNo: 2, shotId: 's', title: '' })).not.toBe(
qualityKey('p', { kind: 'batch', episodeNo: 2, title: '' })
)
})
it('历史输出 JSON 必须具有真实结论,原始数据不冒充通过', () => {
const validation = {
passed: false,
summary: '缺少主体',
subjects: [],
subjectCountConsistent: false,
unauthorizedText: { detected: false, texts: [] },
issues: []
}
expect(parseKeyframeValidationOutput(JSON.stringify(validation))).toEqual(validation)
expect(parseKeyframeValidationOutput('{"raw":"PASS"}')).toBeNull()
expect(parseKeyframeValidationOutput('invalid')).toBeNull()
})
it('历史接口转义目标并传递取消信号', async () => {
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({ data: [] })))
vi.stubGlobal('fetch', fetcher)
await qualityApi.keyframeHistory('s/a', 'k/b', new AbortController().signal)
expect(fetcher.mock.calls[0]![0]).toBe('/api/storyboard-shots/s%2Fa/keyframes/k%2Fb/validations')
expect(fetcher.mock.calls[0]![1]?.signal).toBeInstanceOf(AbortSignal)
})
})
+97 -6
View File
@@ -5,6 +5,7 @@ import { NCheckbox, NInputNumber, NRadioGroup } from 'naive-ui'
import { testProjectContext } from '@/testing/project-context'
import { productionApi } from '@/features/production/api'
import { qualityApi } from '@/features/production/quality-api'
import { generationConfigApi } from '@/features/generation-config/api'
import {
allowedTextLines,
qualityKey,
@@ -108,12 +109,16 @@ function server() {
missingReference: 0,
results: [{ shotId: 'shot-1', success: true, status: 'passed' as const }]
}
const executionState = { status: 'completed' as 'running' | 'completed' | 'failed' }
let batchMetadata: QualityInput | null = null
const fetcher = vi.fn<typeof fetch>().mockImplementation(async (url, options) => {
const path = String(url)
let data: unknown
if (options?.method === 'POST') {
if (path.endsWith('/generate-quality')) data = batch
else if (path.includes('/videos/') && path.endsWith('/repair'))
if (path.endsWith('/generate-quality')) {
batchMetadata = JSON.parse(String(options.body)) as QualityInput
data = { executionId: `exec-${projectId}`, projectId, status: 'running', total: 1 }
} else if (path.includes('/videos/') && path.endsWith('/repair'))
data = {
shotId: 'shot-1',
sourceVideoId: 'video-1',
@@ -142,6 +147,19 @@ function server() {
}
else data = keyframeResult
} else if (path.endsWith(`/projects/${projectId}`)) data = project
else if (path.includes('/workflow-executions/'))
data = {
id: `exec-${projectId}`,
projectId,
workflowName: 'keyframe-quality',
status: executionState.status,
stage: 'keyframe_quality',
current: 1,
total: 1,
metadata: batchMetadata,
result: batch,
error: null
}
else if (path.endsWith('/checkpoints')) data = []
else if (path.includes('/readiness')) data = readiness
else if (path.endsWith('/keyframes')) data = [keyframe]
@@ -170,6 +188,7 @@ function server() {
keyframeResult,
repair,
batch,
executionState,
fetcher,
posts: () => fetcher.mock.calls.filter(([, options]) => options?.method === 'POST')
}
@@ -301,13 +320,54 @@ describe('视觉质量契约与付费边界', () => {
expect(wrapper.emitted('locate')).toEqual([['shot-1']])
})
it('过期优先级与后端一致,当前集无过期项时不误补其他镜头', async () => {
it('后台开始不显示最终通过,关闭切目标后完成仍归原镜头且刷新能恢复', async () => {
const original: QualityTarget = { kind: 'batch', episodeNo: 1, shotId: 'shot-1', title: '原镜头' }
const data = setup(original)
data.executionState.status = 'running'
await data.service.run('batch', input({ shotId: 'shot-1', limit: 1 }))
expect(data.service.session.value.receipt).toBeNull()
expect(data.service.blocked.value).toBe(true)
const postCount = data.posts().length
await data.service.run('batch', input({ shotId: 'shot-1' }))
expect(data.posts()).toHaveLength(postCount)
data.visible.value = false
data.props.target = { kind: 'batch', episodeNo: 2, title: '其他集' }
await flushPromises()
data.executionState.status = 'completed'
await data.service.execution.query.refresh()
await flushPromises()
expect(data.service.session.value.receipt).toBeNull()
expect(qualitySession(qualityKey(data.projectId, original)).receipt).toMatchObject({
kind: 'batch',
result: { passed: 1 }
})
wrapper!.unmount()
let restored!: ReturnType<typeof useQuality>
wrapper = mount(
defineComponent({
setup() {
restored = useQuality(
data.props,
() => false,
() => {}
)
return () => null
}
})
)
await flushPromises()
expect(restored.execution.executionId.value).toBe(`exec-${data.projectId}`)
expect(restored.execution.query.data.value?.status).toBe('completed')
expect(data.posts()).toHaveLength(postCount)
})
it('按真实后端 ready 列表处理本集缺失与过期项', async () => {
const data = setup({ kind: 'batch', episodeNo: 1, title: '第一集' })
data.readiness.stalePrimaryKeyframe = 1
expect(qualityTargets(data.readiness, input())).toHaveLength(0)
expect(qualityTargets(data.readiness, input())).toHaveLength(1)
await data.service.run('batch', input())
expect(data.posts()).toHaveLength(0)
expect(data.service.session.value.error).toContain('切换剧集')
expect(data.posts()).toHaveLength(1)
expect(data.service.session.value.error).toBe('')
expect(qualityTargets(data.readiness, input({ force: true }))).toHaveLength(1)
})
@@ -401,6 +461,37 @@ describe('质量面板渐进展示', () => {
it('批量默认当前集一镜,调整次数撤销费用确认', async () => {
const data = server()
// 明确的项目配置与启用模型;不能依靠缺失配置进入付费确认。
vi.spyOn(generationConfigApi, 'catalog').mockResolvedValue({
defaults: { imageProvider: 'qwen-image', videoProvider: 'wan' },
images: [
{
type: 'image',
provider: 'qwen-image',
providerLabel: 'Qwen',
model: 'qwen-model',
modelLabel: 'Qwen Model',
supported: true,
enabled: true,
isDefault: true,
capabilities: {},
generationOptions: [],
defaults: {},
projectConstraints: []
}
],
videos: []
})
vi.spyOn(generationConfigApi, 'profile').mockResolvedValue({
projectId: data.projectId,
aspectRatio: '9:16',
imageProvider: 'qwen-image',
imageModel: 'qwen-model',
imageOptions: {},
videoProvider: 'wan',
videoModel: 'wan-model',
videoOptions: {}
})
wrapper = mount(QualityDialog, {
attachTo: document.body,
props: {