mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-26 05:08:22 +00:00
* feat(embedding): update compose tiers, docs, and add regenerate-embeddings CLI - Add Lite, Embedding, and Full Docker Compose configurations (and Aliyun mirrors) - Set CONCURRENCY_AGENT to 1 for compose files containing embedding-server - Update README and README_CN with compose options, recommended RAM, and semantic search links - Add LiteRT-LM Embedding Server setup guide in docs/using-shumai/embedding-server.mdx - Add shumai regenerate-embeddings CLI command and EmbeddingService to regenerate embeddings across teams - Add comprehensive test coverage for EmbeddingService * fix(docker): remove basic auth for turntable-renderer in full compose * fix(agent): lock and disable embedding agent when ENABLE_EMBEDDING_AGENT is false Ensure that when ENABLE_EMBEDDING_AGENT is set to 'false', existing embedding agents are automatically disabled on startup, marked as read-only, and blocked from manual API modifications or creations. Additionally guard background task creation and semantic search when the environment variable disables embedding agents. * test(upload): remove flaky status assertion on workflow tasks
891 lines
30 KiB
TypeScript
891 lines
30 KiB
TypeScript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
|
import {
|
|
generateTextEmbeddingActivity,
|
|
extractAiMetadataActivity,
|
|
getEmbeddingContextActivity,
|
|
saveAssetEmbeddingsActivity,
|
|
deleteAssetEmbeddingsActivity,
|
|
generateImageEmbeddingActivity,
|
|
generateVideoChunkEmbeddingActivity,
|
|
getGemmaEmbeddingTargetFrameCount,
|
|
} from './ai'
|
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
|
import { transcodeService } from '@shumai/core'
|
|
import { prisma, AssetType, AssetStatus } from '@shumai/db'
|
|
import { setupTestDbHooks } from '@shumai/db/test'
|
|
import sharp from 'sharp'
|
|
|
|
vi.mock('fs', async (importOriginal) => {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- importOriginal returns the raw fs module, typed dynamically as any here
|
|
const actual = await importOriginal<any>()
|
|
const mockRead = vi.fn((path, options) => {
|
|
if (typeof path === 'string' && (path.includes('video-chunk') || path.includes('out1.webp'))) {
|
|
return Buffer.from('chunk-data')
|
|
}
|
|
return actual.readFileSync(path, options)
|
|
})
|
|
return {
|
|
...actual,
|
|
writeFileSync: vi.fn(),
|
|
readFileSync: mockRead,
|
|
unlinkSync: vi.fn(),
|
|
}
|
|
})
|
|
|
|
vi.mock('@shumai/core/src/s3/s3', () => ({
|
|
s3Service: {
|
|
getObject: vi.fn(),
|
|
putObject: vi.fn(),
|
|
headObject: vi.fn(),
|
|
listObjects: vi.fn(),
|
|
downloadToFile: vi.fn(),
|
|
resolveInput: vi.fn().mockImplementation(async (_bucket, key) => `https://mock-storage/${key}`),
|
|
},
|
|
}))
|
|
|
|
vi.mock('@shumai/core/src/transcode/transcode', () => ({
|
|
transcodeService: {
|
|
extractVideoFrames: vi.fn(),
|
|
createTempDir: vi.fn().mockReturnValue('/tmp'),
|
|
removeDir: vi.fn(),
|
|
},
|
|
}))
|
|
|
|
vi.mock('child_process', () => {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock functions dynamically return varying types based on test command calls
|
|
const execFileMock: any = vi.fn((file: any, args: any, cb: any) => {
|
|
cb(null, '120.0\n', '')
|
|
})
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock functions dynamically return varying types based on test command calls
|
|
execFileMock[Symbol.for('nodejs.util.promisify.custom')] = vi.fn(async (file: any) => {
|
|
if (file === 'ffprobe') {
|
|
return { stdout: '120.0\n', stderr: '' }
|
|
}
|
|
return { stdout: '', stderr: '' }
|
|
})
|
|
return {
|
|
execFile: execFileMock,
|
|
}
|
|
})
|
|
|
|
const mockEmbedContent = vi.fn().mockResolvedValue({
|
|
embeddings: [
|
|
{
|
|
values: [0.1, 0.2, 0.3],
|
|
},
|
|
],
|
|
})
|
|
|
|
vi.mock('@google/genai', () => {
|
|
return {
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention -- matches external library GoogleGenAI export naming convention
|
|
GoogleGenAI: class {
|
|
models = {
|
|
embedContent: mockEmbedContent,
|
|
}
|
|
},
|
|
}
|
|
})
|
|
|
|
describe('AI Activities Unit Tests', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
process.env.GEMINI_API_KEY = 'test-key'
|
|
delete process.env.EMBEDDING_PROVIDER
|
|
delete process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL
|
|
})
|
|
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals()
|
|
delete process.env.EMBEDDING_PROVIDER
|
|
delete process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL
|
|
})
|
|
|
|
it('should generate image embedding', async () => {
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from('test-image'),
|
|
contentType: 'image/png',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateImageEmbeddingActivity({
|
|
teamId: 't1',
|
|
assetKey: 'test.png',
|
|
mediaType: 'image/png',
|
|
})
|
|
|
|
expect(res.embedding).toEqual([0.1, 0.2, 0.3])
|
|
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'test.png')
|
|
})
|
|
|
|
it('should generate video embedding in chunks', async () => {
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from('test-video'),
|
|
contentType: 'video/mp4',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
|
|
})
|
|
|
|
expect(res.embedding).toEqual([0.1, 0.2, 0.3])
|
|
expect(s3Service.getObject).toHaveBeenCalledWith(
|
|
'shumai',
|
|
'files/a1/tmp-embedding-chunks/chunk-0-60.mp4',
|
|
)
|
|
})
|
|
|
|
it('should generate text embedding successfully', async () => {
|
|
const res = await generateTextEmbeddingActivity({
|
|
text: 'Search query',
|
|
teamId: 't1',
|
|
})
|
|
|
|
expect(res.embedding).toEqual([0.1, 0.2, 0.3])
|
|
expect(mockEmbedContent).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
model: 'gemini-embedding-2',
|
|
contents: [
|
|
expect.objectContaining({
|
|
parts: [{ text: 'Search query' }],
|
|
}),
|
|
],
|
|
}),
|
|
)
|
|
})
|
|
|
|
it('should generate text embedding successfully with gemma-embedding-2-openai', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.1) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 15 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
const res = await generateTextEmbeddingActivity({
|
|
text: 'Search query',
|
|
teamId: 't1',
|
|
})
|
|
|
|
expect(res.embedding).toHaveLength(768)
|
|
expect(res.usage.model).toBe('embeddinggemma-2')
|
|
expect(res.usage.inputTokens).toBe(15)
|
|
expect(mockFetch).toHaveBeenCalledWith(
|
|
'http://localhost:9379/v1/embeddings',
|
|
expect.objectContaining({
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({
|
|
model: 'embeddinggemma-2',
|
|
input: 'task: search query | text: Search query',
|
|
}),
|
|
}),
|
|
)
|
|
})
|
|
|
|
it('should generate image embedding successfully with gemma-embedding-2-openai', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.2) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 140 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from('test-image'),
|
|
contentType: 'image/png',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateImageEmbeddingActivity({
|
|
teamId: 't1',
|
|
assetKey: 'img.png',
|
|
mediaType: 'image/png',
|
|
})
|
|
|
|
expect(res.embedding).toHaveLength(768)
|
|
expect(res.usage.model).toBe('embeddinggemma-2')
|
|
expect(res.usage.inputTokens).toBe(140)
|
|
expect(mockFetch).toHaveBeenCalledWith(
|
|
'http://localhost:9379/v1/embeddings',
|
|
expect.objectContaining({
|
|
method: 'POST',
|
|
body: JSON.stringify({
|
|
model: 'embeddinggemma-2',
|
|
input: [
|
|
{
|
|
type: 'image_url',
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
image_url: {
|
|
url: `data:image/png;base64,${Buffer.from('test-image').toString('base64')}`,
|
|
},
|
|
},
|
|
],
|
|
}),
|
|
}),
|
|
)
|
|
})
|
|
|
|
it('should respect custom GEMMA_EMBEDDING_OPENAI_BASE_URL with or without /v1 suffix', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.2) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 10 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
// Test with /v1
|
|
process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL = 'http://custom-host:9379/v1'
|
|
await generateTextEmbeddingActivity({ text: 'test query', teamId: 't1' })
|
|
expect(mockFetch).toHaveBeenLastCalledWith(
|
|
'http://custom-host:9379/v1/embeddings',
|
|
expect.anything(),
|
|
)
|
|
|
|
// Test without /v1
|
|
process.env.GEMMA_EMBEDDING_OPENAI_BASE_URL = 'http://custom-host:9379'
|
|
await generateTextEmbeddingActivity({ text: 'test query', teamId: 't1' })
|
|
expect(mockFetch).toHaveBeenLastCalledWith(
|
|
'http://custom-host:9379/v1/embeddings',
|
|
expect.anything(),
|
|
)
|
|
})
|
|
|
|
it('should convert webp image to jpeg with gemma-embedding-2-openai', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.2) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 140 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
const webpBuffer = await sharp({
|
|
create: { width: 10, height: 10, channels: 3, background: { r: 255, g: 0, b: 0 } },
|
|
})
|
|
.webp()
|
|
.toBuffer()
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: webpBuffer,
|
|
contentType: 'image/webp',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateImageEmbeddingActivity({
|
|
teamId: 't1',
|
|
assetKey: 'img.webp',
|
|
mediaType: 'image/webp',
|
|
})
|
|
|
|
expect(res.embedding).toHaveLength(768)
|
|
expect(mockFetch).toHaveBeenCalledWith(
|
|
'http://localhost:9379/v1/embeddings',
|
|
expect.objectContaining({
|
|
method: 'POST',
|
|
body: expect.stringContaining('data:image/jpeg;base64,'),
|
|
}),
|
|
)
|
|
})
|
|
|
|
it('should generate video chunk embedding from tar archive with gemma-embedding-2-openai', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.3) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 140 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
const sampleArchive = new Bun.Archive({
|
|
'frame_0001.jpg': Buffer.from('frame-1'),
|
|
})
|
|
const archiveBytes = await sampleArchive.bytes()
|
|
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from(archiveBytes.buffer, archiveBytes.byteOffset, archiveBytes.byteLength),
|
|
contentType: 'application/x-tar',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/asset-1/tmp-embedding-chunks/frames-0-60.tar',
|
|
})
|
|
|
|
expect(res.embedding).toHaveLength(768)
|
|
expect(res.usage.model).toBe('embeddinggemma-2')
|
|
expect(mockFetch).toHaveBeenCalled()
|
|
})
|
|
|
|
describe('getGemmaEmbeddingTargetFrameCount', () => {
|
|
it('should return 15 for standard aspect ratios', () => {
|
|
// 16:9
|
|
expect(getGemmaEmbeddingTargetFrameCount(1920, 1080)).toBe(15)
|
|
expect(getGemmaEmbeddingTargetFrameCount(1280, 720)).toBe(15)
|
|
expect(getGemmaEmbeddingTargetFrameCount(854, 480)).toBe(15)
|
|
// 9:16
|
|
expect(getGemmaEmbeddingTargetFrameCount(1080, 1920)).toBe(15)
|
|
// 1:1
|
|
expect(getGemmaEmbeddingTargetFrameCount(1080, 1080)).toBe(15)
|
|
expect(getGemmaEmbeddingTargetFrameCount(480, 480)).toBe(15)
|
|
// 4:3
|
|
expect(getGemmaEmbeddingTargetFrameCount(1440, 1080)).toBe(15)
|
|
expect(getGemmaEmbeddingTargetFrameCount(640, 480)).toBe(15)
|
|
// 3:4
|
|
expect(getGemmaEmbeddingTargetFrameCount(1080, 1440)).toBe(15)
|
|
// 21:9
|
|
expect(getGemmaEmbeddingTargetFrameCount(2560, 1080)).toBe(15)
|
|
expect(getGemmaEmbeddingTargetFrameCount(3440, 1440)).toBe(15)
|
|
})
|
|
|
|
it('should return 14 for non-standard aspect ratios and missing/invalid dimensions', () => {
|
|
expect(getGemmaEmbeddingTargetFrameCount(1000, 600)).toBe(14) // 5:3
|
|
expect(getGemmaEmbeddingTargetFrameCount(700, 500)).toBe(14) // 1.4:1
|
|
expect(getGemmaEmbeddingTargetFrameCount(854, 672)).toBe(14) // ~1.27:1
|
|
expect(getGemmaEmbeddingTargetFrameCount(undefined, undefined)).toBe(14)
|
|
expect(getGemmaEmbeddingTargetFrameCount(0, 0)).toBe(14)
|
|
expect(getGemmaEmbeddingTargetFrameCount(-100, 100)).toBe(14)
|
|
})
|
|
})
|
|
|
|
it('should sample uniform 15 frames when chunk archive contains standard 16:9 frames', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.3) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 140 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
const sampleJpg = await sharp({
|
|
create: {
|
|
width: 160,
|
|
height: 90,
|
|
channels: 3,
|
|
background: { r: 0, g: 0, b: 0 },
|
|
},
|
|
})
|
|
.jpeg()
|
|
.toBuffer()
|
|
|
|
const frames: Record<string, Buffer> = {}
|
|
for (let i = 1; i <= 30; i++) {
|
|
frames[`frame_${String(i).padStart(4, '0')}.jpg`] = sampleJpg
|
|
}
|
|
const sampleArchive = new Bun.Archive(frames)
|
|
const archiveBytes = await sampleArchive.bytes()
|
|
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from(archiveBytes.buffer, archiveBytes.byteOffset, archiveBytes.byteLength),
|
|
contentType: 'application/x-tar',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/asset-1/tmp-embedding-chunks/frames-0-60.tar',
|
|
})
|
|
|
|
expect(res.embedding).toHaveLength(768)
|
|
const requestBody = JSON.parse(mockFetch.mock.calls[0][1].body)
|
|
expect(requestBody.input).toHaveLength(15)
|
|
})
|
|
|
|
it('should fallback to 14 frames when chunk archive contains non-standard or unparseable frames', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const mockFetch = vi.fn().mockResolvedValue({
|
|
ok: true,
|
|
json: async () => ({
|
|
model: 'embeddinggemma-2',
|
|
data: [{ embedding: Array(768).fill(0.3) }],
|
|
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
usage: { prompt_tokens: 140 },
|
|
}),
|
|
})
|
|
vi.stubGlobal('fetch', mockFetch)
|
|
|
|
const frames: Record<string, Buffer> = {}
|
|
for (let i = 1; i <= 30; i++) {
|
|
frames[`frame_${String(i).padStart(4, '0')}.jpg`] = Buffer.from(`frame-${i}`)
|
|
}
|
|
const sampleArchive = new Bun.Archive(frames)
|
|
const archiveBytes = await sampleArchive.bytes()
|
|
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from(archiveBytes.buffer, archiveBytes.byteOffset, archiveBytes.byteLength),
|
|
contentType: 'application/x-tar',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
const res = await generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/asset-1/tmp-embedding-chunks/frames-0-60.tar',
|
|
})
|
|
|
|
expect(res.embedding).toHaveLength(768)
|
|
const requestBody = JSON.parse(mockFetch.mock.calls[0][1].body)
|
|
expect(requestBody.input).toHaveLength(14)
|
|
})
|
|
|
|
it('should throw non-retryable ApplicationFailure when chunk archive contains no valid frames', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const sampleArchive = new Bun.Archive({
|
|
'info.txt': Buffer.from('not an image'),
|
|
})
|
|
const archiveBytes = await sampleArchive.bytes()
|
|
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from(archiveBytes.buffer, archiveBytes.byteOffset, archiveBytes.byteLength),
|
|
contentType: 'application/x-tar',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
await expect(
|
|
generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/asset-1/tmp-embedding-chunks/frames-0-60.tar',
|
|
}),
|
|
).rejects.toThrow('No extracted frames found in chunk archive')
|
|
})
|
|
|
|
it('should throw non-retryable ApplicationFailure when chunk archive data is corrupted', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from('corrupted non-tar bytes'),
|
|
contentType: 'application/x-tar',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
await expect(
|
|
generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/asset-1/tmp-embedding-chunks/frames-0-60.tar',
|
|
}),
|
|
).rejects.toThrow('Failed to read chunk archive')
|
|
})
|
|
|
|
it('should throw non-retryable ApplicationFailure when an extracted frame is empty (0 bytes)', async () => {
|
|
process.env.EMBEDDING_PROVIDER = 'gemma-embedding-2-openai'
|
|
const sampleArchive = new Bun.Archive({
|
|
'frame_0001.jpg': Buffer.alloc(0),
|
|
})
|
|
const archiveBytes = await sampleArchive.bytes()
|
|
|
|
vi.mocked(s3Service.getObject).mockResolvedValue({
|
|
buffer: Buffer.from(archiveBytes.buffer, archiveBytes.byteOffset, archiveBytes.byteLength),
|
|
contentType: 'application/x-tar',
|
|
} as unknown as { buffer: Buffer; contentType: string })
|
|
|
|
await expect(
|
|
generateVideoChunkEmbeddingActivity({
|
|
teamId: 't1',
|
|
chunkKey: 'files/asset-1/tmp-embedding-chunks/frames-0-60.tar',
|
|
}),
|
|
).rejects.toThrow('is empty (0 bytes)')
|
|
})
|
|
|
|
describe('extractAiMetadataActivity', () => {
|
|
it('should return existing images if they are already in S3 storage', async () => {
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock returned object cast as any due to partial implementation
|
|
vi.mocked(s3Service.headObject).mockResolvedValue({} as any)
|
|
vi.mocked(s3Service.listObjects).mockResolvedValue([
|
|
'project/ai_metadata/1.webp',
|
|
'project/ai_metadata/2.webp',
|
|
])
|
|
|
|
const res = await extractAiMetadataActivity({
|
|
assetKey: 'project/video.mp4',
|
|
filePath: '/tmp/video.mp4',
|
|
type: 'autofill',
|
|
isImage: false,
|
|
})
|
|
|
|
expect(res).toEqual(['project/ai_metadata/1.webp', 'project/ai_metadata/2.webp'])
|
|
expect(s3Service.headObject).toHaveBeenCalledWith('shumai', 'project/ai_metadata/1.webp')
|
|
expect(transcodeService.extractVideoFrames).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('should extract frames and upload to S3 if not already present', async () => {
|
|
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not Found'))
|
|
vi.mocked(transcodeService.extractVideoFrames).mockResolvedValue(['/tmp/out1.webp'])
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock returned object cast as any due to partial implementation
|
|
vi.mocked(s3Service.putObject).mockResolvedValue({} as any)
|
|
|
|
const res = await extractAiMetadataActivity({
|
|
assetKey: 'project/video.mp4',
|
|
filePath: '/tmp/video.mp4',
|
|
type: 'autofill',
|
|
isImage: false,
|
|
})
|
|
|
|
expect(res).toEqual(['project/ai_metadata/out1.webp'])
|
|
expect(transcodeService.extractVideoFrames).toHaveBeenCalledWith({
|
|
inputFile: '/tmp/video.mp4',
|
|
outputDir: '/tmp',
|
|
numFrames: 30,
|
|
frameHeight: 720,
|
|
isImage: false,
|
|
})
|
|
expect(s3Service.putObject).toHaveBeenCalledWith(
|
|
'shumai',
|
|
'project/ai_metadata/out1.webp',
|
|
expect.any(Buffer),
|
|
expect.any(Number),
|
|
'image/webp',
|
|
)
|
|
})
|
|
|
|
it('should resolveInput from s3Service when filePath is not provided', async () => {
|
|
vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not Found'))
|
|
vi.mocked(s3Service.resolveInput).mockResolvedValue('https://mock-storage/project/video.mp4')
|
|
vi.mocked(transcodeService.extractVideoFrames).mockResolvedValue(['/tmp/out1.webp'])
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
vi.mocked(s3Service.putObject).mockResolvedValue({} as any)
|
|
|
|
const res = await extractAiMetadataActivity({
|
|
assetKey: 'project/video.mp4',
|
|
type: 'autofill',
|
|
isImage: false,
|
|
})
|
|
|
|
expect(res).toEqual(['project/ai_metadata/out1.webp'])
|
|
expect(s3Service.resolveInput).toHaveBeenCalledWith('shumai', 'project/video.mp4')
|
|
expect(transcodeService.extractVideoFrames).toHaveBeenCalledWith({
|
|
inputFile: 'https://mock-storage/project/video.mp4',
|
|
outputDir: expect.any(String),
|
|
numFrames: 30,
|
|
frameHeight: 720,
|
|
isImage: false,
|
|
})
|
|
})
|
|
})
|
|
})
|
|
|
|
describe('AI Database Activities Integration', () => {
|
|
setupTestDbHooks()
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests
|
|
let team: any
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests
|
|
let user: any
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests
|
|
let asset: any
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests
|
|
let storageKey: any
|
|
|
|
beforeEach(async () => {
|
|
vi.restoreAllMocks()
|
|
|
|
team = await prisma.team.create({
|
|
data: { name: 'AI Team' },
|
|
})
|
|
|
|
user = await prisma.user.create({
|
|
data: {
|
|
name: 'AI Agent User',
|
|
email: 'aiagent@shumai.ai',
|
|
type: 'agent',
|
|
},
|
|
})
|
|
|
|
// Add user as a member of the team
|
|
await prisma.teamMember.create({
|
|
data: {
|
|
teamId: team.id,
|
|
userId: user.id,
|
|
role: 'editor',
|
|
},
|
|
})
|
|
|
|
storageKey = await prisma.storageKey.create({
|
|
data: {
|
|
key: 'media/video.mp4',
|
|
},
|
|
})
|
|
|
|
asset = await prisma.asset.create({
|
|
data: {
|
|
name: 'video.mp4',
|
|
type: AssetType.file,
|
|
status: AssetStatus.uploaded,
|
|
mediaType: 'video/mp4',
|
|
storageKeyId: storageKey.id,
|
|
},
|
|
})
|
|
})
|
|
|
|
describe('getEmbeddingContextActivity', () => {
|
|
it('should retrieve embedding context and throw if embedding agent not configured/enabled', async () => {
|
|
// Expect throw since agent not created yet
|
|
await expect(
|
|
getEmbeddingContextActivity({ teamId: team.id, assetId: asset.id }),
|
|
).rejects.toThrow('embedding feature is disabled or agent not found')
|
|
|
|
// Create embedding agent
|
|
await prisma.agent.create({
|
|
data: {
|
|
id: user.id, // match user.id
|
|
teamId: team.id,
|
|
type: 'embedding',
|
|
enabled: true,
|
|
config: {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
},
|
|
},
|
|
})
|
|
|
|
const ctx = await getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
})
|
|
|
|
expect(ctx.agent.id).toBe(user.id)
|
|
expect(ctx.asset.id).toBe(asset.id)
|
|
expect(ctx.asset.mediaType).toBe('video/mp4')
|
|
|
|
process.env.ENABLE_EMBEDDING_AGENT = 'false'
|
|
try {
|
|
await expect(
|
|
getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
}),
|
|
).rejects.toThrow('embedding feature is disabled or agent not found')
|
|
} finally {
|
|
delete process.env.ENABLE_EMBEDDING_AGENT
|
|
}
|
|
})
|
|
|
|
it('should parse valid positive chunk duration and fallback on invalid or negative ones', async () => {
|
|
// Create embedding agent if not already present
|
|
const existingAgent = await prisma.agent.findUnique({ where: { id: user.id } })
|
|
if (!existingAgent) {
|
|
await prisma.agent.create({
|
|
data: {
|
|
id: user.id,
|
|
teamId: team.id,
|
|
type: 'embedding',
|
|
enabled: true,
|
|
config: {
|
|
provider: 'openai',
|
|
model: 'gpt-4',
|
|
},
|
|
},
|
|
})
|
|
}
|
|
|
|
// Test default/fallback
|
|
delete process.env.EMBEDDING_CHUNK_DURATION
|
|
let ctx = await getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
})
|
|
expect(ctx.chunkDuration).toBe(60.0)
|
|
expect(ctx.chunkOverlap).toBe(5.0)
|
|
|
|
// Test valid positive
|
|
process.env.EMBEDDING_CHUNK_DURATION = '45.5'
|
|
process.env.EMBEDDING_CHUNK_OVERLAP = '10.0'
|
|
ctx = await getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
})
|
|
expect(ctx.chunkDuration).toBe(45.5)
|
|
expect(ctx.chunkOverlap).toBe(10.0)
|
|
|
|
// Test negative/invalid for overlap
|
|
process.env.EMBEDDING_CHUNK_OVERLAP = '-5.0'
|
|
ctx = await getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
})
|
|
expect(ctx.chunkOverlap).toBe(5.0)
|
|
|
|
process.env.EMBEDDING_CHUNK_OVERLAP = 'invalid'
|
|
ctx = await getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
})
|
|
expect(ctx.chunkOverlap).toBe(5.0)
|
|
|
|
// Cleanup env
|
|
delete process.env.EMBEDDING_CHUNK_DURATION
|
|
delete process.env.EMBEDDING_CHUNK_OVERLAP
|
|
})
|
|
|
|
it('should return existing embeddings for the asset', async () => {
|
|
// Ensure agent exists
|
|
await prisma.agent.upsert({
|
|
where: { id: user.id },
|
|
update: {},
|
|
create: {
|
|
id: user.id,
|
|
teamId: team.id,
|
|
type: 'embedding',
|
|
enabled: true,
|
|
config: { provider: 'openai', model: 'gpt-4' },
|
|
},
|
|
})
|
|
|
|
await saveAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
embeddings: [
|
|
{ embedding: Array(1536).fill(0.01), startTime: 0.0, endTime: 60.0 },
|
|
{ embedding: Array(768).fill(0.02), startTime: 55.0, endTime: 115.0 },
|
|
],
|
|
})
|
|
|
|
const ctx = await getEmbeddingContextActivity({
|
|
teamId: team.id,
|
|
assetId: asset.id,
|
|
})
|
|
|
|
expect(ctx.existingEmbeddings).toHaveLength(2)
|
|
const chunk1 = ctx.existingEmbeddings.find((e) => e.startTime === 0)
|
|
expect(chunk1).toBeDefined()
|
|
expect(chunk1?.has1536).toBe(true)
|
|
expect(chunk1?.has768).toBe(false)
|
|
|
|
const chunk2 = ctx.existingEmbeddings.find((e) => e.startTime === 55)
|
|
expect(chunk2).toBeDefined()
|
|
expect(chunk2?.has1536).toBe(false)
|
|
expect(chunk2?.has768).toBe(true)
|
|
})
|
|
})
|
|
|
|
describe('saveAssetEmbeddingsActivity', () => {
|
|
it('should save embeddings with start and end times to the database', async () => {
|
|
const embeddings = [
|
|
{
|
|
embedding: Array(1536).fill(0.01),
|
|
startTime: 0.0,
|
|
endTime: 60.0,
|
|
},
|
|
{
|
|
embedding: Array(1536).fill(0.02),
|
|
},
|
|
]
|
|
|
|
await saveAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
embeddings,
|
|
})
|
|
|
|
// Query raw embeddings from DB
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- db query output is a raw postgres result array typed as any
|
|
const dbEmbeddings: any[] = 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}
|
|
ORDER BY start_time ASC NULLS LAST
|
|
`
|
|
|
|
expect(dbEmbeddings.length).toBe(2)
|
|
expect(dbEmbeddings[0].startTime).toBe(0.0)
|
|
expect(dbEmbeddings[0].endTime).toBe(60.0)
|
|
expect(dbEmbeddings[1].startTime).toBeNull()
|
|
})
|
|
|
|
it('should save 768-dim embeddings to embedding_768 column in database', async () => {
|
|
const embeddings = [
|
|
{
|
|
embedding: Array(768).fill(0.01),
|
|
startTime: 0.0,
|
|
endTime: 60.0,
|
|
},
|
|
{
|
|
embedding: Array(768).fill(0.02),
|
|
},
|
|
]
|
|
|
|
await saveAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
embeddings,
|
|
})
|
|
|
|
// Query raw embeddings from DB
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- db query output is a raw postgres result array typed as any
|
|
const dbEmbeddings: any[] = await prisma.$queryRaw`
|
|
SELECT id, asset_id as "assetId", (embedding_768 IS NOT NULL) as "has768", (embedding IS NOT NULL) as "has1536"
|
|
FROM asset_embeddings
|
|
WHERE asset_id = ${asset.id}
|
|
`
|
|
|
|
expect(dbEmbeddings.length).toBe(2)
|
|
expect(dbEmbeddings[0].has768).toBe(true)
|
|
expect(dbEmbeddings[0].has1536).toBe(false)
|
|
expect(dbEmbeddings[1].has768).toBe(true)
|
|
expect(dbEmbeddings[1].has1536).toBe(false)
|
|
})
|
|
})
|
|
|
|
describe('deleteAssetEmbeddingsActivity', () => {
|
|
it('should delete specific embeddings by id', async () => {
|
|
await saveAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
embeddings: [
|
|
{ embedding: Array(1536).fill(0.01), startTime: 0, endTime: 60 },
|
|
{ embedding: Array(1536).fill(0.02), startTime: 55, endTime: 115 },
|
|
],
|
|
})
|
|
|
|
const before = await prisma.assetEmbedding.findMany({
|
|
where: { assetId: asset.id },
|
|
})
|
|
expect(before).toHaveLength(2)
|
|
|
|
const targetId = before[0].id
|
|
await deleteAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
ids: [targetId],
|
|
})
|
|
|
|
const after = await prisma.assetEmbedding.findMany({
|
|
where: { assetId: asset.id },
|
|
})
|
|
expect(after).toHaveLength(1)
|
|
expect(after[0].id).not.toBe(targetId)
|
|
})
|
|
|
|
it('should delete all embeddings for an asset when ids is not provided', async () => {
|
|
await saveAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
embeddings: [
|
|
{ embedding: Array(1536).fill(0.01), startTime: 0, endTime: 60 },
|
|
{ embedding: Array(1536).fill(0.02), startTime: 55, endTime: 115 },
|
|
],
|
|
})
|
|
|
|
await deleteAssetEmbeddingsActivity({
|
|
assetId: asset.id,
|
|
})
|
|
|
|
const after = await prisma.assetEmbedding.findMany({
|
|
where: { assetId: asset.id },
|
|
})
|
|
expect(after).toHaveLength(0)
|
|
})
|
|
})
|
|
})
|