feat(short-drama-agent-front): 补齐后端生产与质量功能
This commit is contained in:
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)
|
||||
})
|
||||
})
|
||||
@@ -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: {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { afterEach, describe, expect, expectTypeOf, it, vi } from 'vitest'
|
||||
import { storyboardApi } from '@/features/storyboard/api'
|
||||
import { productionApi } from '@/features/production/api'
|
||||
import type { WorkflowExecutionStart } from '@/features/workflows/execution.types'
|
||||
|
||||
/** 清除网络替身,保证边界用例相互隔离。 */
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
/** 既有批处理入口只接收真实 202 句柄,不产生最终回执或重复请求。 */
|
||||
describe('既有生成入口异步契约', () => {
|
||||
it('所有启动入口返回202句柄并保留原请求范围', async () => {
|
||||
const start = { executionId: 'execution-1', status: 'running' as const }
|
||||
const fetcher = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockImplementation(async () => new Response(JSON.stringify({ data: start }), { status: 202 }))
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
const batch = { concurrency: 2, force: false }
|
||||
const calls = [
|
||||
storyboardApi.regenerateEpisodeShots('project-1', 3),
|
||||
storyboardApi.generateDirections('project-1', batch),
|
||||
storyboardApi.generateVisualStates('project-1', { ...batch, maxRepairAttempts: 2 }),
|
||||
storyboardApi.generatePrompts('project-1', batch),
|
||||
productionApi.generateKeyframes('project-1', { ...batch, episodeNo: 3, limit: 1 })
|
||||
]
|
||||
for (const result of await Promise.all(calls)) expect(result).toEqual(start)
|
||||
expect(fetcher).toHaveBeenCalledTimes(5)
|
||||
expect(fetcher.mock.calls[0]?.[1]?.body).toBe(JSON.stringify({ episodeNo: 3 }))
|
||||
expect(fetcher.mock.calls[4]?.[1]?.body).toBe(JSON.stringify({ ...batch, episodeNo: 3, limit: 1 }))
|
||||
})
|
||||
it('启动类型与最终批量回执严格分开', () => {
|
||||
expectTypeOf<
|
||||
Awaited<ReturnType<typeof storyboardApi.regenerateEpisodeShots>>
|
||||
>().toEqualTypeOf<WorkflowExecutionStart>()
|
||||
expectTypeOf<
|
||||
Awaited<ReturnType<typeof storyboardApi.generateDirections>>
|
||||
>().toEqualTypeOf<WorkflowExecutionStart>()
|
||||
expectTypeOf<
|
||||
Awaited<ReturnType<typeof storyboardApi.generateVisualStates>>
|
||||
>().toEqualTypeOf<WorkflowExecutionStart>()
|
||||
expectTypeOf<
|
||||
Awaited<ReturnType<typeof storyboardApi.generatePrompts>>
|
||||
>().toEqualTypeOf<WorkflowExecutionStart>()
|
||||
expectTypeOf<
|
||||
Awaited<ReturnType<typeof productionApi.generateKeyframes>>
|
||||
>().toEqualTypeOf<WorkflowExecutionStart>()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,44 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
/** 重载保护测试后清理本地标记,避免影响其它测试。 */
|
||||
afterEach(() => localStorage.clear())
|
||||
import { currentEpisodeSource, getStoryboardSession, mergeDesignedShots } from '@/features/storyboard/model'
|
||||
import { directionsResult, episodeShots, visualStatesResult } from '@/features/storyboard/testing/fixtures'
|
||||
|
||||
describe('重生成后的正式镜头与旧正文隔离', () => {
|
||||
it('新正式镜头仍可操作,但不能回填已失效的旧标题、剧情和时长', () => {
|
||||
const projectId = 'regenerated-source-project'
|
||||
const session = getStoryboardSession(projectId)
|
||||
session.invalidatedEpisodeSources[1] = true
|
||||
const directions = directionsResult(projectId, 1, false)
|
||||
directions.beats[0]!.shots[0]!.shotId = 'new-shot-a'
|
||||
directions.beats[1]!.shots[0]!.shotId = 'new-shot-b'
|
||||
const rows = mergeDesignedShots(
|
||||
directions,
|
||||
visualStatesResult(projectId, 1, false),
|
||||
currentEpisodeSource(projectId, 1, episodeShots())
|
||||
)
|
||||
expect(
|
||||
rows
|
||||
.filter(row => row.shotId.startsWith('new-shot'))
|
||||
.map(row => [row.shotId, row.title, row.description, row.durationSeconds])
|
||||
).toEqual([
|
||||
['new-shot-a', '镜头 1', '', undefined],
|
||||
['new-shot-b', '镜头 1', '', undefined]
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
it('两集先后重生成后,即使任务句柄被隐藏,重载仍恢复全部失效正文保护', async () => {
|
||||
const module = await import('@/features/storyboard/model')
|
||||
const projectId = 'multi-episode-reload-project'
|
||||
module.invalidateEpisodeSource(projectId, 1)
|
||||
module.invalidateEpisodeSource(projectId, 2)
|
||||
localStorage.removeItem(`short-drama:workflow-execution:${projectId}:breakdown`)
|
||||
vi.resetModules()
|
||||
const restored = await import('@/features/storyboard/model')
|
||||
expect(restored.currentEpisodeSource(projectId, 1, episodeShots(1))).toBeUndefined()
|
||||
expect(restored.currentEpisodeSource(projectId, 2, episodeShots(2))).toBeUndefined()
|
||||
restored.clearEpisodeSourceInvalidations(projectId)
|
||||
expect(restored.currentEpisodeSource(projectId, 1, episodeShots(1))?.episodeNo).toBe(1)
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { subjectIdentityApi } from '@/features/subject-identity/api'
|
||||
|
||||
/** 每个契约用例完成后清理网络替身。 */
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
/** 验证正式身份路由和付费请求没有自动重试。 */
|
||||
describe('身份正式接口契约', () => {
|
||||
it('预览与实际生成传递相同参数,并支持取消预览', async () => {
|
||||
const fetcher = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockImplementation(async () => new Response(JSON.stringify({ data: {} }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
const input = {
|
||||
viewType: 'primary' as const,
|
||||
provider: 'qwen-image',
|
||||
generationOptions: { size: '2048*2048' },
|
||||
referenceImageId: 'image-1',
|
||||
prompt: '真实完整提示词'
|
||||
}
|
||||
await subjectIdentityApi.previewImage('subject-1', input, new AbortController().signal)
|
||||
await subjectIdentityApi.generateImage('subject-1', input)
|
||||
expect(fetcher.mock.calls[0]?.[0]).toContain('/subjects/subject-1/identity/images/preview')
|
||||
expect(fetcher.mock.calls[0]?.[1]?.body).toBe(JSON.stringify(input))
|
||||
expect(fetcher.mock.calls[1]?.[1]?.body).toBe(fetcher.mock.calls[0]?.[1]?.body)
|
||||
})
|
||||
it('校验指定正式图片,质量生成保留有限修复次数和模型参数', async () => {
|
||||
const fetcher = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockImplementation(async () => new Response(JSON.stringify({ data: {} }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
await subjectIdentityApi.validateImage('subject-1', 'image-1')
|
||||
const input = { maxRepairAttempts: 1, provider: 'qwen-image', generationOptions: { size: '2048*2048' } }
|
||||
await subjectIdentityApi.generateStableAnchorQuality('subject-1', input)
|
||||
expect(fetcher.mock.calls[0]?.[0]).toContain('/subjects/subject-1/identity/images/image-1/validate')
|
||||
expect(fetcher.mock.calls[1]?.[0]).toContain('/subjects/subject-1/identity/stable-anchor/generate-quality')
|
||||
expect(fetcher.mock.calls[1]?.[1]?.body).toBe(JSON.stringify(input))
|
||||
expect(fetcher).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,117 @@
|
||||
import { effectScope, ref } from 'vue'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { useWorkflowExecution } from '@/features/workflows/execution'
|
||||
import { workflowExecutionApi } from '@/features/workflows/execution-api'
|
||||
|
||||
/** 每个测试恢复句柄和网络依赖,避免项目任务泄漏到下一次验证。 */
|
||||
afterEach(() => {
|
||||
localStorage.clear()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('异步任务启动后的项目归属', () => {
|
||||
it('原项目的启动回执到达时,只保存原项目句柄,不切换当前项目的观察目标', async () => {
|
||||
const loader = vi.spyOn(workflowExecutionApi, 'get')
|
||||
const scope = effectScope()
|
||||
const projectId = ref('project-b')
|
||||
const execution = scope.run(() => useWorkflowExecution(projectId, 'production'))!
|
||||
await execution.track('execution-a', 'project-a')
|
||||
expect(localStorage.getItem('short-drama:workflow-execution:project-a:production')).toBe('execution-a')
|
||||
expect(localStorage.getItem('short-drama:workflow-execution:project-b:production')).toBeNull()
|
||||
expect(execution.executionId.value).toBe('')
|
||||
expect(loader).not.toHaveBeenCalled()
|
||||
scope.stop()
|
||||
})
|
||||
})
|
||||
|
||||
it('同项目首帧后台任务在各观察器间同步,并阻止其它付费操作直到真实终态', async () => {
|
||||
const { getOperation } = await import('@/features/workflows/operations')
|
||||
const id = ref('shared-quality-project')
|
||||
const record = {
|
||||
id: 'quality-exec',
|
||||
projectId: id.value,
|
||||
workflowName: 'keyframe-quality',
|
||||
status: 'running' as 'running' | 'completed',
|
||||
stage: 'keyframe_quality',
|
||||
current: 0,
|
||||
total: 1,
|
||||
currentResourceId: null,
|
||||
metadata: {},
|
||||
result: null,
|
||||
error: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
createdAt: '2026-10-08',
|
||||
updatedAt: '2026-10-08'
|
||||
}
|
||||
vi.spyOn(workflowExecutionApi, 'get').mockImplementation(async () => ({ ...record }))
|
||||
const scope = effectScope()
|
||||
const [first, second] = scope.run(() => [
|
||||
useWorkflowExecution(id, 'keyframe-quality'),
|
||||
useWorkflowExecution(id, 'keyframe-quality')
|
||||
])!
|
||||
await first!.track(record.id, id.value)
|
||||
expect(getOperation(id.value).pending).toBe(true)
|
||||
expect(second!.executionId.value).toBe(record.id)
|
||||
expect(second!.active.value).toBe(true)
|
||||
record.status = 'completed'
|
||||
await first!.query.refresh()
|
||||
expect(getOperation(id.value).pending).toBe(false)
|
||||
scope.stop()
|
||||
})
|
||||
|
||||
it('已卸载观察器的迟到 running 记录不能重新锁住其它观察器已确认结束的任务', async () => {
|
||||
const { getOperation } = await import('@/features/workflows/operations')
|
||||
const id = ref('terminal-monotonic-project')
|
||||
const record = {
|
||||
id: 'terminal-exec',
|
||||
projectId: id.value,
|
||||
workflowName: 'keyframe-quality',
|
||||
status: 'running' as 'running' | 'completed',
|
||||
stage: 'keyframe_quality',
|
||||
current: 0,
|
||||
total: 1,
|
||||
currentResourceId: null,
|
||||
metadata: {},
|
||||
result: null,
|
||||
error: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
createdAt: '2026-10-08',
|
||||
updatedAt: '2026-10-08'
|
||||
}
|
||||
let delayed = false
|
||||
let finish!: (value: typeof record) => void
|
||||
vi.spyOn(workflowExecutionApi, 'get').mockImplementation(async () => {
|
||||
if (delayed) {
|
||||
delayed = false
|
||||
return new Promise(resolve => {
|
||||
finish = resolve
|
||||
})
|
||||
}
|
||||
return { ...record }
|
||||
})
|
||||
const firstScope = effectScope()
|
||||
const secondScope = effectScope()
|
||||
const first = firstScope.run(() => useWorkflowExecution(id, 'keyframe-quality'))!
|
||||
const second = secondScope.run(() => useWorkflowExecution(id, 'keyframe-quality'))!
|
||||
await first.track(record.id, id.value)
|
||||
delayed = true
|
||||
const lateResponse = first.query.refresh()
|
||||
firstScope.stop()
|
||||
record.status = 'completed'
|
||||
await second.query.refresh()
|
||||
expect(getOperation(id.value).pending).toBe(false)
|
||||
finish({ ...record, status: 'running' })
|
||||
await lateResponse
|
||||
expect(getOperation(id.value).pending).toBe(false)
|
||||
secondScope.stop()
|
||||
})
|
||||
|
||||
it('后台启动未返回编号时不静默当作已跟踪,也不保存虚假句柄', async () => {
|
||||
const scope = effectScope()
|
||||
const execution = scope.run(() => useWorkflowExecution(ref('missing-execution-id-project'), 'production'))!
|
||||
await expect(execution.track('', 'missing-execution-id-project')).rejects.toThrow('任务编号')
|
||||
expect(localStorage.getItem('short-drama:workflow-execution:missing-execution-id-project:production')).toBeNull()
|
||||
scope.stop()
|
||||
})
|
||||
@@ -40,9 +40,7 @@ describe('WorkflowExecution 前端契约', () => {
|
||||
|
||||
it('刷新页面后使用保存的 executionId 读取后端权威状态', async () => {
|
||||
localStorage.setItem('short-drama:workflow-execution:project-1:video-quality', 'execution-1')
|
||||
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(
|
||||
new Response(JSON.stringify({ data: execution() }))
|
||||
)
|
||||
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify({ data: execution() })))
|
||||
vi.stubGlobal('fetch', fetcher)
|
||||
const scope = effectScope()
|
||||
const tracker = scope.run(() => useWorkflowExecution(ref('project-1'), 'video-quality'))!
|
||||
@@ -50,6 +48,11 @@ describe('WorkflowExecution 前端契约', () => {
|
||||
expect(fetcher.mock.calls[0]?.[0]).toBe('/api/workflow-executions/execution-1')
|
||||
expect(tracker.query.data.value?.stage).toBe('validating')
|
||||
tracker.dismiss()
|
||||
expect(localStorage.getItem('short-drama:workflow-execution:project-1:video-quality')).toBe('execution-1')
|
||||
expect(tracker.active.value).toBe(true)
|
||||
fetcher.mockResolvedValue(new Response(JSON.stringify({ data: execution({ status: 'completed' }) })))
|
||||
await tracker.query.refresh()
|
||||
tracker.dismiss()
|
||||
expect(localStorage.getItem('short-drama:workflow-execution:project-1:video-quality')).toBeNull()
|
||||
scope.stop()
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user