test(agent): write solid tests for agent workflows and activities

This commit is contained in:
yiling
2026-06-03 15:48:25 +08:00
parent 6fa6f3d0b4
commit 729d16d3ee
7 changed files with 1723 additions and 40 deletions
@@ -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',
})
})
})
+280 -14
View File
@@ -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' },
})
})
})