mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-23 19:28:19 +00:00
test(agent): write solid tests for agent workflows and activities
This commit is contained in:
@@ -1,8 +1,28 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentChatActivity, autofillAiActivity, type AgentExecutionContext } from './agent'
|
||||
import {
|
||||
agentChatActivity,
|
||||
autofillAiActivity,
|
||||
type AgentExecutionContext,
|
||||
initializeAgentSessionActivity,
|
||||
deleteCommentActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
getAgentChatContextActivity,
|
||||
getAgentAutofillContextActivity,
|
||||
getAssetActivity,
|
||||
getCommentActivity,
|
||||
getProjectAutofillFieldsActivity,
|
||||
updateAssetMetadataActivity,
|
||||
getAssetPathContextActivity,
|
||||
executeAgentToolActivity,
|
||||
} from './agent'
|
||||
import * as piAgent from '../index'
|
||||
import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core'
|
||||
import { type DatabaseSessionMetadata } from '../database-session-storage'
|
||||
import { prisma, AssetType, AssetStatus } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
|
||||
vi.mock('../index', async () => {
|
||||
const actual = await vi.importActual('../index')
|
||||
@@ -112,7 +132,6 @@ describe('Agent Activities', () => {
|
||||
}
|
||||
|
||||
vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: unknown) => {
|
||||
// Simulate tool execution
|
||||
const params = config as {
|
||||
customTools: Array<{
|
||||
name: string
|
||||
@@ -147,3 +166,527 @@ describe('Agent Activities', () => {
|
||||
expect(res.usage.inputTokens).toBe(5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Agent 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 project: 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
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.restoreAllMocks()
|
||||
|
||||
team = await prisma.team.create({
|
||||
data: { name: 'Test Team' },
|
||||
})
|
||||
|
||||
user = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Test Human',
|
||||
email: 'human@shumai.ai',
|
||||
type: 'human',
|
||||
},
|
||||
})
|
||||
|
||||
project = await prisma.project.create({
|
||||
data: {
|
||||
name: 'Test Project',
|
||||
teamId: team.id,
|
||||
},
|
||||
})
|
||||
|
||||
asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file.png',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: user.id,
|
||||
role: 'owner',
|
||||
scope: 'team',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
describe('initializeAgentSessionActivity', () => {
|
||||
it('should initialize a session, create agent/user records if missing, and store existing comments context', async () => {
|
||||
// Create first comment so it acts as context
|
||||
await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
message: 'Hello <@' + user.id + '> check this',
|
||||
creatorId: user.id,
|
||||
},
|
||||
})
|
||||
|
||||
// Create second comment that user responds with, triggering session initialization
|
||||
const userComment = await prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
message: 'Reply comment',
|
||||
creatorId: user.id,
|
||||
},
|
||||
})
|
||||
|
||||
const sessionId = await initializeAgentSessionActivity({
|
||||
teamId: team.id,
|
||||
agentId: 'test-agent-id',
|
||||
userCommentId: userComment.id,
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
expect(sessionId).toBeDefined()
|
||||
|
||||
// Verify agent user created
|
||||
const agentUser = await prisma.user.findUnique({ where: { id: 'test-agent-id' } })
|
||||
expect(agentUser).toBeDefined()
|
||||
expect(agentUser?.type).toBe('agent')
|
||||
|
||||
// Verify agentSession created
|
||||
const agentSession = await prisma.agentSession.findUnique({
|
||||
where: { id: sessionId },
|
||||
include: { entries: true },
|
||||
})
|
||||
expect(agentSession).toBeDefined()
|
||||
expect(agentSession?.leafId).toBeDefined()
|
||||
|
||||
// Verify historical comment is converted and saved to entries (mentions replaced, prefixes added)
|
||||
expect(agentSession?.entries.length).toBe(1)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- entry is stored as Json in DB and needs casting to check properties
|
||||
const parsedEntry = agentSession?.entries[0].entry as any
|
||||
expect(parsedEntry.message.content[0].text).toContain(
|
||||
`[${user.name}]: Hello <@${user.name}> check this`,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Comment Operations', () => {
|
||||
it('should create, update, and delete comments correctly', async () => {
|
||||
const comment = await createCommentActivity({
|
||||
assetId: asset.id,
|
||||
message: 'Drafting response',
|
||||
agentId: 'default',
|
||||
})
|
||||
|
||||
expect(comment.id).toBeDefined()
|
||||
expect(comment.message).toBe('Drafting response')
|
||||
|
||||
const updated = await updateCommentActivity({
|
||||
commentId: comment.id,
|
||||
message: 'Final response',
|
||||
})
|
||||
expect(updated.message).toBe('Final response')
|
||||
|
||||
await deleteCommentActivity(comment.id)
|
||||
const deleted = await prisma.assetComment.findUnique({ where: { id: comment.id } })
|
||||
expect(deleted).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Context Retrievals', () => {
|
||||
it('should retrieve Agent chat and autofill contexts correctly', async () => {
|
||||
const provider = await prisma.provider.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
name: 'openai',
|
||||
config: {
|
||||
api: 'openai',
|
||||
apiKey: 'mock-key',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const model = await prisma.model.create({
|
||||
data: {
|
||||
providerId: provider.id,
|
||||
modelId: 'gpt-4',
|
||||
name: 'GPT 4',
|
||||
config: {
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
contextWindow: 8192,
|
||||
maxTokens: 2048,
|
||||
cost: { input: 0.01, output: 0.03, cacheRead: 0, cacheWrite: 0 }
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Create User to map Agent 1-to-1
|
||||
const agentUser = await prisma.user.create({
|
||||
data: {
|
||||
id: 'chat-agent-id',
|
||||
name: 'Chat Agent User',
|
||||
email: 'chatagent@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: agentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const chatCtx = await getAgentChatContextActivity({
|
||||
teamId: team.id,
|
||||
agentId: agent.id,
|
||||
})
|
||||
|
||||
expect(chatCtx.agent.id).toBe(agent.id)
|
||||
expect(chatCtx.dbProviders[0].name).toBe('openai')
|
||||
|
||||
// Create User for autofill agent
|
||||
const autofillUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Autofill Agent User',
|
||||
email: 'autofillagent@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
|
||||
const autofillAgent = await prisma.agent.create({
|
||||
data: {
|
||||
id: autofillUser.id,
|
||||
teamId: team.id,
|
||||
type: 'autofill',
|
||||
enabled: true,
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
config: {
|
||||
provider: 'openai',
|
||||
model: 'gpt-4',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const autofillCtx = await getAgentAutofillContextActivity({
|
||||
teamId: team.id,
|
||||
})
|
||||
|
||||
expect(autofillCtx.agent.id).toBe(autofillAgent.id)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Asset and Comment Fetching', () => {
|
||||
it('should retrieve asset and comment correctly', async () => {
|
||||
const fetchedAsset = await getAssetActivity(asset.id)
|
||||
expect(fetchedAsset?.id).toBe(asset.id)
|
||||
|
||||
const comment = await createCommentActivity({
|
||||
assetId: asset.id,
|
||||
message: 'draft comment',
|
||||
})
|
||||
const fetchedComment = await getCommentActivity(comment.id)
|
||||
expect(fetchedComment?.id).toBe(comment.id)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getAssetPathContextActivity', () => {
|
||||
it('should build correct asset path context from root to asset', async () => {
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'RootFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
const subfolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'SubFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
},
|
||||
})
|
||||
|
||||
const targetAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'TargetImage.webp',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: subfolder.id,
|
||||
},
|
||||
})
|
||||
|
||||
const pathCtx = await getAssetPathContextActivity(targetAsset.id)
|
||||
expect(pathCtx).toContain('Path: RootFolder/SubFolder/TargetImage.webp')
|
||||
expect(pathCtx).toContain(`name: RootFolder, id: ${rootFolder.id}`)
|
||||
expect(pathCtx).toContain(`name: SubFolder, id: ${subfolder.id}`)
|
||||
expect(pathCtx).toContain(`name: TargetImage.webp, id: ${targetAsset.id}`)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getProjectAutofillFieldsActivity & updateAssetMetadataActivity', () => {
|
||||
it('should get fields and update metadata', async () => {
|
||||
// Create team field
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'field_key_1',
|
||||
scope: 'TEAM',
|
||||
teamId: team.id,
|
||||
aiAutofill: true,
|
||||
config: { name: 'Title Extractor', type: 'text' },
|
||||
},
|
||||
})
|
||||
|
||||
const fields = await getProjectAutofillFieldsActivity(project.id)
|
||||
expect(fields.length).toBe(1)
|
||||
expect(fields[0].key).toBe('field_key_1')
|
||||
|
||||
await updateAssetMetadataActivity({
|
||||
assetId: asset.id,
|
||||
metadata: [{ key: 'field_key_1', value: 'Hello Web' }],
|
||||
})
|
||||
|
||||
const updatedVal = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: asset.id, fieldKey: 'field_key_1' },
|
||||
})
|
||||
expect(updatedVal?.stringValue).toBe('Hello Web')
|
||||
})
|
||||
})
|
||||
|
||||
describe('executeAgentToolActivity', () => {
|
||||
beforeEach(() => {
|
||||
vi.spyOn(authzService, 'hasPermission').mockResolvedValue()
|
||||
vi.spyOn(uploadService, 'triggerPostUploadWorkflows').mockResolvedValue()
|
||||
})
|
||||
|
||||
describe('list_assets', () => {
|
||||
it('should list assets inside a folder with cursor pagination', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file1.txt',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'subfolder1',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'list_assets',
|
||||
args: { parent: folder.id, page: 1, pageSize: 1 },
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
expect(res.assets.length).toBe(1)
|
||||
expect(res.pageInfo.cursor).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('create_folder', () => {
|
||||
it('should create folder and increment parent fileCount', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_folder',
|
||||
args: { parent: folder.id, name: 'subfolder' },
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
expect(res.name).toBe('subfolder')
|
||||
expect(res.type).toBe('folder')
|
||||
|
||||
const parentFolder = await prisma.asset.findUnique({ where: { id: folder.id } })
|
||||
expect(parentFolder?.fileCount).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('create_file', () => {
|
||||
it('should create file, increment parent fileCount, and update parent sizes', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 0,
|
||||
sizeByte: 0,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: folder.id,
|
||||
s3Key: 'uploads/testfile.txt',
|
||||
name: 'testfile.txt',
|
||||
size: 500,
|
||||
contentType: 'text/plain',
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
expect(res.name).toBe('testfile.txt')
|
||||
expect(res.size).toBe(500)
|
||||
|
||||
const parentFolder = await prisma.asset.findUnique({ where: { id: folder.id } })
|
||||
expect(parentFolder?.fileCount).toBe(1)
|
||||
expect(parentFolder?.sizeByte).toBe(500)
|
||||
expect(uploadService.triggerPostUploadWorkflows).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('create_version', () => {
|
||||
it('should create a version stack when parent is a regular file', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 1,
|
||||
sizeByte: 200,
|
||||
},
|
||||
})
|
||||
|
||||
const fileAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'v1.txt',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
sizeByte: 200,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: fileAsset.id,
|
||||
s3Key: 'uploads/v2.txt',
|
||||
name: 'v2.txt',
|
||||
size: 300,
|
||||
contentType: 'text/plain',
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
expect(res.name).toBe('v2.txt')
|
||||
expect(res.size).toBe(300)
|
||||
|
||||
// Check version stack was created
|
||||
const stack = await prisma.asset.findFirst({
|
||||
where: { type: AssetType.version_stack, projectId: project.id },
|
||||
include: { children: true },
|
||||
})
|
||||
|
||||
expect(stack).not.toBeNull()
|
||||
expect(stack?.children.length).toBe(2) // v1.txt and v2.txt should both be inside the stack
|
||||
})
|
||||
|
||||
it('should add to version stack when parent is already inside a version stack', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'VersionStack',
|
||||
type: AssetType.version_stack,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
fileCount: 1,
|
||||
sizeByte: 100,
|
||||
},
|
||||
})
|
||||
|
||||
const existingFileVersion = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'v1.txt',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: stack.id,
|
||||
sizeByte: 100,
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: existingFileVersion.id,
|
||||
s3Key: 'uploads/v2.txt',
|
||||
name: 'v2.txt',
|
||||
size: 250,
|
||||
contentType: 'text/plain',
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
expect(res.name).toBe('v2.txt')
|
||||
|
||||
const updatedStack = await prisma.asset.findUnique({
|
||||
where: { id: stack.id },
|
||||
include: { children: true },
|
||||
})
|
||||
|
||||
expect(updatedStack?.fileCount).toBe(2)
|
||||
expect(updatedStack?.sizeByte).toBe(350)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,33 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { generateEmbeddingActivity } from './ai'
|
||||
import {
|
||||
generateEmbeddingActivity,
|
||||
generateTextEmbeddingActivity,
|
||||
extractAiMetadataActivity,
|
||||
getEmbeddingContextActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
} from './ai'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { transcodeService } from '@shumai/transcode'
|
||||
import { prisma, AssetType, AssetStatus } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import * as fs from 'fs'
|
||||
|
||||
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: {
|
||||
@@ -11,6 +38,30 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/transcode', () => ({
|
||||
transcodeService: {
|
||||
extractVideoFrames: 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 execMock: any = vi.fn((cmd: any, cb: any) => {
|
||||
cb(null, '120.0\n', '')
|
||||
})
|
||||
// Setup custom promisify behavior to return { stdout, stderr }
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock functions dynamically return varying types based on test command calls
|
||||
execMock[Symbol.for('nodejs.util.promisify.custom')] = vi.fn(async (cmd: any) => {
|
||||
if (cmd.includes('ffprobe')) {
|
||||
return { stdout: '120.0\n', stderr: '' }
|
||||
}
|
||||
return { stdout: '', stderr: '' }
|
||||
})
|
||||
return {
|
||||
exec: execMock,
|
||||
}
|
||||
})
|
||||
|
||||
const mockEmbedContent = vi.fn().mockResolvedValue({
|
||||
embeddings: [
|
||||
{
|
||||
@@ -21,7 +72,7 @@ const mockEmbedContent = vi.fn().mockResolvedValue({
|
||||
|
||||
vi.mock('@google/genai', () => {
|
||||
return {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention -- matches external library GoogleGenAI export naming convention
|
||||
GoogleGenAI: class {
|
||||
models = {
|
||||
embedContent: mockEmbedContent,
|
||||
@@ -30,7 +81,7 @@ vi.mock('@google/genai', () => {
|
||||
}
|
||||
})
|
||||
|
||||
describe('AI Activities', () => {
|
||||
describe('AI Activities Unit Tests', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.GEMINI_API_KEY = 'test-key'
|
||||
@@ -40,8 +91,7 @@ describe('AI Activities', () => {
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer: Buffer.from('test-image'),
|
||||
contentType: 'image/png',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock getObject return value needs broad any casting
|
||||
} as any)
|
||||
} as unknown as { buffer: Buffer; contentType: string })
|
||||
|
||||
const context = {
|
||||
agent: { config: { provider: 'google', model: 'gemini' } },
|
||||
@@ -58,4 +108,222 @@ describe('AI Activities', () => {
|
||||
expect(res.embeddings[0].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 context = {
|
||||
agent: { config: { provider: 'google', model: 'gemini' } },
|
||||
asset: { id: 'a2', mediaType: 'video/mp4', storageKey: { key: 'test.mp4' } },
|
||||
}
|
||||
|
||||
const res = await generateEmbeddingActivity({
|
||||
teamId: 't1',
|
||||
assetId: 'a2',
|
||||
context,
|
||||
})
|
||||
|
||||
// Duration is 120s, chunks are 60s, so it should generate 2 chunks (0-60, 60-120)
|
||||
expect(res.embeddings.length).toBe(2)
|
||||
expect(res.embeddings[0]).toEqual({ embedding: [0.1, 0.2, 0.3], startTime: 0, endTime: 60 })
|
||||
expect(res.embeddings[1]).toEqual({ embedding: [0.1, 0.2, 0.3], startTime: 60, endTime: 120 })
|
||||
|
||||
expect(vi.mocked(fs.writeFileSync)).toHaveBeenCalled()
|
||||
expect(vi.mocked(fs.readFileSync)).toHaveBeenCalled()
|
||||
expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
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' }],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
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',
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
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')
|
||||
})
|
||||
})
|
||||
|
||||
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()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,12 +16,13 @@ vi.mock('@shumai/workflow-core', async () => {
|
||||
describe('Agent Autofill Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities holds mock functions cast to expected types
|
||||
let mockActivities: any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should run agent autofill workflow successfully', async () => {
|
||||
const mockActivities = {
|
||||
mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
@@ -54,6 +55,9 @@ describe('Agent Autofill Workflow', () => {
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
}
|
||||
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue')
|
||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'a1',
|
||||
@@ -61,21 +65,19 @@ describe('Agent Autofill Workflow', () => {
|
||||
project: { id: 'p1', teamId: 't1' },
|
||||
mediaType: 'image/png',
|
||||
})
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/test.png',
|
||||
tmpDir: '/tmp',
|
||||
tmpDir: '/tmp/test-dir',
|
||||
})
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue(['/tmp/1.webp'])
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue(['/tmp/test-dir/1.webp'])
|
||||
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
|
||||
{ id: 'f1', key: 'f1', config: { name: 'F1', type: 'text' } },
|
||||
{ key: 'title', config: { name: 'Title', type: 'text' }, description: 'The title' },
|
||||
])
|
||||
mockActivities.getAgentAutofillContextActivity.mockResolvedValue({ agent: { id: 'b1' } })
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.autofillAiActivity.mockResolvedValue({
|
||||
text: '{"f1":"val"}',
|
||||
text: '{"title":"Extracted Title"}',
|
||||
sessionId: 'session-123',
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
|
||||
usage: { inputTokens: 10, outputTokens: 15, model: 'gemini-model' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
@@ -84,6 +86,110 @@ describe('Agent Autofill Workflow', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent autofill workflow successfully', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_metadata_autofill',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { sessionId: 's1', agentId: 'agent-1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentAutofillMedia(task)
|
||||
|
||||
// Verify queue discovery
|
||||
expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.getTranscodeWorkerQueueActivity).toHaveBeenCalled()
|
||||
|
||||
// Verify task processing status
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// Verify placeholder comment created
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'a1',
|
||||
message: '__AUTOFILL__',
|
||||
sessionId: 's1',
|
||||
agentId: 'agent-1',
|
||||
})
|
||||
|
||||
// Verify download, extraction and fields fetched
|
||||
expect(mockActivities.downloadMediaToTmpActivity).toHaveBeenCalledWith({
|
||||
assetKey: 'asset-key',
|
||||
})
|
||||
expect(mockActivities.extractAiMetadataActivity).toHaveBeenCalledWith({
|
||||
assetKey: 'asset-key',
|
||||
filePath: '/tmp/test.png',
|
||||
type: 'autofill',
|
||||
isImage: true,
|
||||
})
|
||||
expect(mockActivities.getProjectAutofillFieldsActivity).toHaveBeenCalledWith('p1')
|
||||
expect(mockActivities.getAgentAutofillContextActivity).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
})
|
||||
|
||||
// Verify AI autofill called with mapped fields
|
||||
expect(mockActivities.autofillAiActivity).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
images: ['/tmp/test-dir/1.webp'],
|
||||
fields: [
|
||||
{
|
||||
id: 'title',
|
||||
config: { name: 'Title', type: 'text' },
|
||||
description: 'The title',
|
||||
},
|
||||
],
|
||||
context: { agent: { id: 'b1' } },
|
||||
})
|
||||
|
||||
// Verify task usage update
|
||||
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
inputTokens: 10,
|
||||
outputTokens: 15,
|
||||
model: 'gemini-model',
|
||||
})
|
||||
|
||||
// Verify metadata updated on asset
|
||||
expect(mockActivities.updateAssetMetadataActivity).toHaveBeenCalledWith({
|
||||
assetId: 'a1',
|
||||
metadata: [
|
||||
{
|
||||
key: 'title',
|
||||
value: 'Extracted Title',
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
// Verify placeholder comment updated
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'comment-placeholder-id',
|
||||
message: 'Autofill completed successfully.',
|
||||
sessionId: 'session-123',
|
||||
})
|
||||
|
||||
// Verify cleanup was called
|
||||
expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({
|
||||
tmpDir: '/tmp/test-dir',
|
||||
})
|
||||
|
||||
// Verify completed task status
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
})
|
||||
|
||||
it('should complete early if no image files could be extracted', async () => {
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue([])
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
@@ -95,7 +201,86 @@ describe('Agent Autofill Workflow', () => {
|
||||
|
||||
await agentAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.getAgentAutofillContextActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.autofillAiActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'comment-placeholder-id',
|
||||
message: 'Autofill completed: No images could be extracted for analysis.',
|
||||
})
|
||||
|
||||
expect(mockActivities.autofillAiActivity).not.toHaveBeenCalled()
|
||||
expect(mockActivities.updateAssetMetadataActivity).not.toHaveBeenCalled()
|
||||
|
||||
// Verify cleanup still runs
|
||||
expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({
|
||||
tmpDir: '/tmp/test-dir',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
})
|
||||
|
||||
it('should complete early if no autofill fields are defined in the project', async () => {
|
||||
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([])
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_metadata_autofill',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
},
|
||||
})
|
||||
|
||||
await agentAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'comment-placeholder-id',
|
||||
message: 'Autofill completed: No autofill fields defined in project.',
|
||||
})
|
||||
|
||||
expect(mockActivities.autofillAiActivity).not.toHaveBeenCalled()
|
||||
expect(mockActivities.updateAssetMetadataActivity).not.toHaveBeenCalled()
|
||||
|
||||
// Verify cleanup still runs
|
||||
expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({
|
||||
tmpDir: '/tmp/test-dir',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures, update placeholder with error, set status to failed, and cleanup tmp directory', async () => {
|
||||
mockActivities.getProjectAutofillFieldsActivity.mockRejectedValue(new Error('DB failure'))
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_metadata_autofill',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
},
|
||||
})
|
||||
|
||||
await expect(agentAutofillMedia(task)).rejects.toThrow('DB failure')
|
||||
|
||||
// Verify placeholder updated with error
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'comment-placeholder-id',
|
||||
message: 'Autofill failed: DB failure',
|
||||
})
|
||||
|
||||
// Verify task failed status
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: 'DB failure' },
|
||||
})
|
||||
|
||||
// Verify cleanup still runs in finally block
|
||||
expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({
|
||||
tmpDir: '/tmp/test-dir',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,12 +16,13 @@ vi.mock('@shumai/workflow-core', async () => {
|
||||
describe('Agent Chat Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities holds mock functions cast to expected types
|
||||
let mockActivities: any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should run agent chat workflow successfully', async () => {
|
||||
const mockActivities = {
|
||||
mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
@@ -46,23 +47,28 @@ describe('Agent Chat Workflow', () => {
|
||||
}),
|
||||
}
|
||||
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'a1',
|
||||
project: { teamId: 't1' },
|
||||
type: 'file',
|
||||
parentId: 'parent-folder-id',
|
||||
})
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'c1',
|
||||
message: 'hello',
|
||||
message: 'hello agent',
|
||||
replyToId: null,
|
||||
attachments: [],
|
||||
})
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getAssetActivity.mockResolvedValue({ id: 'a1', project: { teamId: 't1' } })
|
||||
mockActivities.initializeAgentSessionActivity.mockResolvedValue('session-123')
|
||||
mockActivities.getAgentChatContextActivity.mockResolvedValue({ agent: { id: 'b1' } })
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.getAssetPathContextActivity.mockResolvedValue(
|
||||
'Path: foo/bar/z.png\n\nname: foo, id: foo-id',
|
||||
)
|
||||
mockActivities.getAssetPathContextActivity.mockResolvedValue('Path: folder/subfolder/file.png')
|
||||
mockActivities.agentChatActivity.mockResolvedValue({
|
||||
text: 'arr matey!',
|
||||
text: 'Hello user, how can I help you?',
|
||||
sessionId: 'session-123',
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
|
||||
usage: { inputTokens: 10, outputTokens: 20, model: 'gemini-model' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
@@ -71,6 +77,175 @@ describe('Agent Chat Workflow', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent chat workflow successfully with default configurations', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { userCommentId: 'c1', agentId: 'b1', explicitMention: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
// Verify queue discovery
|
||||
expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled()
|
||||
|
||||
// Verify task status processing
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// Verify comment context fetched
|
||||
expect(mockActivities.getCommentActivity).toHaveBeenCalledWith('c1')
|
||||
|
||||
// Verify placeholder comment created
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'a1',
|
||||
message: '__CHAT__',
|
||||
sessionId: 'pending',
|
||||
agentId: 'b1',
|
||||
replyToId: 'c1',
|
||||
})
|
||||
|
||||
// Verify session initialized since sessionId was missing
|
||||
expect(mockActivities.initializeAgentSessionActivity).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
agentId: 'b1',
|
||||
userCommentId: 'c1',
|
||||
userId: undefined,
|
||||
})
|
||||
|
||||
// Verify agent instruction composition
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
teamId: 't1',
|
||||
agentId: 'b1',
|
||||
message: 'hello agent',
|
||||
agentsInstruction: expect.stringContaining('explicitly mentioned you'),
|
||||
sessionId: 'session-123',
|
||||
folderId: 'parent-folder-id',
|
||||
}),
|
||||
)
|
||||
|
||||
// Verify comment update
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'comment-placeholder-id',
|
||||
message: 'Hello user, how can I help you?',
|
||||
sessionId: 'session-123',
|
||||
})
|
||||
|
||||
// Verify task usage update
|
||||
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
inputTokens: 10,
|
||||
outputTokens: 20,
|
||||
model: 'gemini-model',
|
||||
})
|
||||
|
||||
// Verify task completed status
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: { sessionId: 'session-123' },
|
||||
})
|
||||
})
|
||||
|
||||
it('should skip session initialization if sessionId is already provided', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { userCommentId: 'c1', agentId: 'b1', sessionId: 'existing-session-456' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
expect(mockActivities.initializeAgentSessionActivity).not.toHaveBeenCalled()
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
sessionId: 'existing-session-456',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should delete placeholder comment and finish when AI responds with __NO_REPLY__', async () => {
|
||||
mockActivities.agentChatActivity.mockResolvedValue({
|
||||
text: '__NO_REPLY__',
|
||||
sessionId: 'session-123',
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { userCommentId: 'c1', agentId: 'b1', explicitMention: false },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
// Verify instruction contains not explicitly mentioned instructions
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
agentsInstruction: expect.stringContaining('did not explicitly mention you'),
|
||||
}),
|
||||
)
|
||||
|
||||
// Verify placeholder comment is deleted
|
||||
expect(mockActivities.deleteCommentActivity).toHaveBeenCalledWith('comment-placeholder-id')
|
||||
expect(mockActivities.updateCommentActivity).not.toHaveBeenCalled()
|
||||
|
||||
// Verify task still completes successfully
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: { sessionId: 'session-123' },
|
||||
})
|
||||
})
|
||||
|
||||
it('should collect S3 keys for image attachments from the user comment', async () => {
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'c1',
|
||||
message: 'look at this',
|
||||
replyToId: null,
|
||||
attachments: [
|
||||
{
|
||||
asset: {
|
||||
mediaType: 'image/png',
|
||||
storageKey: { key: 'attachments/image1.png' },
|
||||
},
|
||||
},
|
||||
{
|
||||
asset: {
|
||||
mediaType: 'video/mp4', // non-image, should be ignored
|
||||
storageKey: { key: 'attachments/video.mp4' },
|
||||
},
|
||||
},
|
||||
{
|
||||
asset: {
|
||||
mediaType: 'image/jpeg',
|
||||
storageKey: { key: 'attachments/image2.jpg' },
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
@@ -86,7 +261,98 @@ describe('Agent Chat Workflow', () => {
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
expect(mockActivities.getAgentChatContextActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
imageUrls: ['attachments/image1.png', 'attachments/image2.jpg'],
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should format instructions with asset media info when available', async () => {
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'a1',
|
||||
project: { teamId: 't1' },
|
||||
type: 'file',
|
||||
media: {
|
||||
duration: 10,
|
||||
height: 1080,
|
||||
width: 1920,
|
||||
},
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { userCommentId: 'c1', agentId: 'b1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
agentsInstruction: expect.stringContaining('Asset Media Info:'),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should handle errors gracefully by updating the placeholder comment with error message and marking task as failed', async () => {
|
||||
mockActivities.agentChatActivity.mockRejectedValue(new Error('AI error: API limit reached'))
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { userCommentId: 'c1', agentId: 'b1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await expect(agentChat(task)).rejects.toThrow('AI error: API limit reached')
|
||||
|
||||
// Verify placeholder updated with formatted error message
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'comment-placeholder-id',
|
||||
message: 'AI error: API limit reached',
|
||||
})
|
||||
|
||||
// Verify status updated to failed
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: 'AI error: API limit reached' },
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle generic errors in error handling block', async () => {
|
||||
mockActivities.agentChatActivity.mockRejectedValue(new Error('Some DB connection error'))
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { userCommentId: 'c1', agentId: 'b1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await expect(agentChat(task)).rejects.toThrow('Some DB connection error')
|
||||
|
||||
// Verify placeholder updated with generic error message
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'comment-placeholder-id',
|
||||
message: 'Sorry, I encountered an error while processing your request.',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -16,12 +16,13 @@ vi.mock('@shumai/workflow-core', async () => {
|
||||
describe('Agent Embedding Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities holds mock functions cast to expected types
|
||||
let mockActivities: any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should run agent embedding workflow successfully', async () => {
|
||||
const mockActivities = {
|
||||
mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
@@ -42,13 +43,14 @@ describe('Agent Embedding Workflow', () => {
|
||||
}),
|
||||
}
|
||||
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
|
||||
agent: { id: 'b1' },
|
||||
asset: { id: 'a1' },
|
||||
dbProvider: { name: 'google' },
|
||||
})
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.generateEmbeddingActivity.mockResolvedValue({
|
||||
embeddings: [{ embedding: [0.1, 0.2] }],
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
|
||||
@@ -60,6 +62,109 @@ describe('Agent Embedding Workflow', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent embedding workflow successfully', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_embedding',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
teamId: 't1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agent: { sessionId: 's1', agentId: 'agent-1' },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentEmbeddingMedia(task)
|
||||
|
||||
// Verify queue discovery
|
||||
expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled()
|
||||
|
||||
// Verify task processing status
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// Verify placeholder comment created
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'a1',
|
||||
message: '__EMBEDDING__',
|
||||
sessionId: 's1',
|
||||
agentId: 'agent-1',
|
||||
})
|
||||
|
||||
// Verify context fetching
|
||||
expect(mockActivities.getEmbeddingContextActivity).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
assetId: 'a1',
|
||||
})
|
||||
|
||||
// Verify embedding generation
|
||||
expect(mockActivities.generateEmbeddingActivity).toHaveBeenCalledWith({
|
||||
teamId: 't1',
|
||||
assetId: 'a1',
|
||||
context: {
|
||||
agent: { id: 'b1' },
|
||||
asset: { id: 'a1' },
|
||||
dbProvider: { name: 'google' },
|
||||
},
|
||||
})
|
||||
|
||||
// Verify embeddings saved
|
||||
expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalledWith({
|
||||
assetId: 'a1',
|
||||
embeddings: [{ embedding: [0.1, 0.2] }],
|
||||
})
|
||||
|
||||
// Verify usage update
|
||||
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
inputTokens: 5,
|
||||
outputTokens: 5,
|
||||
model: 'gpt',
|
||||
})
|
||||
|
||||
// Verify placeholder comment updated
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'comment-placeholder-id',
|
||||
message: 'Embedding completed successfully.',
|
||||
})
|
||||
|
||||
// Verify completed task status
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw if task has no teamId', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_embedding',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
},
|
||||
})
|
||||
|
||||
await expect(agentEmbeddingMedia(task)).rejects.toThrow('Task has no teamId')
|
||||
|
||||
// Verify status updated to failed
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: 'Task has no teamId' },
|
||||
})
|
||||
})
|
||||
|
||||
it('should skip saving embeddings if none are returned', async () => {
|
||||
mockActivities.generateEmbeddingActivity.mockResolvedValue({
|
||||
embeddings: [],
|
||||
usage: null,
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
@@ -72,8 +177,39 @@ describe('Agent Embedding Workflow', () => {
|
||||
|
||||
await agentEmbeddingMedia(task)
|
||||
|
||||
expect(mockActivities.getEmbeddingContextActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.generateEmbeddingActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.saveAssetEmbeddingsActivity).not.toHaveBeenCalled()
|
||||
expect(mockActivities.updateTaskUsageActivity).not.toHaveBeenCalled()
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures, update placeholder with error, and set status to failed', async () => {
|
||||
mockActivities.generateEmbeddingActivity.mockRejectedValue(new Error('AI Service Unavailable'))
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_embedding',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
teamId: 't1',
|
||||
},
|
||||
})
|
||||
|
||||
await expect(agentEmbeddingMedia(task)).rejects.toThrow('AI Service Unavailable')
|
||||
|
||||
// Verify placeholder updated with error
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'comment-placeholder-id',
|
||||
message: 'Embedding failed: AI Service Unavailable',
|
||||
})
|
||||
|
||||
// Verify status updated to failed
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: 'AI Service Unavailable' },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentToolCall } from './agent-tool-call'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async () => {
|
||||
const actual = await vi.importActual('@shumai/workflow-core')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent Tool Call Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities holds mock functions cast to expected types
|
||||
let mockActivities: any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
executeAgentToolActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'executeAgentToolActivity',
|
||||
}),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||
mockActivities.executeAgentToolActivity.mockResolvedValue({ success: true, count: 42 })
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent tool call workflow successfully', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'agent_tool_call',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agentToolCall: {
|
||||
toolName: 'list_assets',
|
||||
args: { parent: 'folder-123' },
|
||||
userId: 'user-456',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await agentToolCall(task)
|
||||
|
||||
// Verify queue discovery
|
||||
expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled()
|
||||
|
||||
// Verify task processing status
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// Verify tool execution
|
||||
expect(mockActivities.executeAgentToolActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
toolName: 'list_assets',
|
||||
args: { parent: 'folder-123' },
|
||||
userId: 'user-456',
|
||||
})
|
||||
|
||||
// Verify task completed status with output
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: { success: true, count: 42 },
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw if payload or agentToolCall is missing', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'agent_tool_call',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
},
|
||||
})
|
||||
|
||||
await expect(agentToolCall(task)).rejects.toThrow('Task payload or agentToolCall is missing')
|
||||
|
||||
// Verify status updated to failed
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: 'Task payload or agentToolCall is missing' },
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle tool execution failures by updating task to failed and throwing', async () => {
|
||||
mockActivities.executeAgentToolActivity.mockRejectedValue(new Error('Authz failure'))
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'agent_tool_call',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
agentToolCall: {
|
||||
toolName: 'create_folder',
|
||||
args: { parent: 'folder-123', name: 'new-folder' },
|
||||
userId: 'user-456',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await expect(agentToolCall(task)).rejects.toThrow('Authz failure')
|
||||
|
||||
// Verify task status failed
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: 'Authz failure' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,145 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { queryEmbeddingForSearch } from './query-embedding-for-search'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async () => {
|
||||
const actual = await vi.importActual('@shumai/workflow-core')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Query Embedding For Search Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities holds mock functions cast to expected types
|
||||
let mockActivities: any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockActivities = {
|
||||
updateWorkflowTaskActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateWorkflowTaskActivity',
|
||||
}),
|
||||
generateTextEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateTextEmbeddingActivity',
|
||||
}),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.updateWorkflowTaskActivity.mockResolvedValue({})
|
||||
mockActivities.generateTextEmbeddingActivity.mockResolvedValue({
|
||||
embedding: [0.1, 0.2, 0.3],
|
||||
usage: { inputTokens: 4, outputTokens: 0, model: 'gemini-embedding-2' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
})
|
||||
|
||||
it('should run query embedding workflow successfully', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'query_embedding_for_search',
|
||||
status: 'pending',
|
||||
teamId: 't1',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
queryEmbeddingForSearch: {
|
||||
text: 'search query',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await queryEmbeddingForSearch(task)
|
||||
|
||||
// Verify queue discovery
|
||||
expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled()
|
||||
|
||||
// Verify task processing status
|
||||
expect(mockActivities.updateWorkflowTaskActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
heartbeat: true,
|
||||
})
|
||||
|
||||
// Verify embedding generation
|
||||
expect(mockActivities.generateTextEmbeddingActivity).toHaveBeenCalledWith({
|
||||
text: 'search query',
|
||||
teamId: 't1',
|
||||
})
|
||||
|
||||
// Verify completed status and details
|
||||
expect(mockActivities.updateWorkflowTaskActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: { embedding: [0.1, 0.2, 0.3] },
|
||||
inputTokens: 4,
|
||||
outputTokens: 0,
|
||||
model: 'gemini-embedding-2',
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw immediately if text is missing', async () => {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'query_embedding_for_search',
|
||||
status: 'pending',
|
||||
teamId: 't1',
|
||||
assetId: 'a1',
|
||||
},
|
||||
})
|
||||
|
||||
await expect(queryEmbeddingForSearch(task)).rejects.toThrow(
|
||||
'Missing text in query_embedding_for_search task payload',
|
||||
)
|
||||
|
||||
// Should not call any activities because it throws before queue discovery
|
||||
expect(mockActivities.getAgentWorkerQueueActivity).not.toHaveBeenCalled()
|
||||
expect(mockActivities.updateWorkflowTaskActivity).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should handle activity failure and update task status to failed', async () => {
|
||||
mockActivities.generateTextEmbeddingActivity.mockRejectedValue(
|
||||
new Error('Embedding API failed'),
|
||||
)
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'query_embedding_for_search',
|
||||
status: 'pending',
|
||||
teamId: 't1',
|
||||
assetId: 'a1',
|
||||
payload: {
|
||||
projectId: 'p1',
|
||||
queryEmbeddingForSearch: {
|
||||
text: 'search query',
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await expect(queryEmbeddingForSearch(task)).rejects.toThrow('Embedding API failed')
|
||||
|
||||
// Verify it updates task to failed
|
||||
expect(mockActivities.updateWorkflowTaskActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: 'Embedding API failed' },
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user