mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-23 09:47:15 +00:00
refactor(agent): remove executeAgentToolWorkflow and invoke core services directly (#362)
* refactor(agent): remove executeAgentToolWorkflow and invoke core services directly * fix(core): ensure creation atomicity, strict assetType filtering, and id-desc listing
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
export * from '@shumai/agent/src/workflows/agent-autofill'
|
||||
export * from '@shumai/agent/src/workflows/agent-chat'
|
||||
export * from '@shumai/agent/src/workflows/agent-embedding'
|
||||
export * from '@shumai/agent/src/workflows/agent-tool-call'
|
||||
export * from '@shumai/agent/src/workflows/query-embedding-for-search'
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
getProjectAutofillFieldsActivity,
|
||||
updateAssetMetadataActivity,
|
||||
getAssetPathContextActivity,
|
||||
executeAgentToolActivity,
|
||||
generateSessionNameActivity,
|
||||
type GenerateSessionNameParams,
|
||||
getUserTeamInfoActivity,
|
||||
@@ -36,8 +35,6 @@ import {
|
||||
type Asset,
|
||||
} 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')
|
||||
@@ -1378,556 +1375,6 @@ describe('Agent Database Activities Integration', () => {
|
||||
})
|
||||
})
|
||||
|
||||
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()
|
||||
})
|
||||
|
||||
it('should resolve version_stack name and size from top child version when container name is empty', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
const versionStack = await prisma.asset.create({
|
||||
data: {
|
||||
name: '',
|
||||
type: AssetType.version_stack,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: folder.id,
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'banana_ghost.txt',
|
||||
type: AssetType.file,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
parentId: versionStack.id,
|
||||
sizeByte: 622960,
|
||||
sortIndex: '0|i00000:',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'list_assets',
|
||||
args: { parent: folder.id, page: 1, pageSize: 10 },
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const stackItem = res.assets.find(
|
||||
(a: { id: string; name: string; size: number; type: string }) => a.id === versionStack.id,
|
||||
)
|
||||
expect(stackItem).toBeDefined()
|
||||
expect(stackItem?.name).toBe('banana_ghost.txt')
|
||||
expect(stackItem?.size).toBe(622960)
|
||||
expect(stackItem?.type).toBe('version_stack')
|
||||
})
|
||||
})
|
||||
|
||||
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(Number(parentFolder?.sizeByte)).toBe(500)
|
||||
expect(uploadService.triggerPostUploadWorkflows).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should persist metadata on the created file when metadata map is provided', async () => {
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'prompt',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
config: { name: 'Prompt', type: 'text', autofillSource: 'CREATION_CONTEXT' },
|
||||
},
|
||||
})
|
||||
|
||||
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/ctx.txt',
|
||||
name: 'ctx.txt',
|
||||
size: 100,
|
||||
contentType: 'text/plain',
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const val = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: 'prompt' },
|
||||
})
|
||||
expect(val?.stringValue).toBe('Generated using gemini')
|
||||
})
|
||||
|
||||
it('should persist select and selectMulti metadata with dynamic newOption', async () => {
|
||||
const selectField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'provider',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Provider',
|
||||
type: 'select',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const multiField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'tags',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Tags',
|
||||
type: 'selectMulti',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
selectMulti: { options: [{ id: 'tag1', displayName: 'Tag 1', color: '#3b82f6' }] },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
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/new_opt.txt',
|
||||
name: 'new_opt.txt',
|
||||
size: 100,
|
||||
contentType: 'text/plain',
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
// Verify select field
|
||||
const providerVal = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: selectField.key },
|
||||
})
|
||||
expect(providerVal?.stringValue).toBe('kling')
|
||||
|
||||
// Verify select field config was updated with new option
|
||||
const updatedSelectField = await prisma.metadataField.findUnique({
|
||||
where: { key: selectField.key },
|
||||
})
|
||||
const selectOpts =
|
||||
(updatedSelectField?.config as PrismaJson.FieldConfig)?.select?.options || []
|
||||
expect(selectOpts.some((o) => o.displayName === 'Kling' && o.id === 'kling')).toBe(true)
|
||||
|
||||
// Verify selectMulti field
|
||||
const tagsVal = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: multiField.key },
|
||||
})
|
||||
expect(tagsVal?.jsonValue).toEqual(['tag1', 'tag-2'])
|
||||
|
||||
// Verify selectMulti field config was updated with new option
|
||||
const updatedMultiField = await prisma.metadataField.findUnique({
|
||||
where: { key: multiField.key },
|
||||
})
|
||||
const multiOpts =
|
||||
(updatedMultiField?.config as PrismaJson.FieldConfig)?.selectMulti?.options || []
|
||||
expect(multiOpts.some((o) => o.displayName === 'Tag 2' && o.id === 'tag-2')).toBe(true)
|
||||
})
|
||||
|
||||
it('should reject metadata with keys that are not valid in this project', async () => {
|
||||
const folder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'WorkspaceFolder',
|
||||
type: AssetType.folder,
|
||||
status: AssetStatus.uploaded,
|
||||
projectId: project.id,
|
||||
fileCount: 0,
|
||||
sizeByte: 0,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
executeAgentToolActivity({
|
||||
taskId: 'task-1',
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: folder.id,
|
||||
s3Key: 'uploads/ctx.txt',
|
||||
name: 'ctx.txt',
|
||||
size: 100,
|
||||
contentType: 'text/plain',
|
||||
metadata: { prompt: 'ok', unknownKey: 'not allowed' },
|
||||
},
|
||||
userId: user.id,
|
||||
}),
|
||||
).rejects.toThrow(/not valid in this project/)
|
||||
|
||||
// No metadata value should have been written for the unknown key
|
||||
const val = await prisma.assetMetadataValue.findFirst({
|
||||
where: { fieldKey: 'unknownKey' },
|
||||
})
|
||||
expect(val).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
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(Number(updatedStack?.sizeByte)).toBe(350)
|
||||
})
|
||||
|
||||
it('should persist metadata on the created version when metadata map is provided', async () => {
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'prompt',
|
||||
scope: 'PROJECT',
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
config: { name: 'Prompt', type: 'text', autofillSource: 'CREATION_CONTEXT' },
|
||||
},
|
||||
})
|
||||
|
||||
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',
|
||||
metadata: { prompt: 'Generated using seedance' },
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const val = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: 'prompt' },
|
||||
})
|
||||
expect(val?.stringValue).toBe('Generated using seedance')
|
||||
})
|
||||
|
||||
it('should persist select and selectMulti newOption metadata in create_version', async () => {
|
||||
const selectField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'versionProvider',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Version Provider',
|
||||
type: 'select',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
select: { options: [{ id: 'openai', displayName: 'OpenAI', color: '#f43f5e' }] },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
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',
|
||||
metadata: {
|
||||
versionProvider: { newOption: { value: 'Midjourney' } },
|
||||
},
|
||||
},
|
||||
userId: user.id,
|
||||
})
|
||||
|
||||
const val = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: res.id, fieldKey: selectField.key },
|
||||
})
|
||||
expect(val?.stringValue).toBe('midjourney')
|
||||
|
||||
const updatedField = await prisma.metadataField.findUnique({
|
||||
where: { key: selectField.key },
|
||||
})
|
||||
const opts = (updatedField?.config as PrismaJson.FieldConfig)?.select?.options || []
|
||||
expect(opts.some((o) => o.displayName === 'Midjourney' && o.id === 'midjourney')).toBe(true)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('generateSessionNameActivity', () => {
|
||||
it('should generate and save session name for chat sessions', async () => {
|
||||
await prisma.team.create({
|
||||
|
||||
@@ -5,24 +5,15 @@ import {
|
||||
} from '@earendil-works/pi-agent-core'
|
||||
import { type ImageContent } from '@earendil-works/pi-ai'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import {
|
||||
authzService,
|
||||
Permission,
|
||||
ResourceType,
|
||||
resolveEffectiveRole,
|
||||
} from '@shumai/core/src/authz/authz'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { mcpService } from '@shumai/core/src/mcp/mcp-service'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { encodeCursor, paginateQuery } from '@shumai/core/src/pagination'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import { VersionStackService } from '@shumai/core/src/versionStack/versionStack'
|
||||
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
|
||||
import { AssetType, prisma, Prisma, type Skill } from '@shumai/db'
|
||||
import { registerLocalCancelHandler, unregisterLocalCancelHandler } from '@shumai/workflow-core'
|
||||
import { ApplicationFailure, Context } from '@temporalio/activity'
|
||||
import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { ulid } from 'ulid'
|
||||
import { DatabaseSessionStorage } from '../database-session-storage'
|
||||
import {
|
||||
@@ -1249,460 +1240,6 @@ export async function getAssetPathContextActivity(assetId: string): Promise<stri
|
||||
return contextStr
|
||||
}
|
||||
|
||||
export interface ExecuteAgentToolParams {
|
||||
taskId: string
|
||||
toolName: string
|
||||
// args are dynamic JSON arguments passed from the agent harness at runtime
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
args: any
|
||||
userId?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that every metadata key provided by the agent is a defined
|
||||
* CREATION_CONTEXT field of the project. Unknown keys are rejected with a
|
||||
* non-retryable failure so Temporal does not retry expected validation errors.
|
||||
*/
|
||||
async function validateCreationContextMetadata(
|
||||
userId: string,
|
||||
projectId: string,
|
||||
metadata: Record<string, unknown> | undefined,
|
||||
): Promise<void> {
|
||||
if (!metadata || Object.keys(metadata).length === 0) return
|
||||
|
||||
const fields = await metadataService.listProjectFields(userId, projectId)
|
||||
const allowedKeys = new Set(
|
||||
fields
|
||||
.filter((f) => f.field.config?.autofillSource === 'CREATION_CONTEXT')
|
||||
.map((f) => f.field.key),
|
||||
)
|
||||
const invalidKeys = Object.keys(metadata).filter((key) => !allowedKeys.has(key))
|
||||
if (invalidKeys.length > 0) {
|
||||
throw ApplicationFailure.create({
|
||||
message:
|
||||
`metadata contains keys that are not valid in this project: ${invalidKeys.join(', ')}. ` +
|
||||
"The valid metadata fields are fixed to the current conversation's project. " +
|
||||
'If the target folder or file belongs to a different project, call the tool WITHOUT the metadata parameter.',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Activity return type is a union of tool result shapes
|
||||
export async function executeAgentToolActivity(params: ExecuteAgentToolParams): Promise<any> {
|
||||
const { toolName, args, userId } = params
|
||||
if (!userId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'User ID is required for tool authz',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// 1. Fetch User
|
||||
const user = await prisma.user.findUnique({ where: { id: userId } })
|
||||
if (!user) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `User not found: ${userId}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// 2. Perform Authz and Action based on toolName
|
||||
switch (toolName) {
|
||||
case 'list_assets': {
|
||||
const parent = args.parent
|
||||
if (!parent) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent parameter is required',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Authz check
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: parent,
|
||||
})
|
||||
|
||||
const page = args.page || 1
|
||||
const pageSize = args.pageSize || 20
|
||||
const type = args.type || 'all'
|
||||
|
||||
// We need to list files and folders of parent dir
|
||||
const where: Prisma.AssetWhereInput = {
|
||||
parentId: parent,
|
||||
isDeleted: false,
|
||||
}
|
||||
if (type === 'file') {
|
||||
where.type = { in: ['file', 'version_stack'] }
|
||||
} else if (type === 'folder') {
|
||||
where.type = 'folder'
|
||||
} else {
|
||||
where.type = { in: ['file', 'folder', 'version_stack'] }
|
||||
}
|
||||
|
||||
const limit = pageSize
|
||||
const offset = (page - 1) * limit
|
||||
const after = offset > 0 ? encodeCursor(offset) : undefined
|
||||
|
||||
const { data: assets, pageInfo } = await paginateQuery<
|
||||
Prisma.AssetGetPayload<Record<string, never>>
|
||||
>(
|
||||
async (skip, take) => {
|
||||
return prisma.asset.findMany({
|
||||
where,
|
||||
orderBy: { id: 'desc' }, // sort desc per ULID default in sorting guidelines!
|
||||
skip,
|
||||
take,
|
||||
})
|
||||
},
|
||||
async () => prisma.asset.count({ where }),
|
||||
{ first: limit, after },
|
||||
)
|
||||
|
||||
const stackIds = assets.filter((a) => a.type === AssetType.version_stack).map((a) => a.id)
|
||||
|
||||
const latestVersionsMap = new Map<string, Prisma.AssetGetPayload<Record<string, never>>>()
|
||||
|
||||
if (stackIds.length > 0) {
|
||||
const versions = await prisma.asset.findMany({
|
||||
where: { parentId: { in: stackIds }, isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
})
|
||||
for (const v of versions) {
|
||||
if (!latestVersionsMap.has(v.parentId!)) {
|
||||
latestVersionsMap.set(v.parentId!, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// return asset id, asset name, asset type, asset size (sizeByte or size)
|
||||
const results = assets.map((a) => {
|
||||
const latestVersion = latestVersionsMap.get(a.id)
|
||||
return {
|
||||
id: a.id,
|
||||
name: a.type === AssetType.version_stack ? (latestVersion?.name ?? a.name) : a.name,
|
||||
type: a.type,
|
||||
size:
|
||||
a.type === AssetType.version_stack && latestVersion
|
||||
? Number(latestVersion.sizeByte)
|
||||
: Number(a.sizeByte),
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
assets: results,
|
||||
pageInfo,
|
||||
}
|
||||
}
|
||||
|
||||
case 'create_folder': {
|
||||
const parent = args.parent
|
||||
const name = args.name
|
||||
if (!parent || !name) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent and name parameters are required',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Authz check
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: parent,
|
||||
})
|
||||
|
||||
const newFolder = await assetService.createAsset({
|
||||
name,
|
||||
parentId: parent,
|
||||
type: 'folder',
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
return {
|
||||
id: newFolder.id,
|
||||
name: newFolder.name,
|
||||
type: newFolder.type,
|
||||
size: Number(newFolder.sizeByte),
|
||||
}
|
||||
}
|
||||
|
||||
case 'create_file': {
|
||||
const parent = args.parent
|
||||
const s3Key = args.s3Key as string
|
||||
const name = args.name as string
|
||||
const fileSize = args.size as number
|
||||
const mimeType = args.contentType as string
|
||||
const metadata =
|
||||
typeof args.metadata === 'object' && args.metadata !== null
|
||||
? (args.metadata as Record<string, unknown>)
|
||||
: undefined
|
||||
if (!parent || !s3Key || !name || fileSize === undefined || !mimeType) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent, s3Key, name, size, and contentType parameters are required',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Authz check
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: parent,
|
||||
})
|
||||
|
||||
// Fetch parent folder to resolve projectId and teamId
|
||||
const parentAsset = await prisma.asset.findUnique({
|
||||
where: { id: parent },
|
||||
include: { project: true },
|
||||
})
|
||||
if (!parentAsset) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Parent folder not found with ID: ${parent}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
if (!parentAsset.projectId || !parentAsset.project?.teamId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Parent folder ${parent} has no project or team associated`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Validate that any provided metadata keys are defined CREATION_CONTEXT fields
|
||||
await validateCreationContextMetadata(userId, parentAsset.projectId, metadata)
|
||||
|
||||
// Create asset via assetService
|
||||
const newFile = await assetService.createAsset({
|
||||
name,
|
||||
type: 'file',
|
||||
parentId: parent,
|
||||
key: s3Key,
|
||||
sizeByte: fileSize,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
// Increment update ancestor size
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await assetService.updateAncestorsSize(tx as any, parent, fileSize)
|
||||
|
||||
// Persist creation context metadata provided by the agent
|
||||
if (metadata) {
|
||||
const metadataUpdates = Object.entries(metadata)
|
||||
.filter(([, value]) => value !== null)
|
||||
.map(([key, value]) => ({ key, value }))
|
||||
if (metadataUpdates.length > 0) {
|
||||
await metadataService.updateAssetMetadataInTx(tx, newFile.id, metadataUpdates)
|
||||
}
|
||||
}
|
||||
|
||||
// Trigger post-upload transcode and AI workflows
|
||||
await uploadService.triggerPostUploadWorkflows(
|
||||
tx,
|
||||
newFile.id,
|
||||
parentAsset.project!.teamId,
|
||||
parentAsset.projectId!,
|
||||
)
|
||||
})
|
||||
|
||||
return {
|
||||
id: newFile.id,
|
||||
name: newFile.name,
|
||||
type: newFile.type,
|
||||
size: Number(newFile.sizeByte),
|
||||
}
|
||||
}
|
||||
|
||||
case 'create_version': {
|
||||
const parent = args.parent // parent file id
|
||||
const s3Key = args.s3Key as string
|
||||
const name = args.name as string
|
||||
const fileSize = args.size as number
|
||||
const mimeType = args.contentType as string
|
||||
const metadata =
|
||||
typeof args.metadata === 'object' && args.metadata !== null
|
||||
? (args.metadata as Record<string, unknown>)
|
||||
: undefined
|
||||
if (!parent || !s3Key || !name || fileSize === undefined || !mimeType) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'parent, s3Key, name, size, and contentType parameters are required',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Fetch parent file and cast to any due to Prisma type resolution limits
|
||||
/* prettier-ignore */
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const parentFile = (await prisma.asset.findUnique({ where: { id: parent }, include: { parent: true, project: true } })) as any
|
||||
if (!parentFile) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Parent file not found with ID: ${parent}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
if (!parentFile.projectId || !parentFile.project?.teamId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Parent file ${parent} has no project or team associated`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Validate that any provided metadata keys are defined CREATION_CONTEXT fields
|
||||
await validateCreationContextMetadata(userId, parentFile.projectId, metadata)
|
||||
|
||||
// Authz check: verify Edit permission on the parent file (resource ID is parent file id)
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: parent,
|
||||
})
|
||||
|
||||
// If already in a version stack
|
||||
if (parentFile.parentId && parentFile.parent?.type === AssetType.version_stack) {
|
||||
const stackId = parentFile.parentId
|
||||
|
||||
// Create the new file asset
|
||||
const newFile = await assetService.createAsset({
|
||||
name,
|
||||
type: 'file',
|
||||
parentId: stackId,
|
||||
key: s3Key,
|
||||
sizeByte: fileSize,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
// Generate sort index for new version inside the stack (newest gets the lowest sortIndex)
|
||||
const firstChild = await prisma.asset.findFirst({
|
||||
where: {
|
||||
parentId: stackId,
|
||||
NOT: { id: newFile.id },
|
||||
},
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
})
|
||||
const newSortIndex = generateKeyBetween(null, firstChild?.sortIndex || null)
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// Assign sort index
|
||||
await tx.asset.update({
|
||||
where: { id: newFile.id },
|
||||
data: { sortIndex: newSortIndex },
|
||||
})
|
||||
// Persist creation context metadata provided by the agent
|
||||
if (metadata) {
|
||||
const metadataUpdates = Object.entries(metadata)
|
||||
.filter(([, value]) => value !== null)
|
||||
.map(([key, value]) => ({ key, value }))
|
||||
if (metadataUpdates.length > 0) {
|
||||
await metadataService.updateAssetMetadataInTx(tx, newFile.id, metadataUpdates)
|
||||
}
|
||||
}
|
||||
// Increment stack's size (fileCount is incremented by createAsset already)
|
||||
const updatedStack = await tx.asset.update({
|
||||
where: { id: stackId },
|
||||
data: {
|
||||
sizeByte: { increment: fileSize },
|
||||
},
|
||||
})
|
||||
// Update ancestors' size of stack's parent
|
||||
if (updatedStack.parentId) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await assetService.updateAncestorsSize(tx as any, updatedStack.parentId, fileSize)
|
||||
}
|
||||
|
||||
// Trigger post-upload transcode and AI workflows
|
||||
await uploadService.triggerPostUploadWorkflows(
|
||||
tx,
|
||||
newFile.id,
|
||||
parentFile.project.teamId,
|
||||
parentFile.projectId,
|
||||
)
|
||||
})
|
||||
|
||||
return {
|
||||
id: newFile.id,
|
||||
name: newFile.name,
|
||||
type: newFile.type,
|
||||
size: Number(newFile.sizeByte),
|
||||
}
|
||||
} else {
|
||||
// Parent is a regular file. We must create a new version stack.
|
||||
const folderParentId = parentFile.parentId
|
||||
if (!folderParentId) {
|
||||
throw ApplicationFailure.create({
|
||||
message: `Parent file ${parent} has no parent folder`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
// Create the new file asset under parent folder first (so that createVersionStack can run on them,
|
||||
// which enforces both files must have same parent initially)
|
||||
const newFile = await assetService.createAsset({
|
||||
name,
|
||||
type: 'file',
|
||||
parentId: folderParentId,
|
||||
key: s3Key,
|
||||
sizeByte: fileSize,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const txVersionStackService = new VersionStackService(tx as any)
|
||||
await txVersionStackService.createVersionStack({
|
||||
fileIds: [newFile.id, parentFile.id],
|
||||
projectId: parentFile.projectId!,
|
||||
creatorId: userId,
|
||||
})
|
||||
// Persist creation context metadata provided by the agent
|
||||
if (metadata) {
|
||||
const metadataUpdates = Object.entries(metadata)
|
||||
.filter(([, value]) => value !== null)
|
||||
.map(([key, value]) => ({ key, value }))
|
||||
if (metadataUpdates.length > 0) {
|
||||
await metadataService.updateAssetMetadataInTx(tx, newFile.id, metadataUpdates)
|
||||
}
|
||||
}
|
||||
// Update ancestors' size (add size of the new file version)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
await assetService.updateAncestorsSize(tx as any, folderParentId!, fileSize)
|
||||
|
||||
// Trigger post-upload transcode and AI workflows
|
||||
await uploadService.triggerPostUploadWorkflows(
|
||||
tx,
|
||||
newFile.id,
|
||||
parentFile.project.teamId,
|
||||
parentFile.projectId!,
|
||||
)
|
||||
})
|
||||
|
||||
return {
|
||||
id: newFile.id,
|
||||
name: newFile.name,
|
||||
type: newFile.type,
|
||||
size: Number(newFile.sizeByte),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
throw ApplicationFailure.create({
|
||||
message: `Unsupported tool name: ${toolName}`,
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export interface GenerateSessionNameParams {
|
||||
teamId: string
|
||||
agentId: string
|
||||
|
||||
@@ -613,7 +613,6 @@ import * as aiActivities from './activities/ai'
|
||||
import { agentAutofillMedia } from './workflows/agent-autofill'
|
||||
import { agentChat } from './workflows/agent-chat'
|
||||
import { agentEmbeddingMedia } from './workflows/agent-embedding'
|
||||
import { agentToolCall } from './workflows/agent-tool-call'
|
||||
import { queryEmbeddingForSearch } from './workflows/query-embedding-for-search'
|
||||
|
||||
export function initAgentWorkflows() {
|
||||
@@ -621,7 +620,6 @@ export function initAgentWorkflows() {
|
||||
registerWorkflow(WorkflowTaskType.query_embedding_for_search, queryEmbeddingForSearch)
|
||||
registerWorkflow(WorkflowTaskType.ai_metadata_autofill, agentAutofillMedia)
|
||||
registerWorkflow(WorkflowTaskType.chat, agentChat)
|
||||
registerWorkflow(WorkflowTaskType.agent_tool_call, agentToolCall)
|
||||
|
||||
registerActivities(agentActivities)
|
||||
registerActivities(aiActivities)
|
||||
@@ -643,5 +641,4 @@ export * from './database-session-storage'
|
||||
export * from './workflows/agent-autofill'
|
||||
export * from './workflows/agent-chat'
|
||||
export * from './workflows/agent-embedding'
|
||||
export * from './workflows/agent-tool-call'
|
||||
export * from './workflows/query-embedding-for-search'
|
||||
|
||||
@@ -3,7 +3,8 @@ import { validateToolArguments } from '@earendil-works/pi-ai'
|
||||
import { createCreateFileTool } from './tools/create-file'
|
||||
import { fieldsToTypeBoxSchema } from './index'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { executeAgentToolWorkflow } from './tools/utils'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
s3Service: {
|
||||
@@ -12,8 +13,20 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./tools/utils', () => ({
|
||||
executeAgentToolWorkflow: vi.fn().mockResolvedValue({ id: 'file-1', name: 'test', type: 'file' }),
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: { Edit: 'edit', Read: 'read' },
|
||||
ResourceType: { Asset: 'asset' },
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/asset/asset', () => ({
|
||||
assetService: {
|
||||
createFile: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ id: 'file-1', name: 'test', type: 'file', sizeByte: 100 }),
|
||||
},
|
||||
}))
|
||||
|
||||
/**
|
||||
@@ -63,9 +76,10 @@ describe('reproduce null coercion in harness tool validation', () => {
|
||||
|
||||
// execute must accept the valid call (data-only) without throwing
|
||||
const result = await tool.execute('call-1', validated as never)
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file' })
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file', size: 100 })
|
||||
expect(s3Service.putObject).toHaveBeenCalledTimes(1)
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledTimes(1)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledTimes(1)
|
||||
expect(assetService.createFile).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps null metadata values (the "unknown" sentinel) through validation', () => {
|
||||
|
||||
@@ -2,7 +2,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { createCreateFileTool } from './create-file'
|
||||
import { fieldsToTypeBoxSchema } from '../index'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import { Value } from 'typebox/value'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
@@ -15,8 +16,20 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./utils', () => ({
|
||||
executeAgentToolWorkflow: vi.fn().mockResolvedValue({ id: 'file-1', name: 'test', type: 'file' }),
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: { Edit: 'edit', Read: 'read' },
|
||||
ResourceType: { Asset: 'asset' },
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/asset/asset', () => ({
|
||||
assetService: {
|
||||
createFile: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ id: 'file-1', name: 'test', type: 'file', sizeByte: 100 }),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('createCreateFileTool', () => {
|
||||
@@ -56,23 +69,27 @@ describe('createCreateFileTool', () => {
|
||||
expect(s3Key).toMatch(/^files\/.+\.md$/)
|
||||
expect(uploadArgs[2]).toBe('text/markdown')
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith({
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: 'folder-1',
|
||||
s3Key,
|
||||
name: 'create-file-test.md',
|
||||
size: Buffer.byteLength('# Hello from disk', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
},
|
||||
userId: 'user-1',
|
||||
assetId: 'folder-1',
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'edit',
|
||||
type: 'asset',
|
||||
id: 'folder-1',
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file' })
|
||||
expect(assetService.createFile).toHaveBeenCalledWith({
|
||||
parentId: 'folder-1',
|
||||
name: 'create-file-test.md',
|
||||
key: s3Key,
|
||||
sizeByte: Buffer.byteLength('# Hello from disk', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
metadata: undefined,
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file', size: 100 })
|
||||
})
|
||||
|
||||
it('should forward the metadata to the agent tool workflow when provided', async () => {
|
||||
it('should forward the metadata to assetService.createFile when provided', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
@@ -86,9 +103,9 @@ describe('createCreateFileTool', () => {
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({ metadata: { prompt: 'Generated using gemini' } }),
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -125,19 +142,17 @@ describe('createCreateFileTool', () => {
|
||||
},
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not include metadata in args when metadata is null', async () => {
|
||||
it('should not include metadata when metadata is null', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-file-no-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
@@ -151,8 +166,8 @@ describe('createCreateFileTool', () => {
|
||||
metadata: null,
|
||||
})
|
||||
|
||||
const callArgs = vi.mocked(executeAgentToolWorkflow).mock.calls[0][0].args
|
||||
expect(callArgs).not.toHaveProperty('metadata')
|
||||
const callArgs = vi.mocked(assetService.createFile).mock.calls[0][0]
|
||||
expect(callArgs.metadata).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should throw when the local file does not exist', async () => {
|
||||
@@ -161,7 +176,7 @@ describe('createCreateFileTool', () => {
|
||||
tool.execute('call-1', { parent: 'folder-1', path: '/nonexistent/file.md', data: null }),
|
||||
).rejects.toThrow('Local file not found at path: /nonexistent/file.md')
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(executeAgentToolWorkflow).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should create a file directly from name and content', async () => {
|
||||
@@ -184,20 +199,17 @@ describe('createCreateFileTool', () => {
|
||||
expect(size).toBe(Buffer.byteLength('# Notes\n\nHello', 'utf-8'))
|
||||
expect(contentType).toBe('text/markdown')
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith({
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: 'folder-1',
|
||||
s3Key,
|
||||
name: 'notes.md',
|
||||
size: Buffer.byteLength('# Notes\n\nHello', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
},
|
||||
userId: 'user-1',
|
||||
assetId: 'folder-1',
|
||||
expect(assetService.createFile).toHaveBeenCalledWith({
|
||||
parentId: 'folder-1',
|
||||
name: 'notes.md',
|
||||
key: s3Key,
|
||||
sizeByte: Buffer.byteLength('# Notes\n\nHello', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
metadata: undefined,
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file' })
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'test', type: 'file', size: 100 })
|
||||
})
|
||||
|
||||
it('should default unknown extensions to text/plain when creating from content', async () => {
|
||||
@@ -235,10 +247,8 @@ describe('createCreateFileTool', () => {
|
||||
]
|
||||
expect(s3Key).toContain('my_notes.md')
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({ name: 'my_notes.md' }),
|
||||
}),
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ name: 'my_notes.md' }),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -260,7 +270,7 @@ describe('createCreateFileTool', () => {
|
||||
).rejects.toThrow('Provide exactly one of "path" (a local file) or "data" (name and content).')
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(executeAgentToolWorkflow).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should expose a strict, all-required (nullable) metadata schema when fields are provided', () => {
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import { type User } from '@shumai/db'
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { ulid } from 'ulid'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
|
||||
interface CreateFileToolParams {
|
||||
parent: string
|
||||
@@ -105,19 +107,30 @@ export function createCreateFileTool(userId: string, metadataSchema?: TSchema):
|
||||
await s3Service.putObject(process.env.S3_BUCKET || 'shumai', s3Key, content, size, mimeType)
|
||||
}
|
||||
|
||||
const result = await executeAgentToolWorkflow({
|
||||
toolName: 'create_file',
|
||||
args: {
|
||||
parent: p.parent,
|
||||
s3Key,
|
||||
name,
|
||||
size,
|
||||
contentType: mimeType,
|
||||
...(p.metadata ? { metadata: p.metadata } : {}),
|
||||
},
|
||||
userId,
|
||||
assetId: p.parent,
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: p.parent,
|
||||
})
|
||||
|
||||
const asset = await assetService.createFile({
|
||||
parentId: p.parent,
|
||||
name,
|
||||
key: s3Key,
|
||||
sizeByte: size,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
metadata: p.metadata ?? undefined,
|
||||
})
|
||||
|
||||
const result = {
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
type: asset.type,
|
||||
size: Number(asset.sizeByte),
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
details: result,
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createCreateFolderTool } from './create-folder'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: { Edit: 'edit', Read: 'read' },
|
||||
ResourceType: { Asset: 'asset' },
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/asset/asset', () => ({
|
||||
assetService: {
|
||||
createAsset: vi.fn().mockResolvedValue({
|
||||
id: 'folder-1',
|
||||
name: 'New Folder',
|
||||
type: 'folder',
|
||||
sizeByte: 0,
|
||||
}),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('createCreateFolderTool', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('checks edit permission and calls assetService.createAsset with folder type', async () => {
|
||||
const tool = createCreateFolderTool('user-1')
|
||||
const result = await tool.execute('call-1', { parent: 'root-folder', name: 'New Folder' })
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'edit',
|
||||
type: 'asset',
|
||||
id: 'root-folder',
|
||||
})
|
||||
|
||||
expect(assetService.createAsset).toHaveBeenCalledWith({
|
||||
name: 'New Folder',
|
||||
parentId: 'root-folder',
|
||||
type: 'folder',
|
||||
creatorId: 'user-1',
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({
|
||||
id: 'folder-1',
|
||||
name: 'New Folder',
|
||||
type: 'folder',
|
||||
size: 0,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,8 @@
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { type User } from '@shumai/db'
|
||||
|
||||
const createFolderSchema = Type.Object({
|
||||
parent: Type.String({
|
||||
@@ -19,12 +21,27 @@ export function createCreateFolderTool(userId: string): AgentTool<typeof createF
|
||||
description: 'Create a new folder in a specified parent folder.',
|
||||
parameters: createFolderSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
const result = await executeAgentToolWorkflow({
|
||||
toolName: 'create_folder',
|
||||
args: params,
|
||||
userId,
|
||||
assetId: params.parent,
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: params.parent,
|
||||
})
|
||||
|
||||
const newFolder = await assetService.createAsset({
|
||||
name: params.name,
|
||||
parentId: params.parent,
|
||||
type: 'folder',
|
||||
creatorId: userId,
|
||||
})
|
||||
|
||||
const result = {
|
||||
id: newFolder.id,
|
||||
name: newFolder.name,
|
||||
type: newFolder.type,
|
||||
size: Number(newFolder.sizeByte),
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
details: result,
|
||||
|
||||
@@ -2,7 +2,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { createCreateVersionTool } from './create-version'
|
||||
import { fieldsToTypeBoxSchema } from '../index'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import { Value } from 'typebox/value'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
@@ -14,8 +15,20 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('./utils', () => ({
|
||||
executeAgentToolWorkflow: vi.fn().mockResolvedValue({ id: 'file-1', name: 'v2', type: 'file' }),
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: { Edit: 'edit', Read: 'read' },
|
||||
ResourceType: { Asset: 'asset' },
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/asset/asset', () => ({
|
||||
assetService: {
|
||||
createVersion: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ id: 'file-1', name: 'v2', type: 'file', sizeByte: 100 }),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('createCreateVersionTool', () => {
|
||||
@@ -41,7 +54,7 @@ describe('createCreateVersionTool', () => {
|
||||
return filePath
|
||||
}
|
||||
|
||||
it('should upload a local file and create a version via the agent tool workflow', async () => {
|
||||
it('should upload a local file and create a version via assetService.createVersion', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-test.md')
|
||||
|
||||
const tool = createCreateVersionTool('user-1')
|
||||
@@ -53,23 +66,27 @@ describe('createCreateVersionTool', () => {
|
||||
expect(s3Key).toMatch(/^files\/.+\.md$/)
|
||||
expect(uploadArgs[2]).toBe('text/markdown')
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith({
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: 'file-1',
|
||||
s3Key,
|
||||
name: 'create-version-test.md',
|
||||
size: Buffer.byteLength('# Hello from disk', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
},
|
||||
userId: 'user-1',
|
||||
assetId: 'file-1',
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'edit',
|
||||
type: 'asset',
|
||||
id: 'file-1',
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'v2', type: 'file' })
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith({
|
||||
parentId: 'file-1',
|
||||
name: 'create-version-test.md',
|
||||
key: s3Key,
|
||||
sizeByte: Buffer.byteLength('# Hello from disk', 'utf-8'),
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
metadata: undefined,
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({ id: 'file-1', name: 'v2', type: 'file', size: 100 })
|
||||
})
|
||||
|
||||
it('should forward the metadata to the agent tool workflow when provided', async () => {
|
||||
it('should forward the metadata to assetService.createVersion when provided', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
@@ -82,9 +99,9 @@ describe('createCreateVersionTool', () => {
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({ metadata: { prompt: 'Generated using gemini' } }),
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
}),
|
||||
)
|
||||
})
|
||||
@@ -120,19 +137,17 @@ describe('createCreateVersionTool', () => {
|
||||
},
|
||||
})
|
||||
|
||||
expect(executeAgentToolWorkflow).toHaveBeenCalledWith(
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
args: expect.objectContaining({
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
metadata: {
|
||||
provider: { newOption: { value: 'Kling' } },
|
||||
tags: ['tag1', { newOption: { value: 'Tag 2' } }],
|
||||
},
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should not include metadata in args when metadata is null', async () => {
|
||||
it('should not include metadata when metadata is null', async () => {
|
||||
const filePath = createTempFile('# Hello from disk', 'create-version-no-metadata.md')
|
||||
const metadataSchema = fieldsToTypeBoxSchema([
|
||||
{ id: 'prompt', config: { name: 'Prompt', type: 'text' } },
|
||||
@@ -141,8 +156,8 @@ describe('createCreateVersionTool', () => {
|
||||
const tool = createCreateVersionTool('user-1', metadataSchema)
|
||||
await tool.execute('call-1', { parent: 'file-1', path: filePath, metadata: null })
|
||||
|
||||
const callArgs = vi.mocked(executeAgentToolWorkflow).mock.calls[0][0].args
|
||||
expect(callArgs).not.toHaveProperty('metadata')
|
||||
const callArgs = vi.mocked(assetService.createVersion).mock.calls[0][0]
|
||||
expect(callArgs.metadata).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should throw when the local file does not exist', async () => {
|
||||
@@ -151,7 +166,7 @@ describe('createCreateVersionTool', () => {
|
||||
tool.execute('call-1', { parent: 'file-1', path: '/nonexistent/file.md' }),
|
||||
).rejects.toThrow('Local file not found at path: /nonexistent/file.md')
|
||||
expect(s3Service.uploadFileToKey).not.toHaveBeenCalled()
|
||||
expect(executeAgentToolWorkflow).not.toHaveBeenCalled()
|
||||
expect(assetService.createVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should expose a strict, all-required (nullable) metadata schema when fields are provided', () => {
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { ulid } from 'ulid'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import { type User } from '@shumai/db'
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { ulid } from 'ulid'
|
||||
|
||||
interface CreateVersionToolParams {
|
||||
parent: string
|
||||
@@ -48,24 +50,36 @@ export function createCreateVersionTool(userId: string, metadataSchema?: TSchema
|
||||
|
||||
const fileSize = fs.statSync(absolutePath).size
|
||||
const mimeType = readFileMimeType(absolutePath)
|
||||
const name = path.basename(absolutePath)
|
||||
|
||||
// Generate compliant S3 key matching normal file upload format
|
||||
const s3Key = `files/${ulid()}/${sanitizeFilename(path.basename(absolutePath))}`
|
||||
const s3Key = `files/${ulid()}/${sanitizeFilename(name)}`
|
||||
await s3Service.uploadFileToKey(absolutePath, s3Key, mimeType)
|
||||
|
||||
const result = await executeAgentToolWorkflow({
|
||||
toolName: 'create_version',
|
||||
args: {
|
||||
parent: p.parent,
|
||||
s3Key,
|
||||
name: path.basename(absolutePath),
|
||||
size: fileSize,
|
||||
contentType: mimeType,
|
||||
...(p.metadata ? { metadata: p.metadata } : {}),
|
||||
},
|
||||
userId,
|
||||
assetId: p.parent,
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id: p.parent,
|
||||
})
|
||||
|
||||
const asset = await assetService.createVersion({
|
||||
parentId: p.parent,
|
||||
name,
|
||||
key: s3Key,
|
||||
sizeByte: fileSize,
|
||||
contentType: mimeType,
|
||||
creatorId: userId,
|
||||
metadata: p.metadata ?? undefined,
|
||||
})
|
||||
|
||||
const result = {
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
type: asset.type,
|
||||
size: Number(asset.sizeByte),
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
details: result,
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createListAssetsTool } from './list-assets'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', () => ({
|
||||
authzService: {
|
||||
hasPermission: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
Permission: { Edit: 'edit', Read: 'read' },
|
||||
ResourceType: { Asset: 'asset' },
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/asset/asset', () => ({
|
||||
assetService: {
|
||||
listChildren: vi.fn().mockResolvedValue({
|
||||
data: [
|
||||
{ id: '01M2FILE2', name: 'file2.txt', type: 'file', sizeByte: 200 },
|
||||
{ id: '01M1FILE1', name: 'file1.txt', type: 'file', sizeByte: 100 },
|
||||
],
|
||||
pageInfo: { hasNextPage: false, hasPreviousPage: false, cursor: 'abc' },
|
||||
}),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('createListAssetsTool', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('checks read permissions and invokes assetService.listChildren with default all and id desc ordering', async () => {
|
||||
const tool = createListAssetsTool('user-1')
|
||||
const result = await tool.execute('call-1', { parent: 'folder-1' })
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'read',
|
||||
type: 'asset',
|
||||
id: 'folder-1',
|
||||
})
|
||||
|
||||
expect(assetService.listChildren).toHaveBeenCalledWith({
|
||||
assetId: 'folder-1',
|
||||
assetType: 'all',
|
||||
sort: 'createdAt',
|
||||
order: 'desc',
|
||||
first: 20,
|
||||
after: undefined,
|
||||
})
|
||||
|
||||
expect(result.details).toEqual({
|
||||
assets: [
|
||||
{ id: '01M2FILE2', name: 'file2.txt', type: 'file', size: 200 },
|
||||
{ id: '01M1FILE1', name: 'file1.txt', type: 'file', size: 100 },
|
||||
],
|
||||
pageInfo: { hasNextPage: false, hasPreviousPage: false, cursor: 'abc' },
|
||||
})
|
||||
})
|
||||
|
||||
it('passes explicit pagination and type filter options to assetService.listChildren', async () => {
|
||||
const tool = createListAssetsTool('user-1')
|
||||
await tool.execute('call-1', {
|
||||
parent: 'folder-1',
|
||||
page: 2,
|
||||
pageSize: 10,
|
||||
type: 'folder',
|
||||
})
|
||||
|
||||
expect(assetService.listChildren).toHaveBeenCalledWith({
|
||||
assetId: 'folder-1',
|
||||
assetType: 'folder',
|
||||
sort: 'createdAt',
|
||||
order: 'desc',
|
||||
first: 10,
|
||||
after: expect.any(String),
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,9 @@
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { executeAgentToolWorkflow } from './utils'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { encodeCursor } from '@shumai/core/src/pagination'
|
||||
import { type User } from '@shumai/db'
|
||||
|
||||
const listAssetsSchema = Type.Object({
|
||||
parent: Type.String({
|
||||
@@ -19,9 +22,8 @@ const listAssetsSchema = Type.Object({
|
||||
}),
|
||||
),
|
||||
type: Type.Optional(
|
||||
Type.String({
|
||||
Type.Union([Type.Literal('file'), Type.Literal('folder'), Type.Literal('all')], {
|
||||
description: "Filter assets by type: 'file', 'folder', or 'all'. Default is 'all'.",
|
||||
enum: ['file', 'folder', 'all'],
|
||||
default: 'all',
|
||||
}),
|
||||
),
|
||||
@@ -34,15 +36,41 @@ export function createListAssetsTool(userId: string): AgentTool<typeof listAsset
|
||||
description: 'List the assets (files and folders) inside a parent folder with pagination.',
|
||||
parameters: listAssetsSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
const result = await executeAgentToolWorkflow({
|
||||
toolName: 'list_assets',
|
||||
args: params,
|
||||
userId,
|
||||
assetId: params.parent,
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id: params.parent,
|
||||
})
|
||||
|
||||
const page = params.page || 1
|
||||
const pageSize = params.pageSize || 20
|
||||
const type = params.type || 'all'
|
||||
|
||||
const result = await assetService.listChildren({
|
||||
assetId: params.parent,
|
||||
assetType: type,
|
||||
sort: 'createdAt',
|
||||
order: 'desc',
|
||||
first: pageSize,
|
||||
after: page > 1 ? encodeCursor((page - 1) * pageSize) : undefined,
|
||||
})
|
||||
|
||||
const assets = result.data.map((a) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
type: a.type,
|
||||
size: Number(a.sizeByte),
|
||||
}))
|
||||
|
||||
const output = {
|
||||
assets,
|
||||
pageInfo: result.pageInfo,
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
||||
details: result,
|
||||
content: [{ type: 'text', text: JSON.stringify(output, null, 2) }],
|
||||
details: output,
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db'
|
||||
|
||||
export async function executeAgentToolWorkflow(params: {
|
||||
toolName: string
|
||||
args: Record<string, unknown>
|
||||
userId: string
|
||||
assetId: string
|
||||
}): Promise<unknown> {
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: WorkflowTaskType.agent_tool_call,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
assetId: params.assetId,
|
||||
payload: {
|
||||
projectId: 'none',
|
||||
agentToolCall: {
|
||||
toolName: params.toolName,
|
||||
args: params.args,
|
||||
userId: params.userId,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const completedTask = await workflowService.executeWait(task)
|
||||
if (completedTask.status === WorkflowTaskStatus.failed) {
|
||||
const output = completedTask.output as Record<string, unknown> | null
|
||||
const errorMsg = (output?.error as string) || 'Workflow task failed'
|
||||
throw new Error(errorMsg)
|
||||
}
|
||||
|
||||
return completedTask.output
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
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' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,60 +0,0 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { getActivities, executeActivity, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
|
||||
export async function agentToolCall(task: WorkflowTask): Promise<void> {
|
||||
const { updateTaskStatusActivity, executeAgentToolActivity, getAgentWorkerQueueActivity } =
|
||||
getActivities()
|
||||
|
||||
let agentWorkerQueue = ''
|
||||
|
||||
try {
|
||||
// 0. Discover queue
|
||||
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
// Update status to processing
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
const payload = task.payload
|
||||
if (!payload || !payload.agentToolCall) {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'Task payload or agentToolCall is missing',
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
|
||||
const { toolName, args, userId } = payload.agentToolCall
|
||||
|
||||
// Execute the agent activity on specific queue
|
||||
const result = await executeActivity(agentWorkerQueue, executeAgentToolActivity, {
|
||||
taskId: task.id,
|
||||
toolName,
|
||||
args,
|
||||
userId,
|
||||
})
|
||||
|
||||
// Update status to completed with output
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: result,
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AgentToolCall failed for task ${task.id}:`, err)
|
||||
|
||||
// Update status to failed
|
||||
if (agentWorkerQueue) {
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export const agentToolCallWorkflow = agentToolCall
|
||||
@@ -4,7 +4,7 @@ import { zValidator } from '@hono/zod-validator'
|
||||
import { shareService } from '@shumai/core/src/share/share'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { watermarkService } from '@shumai/core/src/watermark/watermark'
|
||||
import { paginationParamsSchema } from '@shumai/dtos'
|
||||
import { paginationParamsSchema, assetTypeFilterSchema } from '@shumai/dtos'
|
||||
import { z } from 'zod'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { FieldInfo } from '@shumai/dtos'
|
||||
@@ -117,7 +117,7 @@ export function handlePublicShareError(c: Context, err: unknown) {
|
||||
}
|
||||
|
||||
const sharedChildrenRequestSchema = paginationParamsSchema.extend({
|
||||
assetType: z.string().optional(),
|
||||
assetType: assetTypeFilterSchema.optional().default('file'),
|
||||
})
|
||||
|
||||
const route = app
|
||||
|
||||
@@ -5,6 +5,8 @@ import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
import { AssetType, AssetStatus, Prisma } from '@shumai/db'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { AssetService } from './asset'
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3', () => ({
|
||||
@@ -3704,4 +3706,408 @@ describe('AssetService — natural sort by name', () => {
|
||||
expect(purgedSymlink).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('createFile', () => {
|
||||
it('creates a file, updates ancestor sizes, persists metadata, and triggers workflows', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'FileUser', email: `fileuser-${Date.now()}@example.com` },
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 'FileTeam' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'FileProject', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'RootFolder',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
const promptField = await metadataService.createProjectField(project.id, {
|
||||
description: 'Prompt field',
|
||||
config: {
|
||||
name: 'Prompt',
|
||||
type: 'text',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
},
|
||||
})
|
||||
|
||||
const triggerSpy = vi
|
||||
.spyOn(uploadService, 'triggerPostUploadWorkflows')
|
||||
.mockResolvedValue(undefined)
|
||||
|
||||
const fileInfo = await assetService.createFile({
|
||||
parentId: rootFolder.id,
|
||||
name: 'document.txt',
|
||||
key: 'files/test/doc.txt',
|
||||
sizeByte: 1024,
|
||||
contentType: 'text/plain',
|
||||
creatorId: user.id,
|
||||
metadata: { [promptField.key]: 'Project overview document' },
|
||||
})
|
||||
|
||||
expect(fileInfo.id).toBeDefined()
|
||||
expect(fileInfo.name).toBe('document.txt')
|
||||
expect(fileInfo.type).toBe(AssetType.file)
|
||||
expect(fileInfo.sizeByte).toBe(1024)
|
||||
|
||||
const folderAfter = await prisma.asset.findUnique({ where: { id: rootFolder.id } })
|
||||
expect(folderAfter?.sizeByte).toBe(1024n)
|
||||
expect(folderAfter?.fileCount).toBe(1)
|
||||
|
||||
const metaVal = await prisma.assetMetadataValue.findFirst({
|
||||
where: { assetId: fileInfo.id, fieldKey: promptField.key },
|
||||
})
|
||||
expect(metaVal?.stringValue).toBe('Project overview document')
|
||||
|
||||
expect(triggerSpy).toHaveBeenCalledWith(expect.anything(), fileInfo.id, team.id, project.id)
|
||||
})
|
||||
|
||||
it('rejects if metadata contains invalid keys', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'FileUser2', email: `fileuser2-${Date.now()}@example.com` },
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 'FileTeam2' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'FileProject2', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'RootFolder2',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
await expect(
|
||||
assetService.createFile({
|
||||
parentId: rootFolder.id,
|
||||
name: 'invalid.txt',
|
||||
key: 'files/test/inv.txt',
|
||||
sizeByte: 100,
|
||||
contentType: 'text/plain',
|
||||
creatorId: user.id,
|
||||
metadata: { unknownField: 'val' },
|
||||
}),
|
||||
).rejects.toThrow(/metadata contains keys that are not valid in this project/)
|
||||
})
|
||||
|
||||
it('rolls back completely if post-upload workflow fails in transaction', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'FileRollbackUser', email: `filerollback-${Date.now()}@example.com` },
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 'FileRollbackTeam' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'FileRollbackProject', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'RootFolder',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
sizeByte: 0n,
|
||||
fileCount: 0,
|
||||
},
|
||||
})
|
||||
|
||||
vi.spyOn(uploadService, 'triggerPostUploadWorkflows').mockRejectedValueOnce(
|
||||
new Error('Simulated workflow failure'),
|
||||
)
|
||||
|
||||
await expect(
|
||||
assetService.createFile({
|
||||
parentId: rootFolder.id,
|
||||
name: 'should_rollback.txt',
|
||||
key: 'files/test/should_rollback.txt',
|
||||
sizeByte: 1024,
|
||||
contentType: 'text/plain',
|
||||
creatorId: user.id,
|
||||
}),
|
||||
).rejects.toThrow('Simulated workflow failure')
|
||||
|
||||
// Assert no asset was created
|
||||
const created = await prisma.asset.findFirst({
|
||||
where: { name: 'should_rollback.txt', projectId: project.id },
|
||||
})
|
||||
expect(created).toBeNull()
|
||||
|
||||
// Assert parent folder counters remained untouched
|
||||
const folderAfter = await prisma.asset.findUnique({ where: { id: rootFolder.id } })
|
||||
expect(folderAfter?.fileCount).toBe(0)
|
||||
expect(folderAfter?.sizeByte).toBe(0n)
|
||||
})
|
||||
})
|
||||
|
||||
describe('createVersion', () => {
|
||||
it('creates a version stack when target is a regular file', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'VersionUser', email: `veruser-${Date.now()}@example.com` },
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 'VersionTeam' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'VersionProject', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'RootFolder',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
const v1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'image.png',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
status: AssetStatus.uploaded,
|
||||
sizeByte: 2000n,
|
||||
},
|
||||
})
|
||||
|
||||
const triggerSpy = vi
|
||||
.spyOn(uploadService, 'triggerPostUploadWorkflows')
|
||||
.mockResolvedValue(undefined)
|
||||
|
||||
const v2Info = await assetService.createVersion({
|
||||
parentId: v1.id,
|
||||
name: 'image.png',
|
||||
key: 'files/test/v2.png',
|
||||
sizeByte: 3000,
|
||||
contentType: 'image/png',
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
expect(v2Info.id).toBeDefined()
|
||||
|
||||
const v2Record = await prisma.asset.findUnique({
|
||||
where: { id: v2Info.id },
|
||||
include: { parent: true },
|
||||
})
|
||||
expect(v2Record?.parent?.type).toBe(AssetType.version_stack)
|
||||
expect(v2Record?.parent?.parentId).toBe(rootFolder.id)
|
||||
|
||||
const v1Record = await prisma.asset.findUnique({ where: { id: v1.id } })
|
||||
expect(v1Record?.parentId).toBe(v2Record?.parentId)
|
||||
|
||||
const stackRecord = await prisma.asset.findUnique({ where: { id: v2Record!.parentId! } })
|
||||
expect(stackRecord?.fileCount).toBe(2)
|
||||
expect(stackRecord?.sizeByte).toBe(5000n)
|
||||
|
||||
expect(triggerSpy).toHaveBeenCalledWith(expect.anything(), v2Info.id, team.id, project.id)
|
||||
})
|
||||
|
||||
it('appends a new version when target is in an existing version stack', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'VersionUser2', email: `veruser2-${Date.now()}@example.com` },
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 'VersionTeam2' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'VersionProject2', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'RootFolder',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'image.png',
|
||||
type: AssetType.version_stack,
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
status: AssetStatus.uploaded,
|
||||
sizeByte: 2000n,
|
||||
fileCount: 1,
|
||||
},
|
||||
})
|
||||
|
||||
const v1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'image.png',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
parentId: stack.id,
|
||||
status: AssetStatus.uploaded,
|
||||
sortIndex: 'a0',
|
||||
sizeByte: 2000n,
|
||||
},
|
||||
})
|
||||
|
||||
const triggerSpy = vi
|
||||
.spyOn(uploadService, 'triggerPostUploadWorkflows')
|
||||
.mockResolvedValue(undefined)
|
||||
|
||||
const v2Info = await assetService.createVersion({
|
||||
parentId: v1.id,
|
||||
name: 'image_v2.png',
|
||||
key: 'files/test/v2.png',
|
||||
sizeByte: 3000,
|
||||
contentType: 'image/png',
|
||||
creatorId: user.id,
|
||||
})
|
||||
|
||||
expect(v2Info.id).toBeDefined()
|
||||
|
||||
const v2Record = await prisma.asset.findUnique({ where: { id: v2Info.id } })
|
||||
expect(v2Record?.parentId).toBe(stack.id)
|
||||
|
||||
const stackAfter = await prisma.asset.findUnique({ where: { id: stack.id } })
|
||||
expect(stackAfter?.fileCount).toBe(2)
|
||||
expect(stackAfter?.sizeByte).toBe(5000n)
|
||||
|
||||
expect(triggerSpy).toHaveBeenCalledWith(expect.anything(), v2Info.id, team.id, project.id)
|
||||
})
|
||||
|
||||
it('rolls back completely if workflow triggering fails in createVersion', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'VersionRollbackUser', email: `verrollback-${Date.now()}@example.com` },
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 'VersionRollbackTeam' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'VersionRollbackProject', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'RootFolder',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
sizeByte: 2000n,
|
||||
fileCount: 1,
|
||||
},
|
||||
})
|
||||
|
||||
const v1 = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'image.png',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
status: AssetStatus.uploaded,
|
||||
sizeByte: 2000n,
|
||||
},
|
||||
})
|
||||
|
||||
vi.spyOn(uploadService, 'triggerPostUploadWorkflows').mockRejectedValueOnce(
|
||||
new Error('Simulated version workflow failure'),
|
||||
)
|
||||
|
||||
await expect(
|
||||
assetService.createVersion({
|
||||
parentId: v1.id,
|
||||
name: 'image_v2_fail.png',
|
||||
key: 'files/test/v2_fail.png',
|
||||
sizeByte: 3000,
|
||||
contentType: 'image/png',
|
||||
creatorId: user.id,
|
||||
}),
|
||||
).rejects.toThrow('Simulated version workflow failure')
|
||||
|
||||
// Check that new version was rolled back
|
||||
const createdV2 = await prisma.asset.findFirst({
|
||||
where: { name: 'image_v2_fail.png', projectId: project.id },
|
||||
})
|
||||
expect(createdV2).toBeNull()
|
||||
|
||||
// Check that v1 remains under rootFolder (no orphaned version stack created)
|
||||
const v1After = await prisma.asset.findUnique({ where: { id: v1.id } })
|
||||
expect(v1After?.parentId).toBe(rootFolder.id)
|
||||
|
||||
// Check root folder counters remained unchanged
|
||||
const rootFolderAfter = await prisma.asset.findUnique({ where: { id: rootFolder.id } })
|
||||
expect(rootFolderAfter?.fileCount).toBe(1)
|
||||
expect(rootFolderAfter?.sizeByte).toBe(2000n)
|
||||
})
|
||||
})
|
||||
|
||||
describe('listChildren type filtering', () => {
|
||||
it('returns files, folders, and version stacks when assetType is all or omitted', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'ListTypeTeam' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'ListTypeProject', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'RootFolder',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
const subFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'subfolder',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
const file = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'file.txt',
|
||||
type: AssetType.file,
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
const stack = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'stack.png',
|
||||
type: AssetType.version_stack,
|
||||
projectId: project.id,
|
||||
parentId: rootFolder.id,
|
||||
status: AssetStatus.uploaded,
|
||||
},
|
||||
})
|
||||
|
||||
// Query with assetType: 'all'
|
||||
const allRes = await assetService.listChildren({
|
||||
assetId: rootFolder.id,
|
||||
assetType: 'all',
|
||||
})
|
||||
const allIds = allRes.data.map((a) => a.id)
|
||||
expect(allIds).toContain(subFolder.id)
|
||||
expect(allIds).toContain(file.id)
|
||||
expect(allIds).toContain(stack.id)
|
||||
expect(allRes.data.length).toBe(3)
|
||||
|
||||
// Query with assetType: 'file'
|
||||
const fileRes = await assetService.listChildren({
|
||||
assetId: rootFolder.id,
|
||||
assetType: 'file',
|
||||
})
|
||||
const fileIds = fileRes.data.map((a) => a.id)
|
||||
expect(fileIds).toContain(file.id)
|
||||
expect(fileIds).toContain(stack.id)
|
||||
expect(fileIds).not.toContain(subFolder.id)
|
||||
expect(fileRes.data.length).toBe(2)
|
||||
|
||||
// Query with assetType: 'folder'
|
||||
const folderRes = await assetService.listChildren({
|
||||
assetId: rootFolder.id,
|
||||
assetType: 'folder',
|
||||
})
|
||||
const folderIds = folderRes.data.map((a) => a.id)
|
||||
expect(folderIds).toContain(subFolder.id)
|
||||
expect(folderIds).not.toContain(file.id)
|
||||
expect(folderIds).not.toContain(stack.id)
|
||||
expect(folderRes.data.length).toBe(1)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -29,6 +29,8 @@ import { generateKeyBetween } from 'jittered-fractional-indexing'
|
||||
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
|
||||
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
|
||||
import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { uploadService } from '@shumai/core/src/upload/upload'
|
||||
|
||||
export const assetInclude = {
|
||||
creator: true,
|
||||
@@ -614,9 +616,13 @@ export class AssetService {
|
||||
}
|
||||
|
||||
async listChildren(req: ListChildrenRequest): Promise<PaginatedData<AssetInfo[]>> {
|
||||
const typesToQuery: AssetType[] = [req.assetType as AssetType]
|
||||
if (req.assetType === AssetType.file) {
|
||||
typesToQuery.push(AssetType.version_stack)
|
||||
let typesToQuery: AssetType[]
|
||||
if (req.assetType === 'file') {
|
||||
typesToQuery = [AssetType.file, AssetType.version_stack]
|
||||
} else if (req.assetType === 'folder') {
|
||||
typesToQuery = [AssetType.folder]
|
||||
} else {
|
||||
typesToQuery = [AssetType.file, AssetType.folder, AssetType.version_stack]
|
||||
}
|
||||
|
||||
let where: Prisma.AssetWhereInput = {}
|
||||
@@ -721,12 +727,17 @@ export class AssetService {
|
||||
return { data: infos, pageInfo }
|
||||
}
|
||||
|
||||
async createAsset(req: CreateAssetRequest): Promise<AssetInfo> {
|
||||
async createAsset(
|
||||
req: CreateAssetRequest,
|
||||
txClient?: Prisma.TransactionClient,
|
||||
): Promise<AssetInfo> {
|
||||
const db = txClient ?? this.prismaClient
|
||||
|
||||
let projectId = req.projectId
|
||||
let parent: Prisma.AssetGetPayload<{ include: { project: true } }> | null = null
|
||||
|
||||
if (req.parentId) {
|
||||
parent = await this.prismaClient.asset.findUnique({
|
||||
parent = await db.asset.findUnique({
|
||||
where: { id: req.parentId },
|
||||
include: { project: true },
|
||||
})
|
||||
@@ -738,7 +749,7 @@ export class AssetService {
|
||||
|
||||
let sortIndex: string | null = null
|
||||
if (parent) {
|
||||
const firstFile = await this.prismaClient.asset.findFirst({
|
||||
const firstFile = await db.asset.findFirst({
|
||||
where: { parentId: parent.id },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
})
|
||||
@@ -766,7 +777,7 @@ export class AssetService {
|
||||
if (req.contentType) data.mediaType = req.contentType
|
||||
if (req.creatorId) data.creator = { connect: { id: req.creatorId } }
|
||||
|
||||
const asset = await this.prismaClient.$transaction(async (tx) => {
|
||||
const executeInTx = async (tx: Prisma.TransactionClient) => {
|
||||
const createdAsset = await tx.asset.create({
|
||||
data,
|
||||
include: {
|
||||
@@ -803,12 +814,165 @@ export class AssetService {
|
||||
}
|
||||
|
||||
return createdAsset
|
||||
})
|
||||
}
|
||||
|
||||
const asset = txClient
|
||||
? await executeInTx(txClient)
|
||||
: await this.prismaClient.$transaction(executeInTx)
|
||||
|
||||
const infos = await this.toAssetInfos([asset])
|
||||
return infos[0]
|
||||
}
|
||||
|
||||
async createFile(params: {
|
||||
parentId: string
|
||||
name: string
|
||||
key: string
|
||||
sizeByte: number
|
||||
contentType: string
|
||||
creatorId: string
|
||||
metadata?: Record<string, unknown>
|
||||
}): Promise<AssetInfo> {
|
||||
const { parentId, name, key, sizeByte, contentType, creatorId, metadata } = params
|
||||
|
||||
const parentAsset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: parentId },
|
||||
include: { project: true },
|
||||
})
|
||||
if (!parentAsset || !parentAsset.projectId || !parentAsset.project?.teamId) {
|
||||
throw new Error(`Parent folder ${parentId} is invalid or has no project associated`)
|
||||
}
|
||||
|
||||
if (metadata) {
|
||||
await metadataService.validateCreationContextMetadata(
|
||||
creatorId,
|
||||
parentAsset.projectId,
|
||||
metadata,
|
||||
)
|
||||
}
|
||||
|
||||
let newFileId = ''
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
const newFile = await this.createAsset(
|
||||
{
|
||||
name,
|
||||
type: 'file',
|
||||
parentId,
|
||||
key,
|
||||
sizeByte,
|
||||
contentType,
|
||||
creatorId,
|
||||
},
|
||||
tx,
|
||||
)
|
||||
newFileId = newFile.id
|
||||
|
||||
await this.updateAncestorsSize(tx, parentId, sizeByte)
|
||||
if (metadata) {
|
||||
const metadataUpdates = Object.entries(metadata)
|
||||
.filter(([, value]) => value !== null)
|
||||
.map(([k, v]) => ({ key: k, value: v }))
|
||||
if (metadataUpdates.length > 0) {
|
||||
await metadataService.updateAssetMetadataInTx(tx, newFile.id, metadataUpdates)
|
||||
}
|
||||
}
|
||||
await uploadService.triggerPostUploadWorkflows(
|
||||
tx,
|
||||
newFile.id,
|
||||
parentAsset.project!.teamId,
|
||||
parentAsset.projectId!,
|
||||
)
|
||||
})
|
||||
|
||||
return this.getAsset({ assetId: newFileId })
|
||||
}
|
||||
|
||||
async createVersion(params: {
|
||||
parentId: string
|
||||
name: string
|
||||
key: string
|
||||
sizeByte: number
|
||||
contentType: string
|
||||
creatorId: string
|
||||
metadata?: Record<string, unknown>
|
||||
}): Promise<AssetInfo> {
|
||||
const { parentId, name, key, sizeByte, contentType, creatorId, metadata } = params
|
||||
|
||||
const targetAsset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: parentId },
|
||||
include: { project: true, parent: true },
|
||||
})
|
||||
if (!targetAsset || !targetAsset.projectId || !targetAsset.project?.teamId) {
|
||||
throw new Error(`Target file ${parentId} is invalid or has no project associated`)
|
||||
}
|
||||
|
||||
if (metadata) {
|
||||
await metadataService.validateCreationContextMetadata(
|
||||
creatorId,
|
||||
targetAsset.projectId,
|
||||
metadata,
|
||||
)
|
||||
}
|
||||
|
||||
let targetFolderId: string
|
||||
let reparentTargetId: string
|
||||
|
||||
if (targetAsset.type === AssetType.version_stack) {
|
||||
targetFolderId = targetAsset.parentId!
|
||||
reparentTargetId = targetAsset.id
|
||||
} else if (targetAsset.parent?.type === AssetType.version_stack) {
|
||||
targetFolderId = targetAsset.parent.parentId!
|
||||
reparentTargetId = targetAsset.parentId!
|
||||
} else {
|
||||
targetFolderId = targetAsset.parentId!
|
||||
reparentTargetId = targetAsset.id
|
||||
}
|
||||
|
||||
let newFileId = ''
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
const newFile = await this.createAsset(
|
||||
{
|
||||
name,
|
||||
type: 'file',
|
||||
parentId: targetFolderId,
|
||||
key,
|
||||
sizeByte,
|
||||
contentType,
|
||||
creatorId,
|
||||
},
|
||||
tx,
|
||||
)
|
||||
newFileId = newFile.id
|
||||
|
||||
await this.reparentAssets(
|
||||
{
|
||||
assetIds: [newFile.id],
|
||||
newParentId: reparentTargetId,
|
||||
creatorId,
|
||||
},
|
||||
tx,
|
||||
)
|
||||
|
||||
if (metadata) {
|
||||
const metadataUpdates = Object.entries(metadata)
|
||||
.filter(([, value]) => value !== null)
|
||||
.map(([k, v]) => ({ key: k, value: v }))
|
||||
if (metadataUpdates.length > 0) {
|
||||
await metadataService.updateAssetMetadataInTx(tx, newFile.id, metadataUpdates)
|
||||
}
|
||||
}
|
||||
|
||||
await uploadService.triggerPostUploadWorkflows(
|
||||
tx,
|
||||
newFile.id,
|
||||
targetAsset.project!.teamId,
|
||||
targetAsset.projectId!,
|
||||
)
|
||||
})
|
||||
|
||||
return this.getAsset({ assetId: newFileId })
|
||||
}
|
||||
|
||||
async findAsset(parentId: string, name: string): Promise<AssetInfo | null> {
|
||||
const asset = await this.prismaClient.asset.findFirst({
|
||||
where: { parentId, name },
|
||||
|
||||
@@ -549,4 +549,65 @@ describe('MetadataService', () => {
|
||||
]),
|
||||
).rejects.toThrow('expected string or {newOption}')
|
||||
})
|
||||
|
||||
describe('validateCreationContextMetadata', () => {
|
||||
it('passes for allowed CREATION_CONTEXT fields and throws for invalid fields', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'test-team-meta' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'test-project-meta', teamId: team.id },
|
||||
})
|
||||
const validField = await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'prompt_field',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Prompt',
|
||||
type: 'text',
|
||||
autofillSource: 'CREATION_CONTEXT',
|
||||
},
|
||||
},
|
||||
})
|
||||
await prisma.metadataField.create({
|
||||
data: {
|
||||
key: 'other_field',
|
||||
scope: 'PROJECT',
|
||||
project: { connect: { id: project.id } },
|
||||
config: {
|
||||
name: 'Other',
|
||||
type: 'text',
|
||||
autofillSource: 'NONE',
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Valid: empty metadata or null/undefined
|
||||
await expect(
|
||||
metadataService.validateCreationContextMetadata(null, project.id, null),
|
||||
).resolves.toBeUndefined()
|
||||
await expect(
|
||||
metadataService.validateCreationContextMetadata(null, project.id, {}),
|
||||
).resolves.toBeUndefined()
|
||||
|
||||
// Valid: allowed key
|
||||
await expect(
|
||||
metadataService.validateCreationContextMetadata(null, project.id, {
|
||||
[validField.key]: 'valid value',
|
||||
}),
|
||||
).resolves.toBeUndefined()
|
||||
|
||||
// Invalid: non-CREATION_CONTEXT key or non-existent key
|
||||
await expect(
|
||||
metadataService.validateCreationContextMetadata(null, project.id, {
|
||||
otherField: 'value',
|
||||
}),
|
||||
).rejects.toThrow(/metadata contains keys that are not valid in this project/)
|
||||
|
||||
await expect(
|
||||
metadataService.validateCreationContextMetadata(null, project.id, {
|
||||
randomFakeKey: 'value',
|
||||
}),
|
||||
).rejects.toThrow(/metadata contains keys that are not valid in this project/)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -215,6 +215,29 @@ export class MetadataService {
|
||||
return res
|
||||
}
|
||||
|
||||
async validateCreationContextMetadata(
|
||||
userId: string | null,
|
||||
projectId: string,
|
||||
metadata?: Record<string, unknown> | null,
|
||||
): Promise<void> {
|
||||
if (!metadata || Object.keys(metadata).length === 0) return
|
||||
|
||||
const fields = await this.listProjectFields(userId, projectId)
|
||||
const allowedKeys = new Set(
|
||||
fields
|
||||
.filter((f) => f.field.config?.autofillSource === 'CREATION_CONTEXT')
|
||||
.map((f) => f.field.key),
|
||||
)
|
||||
const invalidKeys = Object.keys(metadata).filter((key) => !allowedKeys.has(key))
|
||||
if (invalidKeys.length > 0) {
|
||||
throw new Error(
|
||||
`metadata contains keys that are not valid in this project: ${invalidKeys.join(', ')}. ` +
|
||||
"The valid metadata fields are fixed to the current conversation's project. " +
|
||||
'If the target folder or file belongs to a different project, call the tool WITHOUT the metadata parameter.',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private async getProjectFieldsOrder(
|
||||
userId: string,
|
||||
projectId: string,
|
||||
|
||||
@@ -117,7 +117,7 @@ enum WorkflowTaskType {
|
||||
chat
|
||||
ai_embedding
|
||||
query_embedding_for_search
|
||||
agent_tool_call
|
||||
agent_tool_call // @deprecated: Agent tools now execute directly in-process via Core services
|
||||
kanban_agent_run
|
||||
}
|
||||
|
||||
|
||||
@@ -275,7 +275,6 @@ declare global {
|
||||
queryEmbeddingForSearch?: {
|
||||
text: string
|
||||
}
|
||||
agentToolCall?: AgentToolCallPayload
|
||||
screenshot?: ScreenshotSpec
|
||||
imageAnnotation?: ImageAnnotationSpec
|
||||
pdfPages?: PdfPagesSpec
|
||||
@@ -285,12 +284,6 @@ declare global {
|
||||
// ----------------------------------------------------------------------
|
||||
// Task Spec & Payload
|
||||
// ----------------------------------------------------------------------
|
||||
export interface AgentToolCallPayload {
|
||||
toolName: string
|
||||
args: Record<string, unknown>
|
||||
userId: string
|
||||
}
|
||||
|
||||
export interface TaskSpec {
|
||||
videoStrategy?: VideoTranscodeStrategy
|
||||
hardwareAcceleration?: HardwareAcceleration
|
||||
|
||||
@@ -160,9 +160,12 @@ export const updateAssetNameRequestSchema = z.object({
|
||||
})
|
||||
export type UpdateAssetNameRequest = z.infer<typeof updateAssetNameRequestSchema>
|
||||
|
||||
export const assetTypeFilterSchema = z.enum(['file', 'folder', 'all'])
|
||||
export type AssetTypeFilter = z.infer<typeof assetTypeFilterSchema>
|
||||
|
||||
export const listChildrenRequestSchema = z.object({
|
||||
assetId: z.string().optional(),
|
||||
assetType: z.string(),
|
||||
assetType: assetTypeFilterSchema.optional().default('all'),
|
||||
projectId: z.string().optional(),
|
||||
showDeleted: z.boolean().optional(),
|
||||
prefix: z.string().optional(),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { z } from 'zod'
|
||||
import { UserType } from '@shumai/db/enums'
|
||||
import { paginationPageInfoSchema, paginationParamsSchema } from './pagination'
|
||||
import { assetTypeFilterSchema } from './asset'
|
||||
|
||||
export const createProjectRequestSchema = z.object({
|
||||
name: z.string(),
|
||||
@@ -58,7 +59,7 @@ export type ProjectUserInfo = z.infer<typeof projectUserInfoSchema>
|
||||
|
||||
export const recentlyDeletedRequestSchema = z
|
||||
.object({
|
||||
assetType: z.string(),
|
||||
assetType: assetTypeFilterSchema.optional().default('all'),
|
||||
sort: z.enum(['createdAt', 'name', 'size']).optional(),
|
||||
order: z.enum(['asc', 'desc']).optional(),
|
||||
})
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { workflowService, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
import { initAgentWorkflows } from '@shumai/agent'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { fileURLToPath } from 'url'
|
||||
import * as path from 'path'
|
||||
|
||||
const currentDir = path.dirname(fileURLToPath(import.meta.url))
|
||||
const agentWorkflowsPath = path.resolve(currentDir, '../../../apps/agent/src/workflows.ts')
|
||||
|
||||
describe.each(['local', 'temporal'] as const)(
|
||||
'Workflow E2E - agentToolCall (executor: %s)',
|
||||
(mode) => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let agentWorkerPromise: Promise<void> | null = null
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.S3_BUCKET = 'shumai-e2e-test-bucket-toolcall'
|
||||
process.env.GEMINI_API_KEY = 'dummy-key'
|
||||
|
||||
workflowService.setExecutorType(mode)
|
||||
initAgentWorkflows()
|
||||
|
||||
if (mode === 'temporal') {
|
||||
console.log('Starting background worker for tool call Temporal E2E tests...')
|
||||
agentWorkerPromise = workflowService.startWorkers(TaskQueueAgent, {
|
||||
workflowsPath: agentWorkflowsPath,
|
||||
})
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000))
|
||||
} else {
|
||||
console.log('Starting local workflow service polling...')
|
||||
workflowService.start()
|
||||
}
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
if (mode === 'temporal') {
|
||||
console.log('Shutting down Temporal workers...')
|
||||
await workflowService.shutdownWorkers()
|
||||
await Promise.all([agentWorkerPromise].filter(Boolean))
|
||||
}
|
||||
workflowService.close()
|
||||
vi.restoreAllMocks()
|
||||
try {
|
||||
console.log('Cleaning up local E2E storage files...')
|
||||
await s3Service.deletePrefix('shumai-e2e-test-bucket-toolcall', '')
|
||||
} catch (err) {
|
||||
console.error('Failed to clean up E2E storage folder:', err)
|
||||
}
|
||||
})
|
||||
|
||||
it('should run agentToolCall workflow and execute list_assets successfully', async () => {
|
||||
// 1. Seed Database
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'E2E Tool Call Team' },
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'E2E Tool Call Project', teamId: team.id },
|
||||
})
|
||||
|
||||
const regularUser = await prisma.user.create({
|
||||
data: {
|
||||
name: 'Regular Editor User',
|
||||
email: 'editor@example.com',
|
||||
type: 'human',
|
||||
},
|
||||
})
|
||||
|
||||
// Setup team member with owner/editor role and team scope
|
||||
await prisma.teamMember.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
userId: regularUser.id,
|
||||
role: 'editor',
|
||||
scope: 'team',
|
||||
},
|
||||
})
|
||||
|
||||
// Create a folder asset (parent)
|
||||
const parentFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'TestParentFolder',
|
||||
type: 'folder',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
// Create a child file asset inside the parent folder
|
||||
const childFile = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'TestChildFile.png',
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
mediaType: 'image/png',
|
||||
projectId: project.id,
|
||||
parentId: parentFolder.id,
|
||||
},
|
||||
})
|
||||
|
||||
// 2. Create Workflow Task
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'agent_tool_call',
|
||||
status: 'pending',
|
||||
assetId: parentFolder.id,
|
||||
projectId: project.id,
|
||||
teamId: team.id,
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
agentToolCall: {
|
||||
toolName: 'list_assets',
|
||||
args: {
|
||||
parent: parentFolder.id,
|
||||
page: 1,
|
||||
pageSize: 20,
|
||||
type: 'all',
|
||||
},
|
||||
userId: regularUser.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// 3. Wait for workflow to complete
|
||||
console.log(`Submitted E2E Tool Call Workflow Task. ID: ${task.id}. Awaiting completion...`)
|
||||
const completedTask = await workflowService.executeWait(task, 45000)
|
||||
|
||||
// 4. Verification
|
||||
expect(completedTask.status).toBe('completed')
|
||||
|
||||
// Verify task output contains the list of files, and childFile.id is present in assets
|
||||
const output = completedTask.output as unknown as { assets: { id: string }[] }
|
||||
expect(output).toBeDefined()
|
||||
expect(output.assets).toBeDefined()
|
||||
expect(output.assets.length).toBeGreaterThan(0)
|
||||
|
||||
const assetIds = output.assets.map((a) => a.id)
|
||||
expect(assetIds).toContain(childFile.id)
|
||||
}, 50000)
|
||||
},
|
||||
)
|
||||
@@ -33,10 +33,6 @@ export class TemporalExecutor implements Executor {
|
||||
workflowName = 'agentChatWorkflow'
|
||||
taskQueue = TaskQueueAgent
|
||||
break
|
||||
case WorkflowTaskType.agent_tool_call:
|
||||
workflowName = 'agentToolCallWorkflow'
|
||||
taskQueue = TaskQueueAgent
|
||||
break
|
||||
case WorkflowTaskType.transcode:
|
||||
workflowName = 'transcodeWorkflow'
|
||||
taskQueue = TaskQueueTranscode
|
||||
|
||||
Reference in New Issue
Block a user