import { describe, it, expect, beforeAll, afterEach, afterAll, vi } from 'vitest' import { prisma, WorkflowTaskStatus } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' import { workflowService, TaskQueueAgent, TaskQueueTranscode } from '@shumai/workflow-core' import { initAgentWorkflows } from '@shumai/agent' import { initTranscodeWorkflows } from '@shumai/transcode' import { s3Service } from '@shumai/core/src/s3/s3' import { fileURLToPath } from 'url' import * as path from 'path' import * as fs from 'fs' import sharp from 'sharp' const mockEmbedContent = vi.fn().mockResolvedValue({ embeddings: [ { values: Array(1536).fill(0.2), }, ], }) vi.mock('@google/genai', () => { return { // eslint-disable-next-line @typescript-eslint/naming-convention GoogleGenAI: class { models = { embedContent: mockEmbedContent, } }, } }) const currentDir = path.dirname(fileURLToPath(import.meta.url)) const fixturesDir = path.resolve(currentDir, '../fixtures') describe('Workflow E2E - agentEmbeddingMedia', () => { setupTestDbHooks() beforeAll(async () => { // Set bucket environment process.env.S3_BUCKET = 'shumai-e2e-test-bucket-embedding' process.env.GEMINI_API_KEY = 'dummy-key' // Initialize registries initAgentWorkflows() initTranscodeWorkflows() await workflowService.startWorkers([TaskQueueAgent, TaskQueueTranscode]) }) afterEach(() => { vi.restoreAllMocks() vi.unstubAllEnvs() }) afterAll(async () => { await workflowService.shutdownWorkers() workflowService.close() // Restore spied methods vi.restoreAllMocks() // Clean up E2E files in local filesystem storage try { console.log('Cleaning up local E2E storage files...') await s3Service.deletePrefix('shumai-e2e-test-bucket-embedding', '') } catch (err) { console.error('Failed to clean up E2E storage folder:', err) } }) it('should run agentEmbeddingMedia workflow for an image asset successfully', async () => { // 1. Seed Database const team = await prisma.team.create({ data: { name: 'E2E Image Embedding Team' }, }) const project = await prisma.project.create({ data: { name: 'E2E Image Embedding Project', teamId: team.id }, }) const agentUser = await prisma.user.create({ data: { name: 'E2E Image Embedding Agent User', email: 'e2e-img-emb-agent@shumai.ai', type: 'agent', }, }) await prisma.teamMember.create({ data: { teamId: team.id, userId: agentUser.id, role: 'editor', }, }) const provider = await prisma.provider.create({ data: { name: 'google', teamId: team.id, config: { api: 'google-generative-ai', apiKey: 'dummy-google-api-key' }, }, }) const model = await prisma.model.create({ data: { modelId: 'gemini', name: 'Gemini', providerId: provider.id, config: { input: ['text', 'image'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 8192, maxTokens: 2048, reasoning: false, }, }, }) await prisma.agent.create({ data: { id: agentUser.id, teamId: team.id, type: 'embedding', enabled: true, providerId: provider.id, modelId: model.id, config: { provider: 'google', model: 'gemini', }, }, }) const storageKey = await prisma.storageKey.create({ data: { key: 'projects/e2e/test-image.png', }, }) const asset = await prisma.asset.create({ data: { name: 'test-image.png', type: 'file', status: 'uploaded', mediaType: 'image/png', projectId: project.id, storageKeyId: storageKey.id, }, }) // 2. Seed S3 Storage from Fixture const pngPath = path.join(fixturesDir, 'small.png') const pngBuffer = fs.readFileSync(pngPath) await s3Service.putObject( 'shumai-e2e-test-bucket-embedding', 'projects/e2e/test-image.png', pngBuffer, pngBuffer.length, 'image/png', ) // 3. Create Workflow Task (ai_embedding, pending) const task = await prisma.workflowTask.create({ data: { type: 'ai_embedding', status: 'pending', assetId: asset.id, projectId: project.id, teamId: team.id, payload: { projectId: project.id, agent: { agentId: agentUser.id }, }, }, }) // 4. Wait for workflow to complete console.log( `Submitted E2E Image Embedding Workflow Task. ID: ${task.id}. Awaiting completion...`, ) const completedTask = await workflowService.executeWait(task, 45000) // 5. Verification expect(completedTask.status).toBe('completed') // Verify no comments created on successful embedding const comments = await prisma.assetComment.findMany({ where: { assetId: asset.id }, orderBy: { createdAt: 'asc' }, }) expect(comments.length).toBe(0) // Verify raw embedding is saved in DB const dbEmbeddings = (await prisma.$queryRaw` SELECT id, asset_id as "assetId", start_time as "startTime", end_time as "endTime" FROM asset_embeddings WHERE asset_id = ${asset.id} `) as { id: string; startTime: number | null; endTime: number | null }[] expect(dbEmbeddings.length).toBe(1) expect(dbEmbeddings[0].startTime).toBeNull() expect(dbEmbeddings[0].endTime).toBeNull() }, 50000) it.each([ ['gemini-embedding-2', 'no sprite metadata'], ['gemma-embedding-2-openai', 'no sprite metadata'], ['gemini-embedding-2', 'available full sprite'], ['gemma-embedding-2-openai', 'available full sprite'], ['gemma-embedding-2-openai', 'missing full sprite object'], ])( 'indexes an entire video with %s and %s', async (embeddingProvider, fullSpriteState) => { vi.stubEnv('EMBEDDING_PROVIDER', embeddingProvider) if (embeddingProvider === 'gemma-embedding-2-openai') { const endpoint = 'https://embedding.example.com/v1/embeddings' vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', endpoint) const fetch = globalThis.fetch vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => input === endpoint ? Promise.resolve( Response.json({ data: [{ embedding: Array(768).fill(0.2) }] }), ) : fetch(input, init), ) } // 1. Seed Database const team = await prisma.team.create({ data: { name: 'E2E Video Embedding Team' }, }) const project = await prisma.project.create({ data: { name: 'E2E Video Embedding Project', teamId: team.id }, }) const agentUser = await prisma.user.create({ data: { name: 'E2E Video Embedding Agent User', email: 'e2e-vid-emb-agent@shumai.ai', type: 'agent', }, }) await prisma.teamMember.create({ data: { teamId: team.id, userId: agentUser.id, role: 'editor', }, }) const provider = await prisma.provider.create({ data: { name: 'google', teamId: team.id, config: { api: 'google-generative-ai', apiKey: 'dummy-google-api-key' }, }, }) const model = await prisma.model.create({ data: { modelId: 'gemini', name: 'Gemini', providerId: provider.id, config: { input: ['text', 'image'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 8192, maxTokens: 2048, reasoning: false, }, }, }) await prisma.agent.create({ data: { id: agentUser.id, teamId: team.id, type: 'embedding', enabled: true, providerId: provider.id, modelId: model.id, config: { provider: 'google', model: 'gemini', }, }, }) const storageKey = await prisma.storageKey.create({ data: { key: 'projects/e2e/test-video.mp4', }, }) const bucket = 'shumai-e2e-test-bucket-embedding' const fullSpriteKey = `projects/e2e/${storageKey.id}-full.webp` const hasFullSprite = fullSpriteState === 'available full sprite' if (hasFullSprite) { const fullSprite = await sharp({ create: { width: 640, height: 640, channels: 3, background: 'blue' }, }) .webp() .toBuffer() await s3Service.putObject( bucket, fullSpriteKey, fullSprite, fullSprite.length, 'image/webp', ) } const asset = await prisma.asset.create({ data: { name: 'test-video.mp4', type: 'file', status: 'uploaded', mediaType: 'video/mp4', media: { duration: 1, proxyType: 'video', ...(fullSpriteState !== 'no sprite metadata' && { sprite: { key: fullSpriteKey, frames: 100, tileX: 10, tileY: 10 }, }), } as PrismaJson.MediaInfo, projectId: project.id, storageKeyId: storageKey.id, }, }) // 2. Seed S3 Storage from Fixture const mp4Path = path.join(fixturesDir, 'small.mp4') const mp4Buffer = fs.readFileSync(mp4Path) await s3Service.putObject( 'shumai-e2e-test-bucket-embedding', 'projects/e2e/test-video.mp4', mp4Buffer, mp4Buffer.length, 'video/mp4', ) // 3. Create Workflow Task (ai_embedding, pending) const task = await prisma.workflowTask.create({ data: { type: 'ai_embedding', status: 'pending', assetId: asset.id, projectId: project.id, teamId: team.id, payload: { projectId: project.id, agent: { agentId: agentUser.id }, }, }, }) // 4. Wait for workflow to complete console.log( `Submitted E2E Video Embedding Workflow Task. ID: ${task.id}. Awaiting completion...`, ) const completedTask = await workflowService.executeWait(task, 45000) // 5. Verification expect(completedTask.status).toBe('completed') // Verify batch transcode_video_chunks task was created and completed on TaskQueueTranscode const chunkTasks = await prisma.workflowTask.findMany({ where: { assetId: asset.id, type: 'transcode_video_chunks', }, }) expect(chunkTasks).toHaveLength(1) expect(chunkTasks[0].status).toBe(WorkflowTaskStatus.completed) expect(chunkTasks[0].payload?.videoChunks?.parentTaskId).toBe(task.id) const dbEmbeddings = await prisma.assetEmbedding.findMany({ where: { assetId: asset.id } }) expect(dbEmbeddings).toHaveLength(1) expect(dbEmbeddings[0].startTime).toBe(0) expect(dbEmbeddings[0].endTime).toBe(1) const sprite = dbEmbeddings[0].sprite const format = embeddingProvider === 'gemma-embedding-2-openai' ? 'frames' : 'video' if (hasFullSprite) { expect(sprite).toBeNull() expect( await s3Service.listObjects(bucket, `projects/e2e/chunk-sprites/${asset.id}/`), ).toEqual([]) await s3Service.deleteObject(bucket, fullSpriteKey) } else { expect(chunkTasks[0].output).toMatchObject({ chunks: [{ sprite: { columns: 1, rows: 1, frameCount: 1 } }], }) expect(sprite).toEqual({ key: `projects/e2e/chunk-sprites/${asset.id}/${format}-0-1.webp`, columns: 1, rows: 1, frameCount: 1, }) const { buffer } = await s3Service.getObject(bucket, sprite!.key) expect(await sharp(buffer).metadata()).toMatchObject({ format: 'webp', width: 64, height: 64, }) } // Verify all temporary embedding chunk files were cleaned up from S3 const remainingTmpChunks = await s3Service.listObjects( 'shumai-e2e-test-bucket-embedding', `files/${asset.id}/tmp-embedding-chunks/`, ) expect(remainingTmpChunks).toEqual([]) }, 50000, ) it('should fail agentEmbeddingMedia workflow for an unsupported audio asset', async () => { // 1. Seed Database const team = await prisma.team.create({ data: { name: 'E2E Audio Embedding Team' }, }) const project = await prisma.project.create({ data: { name: 'E2E Audio Embedding Project', teamId: team.id }, }) const agentUser = await prisma.user.create({ data: { name: 'E2E Audio Embedding Agent User', email: 'e2e-aud-emb-agent@shumai.ai', type: 'agent', }, }) await prisma.teamMember.create({ data: { teamId: team.id, userId: agentUser.id, role: 'editor', }, }) const provider = await prisma.provider.create({ data: { name: 'google', teamId: team.id, config: { api: 'google-generative-ai', apiKey: 'dummy-google-api-key' }, }, }) const model = await prisma.model.create({ data: { modelId: 'gemini', name: 'Gemini', providerId: provider.id, config: { input: ['text'], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 8192, maxTokens: 2048, reasoning: false, }, }, }) await prisma.agent.create({ data: { id: agentUser.id, teamId: team.id, type: 'embedding', enabled: true, providerId: provider.id, modelId: model.id, config: { provider: 'google', model: 'gemini', }, }, }) const storageKey = await prisma.storageKey.create({ data: { key: 'projects/e2e/test-audio.wav', }, }) const asset = await prisma.asset.create({ data: { name: 'test-audio.wav', type: 'file', status: 'uploaded', mediaType: 'audio/wav', projectId: project.id, storageKeyId: storageKey.id, }, }) // 2. Seed S3 Storage from Fixture const wavPath = path.join(fixturesDir, 'small.wav') const wavBuffer = fs.readFileSync(wavPath) await s3Service.putObject( 'shumai-e2e-test-bucket-embedding', 'projects/e2e/test-audio.wav', wavBuffer, wavBuffer.length, 'audio/wav', ) // 3. Create Workflow Task (ai_embedding, pending) const task = await prisma.workflowTask.create({ data: { type: 'ai_embedding', status: 'pending', assetId: asset.id, projectId: project.id, teamId: team.id, payload: { projectId: project.id, agent: { agentId: agentUser.id }, }, }, }) // 4. Wait for workflow to fail and verify error message console.log(`Submitted E2E Audio Embedding Workflow Task. ID: ${task.id}. Awaiting failure...`) await expect(workflowService.executeWait(task, 45000)).rejects.toThrow( 'unsupported media type for embeddings: audio/wav', ) // Verify task status in DB is failed const dbTask = await prisma.workflowTask.findUnique({ where: { id: task.id }, }) expect(dbTask?.status).toBe(WorkflowTaskStatus.failed) // Verify failure comment was posted to the asset const comments = await prisma.assetComment.findMany({ where: { assetId: asset.id }, orderBy: { createdAt: 'asc' }, }) expect(comments.length).toBe(1) expect(comments[0].message).toContain( 'Embedding failed: unsupported media type for embeddings: audio/wav', ) }, 50000) })