release: opensource snapshot 2026-02-27 19:25:00

This commit is contained in:
saturn
2026-02-27 19:25:00 +08:00
commit 5de9622c8b
1055 changed files with 164772 additions and 0 deletions

View File

@@ -0,0 +1,146 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const prismaMock = vi.hoisted(() => ({
project: { findUnique: vi.fn() },
novelPromotionProject: { findUnique: vi.fn() },
}))
const llmMock = vi.hoisted(() => ({
chatCompletion: vi.fn(async () => ({ id: 'completion-1' })),
getCompletionContent: vi.fn(() => '{"ok":true}'),
}))
const workerMock = vi.hoisted(() => ({
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
const parseMock = vi.hoisted(() => ({
chunkContent: vi.fn(() => ['chunk-1', 'chunk-2']),
safeParseCharactersResponse: vi.fn(() => ({ new_characters: [] })),
safeParseLocationsResponse: vi.fn(() => ({ locations: [] })),
}))
const persistMock = vi.hoisted(() => ({
createAnalyzeGlobalStats: vi.fn((totalChunks: number) => ({
totalChunks,
processedChunks: 0,
newCharacters: 0,
updatedCharacters: 0,
newLocations: 0,
skippedCharacters: 0,
skippedLocations: 0,
})),
persistAnalyzeGlobalChunk: vi.fn(async (args: { stats: { newCharacters: number; newLocations: number } }) => {
args.stats.newCharacters += 1
args.stats.newLocations += 1
}),
}))
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/llm-client', () => llmMock)
vi.mock('@/lib/llm-observe/internal-stream-context', () => ({
withInternalLLMStreamCallbacks: vi.fn(async (_callbacks: unknown, fn: () => Promise<unknown>) => await fn()),
}))
vi.mock('@/lib/workers/shared', () => ({ reportTaskProgress: workerMock.reportTaskProgress }))
vi.mock('@/lib/workers/utils', () => ({ assertTaskActive: workerMock.assertTaskActive }))
vi.mock('@/lib/workers/handlers/llm-stream', () => ({
createWorkerLLMStreamContext: vi.fn(() => ({ streamRunId: 'run-1', nextSeqByStepLane: {} })),
createWorkerLLMStreamCallbacks: vi.fn(() => ({
onStage: vi.fn(),
onChunk: vi.fn(),
onComplete: vi.fn(),
onError: vi.fn(),
flush: vi.fn(async () => undefined),
})),
}))
vi.mock('@/lib/workers/handlers/analyze-global-parse', () => ({
CHUNK_SIZE: 3000,
chunkContent: parseMock.chunkContent,
parseAliases: vi.fn(() => []),
readText: (value: unknown) => (typeof value === 'string' ? value : ''),
safeParseCharactersResponse: parseMock.safeParseCharactersResponse,
safeParseLocationsResponse: parseMock.safeParseLocationsResponse,
}))
vi.mock('@/lib/workers/handlers/analyze-global-prompt', () => ({
loadAnalyzeGlobalPromptTemplates: vi.fn(() => ({ characterTemplate: 'c', locationTemplate: 'l' })),
buildAnalyzeGlobalPrompts: vi.fn(() => ({
characterPrompt: 'character prompt',
locationPrompt: 'location prompt',
})),
}))
vi.mock('@/lib/workers/handlers/analyze-global-persist', () => ({
createAnalyzeGlobalStats: persistMock.createAnalyzeGlobalStats,
persistAnalyzeGlobalChunk: persistMock.persistAnalyzeGlobalChunk,
}))
import { handleAnalyzeGlobalTask } from '@/lib/workers/handlers/analyze-global'
function buildJob(): Job<TaskJobData> {
return {
data: {
taskId: 'task-analyze-global-1',
type: TASK_TYPE.ANALYZE_GLOBAL,
locale: 'zh',
projectId: 'project-1',
episodeId: null,
targetType: 'NovelPromotionProject',
targetId: 'np-project-1',
payload: {},
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker analyze-global behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
prismaMock.project.findUnique.mockResolvedValue({ id: 'project-1', mode: 'novel-promotion' })
prismaMock.novelPromotionProject.findUnique.mockResolvedValue({
id: 'np-project-1',
analysisModel: 'llm::analysis-1',
globalAssetText: '全局设定',
characters: [{ id: 'char-1', name: 'Hero', aliases: null, introduction: 'hero intro' }],
locations: [{ id: 'loc-1', name: 'Old Town', summary: 'old town summary' }],
episodes: [{ id: 'ep-1', name: '第一集', novelText: 'episode text' }],
})
})
it('no analyzable content -> explicit error', async () => {
prismaMock.novelPromotionProject.findUnique.mockResolvedValueOnce({
id: 'np-project-1',
analysisModel: 'llm::analysis-1',
globalAssetText: '',
characters: [],
locations: [],
episodes: [{ id: 'ep-1', name: '第一集', novelText: '' }],
})
await expect(handleAnalyzeGlobalTask(buildJob())).rejects.toThrow('没有可分析的内容')
})
it('success path -> persists every chunk and returns stats summary', async () => {
const result = await handleAnalyzeGlobalTask(buildJob())
expect(parseMock.chunkContent).toHaveBeenCalled()
expect(persistMock.persistAnalyzeGlobalChunk).toHaveBeenCalledTimes(2)
expect(result).toEqual({
success: true,
stats: {
totalChunks: 2,
newCharacters: 2,
updatedCharacters: 0,
newLocations: 2,
skippedCharacters: 0,
skippedLocations: 0,
totalCharacters: 1,
totalLocations: 1,
},
})
})
})

View File

@@ -0,0 +1,197 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const prismaMock = vi.hoisted(() => ({
project: { findUnique: vi.fn() },
novelPromotionProject: {
findUnique: vi.fn(),
update: vi.fn(async () => ({})),
},
novelPromotionEpisode: { findFirst: vi.fn() },
novelPromotionCharacter: { create: vi.fn(async () => ({ id: 'char-new-1' })) },
novelPromotionLocation: { create: vi.fn(async () => ({ id: 'loc-new-1' })) },
locationImage: { create: vi.fn(async () => ({})) },
}))
const llmMock = vi.hoisted(() => ({
chatCompletion: vi.fn(async () => ({ id: 'completion-1' })),
getCompletionContent: vi.fn(),
}))
const workerMock = vi.hoisted(() => ({
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/llm-client', () => llmMock)
vi.mock('@/lib/llm-observe/internal-stream-context', () => ({
withInternalLLMStreamCallbacks: vi.fn(async (_callbacks: unknown, fn: () => Promise<unknown>) => await fn()),
}))
vi.mock('@/lib/constants', () => ({
getArtStylePrompt: vi.fn(() => 'cinematic style'),
removeLocationPromptSuffix: vi.fn((text: string) => text.replace(' [SUFFIX]', '')),
}))
vi.mock('@/lib/workers/shared', () => ({ reportTaskProgress: workerMock.reportTaskProgress }))
vi.mock('@/lib/workers/utils', () => ({ assertTaskActive: workerMock.assertTaskActive }))
vi.mock('@/lib/workers/handlers/llm-stream', () => ({
createWorkerLLMStreamContext: vi.fn(() => ({ streamRunId: 'run-1', nextSeqByStepLane: {} })),
createWorkerLLMStreamCallbacks: vi.fn(() => ({
onStage: vi.fn(),
onChunk: vi.fn(),
onComplete: vi.fn(),
onError: vi.fn(),
flush: vi.fn(async () => undefined),
})),
}))
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: {
NP_AGENT_CHARACTER_PROFILE: 'char',
NP_SELECT_LOCATION: 'loc',
},
buildPrompt: vi.fn(() => 'analysis-prompt'),
}))
import { handleAnalyzeNovelTask } from '@/lib/workers/handlers/analyze-novel'
function buildJob(): Job<TaskJobData> {
return {
data: {
taskId: 'task-analyze-novel-1',
type: TASK_TYPE.ANALYZE_NOVEL,
locale: 'zh',
projectId: 'project-1',
episodeId: 'episode-1',
targetType: 'NovelPromotionProject',
targetId: 'np-project-1',
payload: {},
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker analyze-novel behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
prismaMock.project.findUnique.mockResolvedValue({
id: 'project-1',
mode: 'novel-promotion',
})
prismaMock.novelPromotionProject.findUnique.mockResolvedValue({
id: 'np-project-1',
analysisModel: 'llm::analysis-1',
artStyle: 'cinematic',
globalAssetText: '全局设定文本',
characters: [{ id: 'char-existing', name: '已有角色' }],
locations: [{ id: 'loc-existing', name: '已有场景', summary: 'old' }],
})
prismaMock.novelPromotionEpisode.findFirst.mockResolvedValue({
novelText: '首集内容',
})
llmMock.getCompletionContent
.mockReturnValueOnce(JSON.stringify({
characters: [
{
name: '新角色',
aliases: ['别名A'],
role_level: 'main',
personality_tags: ['冷静'],
visual_keywords: ['黑发'],
},
],
}))
.mockReturnValueOnce(JSON.stringify({
locations: [
{
name: '新地点',
summary: '雨夜街道',
descriptions: ['雨夜街道 [SUFFIX]'],
},
],
}))
})
it('no global text and no episode text -> explicit error', async () => {
prismaMock.novelPromotionProject.findUnique.mockResolvedValueOnce({
id: 'np-project-1',
analysisModel: 'llm::analysis-1',
artStyle: 'cinematic',
globalAssetText: '',
characters: [],
locations: [],
})
prismaMock.novelPromotionEpisode.findFirst.mockResolvedValueOnce({ novelText: '' })
await expect(handleAnalyzeNovelTask(buildJob())).rejects.toThrow('请先填写全局资产设定或剧本内容')
})
it('success path -> creates character/location and persists cleaned location descriptions', async () => {
const result = await handleAnalyzeNovelTask(buildJob())
expect(result).toEqual({
success: true,
characters: [{ id: 'char-new-1' }],
locations: [{ id: 'loc-new-1' }],
characterCount: 1,
locationCount: 1,
})
expect(prismaMock.novelPromotionCharacter.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
novelPromotionProjectId: 'np-project-1',
name: '新角色',
aliases: JSON.stringify(['别名A']),
}),
}),
)
expect(prismaMock.novelPromotionLocation.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
novelPromotionProjectId: 'np-project-1',
name: '新地点',
summary: '雨夜街道',
}),
}),
)
expect(prismaMock.locationImage.create).toHaveBeenCalledWith({
data: {
locationId: 'loc-new-1',
imageIndex: 0,
description: '雨夜街道',
},
})
expect(prismaMock.novelPromotionProject.update).toHaveBeenCalledWith({
where: { id: 'np-project-1' },
data: { artStylePrompt: 'cinematic style' },
})
expect(workerMock.reportTaskProgress).toHaveBeenCalledWith(
expect.anything(),
60,
expect.objectContaining({
stepId: 'analyze_characters',
done: true,
output: expect.stringContaining('"characters"'),
}),
)
expect(workerMock.reportTaskProgress).toHaveBeenCalledWith(
expect.anything(),
70,
expect.objectContaining({
stepId: 'analyze_locations',
done: true,
output: expect.stringContaining('"locations"'),
}),
)
})
})

View File

@@ -0,0 +1,96 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const configMock = vi.hoisted(() => ({
getUserModelConfig: vi.fn(),
}))
const assetUtilsMock = vi.hoisted(() => ({
aiDesign: vi.fn(),
}))
const workerMock = vi.hoisted(() => ({
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
vi.mock('@/lib/config-service', () => configMock)
vi.mock('@/lib/asset-utils', () => assetUtilsMock)
vi.mock('@/lib/workers/shared', () => ({
reportTaskProgress: workerMock.reportTaskProgress,
}))
vi.mock('@/lib/workers/utils', () => ({
assertTaskActive: workerMock.assertTaskActive,
}))
import { handleAssetHubAIDesignTask } from '@/lib/workers/handlers/asset-hub-ai-design'
function buildJob(type: TaskJobData['type'], payload: Record<string, unknown>): Job<TaskJobData> {
return {
data: {
taskId: 'task-asset-ai-design-1',
type,
locale: 'zh',
projectId: 'global-asset-hub',
episodeId: null,
targetType: 'GlobalCharacter',
targetId: 'target-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker asset-hub-ai-design behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
configMock.getUserModelConfig.mockResolvedValue({ analysisModel: 'llm::analysis-default' })
assetUtilsMock.aiDesign.mockResolvedValue({
success: true,
prompt: 'generated prompt',
})
})
it('missing userInstruction -> explicit error', async () => {
const job = buildJob(TASK_TYPE.ASSET_HUB_AI_DESIGN_CHARACTER, {})
await expect(handleAssetHubAIDesignTask(job)).rejects.toThrow('userInstruction is required')
})
it('unsupported task type -> explicit error', async () => {
const job = buildJob(TASK_TYPE.IMAGE_CHARACTER, { userInstruction: 'design a hero' })
await expect(handleAssetHubAIDesignTask(job)).rejects.toThrow('Unsupported asset hub ai design task type')
})
it('success uses payload analysisModel override and character assetType', async () => {
const job = buildJob(TASK_TYPE.ASSET_HUB_AI_DESIGN_CHARACTER, {
userInstruction: ' design a heroic character ',
analysisModel: ' llm::analysis-override ',
})
const result = await handleAssetHubAIDesignTask(job)
expect(assetUtilsMock.aiDesign).toHaveBeenCalledWith(expect.objectContaining({
userId: 'user-1',
analysisModel: 'llm::analysis-override',
userInstruction: 'design a heroic character',
assetType: 'character',
projectId: 'global-asset-hub',
skipBilling: true,
}))
expect(result).toEqual({ prompt: 'generated prompt' })
})
it('location type success -> passes location assetType', async () => {
const job = buildJob(TASK_TYPE.ASSET_HUB_AI_DESIGN_LOCATION, {
userInstruction: 'design a rainy alley',
})
await handleAssetHubAIDesignTask(job)
expect(assetUtilsMock.aiDesign).toHaveBeenCalledWith(expect.objectContaining({
assetType: 'location',
analysisModel: 'llm::analysis-default',
}))
})
})

View File

@@ -0,0 +1,145 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const llmMock = vi.hoisted(() => ({
chatCompletion: vi.fn(),
getCompletionContent: vi.fn(),
}))
const configMock = vi.hoisted(() => ({
getUserModelConfig: vi.fn(),
}))
const streamContextMock = vi.hoisted(() => ({
withInternalLLMStreamCallbacks: vi.fn(async (_callbacks: unknown, fn: () => Promise<unknown>) => await fn()),
}))
const workerMock = vi.hoisted(() => ({
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
const llmStreamMock = vi.hoisted(() => {
const flush = vi.fn(async () => undefined)
return {
flush,
createWorkerLLMStreamContext: vi.fn(() => ({ streamRunId: 'run-1', nextSeqByStepLane: {} })),
createWorkerLLMStreamCallbacks: vi.fn(() => ({
onStage: vi.fn(),
onChunk: vi.fn(),
onComplete: vi.fn(),
onError: vi.fn(),
flush,
})),
}
})
vi.mock('@/lib/llm-client', () => llmMock)
vi.mock('@/lib/config-service', () => configMock)
vi.mock('@/lib/llm-observe/internal-stream-context', () => streamContextMock)
vi.mock('@/lib/workers/shared', () => ({
reportTaskProgress: workerMock.reportTaskProgress,
}))
vi.mock('@/lib/workers/utils', () => ({
assertTaskActive: workerMock.assertTaskActive,
}))
vi.mock('@/lib/workers/handlers/llm-stream', () => ({
createWorkerLLMStreamContext: llmStreamMock.createWorkerLLMStreamContext,
createWorkerLLMStreamCallbacks: llmStreamMock.createWorkerLLMStreamCallbacks,
}))
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: {
NP_CHARACTER_MODIFY: 'np_character_modify',
NP_LOCATION_MODIFY: 'np_location_modify',
},
buildPrompt: vi.fn((_args: unknown) => 'final-prompt'),
}))
import { handleAssetHubAIModifyTask } from '@/lib/workers/handlers/asset-hub-ai-modify'
function buildJob(type: TaskJobData['type'], payload: Record<string, unknown>): Job<TaskJobData> {
return {
data: {
taskId: 'task-asset-ai-modify-1',
type,
locale: 'zh',
projectId: 'global-asset-hub',
episodeId: null,
targetType: 'GlobalCharacter',
targetId: 'target-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker asset-hub-ai-modify behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
configMock.getUserModelConfig.mockResolvedValue({ analysisModel: 'llm::analysis-1' })
llmMock.chatCompletion.mockResolvedValue({ id: 'completion-1' })
llmMock.getCompletionContent.mockReturnValue('{"prompt":"modified description"}')
})
it('missing analysisModel in user config -> explicit error', async () => {
configMock.getUserModelConfig.mockResolvedValueOnce({ analysisModel: '' })
const job = buildJob(TASK_TYPE.ASSET_HUB_AI_MODIFY_CHARACTER, {
characterId: 'char-1',
currentDescription: 'old',
modifyInstruction: 'new',
})
await expect(handleAssetHubAIModifyTask(job)).rejects.toThrow('请先在用户配置中设置分析模型')
})
it('unsupported type -> explicit error', async () => {
const job = buildJob(TASK_TYPE.IMAGE_CHARACTER, {
characterId: 'char-1',
currentDescription: 'old',
modifyInstruction: 'new',
})
await expect(handleAssetHubAIModifyTask(job)).rejects.toThrow('Unsupported task type')
})
it('character success -> parses JSON prompt and returns modifiedDescription', async () => {
const job = buildJob(TASK_TYPE.ASSET_HUB_AI_MODIFY_CHARACTER, {
characterId: 'char-1',
currentDescription: 'old character description',
modifyInstruction: 'add armor details',
})
const result = await handleAssetHubAIModifyTask(job)
expect(llmMock.chatCompletion).toHaveBeenCalledWith(
'user-1',
'llm::analysis-1',
[{ role: 'user', content: 'final-prompt' }],
expect.objectContaining({
projectId: 'asset-hub',
action: 'ai_modify_character',
}),
)
expect(result).toEqual({
success: true,
modifiedDescription: 'modified description',
})
expect(llmStreamMock.flush).toHaveBeenCalled()
})
it('location success -> requires locationName and returns modifiedDescription', async () => {
const job = buildJob(TASK_TYPE.ASSET_HUB_AI_MODIFY_LOCATION, {
locationId: 'loc-1',
locationName: 'Old Town',
currentDescription: 'old location description',
modifyInstruction: 'add more fog',
})
const result = await handleAssetHubAIModifyTask(job)
expect(result).toEqual({
success: true,
modifiedDescription: 'modified description',
})
})
})

View File

@@ -0,0 +1,103 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { CHARACTER_PROMPT_SUFFIX } from '@/lib/constants'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const workersUtilsMock = vi.hoisted(() => ({
assertTaskActive: vi.fn(async () => {}),
getUserModels: vi.fn(async () => ({
characterModel: 'character-model-1',
locationModel: 'location-model-1',
})),
}))
const prismaMock = vi.hoisted(() => ({
globalCharacter: {
findFirst: vi.fn(),
},
globalCharacterAppearance: {
update: vi.fn(async () => ({})),
},
globalLocation: {
findFirst: vi.fn(),
},
globalLocationImage: {
update: vi.fn(async () => ({})),
},
}))
const sharedMock = vi.hoisted(() => ({
generateLabeledImageToCos: vi.fn(async () => 'cos/generated-character.png'),
parseJsonStringArray: vi.fn(() => []),
}))
vi.mock('@/lib/workers/utils', () => workersUtilsMock)
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/workers/handlers/image-task-handler-shared', async () => {
const actual = await vi.importActual<typeof import('@/lib/workers/handlers/image-task-handler-shared')>(
'@/lib/workers/handlers/image-task-handler-shared',
)
return {
...actual,
generateLabeledImageToCos: sharedMock.generateLabeledImageToCos,
parseJsonStringArray: sharedMock.parseJsonStringArray,
}
})
import { handleAssetHubImageTask } from '@/lib/workers/handlers/asset-hub-image-task-handler'
function buildJob(payload: Record<string, unknown>): Job<TaskJobData> {
return {
data: {
taskId: 'task-asset-hub-image-1',
type: TASK_TYPE.ASSET_HUB_IMAGE,
locale: 'zh',
projectId: 'project-1',
targetType: 'GlobalCharacter',
targetId: 'global-character-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
function countOccurrences(input: string, target: string) {
if (!target) return 0
return input.split(target).length - 1
}
describe('asset hub character image prompt suffix regression', () => {
beforeEach(() => {
vi.clearAllMocks()
prismaMock.globalCharacter.findFirst.mockResolvedValue({
id: 'global-character-1',
name: 'Hero',
appearances: [
{
id: 'appearance-1',
appearanceIndex: 0,
changeReason: 'base',
description: '主角,黑发,冷静',
descriptions: null,
},
],
})
})
it('keeps character prompt suffix in actual generation prompt', async () => {
const job = buildJob({
type: 'character',
id: 'global-character-1',
appearanceIndex: 0,
})
await handleAssetHubImageTask(job)
const callArg = sharedMock.generateLabeledImageToCos.mock.calls[0]?.[0] as { prompt?: string } | undefined
const prompt = callArg?.prompt || ''
expect(prompt).toContain('主角,黑发,冷静')
expect(prompt).toContain(CHARACTER_PROMPT_SUFFIX)
expect(countOccurrences(prompt, CHARACTER_PROMPT_SUFFIX)).toBe(1)
})
})

View File

@@ -0,0 +1,120 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { CHARACTER_PROMPT_SUFFIX } from '@/lib/constants'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const utilsMock = vi.hoisted(() => ({
assertTaskActive: vi.fn(async () => undefined),
getProjectModels: vi.fn(async () => ({ characterModel: 'image-model-1', artStyle: 'noir' })),
toSignedUrlIfCos: vi.fn((url: string | null | undefined) => (url ? `https://signed.example/${url}` : null)),
}))
const outboundMock = vi.hoisted(() => ({
normalizeReferenceImagesForGeneration: vi.fn(async () => ['normalized-primary-ref']),
}))
const prismaMock = vi.hoisted(() => ({
characterAppearance: {
findUnique: vi.fn(),
findFirst: vi.fn(),
update: vi.fn(async () => ({})),
},
novelPromotionCharacter: {
findUnique: vi.fn(),
},
}))
const sharedMock = vi.hoisted(() => ({
generateLabeledImageToCos: vi.fn(async () => 'cos/character-generated-0.png'),
}))
vi.mock('@/lib/workers/utils', () => utilsMock)
vi.mock('@/lib/media/outbound-image', () => outboundMock)
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/workers/shared', () => ({ reportTaskProgress: vi.fn(async () => undefined) }))
vi.mock('@/lib/workers/handlers/image-task-handler-shared', async () => {
const actual = await vi.importActual<typeof import('@/lib/workers/handlers/image-task-handler-shared')>(
'@/lib/workers/handlers/image-task-handler-shared',
)
return {
...actual,
generateLabeledImageToCos: sharedMock.generateLabeledImageToCos,
}
})
import { handleCharacterImageTask } from '@/lib/workers/handlers/character-image-task-handler'
function buildJob(payload: Record<string, unknown>, targetId = 'appearance-2'): Job<TaskJobData> {
return {
data: {
taskId: 'task-character-image-1',
type: TASK_TYPE.IMAGE_CHARACTER,
locale: 'zh',
projectId: 'project-1',
episodeId: null,
targetType: 'CharacterAppearance',
targetId,
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker character-image-task-handler behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
prismaMock.characterAppearance.findUnique.mockResolvedValue({
id: 'appearance-2',
characterId: 'character-1',
appearanceIndex: 1,
descriptions: JSON.stringify(['角色描述A']),
description: '角色描述A',
imageUrls: JSON.stringify([]),
selectedIndex: 0,
imageUrl: null,
changeReason: '战斗形态',
character: { name: 'Hero' },
})
prismaMock.characterAppearance.findFirst.mockResolvedValue({
imageUrl: 'cos/primary.png',
imageUrls: JSON.stringify(['cos/primary.png']),
})
})
it('characterModel not configured -> explicit error', async () => {
utilsMock.getProjectModels.mockResolvedValueOnce({ characterModel: '', artStyle: 'noir' })
await expect(handleCharacterImageTask(buildJob({}))).rejects.toThrow('Character model not configured')
})
it('success path -> uses primary appearance as reference and persists imageUrls', async () => {
const job = buildJob({ imageIndex: 0 })
const result = await handleCharacterImageTask(job)
expect(result).toEqual({
appearanceId: 'appearance-2',
imageCount: 1,
imageUrl: 'cos/character-generated-0.png',
})
const generationInput = sharedMock.generateLabeledImageToCos.mock.calls[0]?.[0] as {
prompt: string
options?: { referenceImages?: string[]; aspectRatio?: string }
}
expect(generationInput.prompt).toContain(CHARACTER_PROMPT_SUFFIX)
expect(generationInput.options).toEqual(expect.objectContaining({
referenceImages: ['normalized-primary-ref'],
aspectRatio: '3:2',
}))
expect(prismaMock.characterAppearance.update).toHaveBeenCalledWith({
where: { id: 'appearance-2' },
data: {
imageUrls: JSON.stringify(['cos/character-generated-0.png']),
imageUrl: 'cos/character-generated-0.png',
},
})
})
})

View File

@@ -0,0 +1,174 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const prismaMock = vi.hoisted(() => ({
novelPromotionCharacter: {
findFirst: vi.fn(),
findMany: vi.fn(),
update: vi.fn(async () => ({})),
},
characterAppearance: {
create: vi.fn(async () => ({})),
},
}))
const llmMock = vi.hoisted(() => ({
chatCompletion: vi.fn(async () => ({ id: 'completion-1' })),
getCompletionContent: vi.fn(),
}))
const helperMock = vi.hoisted(() => ({
resolveProjectModel: vi.fn(async () => ({
id: 'project-1',
novelPromotionData: {
id: 'np-project-1',
analysisModel: 'llm::analysis-1',
},
})),
}))
const workerMock = vi.hoisted(() => ({
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/llm-client', () => llmMock)
vi.mock('@/types/character-profile', () => ({
validateProfileData: vi.fn(() => true),
stringifyProfileData: vi.fn((value: unknown) => JSON.stringify(value)),
}))
vi.mock('@/lib/llm-observe/internal-stream-context', () => ({
withInternalLLMStreamCallbacks: vi.fn(async (_callbacks: unknown, fn: () => Promise<unknown>) => await fn()),
}))
vi.mock('@/lib/workers/shared', () => ({ reportTaskProgress: workerMock.reportTaskProgress }))
vi.mock('@/lib/workers/utils', () => ({ assertTaskActive: workerMock.assertTaskActive }))
vi.mock('@/lib/workers/handlers/llm-stream', () => ({
createWorkerLLMStreamContext: vi.fn(() => ({ streamRunId: 'run-1', nextSeqByStepLane: {} })),
createWorkerLLMStreamCallbacks: vi.fn(() => ({
onStage: vi.fn(),
onChunk: vi.fn(),
onComplete: vi.fn(),
onError: vi.fn(),
flush: vi.fn(async () => undefined),
})),
}))
vi.mock('@/lib/workers/handlers/character-profile-helpers', async () => {
const actual = await vi.importActual<typeof import('@/lib/workers/handlers/character-profile-helpers')>(
'@/lib/workers/handlers/character-profile-helpers',
)
return {
...actual,
resolveProjectModel: helperMock.resolveProjectModel,
}
})
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: { NP_AGENT_CHARACTER_VISUAL: 'np_agent_character_visual' },
buildPrompt: vi.fn(() => 'character-visual-prompt'),
}))
import { handleCharacterProfileTask } from '@/lib/workers/handlers/character-profile'
function buildJob(type: TaskJobData['type'], payload: Record<string, unknown>): Job<TaskJobData> {
return {
data: {
taskId: 'task-character-profile-1',
type,
locale: 'zh',
projectId: 'project-1',
episodeId: null,
targetType: 'NovelPromotionCharacter',
targetId: 'character-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker character-profile behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
llmMock.getCompletionContent.mockReturnValue(
JSON.stringify({
characters: [
{
appearances: [
{
change_reason: '默认形象',
descriptions: ['黑发,冷静,风衣'],
},
],
},
],
}),
)
prismaMock.novelPromotionCharacter.findFirst.mockImplementation(async (args: { where: { id: string } }) => ({
id: args.where.id,
name: args.where.id === 'character-2' ? 'Villain' : 'Hero',
profileData: JSON.stringify({ archetype: 'lead' }),
profileConfirmed: false,
novelPromotionProjectId: 'np-project-1',
}))
prismaMock.novelPromotionCharacter.findMany.mockResolvedValue([
{
id: 'character-1',
name: 'Hero',
profileData: JSON.stringify({ archetype: 'lead' }),
profileConfirmed: false,
},
{
id: 'character-2',
name: 'Villain',
profileData: JSON.stringify({ archetype: 'antagonist' }),
profileConfirmed: false,
},
])
})
it('unsupported task type -> explicit error', async () => {
const job = buildJob(TASK_TYPE.AI_CREATE_CHARACTER, {})
await expect(handleCharacterProfileTask(job)).rejects.toThrow('Unsupported character profile task type')
})
it('confirm profile success -> creates appearance and marks profileConfirmed', async () => {
const job = buildJob(TASK_TYPE.CHARACTER_PROFILE_CONFIRM, { characterId: 'character-1' })
const result = await handleCharacterProfileTask(job)
expect(prismaMock.characterAppearance.create).toHaveBeenCalledWith({
data: expect.objectContaining({
characterId: 'character-1',
appearanceIndex: 0,
changeReason: '默认形象',
description: '黑发,冷静,风衣',
}),
})
expect(prismaMock.novelPromotionCharacter.update).toHaveBeenCalledWith({
where: { id: 'character-1' },
data: { profileConfirmed: true },
})
expect(result).toEqual(expect.objectContaining({
success: true,
character: expect.objectContaining({
id: 'character-1',
profileConfirmed: true,
}),
}))
})
it('batch confirm -> loops through all unconfirmed characters and returns count', async () => {
const job = buildJob(TASK_TYPE.CHARACTER_PROFILE_BATCH_CONFIRM, {})
const result = await handleCharacterProfileTask(job)
expect(result).toEqual({
success: true,
count: 2,
})
expect(prismaMock.characterAppearance.create).toHaveBeenCalledTimes(2)
})
})

View File

@@ -0,0 +1,157 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const prismaMock = vi.hoisted(() => ({
project: { findUnique: vi.fn() },
novelPromotionProject: { findUnique: vi.fn() },
novelPromotionEpisode: { findUnique: vi.fn() },
novelPromotionClip: {
deleteMany: vi.fn(async () => ({})),
create: vi.fn(async () => ({ id: 'clip-row-1' })),
},
}))
const llmMock = vi.hoisted(() => ({
chatCompletion: vi.fn(async () => ({ id: 'completion-1' })),
getCompletionContent: vi.fn(),
}))
const workerMock = vi.hoisted(() => ({
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/llm-client', () => llmMock)
vi.mock('@/lib/llm-observe/internal-stream-context', () => ({
withInternalLLMStreamCallbacks: vi.fn(async (_callbacks: unknown, fn: () => Promise<unknown>) => await fn()),
}))
vi.mock('@/lib/constants', () => ({
buildCharactersIntroduction: vi.fn(() => 'characters-introduction'),
}))
vi.mock('@/lib/workers/shared', () => ({ reportTaskProgress: workerMock.reportTaskProgress }))
vi.mock('@/lib/workers/utils', () => ({ assertTaskActive: workerMock.assertTaskActive }))
vi.mock('@/lib/workers/handlers/llm-stream', () => ({
createWorkerLLMStreamContext: vi.fn(() => ({ streamRunId: 'run-1', nextSeqByStepLane: {} })),
createWorkerLLMStreamCallbacks: vi.fn(() => ({
onStage: vi.fn(),
onChunk: vi.fn(),
onComplete: vi.fn(),
onError: vi.fn(),
flush: vi.fn(async () => undefined),
})),
}))
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: { NP_AGENT_CLIP: 'np_agent_clip' },
buildPrompt: vi.fn(() => 'clip-split-prompt'),
}))
vi.mock('@/lib/novel-promotion/story-to-script/clip-matching', () => ({
createClipContentMatcher: (content: string) => ({
matchBoundary: (start: string, end: string, fromIndex = 0) => {
const startIndex = content.indexOf(start, fromIndex)
if (startIndex === -1) return null
const endStart = content.indexOf(end, startIndex)
if (endStart === -1) return null
return {
startIndex,
endIndex: endStart + end.length,
}
},
}),
}))
import { handleClipsBuildTask } from '@/lib/workers/handlers/clips-build'
function buildJob(payload: Record<string, unknown>, episodeId: string | null = 'episode-1'): Job<TaskJobData> {
return {
data: {
taskId: 'task-clips-build-1',
type: TASK_TYPE.CLIPS_BUILD,
locale: 'zh',
projectId: 'project-1',
episodeId,
targetType: 'NovelPromotionEpisode',
targetId: 'episode-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker clips-build behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
prismaMock.project.findUnique.mockResolvedValue({ id: 'project-1', mode: 'novel-promotion' })
prismaMock.novelPromotionProject.findUnique.mockResolvedValue({
id: 'np-project-1',
analysisModel: 'llm::analysis-1',
characters: [{ id: 'char-1', name: 'Hero' }],
locations: [{ id: 'loc-1', name: 'Old Town' }],
})
prismaMock.novelPromotionEpisode.findUnique.mockResolvedValue({
id: 'episode-1',
name: '第一集',
novelPromotionProjectId: 'np-project-1',
novelText: 'A START one END B START two END C',
})
llmMock.getCompletionContent.mockReturnValue(
JSON.stringify([
{
start: 'START one',
end: 'END',
summary: 'first clip',
location: 'Old Town',
characters: ['Hero'],
},
]),
)
})
it('missing episodeId -> explicit error', async () => {
const job = buildJob({}, null)
await expect(handleClipsBuildTask(job)).rejects.toThrow('episodeId is required')
})
it('success path -> creates clip row with concrete boundaries and characters payload', async () => {
const job = buildJob({ episodeId: 'episode-1' })
const result = await handleClipsBuildTask(job)
expect(result).toEqual({
episodeId: 'episode-1',
count: 1,
})
expect(prismaMock.novelPromotionClip.create).toHaveBeenCalledWith({
data: {
episodeId: 'episode-1',
startText: 'START one',
endText: 'END',
summary: 'first clip',
location: 'Old Town',
characters: JSON.stringify(['Hero']),
content: 'START one END',
},
select: { id: true },
})
})
it('AI boundaries cannot be matched -> explicit boundary error', async () => {
llmMock.getCompletionContent.mockReturnValue(
JSON.stringify([
{
start: 'NOT_FOUND_START',
end: 'NOT_FOUND_END',
summary: 'bad clip',
},
]),
)
const job = buildJob({ episodeId: 'episode-1' })
await expect(handleClipsBuildTask(job)).rejects.toThrow('split_clips boundary matching failed')
})
})

View File

@@ -0,0 +1,127 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const prismaMock = vi.hoisted(() => ({
project: {
findUnique: vi.fn(async () => ({ id: 'project-1', mode: 'novel-promotion' })),
},
novelPromotionProject: {
findFirst: vi.fn(async () => ({ id: 'np-project-1' })),
},
}))
const llmClientMock = vi.hoisted(() => ({
chatCompletion: vi.fn(async () => ({ id: 'completion-1' })),
getCompletionContent: vi.fn(() => JSON.stringify({
episodes: [
{
number: 1,
title: '第一集',
summary: '开端',
startMarker: 'START_MARKER',
endMarker: 'END_MARKER',
},
],
})),
}))
const configServiceMock = vi.hoisted(() => ({
getUserModelConfig: vi.fn(async () => ({
analysisModel: 'llm::analysis-model',
})),
}))
const internalStreamMock = vi.hoisted(() => ({
withInternalLLMStreamCallbacks: vi.fn(async (_callbacks: unknown, fn: () => Promise<unknown>) => await fn()),
}))
const sharedMock = vi.hoisted(() => ({
reportTaskProgress: vi.fn(async () => {}),
}))
const utilsMock = vi.hoisted(() => ({
assertTaskActive: vi.fn(async () => {}),
}))
const llmStreamMock = vi.hoisted(() => ({
createWorkerLLMStreamContext: vi.fn(() => ({ streamId: 'stream-1' })),
createWorkerLLMStreamCallbacks: vi.fn(() => ({
flush: vi.fn(async () => {}),
})),
}))
const promptMock = vi.hoisted(() => ({
PROMPT_IDS: { NP_EPISODE_SPLIT: 'np_episode_split' },
buildPrompt: vi.fn(() => 'EPISODE_SPLIT_PROMPT'),
}))
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/llm-client', () => llmClientMock)
vi.mock('@/lib/config-service', () => configServiceMock)
vi.mock('@/lib/llm-observe/internal-stream-context', () => internalStreamMock)
vi.mock('@/lib/workers/shared', () => sharedMock)
vi.mock('@/lib/workers/utils', () => utilsMock)
vi.mock('@/lib/workers/handlers/llm-stream', () => llmStreamMock)
vi.mock('@/lib/prompt-i18n', () => promptMock)
vi.mock('@/lib/novel-promotion/story-to-script/clip-matching', () => ({
createTextMarkerMatcher: (content: string) => ({
matchMarker: (marker: string, fromIndex = 0) => {
const startIndex = content.indexOf(marker, fromIndex)
if (startIndex === -1) return null
return {
startIndex,
endIndex: startIndex + marker.length,
}
},
}),
}))
import { handleEpisodeSplitTask } from '@/lib/workers/handlers/episode-split'
function buildJob(content: string): Job<TaskJobData> {
return {
data: {
taskId: 'task-episode-split-1',
type: TASK_TYPE.EPISODE_SPLIT_LLM,
locale: 'zh',
projectId: 'project-1',
targetType: 'NovelPromotionProject',
targetId: 'project-1',
payload: { content },
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker episode-split', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('fails fast when content is too short', async () => {
const job = buildJob('short text')
await expect(handleEpisodeSplitTask(job)).rejects.toThrow('文本太短,至少需要 100 字')
})
it('returns matched episodes when ai boundaries are valid', async () => {
const content = [
'前置内容用于凑长度,确保文本超过一百字。这一段会重复两次以保证长度满足阈值。',
'前置内容用于凑长度,确保文本超过一百字。这一段会重复两次以保证长度满足阈值。',
'START_MARKER',
'这里是第一集的正文内容,包含角色冲突与场景推进,长度足够用于单元测试验证。',
'END_MARKER',
'后置内容用于确保边界外还有文本,并继续补足长度。',
].join('')
const job = buildJob(content)
const result = await handleEpisodeSplitTask(job)
expect(result.success).toBe(true)
expect(result.episodes).toHaveLength(1)
expect(result.episodes[0]?.number).toBe(1)
expect(result.episodes[0]?.title).toBe('第一集')
expect(result.episodes[0]?.content).toContain('START_MARKER')
expect(result.episodes[0]?.content).toContain('END_MARKER')
})
})

View File

@@ -0,0 +1,179 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const utilsMock = vi.hoisted(() => ({
assertTaskActive: vi.fn(async () => {}),
getProjectModels: vi.fn(async () => ({ editModel: 'edit-model' })),
getUserModels: vi.fn(async () => ({ editModel: 'edit-model', analysisModel: 'analysis-model' })),
resolveImageSourceFromGeneration: vi.fn(async () => 'generated-image-source'),
stripLabelBar: vi.fn(async () => 'required-reference-image'),
toSignedUrlIfCos: vi.fn(() => 'https://signed/current-image.png'),
uploadImageSourceToCos: vi.fn(async () => 'cos/new-image.png'),
withLabelBar: vi.fn(async (source: unknown) => source),
}))
const outboundImageMock = vi.hoisted(() => ({
normalizeReferenceImagesForGeneration: vi.fn(async () => ['normalized-reference-image']),
normalizeToBase64ForGeneration: vi.fn(async () => 'base64-required-reference'),
}))
const sharedMock = vi.hoisted(() => ({
resolveNovelData: vi.fn(async () => ({ videoRatio: '16:9' })),
}))
const prismaMock = vi.hoisted(() => ({
characterAppearance: {
findUnique: vi.fn(),
update: vi.fn(async () => ({})),
},
locationImage: {
findUnique: vi.fn(),
findFirst: vi.fn(),
update: vi.fn(async () => ({})),
},
novelPromotionPanel: {
findUnique: vi.fn(),
findFirst: vi.fn(),
update: vi.fn(async () => ({})),
},
novelPromotionProject: {
findUnique: vi.fn(),
},
}))
vi.mock('@/lib/workers/utils', () => utilsMock)
vi.mock('@/lib/media/outbound-image', () => outboundImageMock)
vi.mock('@/lib/prisma', () => ({
prisma: prismaMock,
}))
vi.mock('@/lib/workers/handlers/image-task-handler-shared', async () => {
const actual = await vi.importActual<typeof import('@/lib/workers/handlers/image-task-handler-shared')>(
'@/lib/workers/handlers/image-task-handler-shared',
)
return {
...actual,
resolveNovelData: sharedMock.resolveNovelData,
}
})
import { handleModifyAssetImageTask } from '@/lib/workers/handlers/image-task-handlers-core'
function buildJob(payload: Record<string, unknown>): Job<TaskJobData> {
return {
data: {
taskId: 'task-1',
type: TASK_TYPE.MODIFY_ASSET_IMAGE,
locale: 'zh',
projectId: 'project-1',
targetType: 'NovelPromotionPanel',
targetId: 'target-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
function readUpdateData(arg: unknown): Record<string, unknown> {
if (!arg || typeof arg !== 'object') return {}
const data = (arg as { data?: unknown }).data
if (!data || typeof data !== 'object') return {}
return data as Record<string, unknown>
}
describe('worker image-task-handlers-core', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('fails fast when modify task payload is incomplete', async () => {
const job = buildJob({})
await expect(handleModifyAssetImageTask(job)).rejects.toThrow('modify task missing type/modifyPrompt')
})
it('updates location image with expected generation options and persistence payload', async () => {
prismaMock.locationImage.findUnique.mockResolvedValue({
id: 'location-image-1',
locationId: 'location-1',
imageUrl: 'cos/location-old.png',
location: { name: 'Old Town' },
})
const job = buildJob({
type: 'location',
locationImageId: 'location-image-1',
modifyPrompt: 'add heavy rain',
extraImageUrls: [' https://example.com/location-ref.png '],
generationOptions: { resolution: '1536x1024' },
})
const result = await handleModifyAssetImageTask(job)
expect(result).toEqual({
type: 'location',
locationImageId: 'location-image-1',
imageUrl: 'cos/new-image.png',
})
expect(utilsMock.resolveImageSourceFromGeneration).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
options: expect.objectContaining({
aspectRatio: '1:1',
resolution: '1536x1024',
referenceImages: ['required-reference-image', 'normalized-reference-image'],
}),
}),
)
const updateArg = prismaMock.locationImage.update.mock.calls.at(-1)?.[0]
const updateData = readUpdateData(updateArg)
expect(updateData.previousImageUrl).toBe('cos/location-old.png')
expect(updateData.imageUrl).toBe('cos/new-image.png')
})
it('updates storyboard panel image and keeps candidateImages reset', async () => {
prismaMock.novelPromotionPanel.findUnique.mockResolvedValue({
id: 'panel-1',
storyboardId: 'storyboard-1',
panelIndex: 0,
imageUrl: 'cos/panel-old.png',
previousImageUrl: null,
})
const job = buildJob({
type: 'storyboard',
panelId: 'panel-1',
modifyPrompt: 'cinematic backlight',
selectedAssets: [{ imageUrl: 'https://example.com/asset-ref.png' }],
extraImageUrls: ['https://example.com/extra-ref.png'],
generationOptions: { resolution: '2048x1152' },
})
const result = await handleModifyAssetImageTask(job)
expect(result).toEqual({
type: 'storyboard',
panelId: 'panel-1',
imageUrl: 'cos/new-image.png',
})
expect(utilsMock.resolveImageSourceFromGeneration).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
options: expect.objectContaining({
aspectRatio: '16:9',
resolution: '2048x1152',
referenceImages: [
'base64-required-reference',
'normalized-reference-image',
],
}),
}),
)
const updateArg = prismaMock.novelPromotionPanel.update.mock.calls.at(-1)?.[0]
const updateData = readUpdateData(updateArg)
expect(updateData.previousImageUrl).toBe('cos/panel-old.png')
expect(updateData.imageUrl).toBe('cos/new-image.png')
expect(updateData.candidateImages).toBeNull()
})
})

View File

@@ -0,0 +1,32 @@
import type { Job } from 'bullmq'
import { describe, expect, it } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
import { handleLLMProxyTask, isLLMProxyTaskType } from '@/lib/workers/handlers/llm-proxy'
function buildJob(type: TaskJobData['type']): Job<TaskJobData> {
return {
data: {
taskId: 'task-llm-proxy-1',
type,
locale: 'zh',
projectId: 'project-1',
episodeId: 'episode-1',
targetType: 'NovelPromotionEpisode',
targetId: 'episode-1',
payload: { episodeId: 'episode-1' },
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker llm-proxy behavior', () => {
it('current route map has no enabled proxy task type', () => {
expect(isLLMProxyTaskType(TASK_TYPE.STORY_TO_SCRIPT_RUN)).toBe(false)
expect(isLLMProxyTaskType(TASK_TYPE.SCRIPT_TO_STORYBOARD_RUN)).toBe(false)
})
it('unsupported proxy task type -> explicit error', async () => {
const job = buildJob(TASK_TYPE.STORY_TO_SCRIPT_RUN)
await expect(handleLLMProxyTask(job)).rejects.toThrow('Unsupported llm proxy task type')
})
})

View File

@@ -0,0 +1,131 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { Job } from 'bullmq'
import type { TaskJobData } from '@/lib/task/types'
const reportTaskProgressMock = vi.hoisted(() => vi.fn(async () => undefined))
const reportTaskStreamChunkMock = vi.hoisted(() => vi.fn(async () => undefined))
const assertTaskActiveMock = vi.hoisted(() => vi.fn(async () => undefined))
const isTaskActiveMock = vi.hoisted(() => vi.fn(async () => true))
vi.mock('@/lib/workers/shared', () => ({
reportTaskProgress: reportTaskProgressMock,
reportTaskStreamChunk: reportTaskStreamChunkMock,
}))
vi.mock('@/lib/workers/utils', () => ({
assertTaskActive: assertTaskActiveMock,
}))
vi.mock('@/lib/task/service', () => ({
isTaskActive: isTaskActiveMock,
}))
import { createWorkerLLMStreamCallbacks, createWorkerLLMStreamContext } from '@/lib/workers/handlers/llm-stream'
function buildJob(): Job<TaskJobData> {
const data: TaskJobData = {
taskId: 'task-1',
type: 'story_to_script_run',
locale: 'zh',
projectId: 'project-1',
userId: 'user-1',
targetType: 'NovelPromotionEpisode',
targetId: 'episode-1',
payload: {},
trace: null,
}
return {
data,
} as unknown as Job<TaskJobData>
}
describe('createWorkerLLMStreamCallbacks', () => {
beforeEach(() => {
reportTaskProgressMock.mockReset()
reportTaskStreamChunkMock.mockReset()
assertTaskActiveMock.mockReset()
isTaskActiveMock.mockReset()
isTaskActiveMock.mockResolvedValue(true)
})
it('publishes final step output on onComplete for replay recovery', async () => {
const job = buildJob()
const context = createWorkerLLMStreamContext(job, 'story_to_script')
const callbacks = createWorkerLLMStreamCallbacks(job, context)
callbacks.onStage({
stage: 'streaming',
provider: 'ark',
step: {
id: 'screenplay_clip_1',
attempt: 2,
title: 'progress.streamStep.screenplayConversion',
index: 1,
total: 1,
},
})
callbacks.onComplete('final screenplay text', {
id: 'screenplay_clip_1',
attempt: 2,
title: 'progress.streamStep.screenplayConversion',
index: 1,
total: 1,
})
await callbacks.flush()
const finalProgressCall = reportTaskProgressMock.mock.calls.find((call) => {
const payload = call[2] as Record<string, unknown> | undefined
return payload?.stage === 'worker_llm_complete'
})
expect(finalProgressCall).toBeDefined()
const payload = finalProgressCall?.[2] as Record<string, unknown>
expect(payload.done).toBe(true)
expect(payload.output).toBe('final screenplay text')
expect(payload.stepId).toBe('screenplay_clip_1')
expect(payload.stepAttempt).toBe(2)
expect(payload.stepTitle).toBe('progress.streamStep.screenplayConversion')
expect(payload.stepIndex).toBe(1)
expect(payload.stepTotal).toBe(1)
})
it('keeps completion payload bound to provided step under interleaved steps', async () => {
const job = buildJob()
const context = createWorkerLLMStreamContext(job, 'story_to_script')
const callbacks = createWorkerLLMStreamCallbacks(job, context)
callbacks.onChunk({
kind: 'text',
delta: 'A-',
seq: 1,
lane: 'main',
step: { id: 'analyze_characters', attempt: 1, title: 'A', index: 1, total: 2 },
})
callbacks.onChunk({
kind: 'text',
delta: 'B-',
seq: 1,
lane: 'main',
step: { id: 'analyze_locations', attempt: 1, title: 'B', index: 2, total: 2 },
})
callbacks.onComplete('characters-final', {
id: 'analyze_characters',
attempt: 1,
title: 'A',
index: 1,
total: 2,
})
await callbacks.flush()
const finalProgressCall = reportTaskProgressMock.mock.calls.find((call) => {
const payload = call[2] as Record<string, unknown> | undefined
return payload?.stage === 'worker_llm_complete'
})
expect(finalProgressCall).toBeDefined()
const payload = finalProgressCall?.[2] as Record<string, unknown>
expect(payload.stepId).toBe('analyze_characters')
expect(payload.stepTitle).toBe('A')
expect(payload.output).toBe('characters-final')
})
})

View File

@@ -0,0 +1,109 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const utilsMock = vi.hoisted(() => ({
assertTaskActive: vi.fn(async () => undefined),
getProjectModels: vi.fn(async () => ({ locationModel: 'location-model-1', artStyle: 'anime' })),
}))
const prismaMock = vi.hoisted(() => ({
locationImage: {
findUnique: vi.fn(),
update: vi.fn(async () => ({})),
},
novelPromotionLocation: {
findUnique: vi.fn(),
findMany: vi.fn(async () => []),
},
}))
const sharedMock = vi.hoisted(() => ({
generateLabeledImageToCos: vi.fn(async () => 'cos/location-generated-1.png'),
}))
vi.mock('@/lib/workers/utils', () => utilsMock)
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/workers/shared', () => ({ reportTaskProgress: vi.fn(async () => undefined) }))
vi.mock('@/lib/workers/handlers/image-task-handler-shared', async () => {
const actual = await vi.importActual<typeof import('@/lib/workers/handlers/image-task-handler-shared')>(
'@/lib/workers/handlers/image-task-handler-shared',
)
return {
...actual,
generateLabeledImageToCos: sharedMock.generateLabeledImageToCos,
}
})
import { handleLocationImageTask } from '@/lib/workers/handlers/location-image-task-handler'
function buildJob(payload: Record<string, unknown>, targetId = 'location-image-1'): Job<TaskJobData> {
return {
data: {
taskId: 'task-location-image-1',
type: TASK_TYPE.IMAGE_LOCATION,
locale: 'zh',
projectId: 'project-1',
episodeId: null,
targetType: 'LocationImage',
targetId,
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker location-image-task-handler behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
prismaMock.locationImage.findUnique.mockResolvedValue({
id: 'location-image-1',
locationId: 'location-1',
imageIndex: 0,
description: '雨夜街道',
location: { name: 'Old Town' },
})
prismaMock.novelPromotionLocation.findUnique.mockResolvedValue({
id: 'location-1',
name: 'Old Town',
images: [
{
id: 'location-image-1',
locationId: 'location-1',
imageIndex: 0,
description: '雨夜街道',
},
],
})
})
it('locationModel missing -> explicit error', async () => {
utilsMock.getProjectModels.mockResolvedValueOnce({ locationModel: '', artStyle: 'anime' })
await expect(handleLocationImageTask(buildJob({}))).rejects.toThrow('Location model not configured')
})
it('success path -> generates and persists concrete location image url', async () => {
const result = await handleLocationImageTask(buildJob({ imageIndex: 0 }))
expect(result).toEqual({
updated: 1,
locationIds: ['location-1'],
})
expect(sharedMock.generateLabeledImageToCos).toHaveBeenCalledWith(
expect.objectContaining({
prompt: '雨夜街道',
label: 'Old Town',
targetId: 'location-image-1',
options: expect.objectContaining({ aspectRatio: '1:1' }),
}),
)
expect(prismaMock.locationImage.update).toHaveBeenCalledWith({
where: { id: 'location-image-1' },
data: { imageUrl: 'cos/location-generated-1.png' },
})
})
})

View File

@@ -0,0 +1,183 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData, type TaskType } from '@/lib/task/types'
const utilsMock = vi.hoisted(() => ({
assertTaskActive: vi.fn(async () => {}),
getProjectModels: vi.fn(async () => ({ editModel: 'edit-model' })),
getUserModels: vi.fn(async () => ({ editModel: 'edit-model', analysisModel: 'analysis-model' })),
resolveImageSourceFromGeneration: vi.fn(async () => 'generated-image-source'),
stripLabelBar: vi.fn(async () => 'required-reference-image'),
toSignedUrlIfCos: vi.fn(() => 'https://signed/current-image.png'),
uploadImageSourceToCos: vi.fn(async () => 'cos/new-image.png'),
withLabelBar: vi.fn(async (source: unknown) => source),
}))
const outboundImageMock = vi.hoisted(() => ({
normalizeReferenceImagesForGeneration: vi.fn(async () => ['normalized-reference-image']),
normalizeToBase64ForGeneration: vi.fn(async () => 'base64-reference'),
}))
const llmClientMock = vi.hoisted(() => ({
chatCompletionWithVision: vi.fn(async () => ({ output_text: 'AI_EXTRACTED_DESCRIPTION' })),
getCompletionContent: vi.fn(() => 'AI_EXTRACTED_DESCRIPTION'),
}))
const promptMock = vi.hoisted(() => ({
PROMPT_IDS: {
CHARACTER_IMAGE_TO_DESCRIPTION: 'character_image_to_description',
},
buildPrompt: vi.fn(() => 'vision-prompt-template'),
}))
const loggerWarnMock = vi.hoisted(() => vi.fn())
const loggingMock = vi.hoisted(() => ({
createScopedLogger: vi.fn(() => ({
warn: loggerWarnMock,
})),
}))
const prismaMock = vi.hoisted(() => ({
characterAppearance: {
findUnique: vi.fn(),
update: vi.fn(async () => ({})),
},
locationImage: {
findUnique: vi.fn(),
findFirst: vi.fn(),
update: vi.fn(async () => ({})),
},
novelPromotionPanel: {
findUnique: vi.fn(),
findFirst: vi.fn(),
update: vi.fn(async () => ({})),
},
novelPromotionProject: {
findUnique: vi.fn(),
},
globalCharacter: {
findFirst: vi.fn(),
},
globalCharacterAppearance: {
update: vi.fn(async () => ({})),
},
globalLocation: {
findFirst: vi.fn(),
},
globalLocationImage: {
update: vi.fn(async () => ({})),
},
}))
vi.mock('@/lib/workers/utils', () => utilsMock)
vi.mock('@/lib/media/outbound-image', () => outboundImageMock)
vi.mock('@/lib/llm-client', () => llmClientMock)
vi.mock('@/lib/prompt-i18n', () => promptMock)
vi.mock('@/lib/logging/core', () => loggingMock)
vi.mock('@/lib/prisma', () => ({
prisma: prismaMock,
}))
import { handleModifyAssetImageTask } from '@/lib/workers/handlers/image-task-handlers-core'
import { handleAssetHubModifyTask } from '@/lib/workers/handlers/asset-hub-modify-task-handler'
function buildJob(type: TaskType, payload: Record<string, unknown>): Job<TaskJobData> {
return {
data: {
taskId: 'task-1',
type,
locale: 'zh',
projectId: 'project-1',
targetType: 'GlobalCharacter',
targetId: 'target-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
function getUpdateData(callArg: unknown): Record<string, unknown> {
if (!callArg || typeof callArg !== 'object') return {}
const maybeData = (callArg as { data?: unknown }).data
if (!maybeData || typeof maybeData !== 'object') return {}
return maybeData as Record<string, unknown>
}
describe('modify image with references writes real description', () => {
beforeEach(() => {
vi.clearAllMocks()
prismaMock.characterAppearance.findUnique.mockResolvedValue({
id: 'appearance-1',
imageUrls: JSON.stringify(['cos/original-image.png']),
imageUrl: 'cos/original-image.png',
selectedIndex: 0,
changeReason: 'base',
description: 'old description',
character: { name: 'Hero' },
})
prismaMock.globalCharacter.findFirst.mockResolvedValue({
id: 'global-character-1',
name: 'Hero',
appearances: [
{
id: 'global-appearance-1',
appearanceIndex: 0,
changeReason: 'base',
imageUrl: 'cos/original-global.png',
imageUrls: JSON.stringify(['cos/original-global.png']),
selectedIndex: 0,
},
],
})
})
it('updates character appearance description from vision output in project modify handler', async () => {
const job = buildJob(TASK_TYPE.MODIFY_ASSET_IMAGE, {
type: 'character',
appearanceId: 'appearance-1',
modifyPrompt: 'enhance details',
extraImageUrls: [' https://ref.example/a.png '],
})
await handleModifyAssetImageTask(job)
expect(utilsMock.resolveImageSourceFromGeneration).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
options: expect.objectContaining({
aspectRatio: '3:2',
referenceImages: ['required-reference-image', 'normalized-reference-image'],
}),
}),
)
const updateArg = prismaMock.characterAppearance.update.mock.calls.at(-1)?.[0]
const updateData = getUpdateData(updateArg)
expect(updateData.description).toBe('AI_EXTRACTED_DESCRIPTION')
expect(updateData.previousDescription).toBe('old description')
expect(updateData.imageUrl).toBe('cos/new-image.png')
})
it('updates asset-hub character description from vision output when reference image exists', async () => {
utilsMock.uploadImageSourceToCos.mockResolvedValueOnce('cos/new-global-image.png')
const job = buildJob(TASK_TYPE.ASSET_HUB_MODIFY, {
type: 'character',
id: 'global-character-1',
appearanceIndex: 0,
imageIndex: 0,
modifyPrompt: 'make it sharper',
extraImageUrls: ['https://ref.example/b.png'],
})
await handleAssetHubModifyTask(job)
const updateArg = prismaMock.globalCharacterAppearance.update.mock.calls.at(-1)?.[0]
const updateData = getUpdateData(updateArg)
expect(updateData.description).toBe('AI_EXTRACTED_DESCRIPTION')
expect(updateData.imageUrl).toBe('cos/new-global-image.png')
expect(updateData.imageUrls).toBe(JSON.stringify(['cos/new-global-image.png']))
})
})

View File

@@ -0,0 +1,187 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const prismaMock = vi.hoisted(() => ({
novelPromotionPanel: {
findUnique: vi.fn(),
update: vi.fn(async () => ({})),
},
}))
const utilsMock = vi.hoisted(() => ({
assertTaskActive: vi.fn(async () => undefined),
getProjectModels: vi.fn(async () => ({ storyboardModel: 'storyboard-model-1', artStyle: 'cinematic' })),
resolveImageSourceFromGeneration: vi.fn(),
uploadImageSourceToCos: vi.fn(),
}))
const sharedMock = vi.hoisted(() => ({
collectPanelReferenceImages: vi.fn(async () => ['https://signed.example/ref-1.png']),
resolveNovelData: vi.fn(async () => ({
videoRatio: '16:9',
characters: [],
locations: [],
})),
}))
const outboundMock = vi.hoisted(() => ({
normalizeReferenceImagesForGeneration: vi.fn(async () => ['normalized-ref-1']),
}))
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/workers/utils', () => utilsMock)
vi.mock('@/lib/media/outbound-image', () => outboundMock)
vi.mock('@/lib/workers/shared', () => ({ reportTaskProgress: vi.fn(async () => undefined) }))
vi.mock('@/lib/logging/core', () => ({
logInfo: vi.fn(),
createScopedLogger: vi.fn(() => ({
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
event: vi.fn(),
child: vi.fn(),
})),
}))
vi.mock('@/lib/workers/handlers/image-task-handler-shared', async () => {
const actual = await vi.importActual<typeof import('@/lib/workers/handlers/image-task-handler-shared')>(
'@/lib/workers/handlers/image-task-handler-shared',
)
return {
...actual,
collectPanelReferenceImages: sharedMock.collectPanelReferenceImages,
resolveNovelData: sharedMock.resolveNovelData,
}
})
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: { NP_SINGLE_PANEL_IMAGE: 'np_single_panel_image' },
buildPrompt: vi.fn(() => 'panel-image-prompt'),
}))
import { handlePanelImageTask } from '@/lib/workers/handlers/panel-image-task-handler'
function buildJob(payload: Record<string, unknown>, targetId = 'panel-1'): Job<TaskJobData> {
return {
data: {
taskId: 'task-panel-image-1',
type: TASK_TYPE.IMAGE_PANEL,
locale: 'zh',
projectId: 'project-1',
episodeId: 'episode-1',
targetType: 'NovelPromotionPanel',
targetId,
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker panel-image-task-handler behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
prismaMock.novelPromotionPanel.findUnique.mockResolvedValue({
id: 'panel-1',
storyboardId: 'storyboard-1',
panelIndex: 0,
shotType: 'close-up',
cameraMove: 'static',
description: 'hero close-up',
videoPrompt: 'dramatic',
location: 'Old Town',
characters: JSON.stringify([{ name: 'Hero', appearance: 'default' }]),
srtSegment: '台词片段',
photographyRules: null,
actingNotes: null,
sketchImageUrl: null,
imageUrl: null,
})
utilsMock.resolveImageSourceFromGeneration
.mockResolvedValueOnce('generated-source-1')
.mockResolvedValueOnce('generated-source-2')
utilsMock.uploadImageSourceToCos
.mockResolvedValueOnce('cos/panel-candidate-1.png')
.mockResolvedValueOnce('cos/panel-candidate-2.png')
})
it('missing panelId -> explicit error', async () => {
const job = buildJob({}, '')
await expect(handlePanelImageTask(job)).rejects.toThrow('panelId missing')
})
it('first generation -> persists main image and candidate list', async () => {
const job = buildJob({ candidateCount: 2 })
const result = await handlePanelImageTask(job)
expect(result).toEqual({
panelId: 'panel-1',
candidateCount: 2,
imageUrl: 'cos/panel-candidate-1.png',
})
expect(utilsMock.resolveImageSourceFromGeneration).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
modelId: 'storyboard-model-1',
prompt: 'panel-image-prompt',
options: expect.objectContaining({
referenceImages: ['normalized-ref-1'],
aspectRatio: '16:9',
}),
}),
)
expect(prismaMock.novelPromotionPanel.update).toHaveBeenCalledWith({
where: { id: 'panel-1' },
data: {
imageUrl: 'cos/panel-candidate-1.png',
candidateImages: JSON.stringify(['cos/panel-candidate-1.png', 'cos/panel-candidate-2.png']),
},
})
})
it('regeneration branch -> keeps old image in previousImageUrl and stores candidates only', async () => {
utilsMock.resolveImageSourceFromGeneration.mockReset()
utilsMock.uploadImageSourceToCos.mockReset()
prismaMock.novelPromotionPanel.findUnique.mockResolvedValueOnce({
id: 'panel-1',
storyboardId: 'storyboard-1',
panelIndex: 0,
shotType: 'close-up',
cameraMove: 'static',
description: 'hero close-up',
videoPrompt: 'dramatic',
location: 'Old Town',
characters: '[]',
srtSegment: null,
photographyRules: null,
actingNotes: null,
sketchImageUrl: null,
imageUrl: 'cos/panel-old.png',
})
utilsMock.resolveImageSourceFromGeneration.mockResolvedValueOnce('generated-source-regen')
utilsMock.uploadImageSourceToCos.mockResolvedValueOnce('cos/panel-regenerated.png')
const job = buildJob({ candidateCount: 1 })
const result = await handlePanelImageTask(job)
expect(result).toEqual({
panelId: 'panel-1',
candidateCount: 1,
imageUrl: null,
})
expect(prismaMock.novelPromotionPanel.update).toHaveBeenCalledWith({
where: { id: 'panel-1' },
data: {
previousImageUrl: 'cos/panel-old.png',
candidateImages: JSON.stringify(['cos/panel-regenerated.png']),
},
})
})
})

View File

@@ -0,0 +1,143 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const prismaMock = vi.hoisted(() => ({
novelPromotionPanel: {
findUnique: vi.fn(),
update: vi.fn(async () => ({})),
},
}))
const utilsMock = vi.hoisted(() => ({
assertTaskActive: vi.fn(async () => undefined),
getProjectModels: vi.fn(async () => ({ storyboardModel: 'storyboard-model-1', artStyle: 'cinematic' })),
resolveImageSourceFromGeneration: vi.fn(async () => 'generated-variant-source'),
toSignedUrlIfCos: vi.fn((url: string | null | undefined) => (url ? `https://signed.example/${url}` : null)),
uploadImageSourceToCos: vi.fn(async () => 'cos/panel-variant-new.png'),
}))
const sharedMock = vi.hoisted(() => ({
collectPanelReferenceImages: vi.fn(async () => ['https://signed.example/ref-character.png']),
resolveNovelData: vi.fn(async () => ({
videoRatio: '16:9',
characters: [{ name: 'Hero', introduction: '主角' }],
locations: [{ name: 'Old Town' }],
})),
}))
const outboundMock = vi.hoisted(() => ({
normalizeReferenceImagesForGeneration: vi.fn(async (refs: string[]) => refs.map((item) => `normalized:${item}`)),
}))
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/workers/utils', () => utilsMock)
vi.mock('@/lib/media/outbound-image', () => outboundMock)
vi.mock('@/lib/logging/core', () => ({ logInfo: vi.fn() }))
vi.mock('@/lib/workers/handlers/image-task-handler-shared', async () => {
const actual = await vi.importActual<typeof import('@/lib/workers/handlers/image-task-handler-shared')>(
'@/lib/workers/handlers/image-task-handler-shared',
)
return {
...actual,
collectPanelReferenceImages: sharedMock.collectPanelReferenceImages,
resolveNovelData: sharedMock.resolveNovelData,
}
})
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: { NP_AGENT_SHOT_VARIANT_GENERATE: 'np_agent_shot_variant_generate' },
buildPrompt: vi.fn(() => 'panel-variant-prompt'),
}))
import { handlePanelVariantTask } from '@/lib/workers/handlers/panel-variant-task-handler'
function buildJob(payload: Record<string, unknown>): Job<TaskJobData> {
return {
data: {
taskId: 'task-panel-variant-1',
type: TASK_TYPE.PANEL_VARIANT,
locale: 'zh',
projectId: 'project-1',
episodeId: 'episode-1',
targetType: 'NovelPromotionPanel',
targetId: 'panel-new',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker panel-variant-task-handler behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
prismaMock.novelPromotionPanel.findUnique.mockImplementation(async (args: { where: { id: string } }) => {
if (args.where.id === 'panel-new') {
return {
id: 'panel-new',
storyboardId: 'storyboard-1',
imageUrl: null,
location: 'Old Town',
characters: JSON.stringify([{ name: 'Hero', appearance: 'default' }]),
}
}
if (args.where.id === 'panel-source') {
return {
id: 'panel-source',
storyboardId: 'storyboard-1',
imageUrl: 'cos/panel-source.png',
description: 'source description',
shotType: 'medium',
cameraMove: 'pan',
location: 'Old Town',
characters: JSON.stringify([{ name: 'Hero' }]),
}
}
return null
})
})
it('missing source/new panel ids -> explicit error', async () => {
const job = buildJob({})
await expect(handlePanelVariantTask(job)).rejects.toThrow('panel_variant missing newPanelId/sourcePanelId')
})
it('success path -> includes source panel image in referenceImages and persists new image', async () => {
const payload = {
newPanelId: 'panel-new',
sourcePanelId: 'panel-source',
variant: {
title: '雨夜版本',
description: '加强雨夜氛围',
},
}
const result = await handlePanelVariantTask(buildJob(payload))
expect(utilsMock.resolveImageSourceFromGeneration).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
modelId: 'storyboard-model-1',
prompt: 'panel-variant-prompt',
options: expect.objectContaining({
aspectRatio: '16:9',
referenceImages: [
'normalized:https://signed.example/cos/panel-source.png',
'normalized:https://signed.example/ref-character.png',
],
}),
}),
)
expect(prismaMock.novelPromotionPanel.update).toHaveBeenCalledWith({
where: { id: 'panel-new' },
data: { imageUrl: 'cos/panel-variant-new.png' },
})
expect(result).toEqual({
panelId: 'panel-new',
storyboardId: 'storyboard-1',
imageUrl: 'cos/panel-variant-new.png',
})
})
})

View File

@@ -0,0 +1,215 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { CHARACTER_PROMPT_SUFFIX, CHARACTER_IMAGE_BANANA_RATIO } from '@/lib/constants'
import { TASK_TYPE, type TaskJobData, type TaskType } from '@/lib/task/types'
const sharpMock = vi.hoisted(() =>
vi.fn(() => {
const chain = {
metadata: vi.fn(async () => ({ width: 2160, height: 2160 })),
extend: vi.fn(() => chain),
composite: vi.fn(() => chain),
jpeg: vi.fn(() => chain),
toBuffer: vi.fn(async () => Buffer.from('processed-image')),
}
return chain
}),
)
const generatorApiMock = vi.hoisted(() => ({
generateImage: vi.fn(async () => ({
success: true,
imageUrl: 'https://example.com/generated.jpg',
async: false,
})),
}))
const asyncSubmitMock = vi.hoisted(() => ({
queryFalStatus: vi.fn(async () => ({ completed: false, failed: false, resultUrl: null })),
}))
const arkApiMock = vi.hoisted(() => ({
fetchWithTimeoutAndRetry: vi.fn(async () => ({
arrayBuffer: async () => new Uint8Array([1, 2, 3]).buffer,
})),
}))
const apiConfigMock = vi.hoisted(() => ({
getProviderConfig: vi.fn(async () => ({ apiKey: 'fal-key' })),
}))
const configServiceMock = vi.hoisted(() => ({
getUserModelConfig: vi.fn(async () => ({
characterModel: 'character-model-1',
analysisModel: 'analysis-model-1',
})),
}))
const llmClientMock = vi.hoisted(() => ({
chatCompletionWithVision: vi.fn(async () => ({ output_text: 'AI_EXTRACTED_DESCRIPTION' })),
getCompletionContent: vi.fn(() => 'AI_EXTRACTED_DESCRIPTION'),
}))
const cosMock = vi.hoisted(() => {
let keyIndex = 0
return {
generateUniqueKey: vi.fn(() => `reference-key-${++keyIndex}.jpg`),
getSignedUrl: vi.fn((key: string) => `https://signed.example/${key}`),
uploadToCOS: vi.fn(async (_buffer: Buffer, key: string) => `cos/${key}`),
}
})
const fontsMock = vi.hoisted(() => ({
initializeFonts: vi.fn(async () => {}),
createLabelSVG: vi.fn(async () => Buffer.from('<svg />')),
}))
const workersSharedMock = vi.hoisted(() => ({
reportTaskProgress: vi.fn(async () => {}),
}))
const workersUtilsMock = vi.hoisted(() => ({
assertTaskActive: vi.fn(async () => {}),
}))
const promptI18nMock = vi.hoisted(() => ({
PROMPT_IDS: {
CHARACTER_IMAGE_TO_DESCRIPTION: 'character_image_to_description',
CHARACTER_REFERENCE_TO_SHEET: 'character_reference_to_sheet',
},
buildPrompt: vi.fn((input: { promptId: string }) => (
input.promptId === 'character_reference_to_sheet'
? 'BASE_REFERENCE_PROMPT'
: 'ANALYSIS_PROMPT'
)),
}))
const prismaMock = vi.hoisted(() => ({
globalCharacterAppearance: {
update: vi.fn(async () => ({})),
},
characterAppearance: {
update: vi.fn(async () => ({})),
},
}))
vi.mock('sharp', () => ({
default: sharpMock,
}))
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/generator-api', () => generatorApiMock)
vi.mock('@/lib/async-submit', () => asyncSubmitMock)
vi.mock('@/lib/ark-api', () => arkApiMock)
vi.mock('@/lib/api-config', () => apiConfigMock)
vi.mock('@/lib/config-service', () => configServiceMock)
vi.mock('@/lib/llm-client', () => llmClientMock)
vi.mock('@/lib/cos', () => cosMock)
vi.mock('@/lib/fonts', () => fontsMock)
vi.mock('@/lib/workers/shared', () => workersSharedMock)
vi.mock('@/lib/workers/utils', () => workersUtilsMock)
vi.mock('@/lib/prompt-i18n', () => promptI18nMock)
import { handleReferenceToCharacterTask } from '@/lib/workers/handlers/reference-to-character'
function buildJob(payload: Record<string, unknown>, type: TaskType): Job<TaskJobData> {
return {
data: {
taskId: 'task-1',
type,
locale: 'zh',
projectId: 'project-1',
targetType: 'GlobalCharacter',
targetId: 'target-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
function readGenerateCall(index: number) {
const call = generatorApiMock.generateImage.mock.calls[index]
if (!call) {
return {
prompt: '',
options: {} as Record<string, unknown>,
}
}
const prompt = typeof call[2] === 'string' ? call[2] : ''
const options = (typeof call[3] === 'object' && call[3]) ? call[3] as Record<string, unknown> : {}
return { prompt, options }
}
describe('worker reference-to-character', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('fails fast when reference images are missing', async () => {
const job = buildJob({}, TASK_TYPE.ASSET_HUB_REFERENCE_TO_CHARACTER)
await expect(handleReferenceToCharacterTask(job)).rejects.toThrow('Missing referenceImageUrl or referenceImageUrls')
})
it('fails fast on unsupported task type', async () => {
const job = buildJob(
{ referenceImageUrl: 'https://example.com/ref.png' },
'unsupported-task' as TaskType,
)
await expect(handleReferenceToCharacterTask(job)).rejects.toThrow('Unsupported task type')
})
it('uses suffix prompt and disables reference-image injection when customDescription is provided', async () => {
const job = buildJob(
{
referenceImageUrls: ['https://example.com/ref-a.png', 'https://example.com/ref-b.png'],
customDescription: '冷静黑发角色',
characterName: 'Hero',
},
TASK_TYPE.ASSET_HUB_REFERENCE_TO_CHARACTER,
)
const result = await handleReferenceToCharacterTask(job)
expect(result).toEqual(expect.objectContaining({ success: true }))
expect(generatorApiMock.generateImage).toHaveBeenCalledTimes(3)
const { prompt, options } = readGenerateCall(0)
expect(prompt).toContain('冷静黑发角色')
expect(prompt).toContain(CHARACTER_PROMPT_SUFFIX)
expect(options.aspectRatio).toBe(CHARACTER_IMAGE_BANANA_RATIO)
expect(options.referenceImages).toBeUndefined()
})
it('keeps three-view suffix in template flow and writes extracted description in background mode', async () => {
const job = buildJob(
{
referenceImageUrls: [' https://example.com/ref-a.png ', 'https://example.com/ref-b.png'],
isBackgroundJob: true,
characterId: 'character-1',
appearanceId: 'appearance-1',
characterName: 'Hero',
},
TASK_TYPE.ASSET_HUB_REFERENCE_TO_CHARACTER,
)
const result = await handleReferenceToCharacterTask(job)
expect(result).toEqual({ success: true })
expect(generatorApiMock.generateImage).toHaveBeenCalledTimes(3)
const { prompt, options } = readGenerateCall(0)
expect(prompt).toContain('BASE_REFERENCE_PROMPT')
expect(prompt).toContain(CHARACTER_PROMPT_SUFFIX)
expect(options.referenceImages).toEqual(['https://example.com/ref-a.png', 'https://example.com/ref-b.png'])
expect(options.aspectRatio).toBe(CHARACTER_IMAGE_BANANA_RATIO)
const updateArg = prismaMock.globalCharacterAppearance.update.mock.calls[0]?.[0] as {
data?: Record<string, unknown>
where?: Record<string, unknown>
} | undefined
const updateData = updateArg?.data || {}
expect(updateArg?.where).toEqual({ id: 'appearance-1' })
expect(updateData.description).toBe('AI_EXTRACTED_DESCRIPTION')
expect(typeof updateData.imageUrls).toBe('string')
expect(updateData.imageUrl).toMatch(/^cos\/reference-key-\d+\.jpg$/)
})
})

View File

@@ -0,0 +1,141 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const prismaMock = vi.hoisted(() => ({
project: { findUnique: vi.fn() },
novelPromotionProject: { findUnique: vi.fn() },
novelPromotionEpisode: { findUnique: vi.fn() },
novelPromotionClip: { update: vi.fn(async () => ({})) },
}))
const llmMock = vi.hoisted(() => ({
chatCompletion: vi.fn(async () => ({ id: 'completion-1' })),
getCompletionContent: vi.fn(() => '{"scenes":[{"index":1}]}'),
}))
const workerMock = vi.hoisted(() => ({
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
const helpersMock = vi.hoisted(() => ({
parseScreenplayPayload: vi.fn(() => ({ scenes: [{ index: 1 }] })),
}))
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/llm-client', () => llmMock)
vi.mock('@/lib/llm-observe/internal-stream-context', () => ({
withInternalLLMStreamCallbacks: vi.fn(async (_callbacks: unknown, fn: () => Promise<unknown>) => await fn()),
}))
vi.mock('@/lib/constants', () => ({
buildCharactersIntroduction: vi.fn(() => 'characters introduction'),
}))
vi.mock('@/lib/workers/shared', () => ({ reportTaskProgress: workerMock.reportTaskProgress }))
vi.mock('@/lib/workers/utils', () => ({ assertTaskActive: workerMock.assertTaskActive }))
vi.mock('@/lib/logging/semantic', () => ({ logAIAnalysis: vi.fn() }))
vi.mock('@/lib/logging/file-writer', () => ({ onProjectNameAvailable: vi.fn() }))
vi.mock('@/lib/workers/handlers/llm-stream', () => ({
createWorkerLLMStreamContext: vi.fn(() => ({ streamRunId: 'run-1', nextSeqByStepLane: {} })),
createWorkerLLMStreamCallbacks: vi.fn(() => ({
onStage: vi.fn(),
onChunk: vi.fn(),
onComplete: vi.fn(),
onError: vi.fn(),
flush: vi.fn(async () => undefined),
})),
}))
vi.mock('@/lib/workers/handlers/screenplay-convert-helpers', () => ({
readText: (value: unknown) => (typeof value === 'string' ? value : ''),
parseScreenplayPayload: helpersMock.parseScreenplayPayload,
}))
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: { NP_SCREENPLAY_CONVERSION: 'np_screenplay_conversion' },
getPromptTemplate: vi.fn(() => 'screenplay-template-{clip_content}-{clip_id}'),
}))
import { handleScreenplayConvertTask } from '@/lib/workers/handlers/screenplay-convert'
function buildJob(payload: Record<string, unknown>, episodeId: string | null = 'episode-1'): Job<TaskJobData> {
return {
data: {
taskId: 'task-screenplay-1',
type: TASK_TYPE.SCREENPLAY_CONVERT,
locale: 'zh',
projectId: 'project-1',
episodeId,
targetType: 'NovelPromotionEpisode',
targetId: 'episode-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker screenplay-convert behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
prismaMock.project.findUnique.mockResolvedValue({
id: 'project-1',
name: 'Project One',
mode: 'novel-promotion',
})
prismaMock.novelPromotionProject.findUnique.mockResolvedValue({
id: 'np-project-1',
analysisModel: 'llm::analysis-1',
characters: [{ name: 'Hero' }],
locations: [{ name: 'Old Town' }],
})
prismaMock.novelPromotionEpisode.findUnique.mockResolvedValue({
id: 'episode-1',
novelPromotionProjectId: 'np-project-1',
clips: [
{
id: 'clip-1',
content: 'clip 1 content',
},
],
})
})
it('missing episodeId -> explicit error', async () => {
const job = buildJob({}, null)
await expect(handleScreenplayConvertTask(job)).rejects.toThrow('episodeId is required')
})
it('success path -> writes screenplay json to clip row', async () => {
const job = buildJob({ episodeId: 'episode-1' })
const result = await handleScreenplayConvertTask(job)
expect(result).toEqual(expect.objectContaining({
episodeId: 'episode-1',
total: 1,
successCount: 1,
failCount: 0,
totalScenes: 1,
}))
expect(prismaMock.novelPromotionClip.update).toHaveBeenCalledWith({
where: { id: 'clip-1' },
data: {
screenplay: JSON.stringify({
scenes: [{ index: 1 }],
clip_id: 'clip-1',
original_text: 'clip 1 content',
}),
},
})
})
it('clip parse failed -> throws partial failure error with code prefix', async () => {
helpersMock.parseScreenplayPayload.mockImplementation(() => {
throw new Error('invalid screenplay payload')
})
const job = buildJob({ episodeId: 'episode-1' })
await expect(handleScreenplayConvertTask(job)).rejects.toThrow('SCREENPLAY_CONVERT_PARTIAL_FAILED')
})
})

View File

@@ -0,0 +1,106 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { runScriptToStoryboardOrchestrator } from '@/lib/novel-promotion/script-to-storyboard/orchestrator'
describe('script-to-storyboard orchestrator retry', () => {
afterEach(() => {
delete process.env.NP_SCRIPT_TO_STORYBOARD_CONCURRENCY
})
it('retries retryable step failures up to 3 attempts', async () => {
const attemptsByAction = new Map<string, number>()
const phase1Metas: Array<{ stepId: string; stepAttempt?: number }> = []
const runStep = vi.fn(async (meta, _prompt, action: string) => {
attemptsByAction.set(action, (attemptsByAction.get(action) || 0) + 1)
if (action === 'storyboard_phase1_plan') {
phase1Metas.push({ stepId: meta.stepId, stepAttempt: meta.stepAttempt })
const attempt = attemptsByAction.get(action) || 0
if (attempt < 3) {
throw new TypeError('terminated')
}
return {
text: JSON.stringify([{ panel_number: 1, description: '镜头', location: '场景A', source_text: '原文', characters: [] }]),
reasoning: '',
}
}
if (action === 'storyboard_phase2_cinematography') {
return { text: JSON.stringify([{ panel_number: 1, composition: '居中' }]), reasoning: '' }
}
if (action === 'storyboard_phase2_acting') {
return { text: JSON.stringify([{ panel_number: 1, characters: [] }]), reasoning: '' }
}
return {
text: JSON.stringify([{ panel_number: 1, description: '镜头', location: '场景A', source_text: '原文', characters: [] }]),
reasoning: '',
}
})
const result = await runScriptToStoryboardOrchestrator({
clips: [
{
id: 'clip-1',
content: '文本',
characters: JSON.stringify([{ name: '角色A' }]),
location: '场景A',
screenplay: null,
},
],
novelPromotionData: {
characters: [{ name: '角色A', appearances: [] }],
locations: [{ name: '场景A', images: [] }],
},
promptTemplates: {
phase1PlanTemplate: '{clip_content} {clip_json} {characters_lib_name} {locations_lib_name} {characters_introduction} {characters_appearance_list} {characters_full_description}',
phase2CinematographyTemplate: '{panels_json} {panel_count} {locations_description} {characters_info}',
phase2ActingTemplate: '{panels_json} {panel_count} {characters_info}',
phase3DetailTemplate: '{panels_json} {characters_age_gender} {locations_description}',
},
runStep,
})
expect(result.summary.clipCount).toBe(1)
expect(runStep).toHaveBeenCalled()
expect(attemptsByAction.get('storyboard_phase1_plan')).toBe(3)
expect(phase1Metas).toEqual([
{ stepId: 'clip_clip-1_phase1', stepAttempt: undefined },
{ stepId: 'clip_clip-1_phase1', stepAttempt: 2 },
{ stepId: 'clip_clip-1_phase1', stepAttempt: 3 },
])
})
it('does not retry non-retryable step failure', async () => {
let callCount = 0
const runStep = vi.fn(async () => {
callCount += 1
throw new Error('SENSITIVE_CONTENT: blocked')
})
await expect(
runScriptToStoryboardOrchestrator({
clips: [
{
id: 'clip-1',
content: '文本',
characters: JSON.stringify([{ name: '角色A' }]),
location: '场景A',
screenplay: null,
},
],
novelPromotionData: {
characters: [{ name: '角色A', appearances: [] }],
locations: [{ name: '场景A', images: [] }],
},
promptTemplates: {
phase1PlanTemplate: '{clip_content} {clip_json} {characters_lib_name} {locations_lib_name} {characters_introduction} {characters_appearance_list} {characters_full_description}',
phase2CinematographyTemplate: '{panels_json} {panel_count} {locations_description} {characters_info}',
phase2ActingTemplate: '{panels_json} {panel_count} {characters_info}',
phase3DetailTemplate: '{panels_json} {characters_age_gender} {locations_description}',
},
runStep,
}),
).rejects.toThrow('SENSITIVE_CONTENT')
expect(callCount).toBe(1)
})
})

View File

@@ -0,0 +1,297 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
type VoiceLineInput = {
lineIndex: number
speaker: string
content: string
emotionStrength: number
matchedPanel: {
storyboardId: string
panelIndex: number
}
}
const reportTaskProgressMock = vi.hoisted(() => vi.fn(async () => undefined))
const assertTaskActiveMock = vi.hoisted(() => vi.fn(async () => undefined))
const chatCompletionMock = vi.hoisted(() => vi.fn(async () => ({ responseId: 'resp-1' })))
const getCompletionPartsMock = vi.hoisted(() => vi.fn(() => ({ text: 'voice lines json', reasoning: '' })))
const resolveProjectModelCapabilityGenerationOptionsMock = vi.hoisted(() =>
vi.fn(async () => ({ reasoningEffort: 'high' })),
)
const runScriptToStoryboardOrchestratorMock = vi.hoisted(() =>
vi.fn(async () => ({
clipPanels: [
{
clipId: 'clip-1',
panels: [
{
panelIndex: 1,
shotType: 'close-up',
cameraMove: 'static',
description: 'panel desc',
videoPrompt: 'panel prompt',
location: 'room',
characters: ['Narrator'],
},
],
},
],
summary: {
totalPanelCount: 1,
totalStepCount: 4,
},
})),
)
const parseVoiceLinesJsonMock = vi.hoisted(() => vi.fn())
const persistStoryboardsAndPanelsMock = vi.hoisted(() => vi.fn())
const txState = vi.hoisted(() => ({
createdRows: [] as Array<Record<string, unknown>>,
}))
const prismaMock = vi.hoisted(() => ({
project: {
findUnique: vi.fn(),
},
novelPromotionProject: {
findUnique: vi.fn(),
},
novelPromotionEpisode: {
findUnique: vi.fn(),
},
$transaction: vi.fn(),
}))
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/llm-client', () => ({
chatCompletion: chatCompletionMock,
getCompletionParts: getCompletionPartsMock,
}))
vi.mock('@/lib/config-service', () => ({
resolveProjectModelCapabilityGenerationOptions: resolveProjectModelCapabilityGenerationOptionsMock,
}))
vi.mock('@/lib/llm-observe/internal-stream-context', () => ({
withInternalLLMStreamCallbacks: vi.fn(async (_callbacks: unknown, fn: () => Promise<unknown>) => await fn()),
}))
vi.mock('@/lib/logging/semantic', () => ({
logAIAnalysis: vi.fn(),
}))
vi.mock('@/lib/logging/file-writer', () => ({
onProjectNameAvailable: vi.fn(),
}))
vi.mock('@/lib/constants', () => ({
buildCharactersIntroduction: vi.fn(() => 'characters-introduction'),
}))
vi.mock('@/lib/workers/shared', () => ({
reportTaskProgress: reportTaskProgressMock,
}))
vi.mock('@/lib/workers/utils', () => ({
assertTaskActive: assertTaskActiveMock,
}))
vi.mock('@/lib/novel-promotion/script-to-storyboard/orchestrator', () => ({
runScriptToStoryboardOrchestrator: runScriptToStoryboardOrchestratorMock,
JsonParseError: class JsonParseError extends Error {
rawText: string
constructor(message: string, rawText: string) {
super(message)
this.name = 'JsonParseError'
this.rawText = rawText
}
},
}))
vi.mock('@/lib/workers/handlers/llm-stream', () => ({
createWorkerLLMStreamContext: vi.fn(() => ({ streamRunId: 'run-1', nextSeqByStepLane: {} })),
createWorkerLLMStreamCallbacks: vi.fn(() => ({
onStage: vi.fn(),
onChunk: vi.fn(),
onComplete: vi.fn(),
onError: vi.fn(),
flush: vi.fn(async () => undefined),
})),
}))
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: {
NP_AGENT_STORYBOARD_PLAN: 'plan',
NP_AGENT_CINEMATOGRAPHER: 'cinematographer',
NP_AGENT_ACTING_DIRECTION: 'acting',
NP_AGENT_STORYBOARD_DETAIL: 'detail',
NP_VOICE_ANALYSIS: 'voice-analysis',
},
getPromptTemplate: vi.fn(() => 'prompt-template'),
buildPrompt: vi.fn(() => 'voice-analysis-prompt'),
}))
vi.mock('@/lib/workers/handlers/script-to-storyboard-helpers', () => ({
asJsonRecord: (value: unknown) => {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null
return value as Record<string, unknown>
},
buildStoryboardJson: vi.fn(() => '[]'),
parseEffort: vi.fn(() => null),
parseTemperature: vi.fn(() => 0.7),
parseVoiceLinesJson: parseVoiceLinesJsonMock,
persistStoryboardsAndPanels: persistStoryboardsAndPanelsMock,
toPositiveInt: (value: unknown) => {
if (typeof value !== 'number' || !Number.isFinite(value)) return null
const n = Math.floor(value)
return n > 0 ? n : null
},
}))
import { handleScriptToStoryboardTask } from '@/lib/workers/handlers/script-to-storyboard'
function buildJob(payload: Record<string, unknown>, episodeId: string | null = 'episode-1'): Job<TaskJobData> {
return {
data: {
taskId: 'task-1',
type: TASK_TYPE.SCRIPT_TO_STORYBOARD_RUN,
locale: 'zh',
projectId: 'project-1',
episodeId,
targetType: 'NovelPromotionEpisode',
targetId: 'episode-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
function baseVoiceRows(): VoiceLineInput[] {
return [
{
lineIndex: 1,
speaker: 'Narrator',
content: 'Hello world',
emotionStrength: 0.8,
matchedPanel: {
storyboardId: 'storyboard-1',
panelIndex: 1,
},
},
]
}
describe('worker script-to-storyboard behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
txState.createdRows = []
prismaMock.project.findUnique.mockResolvedValue({
id: 'project-1',
name: 'Project One',
mode: 'novel-promotion',
})
prismaMock.novelPromotionProject.findUnique.mockResolvedValue({
id: 'np-project-1',
analysisModel: 'llm::analysis-model',
characters: [{ id: 'char-1', name: 'Narrator' }],
locations: [{ id: 'loc-1', name: 'Office' }],
})
prismaMock.novelPromotionEpisode.findUnique.mockResolvedValue({
id: 'episode-1',
novelPromotionProjectId: 'np-project-1',
novelText: 'A complete chapter text for voice analyze.',
clips: [
{
id: 'clip-1',
content: 'clip content',
characters: JSON.stringify(['Narrator']),
location: 'Office',
screenplay: 'Screenplay text',
},
],
})
prismaMock.$transaction.mockImplementation(async (fn: (tx: {
novelPromotionVoiceLine: {
deleteMany: (args: { where: { episodeId: string } }) => Promise<unknown>
create: (args: { data: Record<string, unknown>; select: { id: boolean } }) => Promise<{ id: string }>
}
}) => Promise<unknown>) => {
const tx = {
novelPromotionVoiceLine: {
deleteMany: async () => undefined,
create: async (args: { data: Record<string, unknown>; select: { id: boolean } }) => {
txState.createdRows.push(args.data)
return { id: `voice-${txState.createdRows.length}` }
},
},
}
return await fn(tx)
})
persistStoryboardsAndPanelsMock.mockResolvedValue([
{
storyboardId: 'storyboard-1',
panels: [{ id: 'panel-1', panelIndex: 1 }],
},
])
parseVoiceLinesJsonMock.mockReturnValue(baseVoiceRows())
})
it('缺少 episodeId -> 显式失败', async () => {
const job = buildJob({}, null)
await expect(handleScriptToStoryboardTask(job)).rejects.toThrow('episodeId is required')
})
it('成功路径: 写入 voice line 时包含 matchedPanel 映射后的 panelId', async () => {
const job = buildJob({ episodeId: 'episode-1' })
const result = await handleScriptToStoryboardTask(job)
expect(result).toEqual({
episodeId: 'episode-1',
storyboardCount: 1,
panelCount: 1,
voiceLineCount: 1,
})
expect(txState.createdRows).toHaveLength(1)
expect(txState.createdRows[0]).toEqual(expect.objectContaining({
episodeId: 'episode-1',
lineIndex: 1,
speaker: 'Narrator',
content: 'Hello world',
emotionStrength: 0.8,
matchedPanelId: 'panel-1',
matchedStoryboardId: 'storyboard-1',
matchedPanelIndex: 1,
}))
})
it('voice 解析失败后会重试一次再成功', async () => {
parseVoiceLinesJsonMock
.mockImplementationOnce(() => {
throw new Error('invalid voice json')
})
.mockImplementationOnce(() => baseVoiceRows())
const job = buildJob({ episodeId: 'episode-1' })
const result = await handleScriptToStoryboardTask(job)
expect(result).toEqual(expect.objectContaining({
episodeId: 'episode-1',
voiceLineCount: 1,
}))
expect(chatCompletionMock).toHaveBeenCalledTimes(2)
expect(parseVoiceLinesJsonMock).toHaveBeenCalledTimes(2)
})
})

View File

@@ -0,0 +1,92 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const llmMock = vi.hoisted(() => ({
getCompletionContent: vi.fn(),
}))
const persistMock = vi.hoisted(() => ({
resolveAnalysisModel: vi.fn(),
}))
const runtimeMock = vi.hoisted(() => ({
runShotPromptCompletion: vi.fn(),
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
vi.mock('@/lib/llm-client', () => llmMock)
vi.mock('@/lib/workers/handlers/shot-ai-persist', () => persistMock)
vi.mock('@/lib/workers/handlers/shot-ai-prompt-runtime', () => ({
runShotPromptCompletion: runtimeMock.runShotPromptCompletion,
}))
vi.mock('@/lib/workers/shared', () => ({
reportTaskProgress: runtimeMock.reportTaskProgress,
}))
vi.mock('@/lib/workers/utils', () => ({
assertTaskActive: runtimeMock.assertTaskActive,
}))
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: { NP_CHARACTER_MODIFY: 'np_character_modify' },
buildPrompt: vi.fn(() => 'appearance-final-prompt'),
}))
import { handleModifyAppearanceTask } from '@/lib/workers/handlers/shot-ai-prompt-appearance'
function buildJob(payload: Record<string, unknown>): Job<TaskJobData> {
return {
data: {
taskId: 'task-shot-appearance-1',
type: TASK_TYPE.AI_MODIFY_APPEARANCE,
locale: 'zh',
projectId: 'project-1',
episodeId: 'episode-1',
targetType: 'CharacterAppearance',
targetId: 'appearance-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker shot-ai-prompt-appearance behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
persistMock.resolveAnalysisModel.mockResolvedValue({ id: 'np-1', analysisModel: 'llm::analysis' })
runtimeMock.runShotPromptCompletion.mockResolvedValue({ id: 'completion-1' })
llmMock.getCompletionContent.mockReturnValue('{"prompt":"updated appearance description"}')
})
it('missing characterId -> explicit error', async () => {
const job = buildJob({
appearanceId: 'appearance-1',
currentDescription: 'old desc',
modifyInstruction: 'new style',
})
await expect(handleModifyAppearanceTask(job, job.data.payload as Record<string, unknown>)).rejects.toThrow('characterId is required')
})
it('success -> returns modifiedDescription and rawResponse', async () => {
const payload = {
characterId: 'character-1',
appearanceId: 'appearance-1',
currentDescription: 'old desc',
modifyInstruction: 'new style',
}
const job = buildJob(payload)
const result = await handleModifyAppearanceTask(job, payload)
expect(runtimeMock.runShotPromptCompletion).toHaveBeenCalledWith(expect.objectContaining({
action: 'ai_modify_appearance',
prompt: 'appearance-final-prompt',
}))
expect(result).toEqual(expect.objectContaining({
success: true,
modifiedDescription: 'updated appearance description',
rawResponse: '{"prompt":"updated appearance description"}',
}))
})
})

View File

@@ -0,0 +1,101 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const llmMock = vi.hoisted(() => ({
getCompletionContent: vi.fn(),
}))
const persistMock = vi.hoisted(() => ({
resolveAnalysisModel: vi.fn(),
requireProjectLocation: vi.fn(),
persistLocationDescription: vi.fn(),
}))
const runtimeMock = vi.hoisted(() => ({
runShotPromptCompletion: vi.fn(),
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
vi.mock('@/lib/llm-client', () => llmMock)
vi.mock('@/lib/workers/handlers/shot-ai-persist', () => persistMock)
vi.mock('@/lib/workers/handlers/shot-ai-prompt-runtime', () => ({
runShotPromptCompletion: runtimeMock.runShotPromptCompletion,
}))
vi.mock('@/lib/workers/shared', () => ({
reportTaskProgress: runtimeMock.reportTaskProgress,
}))
vi.mock('@/lib/workers/utils', () => ({
assertTaskActive: runtimeMock.assertTaskActive,
}))
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: { NP_LOCATION_MODIFY: 'np_location_modify' },
buildPrompt: vi.fn(() => 'location-final-prompt'),
}))
import { handleModifyLocationTask } from '@/lib/workers/handlers/shot-ai-prompt-location'
function buildJob(payload: Record<string, unknown>): Job<TaskJobData> {
return {
data: {
taskId: 'task-shot-location-1',
type: TASK_TYPE.AI_MODIFY_LOCATION,
locale: 'zh',
projectId: 'project-1',
episodeId: 'episode-1',
targetType: 'NovelPromotionLocation',
targetId: 'location-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker shot-ai-prompt-location behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
persistMock.resolveAnalysisModel.mockResolvedValue({ id: 'np-1', analysisModel: 'llm::analysis' })
persistMock.requireProjectLocation.mockResolvedValue({ id: 'location-1', name: 'Old Town' })
runtimeMock.runShotPromptCompletion.mockResolvedValue({ id: 'completion-1' })
llmMock.getCompletionContent.mockReturnValue('{"prompt":"updated location description"}')
persistMock.persistLocationDescription.mockResolvedValue({ id: 'location-1', images: [] })
})
it('missing locationId -> explicit error', async () => {
const payload = {
currentDescription: 'old location',
modifyInstruction: 'new style',
}
const job = buildJob(payload)
await expect(handleModifyLocationTask(job, payload)).rejects.toThrow('locationId is required')
})
it('success -> persists modifiedDescription with computed imageIndex', async () => {
const payload = {
locationId: 'location-1',
imageIndex: 2,
currentDescription: 'old location',
modifyInstruction: 'add fog',
}
const job = buildJob(payload)
const result = await handleModifyLocationTask(job, payload)
expect(runtimeMock.runShotPromptCompletion).toHaveBeenCalledWith(expect.objectContaining({
action: 'ai_modify_location',
prompt: 'location-final-prompt',
}))
expect(persistMock.persistLocationDescription).toHaveBeenCalledWith({
locationId: 'location-1',
imageIndex: 2,
modifiedDescription: 'updated location description',
})
expect(result).toEqual(expect.objectContaining({
success: true,
modifiedDescription: 'updated location description',
location: { id: 'location-1', images: [] },
}))
})
})

View File

@@ -0,0 +1,90 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const llmMock = vi.hoisted(() => ({
getCompletionContent: vi.fn(),
}))
const persistMock = vi.hoisted(() => ({
resolveAnalysisModel: vi.fn(),
}))
const runtimeMock = vi.hoisted(() => ({
runShotPromptCompletion: vi.fn(),
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
vi.mock('@/lib/llm-client', () => llmMock)
vi.mock('@/lib/workers/handlers/shot-ai-persist', () => persistMock)
vi.mock('@/lib/workers/handlers/shot-ai-prompt-runtime', () => ({
runShotPromptCompletion: runtimeMock.runShotPromptCompletion,
}))
vi.mock('@/lib/workers/shared', () => ({
reportTaskProgress: runtimeMock.reportTaskProgress,
}))
vi.mock('@/lib/workers/utils', () => ({
assertTaskActive: runtimeMock.assertTaskActive,
}))
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: { NP_IMAGE_PROMPT_MODIFY: 'np_image_prompt_modify' },
buildPrompt: vi.fn(() => 'shot-final-prompt'),
}))
import { handleModifyShotPromptTask } from '@/lib/workers/handlers/shot-ai-prompt-shot'
function buildJob(payload: Record<string, unknown>): Job<TaskJobData> {
return {
data: {
taskId: 'task-shot-prompt-1',
type: TASK_TYPE.AI_MODIFY_SHOT_PROMPT,
locale: 'zh',
projectId: 'project-1',
episodeId: 'episode-1',
targetType: 'NovelPromotionPanel',
targetId: 'panel-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker shot-ai-prompt-shot behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
persistMock.resolveAnalysisModel.mockResolvedValue({ id: 'np-1', analysisModel: 'llm::analysis' })
runtimeMock.runShotPromptCompletion.mockResolvedValue({ id: 'completion-1' })
llmMock.getCompletionContent.mockReturnValue('{"image_prompt":"updated image prompt","video_prompt":"updated video prompt"}')
})
it('missing currentPrompt -> explicit error', async () => {
const payload = { modifyInstruction: 'new angle' }
const job = buildJob(payload)
await expect(handleModifyShotPromptTask(job, payload)).rejects.toThrow('currentPrompt is required')
})
it('success -> returns modified image/video prompts and passes referencedAssets', async () => {
const payload = {
currentPrompt: 'old image prompt',
currentVideoPrompt: 'old video prompt',
modifyInstruction: 'new camera movement',
referencedAssets: [{ name: 'Hero', description: 'black coat' }],
}
const job = buildJob(payload)
const result = await handleModifyShotPromptTask(job, payload)
expect(runtimeMock.runShotPromptCompletion).toHaveBeenCalledWith(expect.objectContaining({
action: 'ai_modify_shot_prompt',
prompt: 'shot-final-prompt',
}))
expect(result).toEqual({
success: true,
modifiedImagePrompt: 'updated image prompt',
modifiedVideoPrompt: 'updated video prompt',
referencedAssets: [{ name: 'Hero', description: 'black coat' }],
})
})
})

View File

@@ -0,0 +1,80 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const handlersMock = vi.hoisted(() => ({
handleModifyAppearanceTask: vi.fn(),
handleModifyLocationTask: vi.fn(),
handleModifyShotPromptTask: vi.fn(),
handleAnalyzeShotVariantsTask: vi.fn(),
}))
vi.mock('@/lib/workers/handlers/shot-ai-prompt', () => ({
handleModifyAppearanceTask: handlersMock.handleModifyAppearanceTask,
handleModifyLocationTask: handlersMock.handleModifyLocationTask,
handleModifyShotPromptTask: handlersMock.handleModifyShotPromptTask,
}))
vi.mock('@/lib/workers/handlers/shot-ai-variants', () => ({
handleAnalyzeShotVariantsTask: handlersMock.handleAnalyzeShotVariantsTask,
}))
import { handleShotAITask } from '@/lib/workers/handlers/shot-ai-tasks'
function buildJob(type: TaskJobData['type'], payload: Record<string, unknown>): Job<TaskJobData> {
return {
data: {
taskId: 'task-1',
type,
locale: 'zh',
projectId: 'project-1',
episodeId: 'episode-1',
targetType: 'NovelPromotionPanel',
targetId: 'panel-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker shot-ai-tasks behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
handlersMock.handleModifyAppearanceTask.mockResolvedValue({ type: 'appearance' })
handlersMock.handleModifyLocationTask.mockResolvedValue({ type: 'location' })
handlersMock.handleModifyShotPromptTask.mockResolvedValue({ type: 'shot-prompt' })
handlersMock.handleAnalyzeShotVariantsTask.mockResolvedValue({ type: 'variants' })
})
it('AI_MODIFY_APPEARANCE -> routes to appearance handler with payload', async () => {
const payload = { characterId: 'char-1', appearanceId: 'app-1' }
const job = buildJob(TASK_TYPE.AI_MODIFY_APPEARANCE, payload)
const result = await handleShotAITask(job)
expect(result).toEqual({ type: 'appearance' })
expect(handlersMock.handleModifyAppearanceTask).toHaveBeenCalledWith(job, payload)
})
it('AI_MODIFY_LOCATION / AI_MODIFY_SHOT_PROMPT / ANALYZE_SHOT_VARIANTS route correctly', async () => {
const locationPayload = { locationId: 'loc-1' }
const locationJob = buildJob(TASK_TYPE.AI_MODIFY_LOCATION, locationPayload)
await handleShotAITask(locationJob)
expect(handlersMock.handleModifyLocationTask).toHaveBeenCalledWith(locationJob, locationPayload)
const shotPayload = { currentPrompt: 'old prompt', modifyInstruction: 'new angle' }
const shotJob = buildJob(TASK_TYPE.AI_MODIFY_SHOT_PROMPT, shotPayload)
await handleShotAITask(shotJob)
expect(handlersMock.handleModifyShotPromptTask).toHaveBeenCalledWith(shotJob, shotPayload)
const variantPayload = { panelId: 'panel-1' }
const variantJob = buildJob(TASK_TYPE.ANALYZE_SHOT_VARIANTS, variantPayload)
await handleShotAITask(variantJob)
expect(handlersMock.handleAnalyzeShotVariantsTask).toHaveBeenCalledWith(variantJob, variantPayload)
})
it('unsupported type -> throws explicit error', async () => {
const job = buildJob(TASK_TYPE.IMAGE_CHARACTER, {})
await expect(handleShotAITask(job)).rejects.toThrow('Unsupported shot AI task type')
})
})

View File

@@ -0,0 +1,147 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const prismaMock = vi.hoisted(() => ({
novelPromotionPanel: {
findUnique: vi.fn(),
},
}))
const llmMock = vi.hoisted(() => ({
chatCompletionWithVision: vi.fn(),
getCompletionContent: vi.fn(),
}))
const cosMock = vi.hoisted(() => ({
getSignedUrl: vi.fn(),
}))
const streamCtxMock = vi.hoisted(() => ({
withInternalLLMStreamCallbacks: vi.fn(async (_callbacks: unknown, fn: () => Promise<unknown>) => await fn()),
}))
const workerMock = vi.hoisted(() => ({
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
const llmStreamMock = vi.hoisted(() => {
const flush = vi.fn(async () => undefined)
return {
flush,
createWorkerLLMStreamContext: vi.fn(() => ({ streamRunId: 'run-1', nextSeqByStepLane: {} })),
createWorkerLLMStreamCallbacks: vi.fn(() => ({
onStage: vi.fn(),
onChunk: vi.fn(),
onComplete: vi.fn(),
onError: vi.fn(),
flush,
})),
}
})
const persistMock = vi.hoisted(() => ({
resolveAnalysisModel: vi.fn(),
}))
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/llm-client', () => llmMock)
vi.mock('@/lib/cos', () => cosMock)
vi.mock('@/lib/llm-observe/internal-stream-context', () => streamCtxMock)
vi.mock('@/lib/workers/shared', () => ({
reportTaskProgress: workerMock.reportTaskProgress,
}))
vi.mock('@/lib/workers/utils', () => ({
assertTaskActive: workerMock.assertTaskActive,
}))
vi.mock('@/lib/workers/handlers/llm-stream', () => ({
createWorkerLLMStreamContext: llmStreamMock.createWorkerLLMStreamContext,
createWorkerLLMStreamCallbacks: llmStreamMock.createWorkerLLMStreamCallbacks,
}))
vi.mock('@/lib/workers/handlers/shot-ai-persist', () => persistMock)
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: { NP_AGENT_SHOT_VARIANT_ANALYSIS: 'np_agent_shot_variant_analysis' },
buildPrompt: vi.fn(() => 'shot-variants-prompt'),
}))
import { handleAnalyzeShotVariantsTask } from '@/lib/workers/handlers/shot-ai-variants'
function buildJob(payload: Record<string, unknown>): Job<TaskJobData> {
return {
data: {
taskId: 'task-shot-variants-1',
type: TASK_TYPE.ANALYZE_SHOT_VARIANTS,
locale: 'zh',
projectId: 'project-1',
episodeId: 'episode-1',
targetType: 'NovelPromotionPanel',
targetId: 'panel-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker shot-ai-variants behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
persistMock.resolveAnalysisModel.mockResolvedValue({ id: 'np-1', analysisModel: 'llm::analysis-1' })
prismaMock.novelPromotionPanel.findUnique.mockResolvedValue({
id: 'panel-1',
panelNumber: 3,
imageUrl: 'images/panel-1.png',
description: 'panel desc',
shotType: 'medium',
cameraMove: 'static',
location: 'Old Town',
characters: JSON.stringify([{ name: 'Hero', appearance: 'black coat' }]),
})
cosMock.getSignedUrl.mockReturnValue('https://signed.example/panel-1.png')
llmMock.chatCompletionWithVision.mockResolvedValue({ id: 'vision-1' })
llmMock.getCompletionContent.mockReturnValue('[{"name":"v1"},{"name":"v2"},{"name":"v3"}]')
})
it('panel not found -> explicit error', async () => {
prismaMock.novelPromotionPanel.findUnique.mockResolvedValueOnce(null)
const job = buildJob({ panelId: 'panel-404' })
await expect(handleAnalyzeShotVariantsTask(job, job.data.payload as Record<string, unknown>)).rejects.toThrow('Panel not found')
})
it('success -> returns suggestions and signed panel image', async () => {
const payload = { panelId: 'panel-1' }
const job = buildJob(payload)
const result = await handleAnalyzeShotVariantsTask(job, payload)
expect(llmMock.chatCompletionWithVision).toHaveBeenCalledWith(
'user-1',
'llm::analysis-1',
'shot-variants-prompt',
['https://signed.example/panel-1.png'],
expect.objectContaining({
projectId: 'project-1',
action: 'analyze_shot_variants',
}),
)
expect(result).toEqual(expect.objectContaining({
success: true,
suggestions: [{ name: 'v1' }, { name: 'v2' }, { name: 'v3' }],
panelInfo: expect.objectContaining({
panelNumber: 3,
imageUrl: 'https://signed.example/panel-1.png',
}),
}))
expect(llmStreamMock.flush).toHaveBeenCalled()
})
it('suggestions fewer than 3 -> explicit error', async () => {
llmMock.getCompletionContent.mockReturnValueOnce('[{"name":"only-one"}]')
const payload = { panelId: 'panel-1' }
const job = buildJob(payload)
await expect(handleAnalyzeShotVariantsTask(job, payload)).rejects.toThrow('生成的变体数量不足')
})
})

View File

@@ -0,0 +1,90 @@
import { describe, expect, it, vi } from 'vitest'
import { runStoryToScriptOrchestrator } from '@/lib/novel-promotion/story-to-script/orchestrator'
describe('story-to-script orchestrator retry', () => {
it('retries retryable step failure up to 3 attempts', async () => {
const actionCalls = new Map<string, number>()
const characterMetas: Array<{ stepId: string; stepAttempt?: number }> = []
const runStep = vi.fn(async (meta, _prompt, action: string) => {
actionCalls.set(action, (actionCalls.get(action) || 0) + 1)
if (action === 'analyze_characters') {
characterMetas.push({ stepId: meta.stepId, stepAttempt: meta.stepAttempt })
const count = actionCalls.get(action) || 0
if (count < 3) {
throw new TypeError('terminated')
}
return { text: JSON.stringify({ characters: [{ name: '甲', introduction: '人物介绍' }] }), reasoning: '' }
}
if (action === 'analyze_locations') {
return { text: JSON.stringify({ locations: [{ name: '地点A' }] }), reasoning: '' }
}
if (action === 'split_clips') {
return {
text: JSON.stringify([
{
start: '甲在门口',
end: '乙回答',
summary: '片段摘要',
location: '地点A',
characters: ['甲'],
},
]),
reasoning: '',
}
}
return { text: JSON.stringify({ scenes: [{ id: 1 }] }), reasoning: '' }
})
const result = await runStoryToScriptOrchestrator({
content: '甲在门口。乙回答。',
baseCharacters: [],
baseLocations: [],
baseCharacterIntroductions: [],
promptTemplates: {
characterPromptTemplate: '{input} {characters_lib_name} {characters_lib_info}',
locationPromptTemplate: '{input} {locations_lib_name}',
clipPromptTemplate: '{input} {locations_lib_name} {characters_lib_name} {characters_introduction}',
screenplayPromptTemplate: '{clip_content} {locations_lib_name} {characters_lib_name} {characters_introduction} {clip_id}',
},
runStep,
})
expect(result.summary.clipCount).toBe(1)
expect(actionCalls.get('analyze_characters')).toBe(3)
expect(characterMetas).toEqual([
{ stepId: 'analyze_characters', stepAttempt: undefined },
{ stepId: 'analyze_characters', stepAttempt: 2 },
{ stepId: 'analyze_characters', stepAttempt: 3 },
])
})
it('does not retry non-retryable failures', async () => {
const actionCalls = new Map<string, number>()
const runStep = vi.fn(async (_meta, _prompt, action: string) => {
actionCalls.set(action, (actionCalls.get(action) || 0) + 1)
if (action === 'analyze_characters') {
throw new Error('SENSITIVE_CONTENT: blocked')
}
return { text: JSON.stringify({ locations: [{ name: '地点A' }] }), reasoning: '' }
})
await expect(
runStoryToScriptOrchestrator({
content: '甲在门口。乙回答。',
baseCharacters: [],
baseLocations: [],
baseCharacterIntroductions: [],
promptTemplates: {
characterPromptTemplate: '{input} {characters_lib_name} {characters_lib_info}',
locationPromptTemplate: '{input} {locations_lib_name}',
clipPromptTemplate: '{input} {locations_lib_name} {characters_lib_name} {characters_introduction}',
screenplayPromptTemplate: '{clip_content} {locations_lib_name} {characters_lib_name} {characters_introduction} {clip_id}',
},
runStep,
}),
).rejects.toThrow('SENSITIVE_CONTENT')
expect(actionCalls.get('analyze_characters')).toBe(1)
})
})

View File

@@ -0,0 +1,190 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const prismaMock = vi.hoisted(() => ({
project: { findUnique: vi.fn() },
novelPromotionProject: { findUnique: vi.fn() },
novelPromotionEpisode: { findUnique: vi.fn() },
novelPromotionClip: { update: vi.fn(async () => ({})) },
}))
const workerMock = vi.hoisted(() => ({
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
const configMock = vi.hoisted(() => ({
resolveProjectModelCapabilityGenerationOptions: vi.fn(async () => ({ reasoningEffort: 'high' })),
}))
const orchestratorMock = vi.hoisted(() => ({
runStoryToScriptOrchestrator: vi.fn(),
}))
const helperMock = vi.hoisted(() => ({
persistAnalyzedCharacters: vi.fn(async () => [{ id: 'character-new-1' }]),
persistAnalyzedLocations: vi.fn(async () => [{ id: 'location-new-1' }]),
persistClips: vi.fn(async () => [{ clipKey: 'clip-1', id: 'clip-row-1' }]),
}))
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/llm-client', () => ({
chatCompletion: vi.fn(),
getCompletionParts: vi.fn(() => ({ text: '', reasoning: '' })),
}))
vi.mock('@/lib/config-service', () => configMock)
vi.mock('@/lib/llm-observe/internal-stream-context', () => ({
withInternalLLMStreamCallbacks: vi.fn(async (_callbacks: unknown, fn: () => Promise<unknown>) => await fn()),
}))
vi.mock('@/lib/logging/semantic', () => ({ logAIAnalysis: vi.fn() }))
vi.mock('@/lib/logging/file-writer', () => ({ onProjectNameAvailable: vi.fn() }))
vi.mock('@/lib/workers/shared', () => ({ reportTaskProgress: workerMock.reportTaskProgress }))
vi.mock('@/lib/workers/utils', () => ({ assertTaskActive: workerMock.assertTaskActive }))
vi.mock('@/lib/novel-promotion/story-to-script/orchestrator', () => orchestratorMock)
vi.mock('@/lib/workers/handlers/llm-stream', () => ({
createWorkerLLMStreamContext: vi.fn(() => ({ streamRunId: 'run-1', nextSeqByStepLane: {} })),
createWorkerLLMStreamCallbacks: vi.fn(() => ({
onStage: vi.fn(),
onChunk: vi.fn(),
onComplete: vi.fn(),
onError: vi.fn(),
flush: vi.fn(async () => undefined),
})),
}))
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: {
NP_AGENT_CHARACTER_PROFILE: 'a',
NP_SELECT_LOCATION: 'b',
NP_AGENT_CLIP: 'c',
NP_SCREENPLAY_CONVERSION: 'd',
},
getPromptTemplate: vi.fn(() => 'prompt-template'),
}))
vi.mock('@/lib/workers/handlers/story-to-script-helpers', () => ({
asString: (value: unknown) => (typeof value === 'string' ? value : ''),
parseEffort: vi.fn(() => null),
parseTemperature: vi.fn(() => 0.7),
persistAnalyzedCharacters: helperMock.persistAnalyzedCharacters,
persistAnalyzedLocations: helperMock.persistAnalyzedLocations,
persistClips: helperMock.persistClips,
resolveClipRecordId: (clipIdMap: Map<string, string>, clipId: string) => clipIdMap.get(clipId) ?? null,
}))
import { handleStoryToScriptTask } from '@/lib/workers/handlers/story-to-script'
function buildJob(payload: Record<string, unknown>, episodeId: string | null = 'episode-1'): Job<TaskJobData> {
return {
data: {
taskId: 'task-story-to-script-1',
type: TASK_TYPE.STORY_TO_SCRIPT_RUN,
locale: 'zh',
projectId: 'project-1',
episodeId,
targetType: 'NovelPromotionEpisode',
targetId: 'episode-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker story-to-script behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
prismaMock.project.findUnique.mockResolvedValue({
id: 'project-1',
name: 'Project One',
mode: 'novel-promotion',
})
prismaMock.novelPromotionProject.findUnique.mockResolvedValue({
id: 'np-project-1',
analysisModel: 'llm::analysis-1',
characters: [{ id: 'char-1', name: 'Hero', introduction: 'hero intro' }],
locations: [{ id: 'loc-1', name: 'Old Town', summary: 'town' }],
})
prismaMock.novelPromotionEpisode.findUnique
.mockResolvedValueOnce({
id: 'episode-1',
novelPromotionProjectId: 'np-project-1',
novelText: 'episode text',
})
.mockResolvedValueOnce({ id: 'episode-1' })
orchestratorMock.runStoryToScriptOrchestrator.mockResolvedValue({
analyzedCharacters: [{ name: 'New Hero' }],
analyzedLocations: [{ name: 'Market' }],
clipList: [{ clipId: 'clip-1', content: 'clip content' }],
screenplayResults: [
{
clipId: 'clip-1',
success: true,
screenplay: { scenes: [{ shot: 'close-up' }] },
},
],
summary: {
clipCount: 1,
screenplaySuccessCount: 1,
screenplayFailedCount: 0,
},
})
})
it('missing episodeId -> explicit error', async () => {
const job = buildJob({}, null)
await expect(handleStoryToScriptTask(job)).rejects.toThrow('episodeId is required')
})
it('success path -> persists clips and screenplay with concrete fields', async () => {
const job = buildJob({ episodeId: 'episode-1', content: 'input content' })
const result = await handleStoryToScriptTask(job)
expect(result).toEqual({
episodeId: 'episode-1',
clipCount: 1,
screenplaySuccessCount: 1,
screenplayFailedCount: 0,
persistedCharacters: 1,
persistedLocations: 1,
persistedClips: 1,
})
expect(helperMock.persistClips).toHaveBeenCalledWith({
episodeId: 'episode-1',
clipList: [{ clipId: 'clip-1', content: 'clip content' }],
})
expect(prismaMock.novelPromotionClip.update).toHaveBeenCalledWith({
where: { id: 'clip-row-1' },
data: {
screenplay: JSON.stringify({ scenes: [{ shot: 'close-up' }] }),
},
})
})
it('orchestrator partial failure summary -> throws explicit error', async () => {
orchestratorMock.runStoryToScriptOrchestrator.mockResolvedValueOnce({
analyzedCharacters: [],
analyzedLocations: [],
clipList: [],
screenplayResults: [
{
clipId: 'clip-3',
success: false,
error: 'bad screenplay json',
},
],
summary: {
clipCount: 1,
screenplaySuccessCount: 0,
screenplayFailedCount: 1,
},
})
const job = buildJob({ episodeId: 'episode-1', content: 'input content' })
await expect(handleStoryToScriptTask(job)).rejects.toThrow('STORY_TO_SCRIPT_PARTIAL_FAILED')
})
})

View File

@@ -0,0 +1,206 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
type WorkerProcessor = (job: Job<TaskJobData>) => Promise<unknown>
type PanelRow = {
id: string
videoUrl: string | null
imageUrl: string | null
videoPrompt: string | null
description: string | null
firstLastFramePrompt: string | null
}
const workerState = vi.hoisted(() => ({
processor: null as WorkerProcessor | null,
}))
const reportTaskProgressMock = vi.hoisted(() => vi.fn(async () => undefined))
const withTaskLifecycleMock = vi.hoisted(() =>
vi.fn(async (job: Job<TaskJobData>, handler: WorkerProcessor) => await handler(job)),
)
const utilsMock = vi.hoisted(() => ({
assertTaskActive: vi.fn(async () => undefined),
getProjectModels: vi.fn(async () => ({ videoRatio: '16:9' })),
resolveLipSyncVideoSource: vi.fn(async () => 'https://provider.example/lipsync.mp4'),
resolveVideoSourceFromGeneration: vi.fn(async () => 'https://provider.example/video.mp4'),
toSignedUrlIfCos: vi.fn((url: string | null) => (url ? `https://signed.example/${url}` : null)),
uploadVideoSourceToCos: vi.fn(async () => 'cos/lip-sync/video.mp4'),
}))
const prismaMock = vi.hoisted(() => ({
novelPromotionPanel: {
findUnique: vi.fn(),
findFirst: vi.fn(),
update: vi.fn(async () => undefined),
},
novelPromotionVoiceLine: {
findUnique: vi.fn(),
},
}))
vi.mock('bullmq', () => ({
Queue: class {
constructor(_name: string) {}
async add() {
return { id: 'job-1' }
}
async getJob() {
return null
}
},
Worker: class {
constructor(_name: string, processor: WorkerProcessor) {
workerState.processor = processor
}
},
}))
vi.mock('@/lib/redis', () => ({ queueRedis: {} }))
vi.mock('@/lib/workers/shared', () => ({
reportTaskProgress: reportTaskProgressMock,
withTaskLifecycle: withTaskLifecycleMock,
}))
vi.mock('@/lib/workers/utils', () => utilsMock)
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/media/outbound-image', () => ({
normalizeToBase64ForGeneration: vi.fn(async (input: string) => input),
}))
vi.mock('@/lib/model-capabilities/lookup', () => ({
resolveBuiltinCapabilitiesByModelKey: vi.fn(() => ({ video: { firstlastframe: true } })),
}))
vi.mock('@/lib/model-config-contract', () => ({
parseModelKeyStrict: vi.fn(() => ({ provider: 'fal' })),
}))
vi.mock('@/lib/api-config', () => ({
getProviderConfig: vi.fn(async () => ({ apiKey: 'api-key' })),
}))
function buildPanel(overrides?: Partial<PanelRow>): PanelRow {
return {
id: 'panel-1',
videoUrl: 'cos/base-video.mp4',
imageUrl: 'cos/panel-image.png',
videoPrompt: 'panel prompt',
description: 'panel description',
firstLastFramePrompt: null,
...(overrides || {}),
}
}
function buildJob(params: {
type: TaskJobData['type']
payload?: Record<string, unknown>
targetType?: string
targetId?: string
}): Job<TaskJobData> {
return {
data: {
taskId: 'task-1',
type: params.type,
locale: 'zh',
projectId: 'project-1',
episodeId: 'episode-1',
targetType: params.targetType ?? 'NovelPromotionPanel',
targetId: params.targetId ?? 'panel-1',
payload: params.payload ?? {},
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker video processor behavior', () => {
beforeEach(async () => {
vi.clearAllMocks()
workerState.processor = null
prismaMock.novelPromotionPanel.findUnique.mockResolvedValue(buildPanel())
prismaMock.novelPromotionPanel.findFirst.mockResolvedValue(buildPanel())
prismaMock.novelPromotionVoiceLine.findUnique.mockResolvedValue({
id: 'line-1',
audioUrl: 'cos/line-1.mp3',
})
const mod = await import('@/lib/workers/video.worker')
mod.createVideoWorker()
})
it('VIDEO_PANEL: 缺少 payload.videoModel 时显式失败', async () => {
const processor = workerState.processor
expect(processor).toBeTruthy()
const job = buildJob({
type: TASK_TYPE.VIDEO_PANEL,
payload: {},
})
await expect(processor!(job)).rejects.toThrow('VIDEO_MODEL_REQUIRED: payload.videoModel is required')
})
it('LIP_SYNC: 缺少 panel 时显式失败', async () => {
const processor = workerState.processor
expect(processor).toBeTruthy()
prismaMock.novelPromotionPanel.findUnique.mockResolvedValueOnce(null)
const job = buildJob({
type: TASK_TYPE.LIP_SYNC,
payload: { voiceLineId: 'line-1' },
targetId: 'panel-missing',
})
await expect(processor!(job)).rejects.toThrow('Lip-sync panel not found')
})
it('LIP_SYNC: 正常路径写回 lipSyncVideoUrl 并清理 lipSyncTaskId', async () => {
const processor = workerState.processor
expect(processor).toBeTruthy()
const job = buildJob({
type: TASK_TYPE.LIP_SYNC,
payload: {
voiceLineId: 'line-1',
lipSyncModel: 'fal::lipsync-model',
},
targetId: 'panel-1',
})
const result = await processor!(job) as { panelId: string; voiceLineId: string; lipSyncVideoUrl: string }
expect(result).toEqual({
panelId: 'panel-1',
voiceLineId: 'line-1',
lipSyncVideoUrl: 'cos/lip-sync/video.mp4',
})
expect(utilsMock.resolveLipSyncVideoSource).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
userId: 'user-1',
modelKey: 'fal::lipsync-model',
}),
)
expect(prismaMock.novelPromotionPanel.update).toHaveBeenCalledWith({
where: { id: 'panel-1' },
data: {
lipSyncVideoUrl: 'cos/lip-sync/video.mp4',
lipSyncTaskId: null,
},
})
})
it('未知任务类型: 显式报错', async () => {
const processor = workerState.processor
expect(processor).toBeTruthy()
const unsupportedJob = buildJob({
type: TASK_TYPE.AI_CREATE_CHARACTER,
})
await expect(processor!(unsupportedJob)).rejects.toThrow('Unsupported video task type')
})
})

View File

@@ -0,0 +1,200 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const txState = vi.hoisted(() => ({
createdRows: [] as Array<Record<string, unknown>>,
}))
const prismaMock = vi.hoisted(() => ({
project: { findUnique: vi.fn() },
novelPromotionProject: { findUnique: vi.fn() },
novelPromotionEpisode: { findUnique: vi.fn() },
$transaction: vi.fn(),
}))
const llmMock = vi.hoisted(() => ({
chatCompletion: vi.fn(async () => ({ id: 'completion-1' })),
getCompletionContent: vi.fn(() => 'voice-line-json'),
}))
const helperMock = vi.hoisted(() => ({
parseVoiceLinesJson: vi.fn(),
buildStoryboardJson: vi.fn(() => 'storyboard-json'),
}))
const workerMock = vi.hoisted(() => ({
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
vi.mock('@/lib/prisma', () => ({ prisma: prismaMock }))
vi.mock('@/lib/llm-client', () => llmMock)
vi.mock('@/lib/llm-observe/internal-stream-context', () => ({
withInternalLLMStreamCallbacks: vi.fn(async (_callbacks: unknown, fn: () => Promise<unknown>) => await fn()),
}))
vi.mock('@/lib/constants', () => ({
buildCharactersIntroduction: vi.fn(() => 'characters-introduction'),
}))
vi.mock('@/lib/workers/shared', () => ({ reportTaskProgress: workerMock.reportTaskProgress }))
vi.mock('@/lib/workers/utils', () => ({ assertTaskActive: workerMock.assertTaskActive }))
vi.mock('@/lib/workers/handlers/llm-stream', () => ({
createWorkerLLMStreamContext: vi.fn(() => ({ streamRunId: 'run-1', nextSeqByStepLane: {} })),
createWorkerLLMStreamCallbacks: vi.fn(() => ({
onStage: vi.fn(),
onChunk: vi.fn(),
onComplete: vi.fn(),
onError: vi.fn(),
flush: vi.fn(async () => undefined),
})),
}))
vi.mock('@/lib/workers/handlers/voice-analyze-helpers', () => ({
buildStoryboardJson: helperMock.buildStoryboardJson,
parseVoiceLinesJson: helperMock.parseVoiceLinesJson,
}))
vi.mock('@/lib/prompt-i18n', () => ({
PROMPT_IDS: { NP_VOICE_ANALYSIS: 'np_voice_analysis' },
buildPrompt: vi.fn(() => 'voice-analysis-prompt'),
}))
import { handleVoiceAnalyzeTask } from '@/lib/workers/handlers/voice-analyze'
function buildJob(payload: Record<string, unknown>, episodeId: string | null = 'episode-1'): Job<TaskJobData> {
return {
data: {
taskId: 'task-voice-analyze-1',
type: TASK_TYPE.VOICE_ANALYZE,
locale: 'zh',
projectId: 'project-1',
episodeId,
targetType: 'NovelPromotionEpisode',
targetId: 'episode-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker voice-analyze behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
txState.createdRows = []
prismaMock.project.findUnique.mockResolvedValue({ id: 'project-1', mode: 'novel-promotion' })
prismaMock.novelPromotionProject.findUnique.mockResolvedValue({
id: 'np-project-1',
analysisModel: 'llm::analysis-1',
characters: [{ id: 'char-1', name: 'Hero' }],
})
prismaMock.novelPromotionEpisode.findUnique.mockResolvedValue({
id: 'episode-1',
novelPromotionProjectId: 'np-project-1',
novelText: '这是可以用于台词分析的文本',
storyboards: [
{
id: 'storyboard-1',
clip: { id: 'clip-1' },
panels: [{ id: 'panel-1', panelIndex: 0 }],
},
],
})
helperMock.parseVoiceLinesJson.mockReturnValue([
{
lineIndex: 1,
speaker: 'Hero',
content: '第一句台词',
emotionStrength: 0.7,
matchedPanel: {
storyboardId: 'storyboard-1',
panelIndex: 0,
},
},
{
lineIndex: 2,
speaker: 'Narrator',
content: '第二句旁白',
emotionStrength: 0.5,
},
])
prismaMock.$transaction.mockImplementation(async (fn: (tx: {
novelPromotionVoiceLine: {
deleteMany: (args: { where: { episodeId: string } }) => Promise<unknown>
create: (args: { data: Record<string, unknown>; select: { id: boolean; speaker: boolean; matchedStoryboardId: boolean } }) => Promise<{
id: string
speaker: string
matchedStoryboardId: string | null
}>
}
}) => Promise<unknown>) => {
const tx = {
novelPromotionVoiceLine: {
deleteMany: async () => undefined,
create: async (args: { data: Record<string, unknown>; select: { id: boolean; speaker: boolean; matchedStoryboardId: boolean } }) => {
txState.createdRows.push(args.data)
const speaker = typeof args.data.speaker === 'string' ? args.data.speaker : 'unknown'
const matchedStoryboardId = typeof args.data.matchedStoryboardId === 'string'
? args.data.matchedStoryboardId
: null
return {
id: `line-${txState.createdRows.length}`,
speaker,
matchedStoryboardId,
}
},
},
}
return await fn(tx)
})
})
it('missing episodeId -> explicit error', async () => {
const job = buildJob({}, null)
await expect(handleVoiceAnalyzeTask(job)).rejects.toThrow('episodeId is required')
})
it('success path -> persists mapped panelId and speaker stats', async () => {
const job = buildJob({ episodeId: 'episode-1' })
const result = await handleVoiceAnalyzeTask(job)
expect(result).toEqual({
episodeId: 'episode-1',
count: 2,
matchedCount: 1,
speakerStats: {
Hero: 1,
Narrator: 1,
},
})
expect(txState.createdRows[0]).toEqual(expect.objectContaining({
episodeId: 'episode-1',
lineIndex: 1,
speaker: 'Hero',
content: '第一句台词',
matchedPanelId: 'panel-1',
matchedStoryboardId: 'storyboard-1',
matchedPanelIndex: 0,
}))
})
it('line references non-existent storyboard panel -> explicit error', async () => {
helperMock.parseVoiceLinesJson.mockImplementation(() => [
{
lineIndex: 1,
speaker: 'Hero',
content: 'bad line',
emotionStrength: 0.8,
matchedPanel: {
storyboardId: 'storyboard-404',
panelIndex: 0,
},
},
])
const job = buildJob({ episodeId: 'episode-1' })
await expect(handleVoiceAnalyzeTask(job)).rejects.toThrow('references non-existent panel')
})
})

View File

@@ -0,0 +1,104 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
const qwenMock = vi.hoisted(() => ({
createVoiceDesign: vi.fn(),
validateVoicePrompt: vi.fn(),
validatePreviewText: vi.fn(),
}))
const apiConfigMock = vi.hoisted(() => ({
getProviderConfig: vi.fn(),
}))
const workerMock = vi.hoisted(() => ({
reportTaskProgress: vi.fn(async () => undefined),
assertTaskActive: vi.fn(async () => undefined),
}))
vi.mock('@/lib/qwen-voice-design', () => qwenMock)
vi.mock('@/lib/api-config', () => apiConfigMock)
vi.mock('@/lib/workers/shared', () => ({
reportTaskProgress: workerMock.reportTaskProgress,
}))
vi.mock('@/lib/workers/utils', () => ({
assertTaskActive: workerMock.assertTaskActive,
}))
import { handleVoiceDesignTask } from '@/lib/workers/handlers/voice-design'
function buildJob(type: TaskJobData['type'], payload: Record<string, unknown>): Job<TaskJobData> {
return {
data: {
taskId: 'task-voice-1',
type,
locale: 'zh',
projectId: 'project-1',
episodeId: null,
targetType: 'VoiceDesign',
targetId: 'voice-design-1',
payload,
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker voice-design behavior', () => {
beforeEach(() => {
vi.clearAllMocks()
qwenMock.validateVoicePrompt.mockReturnValue({ valid: true })
qwenMock.validatePreviewText.mockReturnValue({ valid: true })
apiConfigMock.getProviderConfig.mockResolvedValue({ apiKey: 'qwen-key' })
qwenMock.createVoiceDesign.mockResolvedValue({
success: true,
voiceId: 'voice-id-1',
targetModel: 'qwen-tts',
audioBase64: 'base64-audio',
sampleRate: 24000,
responseFormat: 'mp3',
usageCount: 11,
requestId: 'req-1',
})
})
it('missing required fields -> explicit error', async () => {
const job = buildJob(TASK_TYPE.VOICE_DESIGN, { previewText: 'hello' })
await expect(handleVoiceDesignTask(job)).rejects.toThrow('voicePrompt is required')
})
it('invalid prompt validation -> explicit error message from validator', async () => {
qwenMock.validateVoicePrompt.mockReturnValue({ valid: false, error: 'bad prompt' })
const job = buildJob(TASK_TYPE.VOICE_DESIGN, {
voicePrompt: 'x',
previewText: 'hello',
})
await expect(handleVoiceDesignTask(job)).rejects.toThrow('bad prompt')
})
it('success path -> submits normalized input and returns typed result', async () => {
const job = buildJob(TASK_TYPE.ASSET_HUB_VOICE_DESIGN, {
voicePrompt: ' calm female narrator ',
previewText: ' hello world ',
preferredName: ' custom_name ',
language: 'en',
})
const result = await handleVoiceDesignTask(job)
expect(apiConfigMock.getProviderConfig).toHaveBeenCalledWith('user-1', 'qwen')
expect(qwenMock.createVoiceDesign).toHaveBeenCalledWith({
voicePrompt: 'calm female narrator',
previewText: 'hello world',
preferredName: 'custom_name',
language: 'en',
}, 'qwen-key')
expect(result).toEqual(expect.objectContaining({
success: true,
voiceId: 'voice-id-1',
taskType: TASK_TYPE.ASSET_HUB_VOICE_DESIGN,
}))
})
})

View File

@@ -0,0 +1,172 @@
import type { Job } from 'bullmq'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { TASK_TYPE, type TaskJobData } from '@/lib/task/types'
type WorkerProcessor = (job: Job<TaskJobData>) => Promise<unknown>
const workerState = vi.hoisted(() => ({
processor: null as WorkerProcessor | null,
}))
const generateVoiceLineMock = vi.hoisted(() => vi.fn())
const handleVoiceDesignTaskMock = vi.hoisted(() => vi.fn())
const reportTaskProgressMock = vi.hoisted(() => vi.fn(async () => undefined))
const withTaskLifecycleMock = vi.hoisted(() =>
vi.fn(async (job: Job<TaskJobData>, handler: WorkerProcessor) => await handler(job)),
)
vi.mock('bullmq', () => ({
Queue: class {
constructor(_name: string) {}
async add() {
return { id: 'job-1' }
}
async getJob() {
return null
}
},
Worker: class {
constructor(_name: string, processor: WorkerProcessor) {
workerState.processor = processor
}
},
}))
vi.mock('@/lib/redis', () => ({
queueRedis: {},
}))
vi.mock('@/lib/voice/generate-voice-line', () => ({
generateVoiceLine: generateVoiceLineMock,
}))
vi.mock('@/lib/workers/shared', () => ({
reportTaskProgress: reportTaskProgressMock,
withTaskLifecycle: withTaskLifecycleMock,
}))
vi.mock('@/lib/workers/handlers/voice-design', () => ({
handleVoiceDesignTask: handleVoiceDesignTaskMock,
}))
function buildJob(params: {
type: TaskJobData['type']
targetType?: string
targetId?: string
episodeId?: string | null
payload?: Record<string, unknown>
}): Job<TaskJobData> {
return {
data: {
taskId: 'task-1',
type: params.type,
locale: 'zh',
projectId: 'project-1',
episodeId: params.episodeId !== undefined ? params.episodeId : 'episode-1',
targetType: params.targetType ?? 'NovelPromotionVoiceLine',
targetId: params.targetId ?? 'line-1',
payload: params.payload ?? {},
userId: 'user-1',
},
} as unknown as Job<TaskJobData>
}
describe('worker voice processor behavior', () => {
beforeEach(async () => {
vi.clearAllMocks()
workerState.processor = null
generateVoiceLineMock.mockResolvedValue({
lineId: 'line-1',
audioUrl: 'cos/voice-line-1.mp3',
})
handleVoiceDesignTaskMock.mockResolvedValue({
presetId: 'preset-1',
previewAudioUrl: 'cos/preset-1.mp3',
})
const mod = await import('@/lib/workers/voice.worker')
mod.createVoiceWorker()
})
it('VOICE_LINE: lineId/episodeId 缺失时显式失败', async () => {
const processor = workerState.processor
expect(processor).toBeTruthy()
const missingLineJob = buildJob({
type: TASK_TYPE.VOICE_LINE,
targetId: '',
payload: { episodeId: 'episode-1' },
})
await expect(processor!(missingLineJob)).rejects.toThrow('VOICE_LINE task missing lineId')
const missingEpisodeJob = buildJob({
type: TASK_TYPE.VOICE_LINE,
episodeId: null,
targetId: 'line-1',
payload: {},
})
await expect(processor!(missingEpisodeJob)).rejects.toThrow('VOICE_LINE task missing episodeId')
})
it('VOICE_LINE: 正常生成时把核心参数传给 generateVoiceLine', async () => {
const processor = workerState.processor
expect(processor).toBeTruthy()
const job = buildJob({
type: TASK_TYPE.VOICE_LINE,
payload: {
lineId: 'line-9',
episodeId: 'episode-9',
audioModel: 'fal::voice-model',
},
})
const result = await processor!(job)
expect(result).toEqual({ lineId: 'line-1', audioUrl: 'cos/voice-line-1.mp3' })
expect(generateVoiceLineMock).toHaveBeenCalledWith({
projectId: 'project-1',
episodeId: 'episode-9',
lineId: 'line-9',
userId: 'user-1',
audioModel: 'fal::voice-model',
})
})
it('VOICE_DESIGN / ASSET_HUB_VOICE_DESIGN: 路由到 voice design handler', async () => {
const processor = workerState.processor
expect(processor).toBeTruthy()
const designJob = buildJob({
type: TASK_TYPE.VOICE_DESIGN,
targetType: 'NovelPromotionVoiceDesign',
targetId: 'voice-design-1',
})
const assetHubJob = buildJob({
type: TASK_TYPE.ASSET_HUB_VOICE_DESIGN,
targetType: 'GlobalAssetHubVoiceDesign',
targetId: 'asset-hub-voice-design-1',
})
await processor!(designJob)
await processor!(assetHubJob)
expect(handleVoiceDesignTaskMock).toHaveBeenCalledTimes(2)
expect(generateVoiceLineMock).not.toHaveBeenCalled()
})
it('未知任务类型: 显式报错', async () => {
const processor = workerState.processor
expect(processor).toBeTruthy()
const unsupportedJob = buildJob({
type: TASK_TYPE.AI_CREATE_CHARACTER,
targetId: 'character-1',
})
await expect(processor!(unsupportedJob)).rejects.toThrow('Unsupported voice task type')
})
})