mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 09:06:54 +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:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user