feat(agent): add asset management tools and CLI commands (#387)

* feat(agent): add asset management tools and CLI commands

* fix(core): resolve code review findings for reparenting cycles, agent deniedTools update, and CLI folder delete
This commit is contained in:
Yiling-J
2026-09-06 17:15:58 +08:00
committed by GitHub
parent b087bf73ae
commit 8c1e59d131
28 changed files with 1300 additions and 10 deletions
+1 -1
View File
@@ -111,7 +111,7 @@ async function executeAgentPrompt(params: {
let systemPrompt = `You are the AI assistant for shumai.
shumai is a professional creative collaboration platform similar to frame.io, where users can upload creative files, manage projects, assign tasks, get precise feedback, and share their work. As the agent, your role is to help users use and manage this platform.
shumai has its own cloud file system. If a user asks you to perform file system operations (for example: creating a folder, creating a file, stacking a version, or listing assets), you MUST use the corresponding agent system tools (e.g., 'create_folder', 'create_file', 'create_version', 'list_assets'). Before calling 'create_folder', first check if the folder exists using 'list_assets'. Do NOT use local bash commands or the local bash tool to perform these operations locally on the host environment; all operations must be executed through the platform's cloud file system tools so they are correctly registered and visible within the platform.
shumai has its own cloud file system. If a user asks you to perform file system operations (for example: creating a folder, creating a file, stacking a version, listing assets, renaming an asset, moving assets, or deleting an asset), you MUST use the corresponding agent system tools (e.g., 'create_folder', 'create_file', 'create_version', 'list_assets', 'rename_asset', 'move_assets', 'delete_asset'). Before calling 'create_folder', first check if the folder exists using 'list_assets'. Do NOT use local bash commands or the local bash tool to perform these operations locally on the host environment; all operations must be executed through the platform's cloud file system tools so they are correctly registered and visible within the platform.
If you need to create files in the local filesystem (for example, a temporary file for uploading), only the '.pi' folder in the current directory has write permissions. Do NOT attempt to create files in any other directories.
+58
View File
@@ -1029,6 +1029,64 @@ describe('createAgentSession typed metadata schema', () => {
expect('metadata' in fileProps).toBe(false)
expect('metadata' in versionProps).toBe(false)
})
it('should include rename_asset and move_assets by default, but exclude delete_asset', async () => {
const { harness } = await setupSessionWithProject({ withCreationFields: false })
const toolNames = harness.getTools().map((t) => t.name)
expect(toolNames).toContain('rename_asset')
expect(toolNames).toContain('move_assets')
expect(toolNames).not.toContain('delete_asset')
})
it('should include delete_asset when deniedTools is explicitly empty', async () => {
const team = await prisma.team.create({ data: { name: 'Delete Asset Team' } })
const user = await prisma.user.create({
data: { name: 'Owner', email: 'owner-del@shumai.ai' },
})
await prisma.teamMember.create({
data: { teamId: team.id, userId: user.id, role: 'owner' },
})
await prisma.user.create({
data: {
id: 'del-agent',
name: 'Del Agent',
email: 'del-agent@shumai.ai',
type: 'agent',
},
})
await prisma.agent.create({
data: {
id: 'del-agent',
teamId: team.id,
type: 'chat',
config: {
provider: 'google',
model: 'gemini',
deniedTools: [],
},
},
})
const initializeSpy = vi.spyOn(SandboxManager, 'initialize').mockResolvedValue()
try {
const { harness } = await createAgentSession({
teamId: team.id,
agentId: 'del-agent',
providerName: 'google',
modelId: 'gemini',
systemPrompt: 'prompt',
teamSkills: [],
allowedDomains: [],
providers: mockProviders,
userId: user.id,
})
const toolNames = harness.getTools().map((t) => t.name)
expect(toolNames).toContain('delete_asset')
} finally {
initializeSpy.mockRestore()
}
})
})
describe('createAgentSession enabled skill filtering', () => {
+11 -2
View File
@@ -30,9 +30,12 @@ import { createReadThreadTool } from './tools/read-thread'
import { createSandboxedBashTool } from './tools/sandboxed-bash'
import { createGenerateImageTool } from './tools/generate-image'
import { createGenerateVideoTool } from './tools/generate-video'
import { createRenameAssetTool } from './tools/rename-asset'
import { createMoveAssetsTool } from './tools/move-assets'
import { createDeleteAssetTool } from './tools/delete-asset'
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
import { serializeContextToXml } from './context/serialize-context'
import type { ShumaiMessageContext } from '@shumai/dtos'
import { DEFAULT_DENIED_TOOLS, type ShumaiMessageContext } from '@shumai/dtos'
export interface DbModelInfo {
modelId: string
@@ -322,7 +325,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
where: { id: agentId },
})
const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined
const deniedTools = agentConfig?.deniedTools || []
const deniedTools = agentConfig?.deniedTools ?? [...DEFAULT_DENIED_TOOLS]
if (!deniedTools.includes('generate_image') || !deniedTools.includes('generate_video')) {
try {
@@ -387,6 +390,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
createCreateFileTool(userId, metadataSchema, agentContext),
createCreateVersionTool(userId, metadataSchema, agentContext),
createDownloadAssetTool(userId),
createRenameAssetTool(userId, agentContext),
createMoveAssetsTool(userId, agentContext),
createDeleteAssetTool(userId, agentContext),
)
}
@@ -680,3 +686,6 @@ export * from './workflows/agent-embedding'
export * from './workflows/query-embedding-for-search'
export * from './tools/generate-image'
export * from './tools/generate-video'
export * from './tools/rename-asset'
export * from './tools/move-assets'
export * from './tools/delete-asset'
@@ -0,0 +1,128 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createDeleteAssetTool } from './delete-asset'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService } from '@shumai/core/src/authz/authz'
import { prisma } from '@shumai/db'
import { AuditAction } from '@shumai/dtos'
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: {
deleteAssets: vi.fn().mockResolvedValue(undefined),
getAssetContext: vi.fn().mockResolvedValue({
teamId: 'team-1',
projectId: 'proj-1',
}),
},
}))
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue(undefined),
},
}))
vi.mock('@shumai/db', () => ({
prisma: {
asset: {
findUnique: vi.fn(),
},
},
}))
describe('createDeleteAssetTool', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('checks edit permission, deletes asset, and returns success for a file', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'asset-1',
type: 'file',
projectId: 'proj-1',
} as unknown as never)
const tool = createDeleteAssetTool('user-1')
const result = await tool.execute('call-1', { assetId: 'asset-1' })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'edit',
type: 'asset',
id: 'asset-1',
})
expect(assetService.deleteAssets).toHaveBeenCalledWith(['asset-1'])
expect(result.details).toEqual({})
expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({
success: true,
deletedAssetId: 'asset-1',
})
})
it('logs file_delete audit action when deleting a file with agentContext', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'asset-1',
type: 'file',
projectId: 'proj-1',
} as unknown as never)
const tool = createDeleteAssetTool('user-1', { teamId: 'team-1', agentId: 'agent-1' })
await tool.execute('call-1', { assetId: 'asset-1' })
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.file_delete,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'asset-1',
})
})
it('logs folder_delete audit action when deleting a folder with agentContext', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
id: 'folder-1',
type: 'folder',
projectId: 'proj-1',
} as unknown as never)
const tool = createDeleteAssetTool('user-1', { teamId: 'team-1', agentId: 'agent-1' })
await tool.execute('call-1', { assetId: 'folder-1' })
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.folder_delete,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'folder-1',
})
})
it('throws when asset is not found', async () => {
vi.mocked(prisma.asset.findUnique).mockResolvedValue(null)
const tool = createDeleteAssetTool('user-1')
await expect(tool.execute('call-1', { assetId: 'missing-asset' })).rejects.toThrow(
'Asset not found',
)
})
it('fails when permission check fails', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new Error('Permission denied'))
const tool = createDeleteAssetTool('user-1')
await expect(tool.execute('call-1', { assetId: 'asset-1' })).rejects.toThrow(
'Permission denied',
)
})
})
+74
View File
@@ -0,0 +1,74 @@
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { prisma, type User } from '@shumai/db'
import { AuditAction } from '@shumai/dtos'
const deleteAssetSchema = Type.Object(
{
assetId: Type.String({
description:
'The ID of the single asset (file or folder) to delete. This parameter is required.',
}),
},
{ additionalProperties: false },
)
export function createDeleteAssetTool(
userId: string,
agentContext?: { teamId?: string; agentId?: string },
): AgentTool<typeof deleteAssetSchema> {
return {
name: 'delete_asset',
label: 'Delete Asset',
description:
'Delete a single asset (file or folder) by its ID. Can only delete one asset at a time.',
parameters: deleteAssetSchema,
execute: async (_toolCallId, params) => {
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Edit,
type: ResourceType.Asset,
id: params.assetId,
})
const asset = await prisma.asset.findUnique({
where: { id: params.assetId },
select: { id: true, type: true, projectId: true },
})
if (!asset) {
throw new Error('Asset not found')
}
const ctx = await assetService.getAssetContext(params.assetId).catch(() => ({
teamId: agentContext?.teamId || '',
projectId: asset.projectId ?? undefined,
}))
await assetService.deleteAssets([params.assetId])
if (agentContext?.teamId) {
await auditLogService.logAction({
action: asset.type === 'folder' ? AuditAction.folder_delete : AuditAction.file_delete,
teamId: agentContext.teamId || ctx.teamId,
userId,
agentId: agentContext.agentId,
projectId: ctx.projectId ?? asset.projectId ?? undefined,
itemId: params.assetId,
})
}
const result = {
success: true,
deletedAssetId: params.assetId,
}
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: {},
}
},
}
}
@@ -0,0 +1,118 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMoveAssetsTool } from './move-assets'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService } from '@shumai/core/src/authz/authz'
import { AuditAction } from '@shumai/dtos'
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: {
reparentAssets: vi.fn().mockResolvedValue(undefined),
getAssetContext: vi.fn().mockResolvedValue({
teamId: 'team-1',
projectId: 'proj-1',
}),
},
}))
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue(undefined),
},
}))
describe('createMoveAssetsTool', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('checks permissions on destination and all assets, and calls reparentAssets', async () => {
const tool = createMoveAssetsTool('user-1')
const result = await tool.execute('call-1', {
assetIds: ['asset-1', 'asset-2'],
newParentId: 'folder-dest',
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'edit',
type: 'asset',
id: 'folder-dest',
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'edit',
type: 'asset',
id: 'asset-1',
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'edit',
type: 'asset',
id: 'asset-2',
})
expect(assetService.reparentAssets).toHaveBeenCalledWith({
assetIds: ['asset-1', 'asset-2'],
newParentId: 'folder-dest',
creatorId: 'user-1',
})
expect(result.details).toEqual({})
expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({
success: true,
movedAssetIds: ['asset-1', 'asset-2'],
newParentId: 'folder-dest',
})
})
it('logs asset_reparent for each asset when agentContext is provided', async () => {
const tool = createMoveAssetsTool('user-1', { teamId: 'team-1', agentId: 'agent-1' })
await tool.execute('call-1', {
assetIds: ['asset-1', 'asset-2'],
newParentId: 'folder-dest',
})
expect(auditLogService.logAction).toHaveBeenCalledTimes(2)
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.asset_reparent,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'asset-1',
})
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.asset_reparent,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'asset-2',
})
})
it('fails when permission check on target folder fails', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(
new Error('Access denied to destination'),
)
const tool = createMoveAssetsTool('user-1')
await expect(
tool.execute('call-1', {
assetIds: ['asset-1'],
newParentId: 'folder-dest',
}),
).rejects.toThrow('Access denied to destination')
})
})
+84
View File
@@ -0,0 +1,84 @@
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { type User } from '@shumai/db'
import { AuditAction } from '@shumai/dtos'
const moveAssetsSchema = Type.Object({
assetIds: Type.Array(Type.String(), {
description:
'The IDs of the assets to move. All assets must belong to the same parent folder. At least one asset ID is required.',
minItems: 1,
}),
newParentId: Type.String({
description:
'The destination parent folder ID to move the assets into. This parameter is required.',
}),
})
export function createMoveAssetsTool(
userId: string,
agentContext?: { teamId?: string; agentId?: string },
): AgentTool<typeof moveAssetsSchema> {
return {
name: 'move_assets',
label: 'Move Assets',
description:
'Move one or more assets (files or folders) to a specified parent folder. Note: All assets to be moved must belong to the same current parent folder.',
parameters: moveAssetsSchema,
execute: async (_toolCallId, params) => {
// Check Edit permission on destination folder
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Edit,
type: ResourceType.Asset,
id: params.newParentId,
})
// Check Edit permission on all source assets
for (const assetId of params.assetIds) {
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Edit,
type: ResourceType.Asset,
id: assetId,
})
}
await assetService.reparentAssets({
assetIds: params.assetIds,
newParentId: params.newParentId,
creatorId: userId,
})
if (agentContext?.teamId) {
const ctx = await assetService
.getAssetContext(params.newParentId)
.catch(() => ({ teamId: agentContext.teamId!, projectId: undefined }))
for (const assetId of params.assetIds) {
await auditLogService.logAction({
action: AuditAction.asset_reparent,
teamId: agentContext.teamId || ctx.teamId,
userId,
agentId: agentContext.agentId,
projectId: ctx.projectId,
itemId: assetId,
})
}
}
const result = {
success: true,
movedAssetIds: params.assetIds,
newParentId: params.newParentId,
}
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: {},
}
},
}
}
@@ -0,0 +1,112 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createRenameAssetTool } from './rename-asset'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService } from '@shumai/core/src/authz/authz'
import { AuditAction, type AssetInfo } from '@shumai/dtos'
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: {
updateAssetName: vi.fn().mockResolvedValue({
id: 'asset-1',
name: 'Renamed Asset',
type: 'file',
sizeByte: 1024,
projectId: 'proj-1',
}),
getAssetContext: vi.fn().mockResolvedValue({
teamId: 'team-1',
projectId: 'proj-1',
}),
},
}))
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue(undefined),
},
}))
describe('createRenameAssetTool', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('checks edit permission and calls assetService.updateAssetName', async () => {
const tool = createRenameAssetTool('user-1')
const result = await tool.execute('call-1', { assetId: 'asset-1', name: 'Renamed Asset' })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: { id: 'user-1' },
permission: 'edit',
type: 'asset',
id: 'asset-1',
})
expect(assetService.updateAssetName).toHaveBeenCalledWith({
id: 'asset-1',
name: 'Renamed Asset',
})
expect(result.details).toEqual({})
expect(JSON.parse((result.content[0] as { text: string }).text)).toEqual({
id: 'asset-1',
name: 'Renamed Asset',
type: 'file',
size: 1024,
})
})
it('logs file_update audit action when renaming a file with agentContext', async () => {
const tool = createRenameAssetTool('user-1', { teamId: 'team-1', agentId: 'agent-1' })
await tool.execute('call-1', { assetId: 'asset-1', name: 'Renamed File' })
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.file_update,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'asset-1',
})
})
it('logs folder_update audit action when renaming a folder with agentContext', async () => {
vi.mocked(assetService.updateAssetName).mockResolvedValueOnce({
id: 'folder-1',
name: 'Renamed Folder',
type: 'folder',
sizeByte: 0,
projectId: 'proj-1',
} as unknown as AssetInfo)
const tool = createRenameAssetTool('user-1', { teamId: 'team-1', agentId: 'agent-1' })
await tool.execute('call-1', { assetId: 'folder-1', name: 'Renamed Folder' })
expect(auditLogService.logAction).toHaveBeenCalledWith({
action: AuditAction.folder_update,
teamId: 'team-1',
userId: 'user-1',
agentId: 'agent-1',
projectId: 'proj-1',
itemId: 'folder-1',
})
})
it('fails when permission check rejects', async () => {
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(new Error('Permission denied'))
const tool = createRenameAssetTool('user-1')
await expect(tool.execute('call-1', { assetId: 'asset-1', name: 'New' })).rejects.toThrow(
'Permission denied',
)
})
})
+69
View File
@@ -0,0 +1,69 @@
import { Type } from 'typebox'
import { type AgentTool } from '@earendil-works/pi-agent-core'
import { assetService } from '@shumai/core/src/asset/asset'
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { type User } from '@shumai/db'
import { AuditAction } from '@shumai/dtos'
const renameAssetSchema = Type.Object({
assetId: Type.String({
description: 'The ID of the asset (file or folder) to rename. This parameter is required.',
}),
name: Type.String({
description: 'The new name for the asset. This parameter is required.',
}),
})
export function createRenameAssetTool(
userId: string,
agentContext?: { teamId?: string; agentId?: string },
): AgentTool<typeof renameAssetSchema> {
return {
name: 'rename_asset',
label: 'Rename Asset',
description: 'Rename an existing asset (file or folder).',
parameters: renameAssetSchema,
execute: async (_toolCallId, params) => {
await authzService.hasPermission({
user: { id: userId } as User,
permission: Permission.Edit,
type: ResourceType.Asset,
id: params.assetId,
})
const updatedAsset = await assetService.updateAssetName({
id: params.assetId,
name: params.name,
})
if (agentContext?.teamId) {
const ctx = await assetService.getAssetContext(params.assetId).catch(() => ({
teamId: agentContext.teamId!,
projectId: updatedAsset.projectId ?? undefined,
}))
await auditLogService.logAction({
action:
updatedAsset.type === 'folder' ? AuditAction.folder_update : AuditAction.file_update,
teamId: agentContext.teamId || ctx.teamId,
userId,
agentId: agentContext.agentId,
projectId: ctx.projectId ?? updatedAsset.projectId ?? undefined,
itemId: params.assetId,
})
}
const result = {
id: updatedAsset.id,
name: updatedAsset.name,
type: updatedAsset.type,
size: Number(updatedAsset.sizeByte),
}
return {
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
details: {},
}
},
}
}
+62
View File
@@ -257,6 +257,68 @@ describe('AgentService', () => {
expect(updated.user.image).toBe('files/01JK23456789ABCDEF01234567')
})
test('Update Agent preserves deniedTools when omitted, and allows explicit empty array', async () => {
const db = prisma
const svc = new AgentService()
const { team, provider, model, agent: legacyAgent } = await setupTestData(db)
// Legacy agent has no deniedTools in config, update without deniedTools should fall back to DEFAULT_DENIED_TOOLS
const updatedLegacy = await svc.updateAgent({
agentId: legacyAgent.id,
name: 'Updated Legacy',
type: 'chat',
enabled: true,
providerId: legacyAgent.providerId!,
modelId: legacyAgent.modelId!,
thinkingLevel: 'medium',
})
expect((updatedLegacy.config as PrismaJson.AgentConfig).deniedTools).toEqual(['delete_asset'])
// Create new agent with default deniedTools
const agent = await svc.createAgent({
teamId: team.id,
name: 'New Agent with Defaults',
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
thinkingLevel: 'medium',
})
expect(agent).not.toBeNull()
// Agent created with default deniedTools: ['delete_asset']
const createdConfig = agent!.config as PrismaJson.AgentConfig
expect(createdConfig.deniedTools).toEqual(['delete_asset'])
// Update without deniedTools: should preserve ['delete_asset']
const updatedWithoutDenied = await svc.updateAgent({
agentId: agent!.id,
name: 'Updated Name',
type: 'chat',
enabled: true,
providerId: agent!.providerId!,
modelId: agent!.modelId!,
thinkingLevel: 'medium',
})
const config1 = updatedWithoutDenied.config as PrismaJson.AgentConfig
expect(config1.deniedTools).toEqual(['delete_asset'])
// Update with explicit deniedTools: []
const updatedWithEmptyDenied = await svc.updateAgent({
agentId: agent!.id,
name: 'Updated Name 2',
type: 'chat',
enabled: true,
providerId: agent!.providerId!,
modelId: agent!.modelId!,
thinkingLevel: 'medium',
deniedTools: [],
})
const config2 = updatedWithEmptyDenied.config as PrismaJson.AgentConfig
expect(config2.deniedTools).toEqual([])
})
test('Create and Update Agent with Preset Avatars', async () => {
const db = prisma
const svc = new AgentService()
+6 -2
View File
@@ -7,6 +7,7 @@ import {
AgentSessionInfo,
AgentInfo,
AgentType,
DEFAULT_DENIED_TOOLS,
} from '@shumai/dtos'
import {
paginateQuery,
@@ -208,7 +209,7 @@ export class AgentService {
model: modelId || '',
thinkingLevel,
systemPrompt,
deniedTools: deniedTools || [],
deniedTools: deniedTools ?? [...DEFAULT_DENIED_TOOLS],
avatarPreset,
}
@@ -351,7 +352,10 @@ export class AgentService {
model: modelId || '',
thinkingLevel,
systemPrompt,
deniedTools: deniedTools || [],
deniedTools:
deniedTools !== undefined
? deniedTools
: (currentConfig.deniedTools ?? [...DEFAULT_DENIED_TOOLS]),
avatarPreset: newAvatarPreset,
}
+33
View File
@@ -626,6 +626,39 @@ describe('AssetService', () => {
).rejects.toThrow('Can only move one file at a time into a version stack')
})
it('rejects reparenting a folder into itself', async () => {
const { user, assets } = await setupBasicAssets()
await expect(
assetService.reparentAssets({
assetIds: [assets.folderA.id],
newParentId: assets.folderA.id,
creatorId: user.id,
}),
).rejects.toThrow('Cannot move an asset into itself or its own descendant')
})
it('rejects reparenting a folder into its own descendant', async () => {
const { user, assets, project } = await setupBasicAssets()
const subfolder = await prisma.asset.create({
data: {
name: 'subfolderA',
type: AssetType.folder,
projectId: project.id,
parentId: assets.folderA.id,
creatorId: user.id,
status: 'uploaded',
},
})
await expect(
assetService.reparentAssets({
assetIds: [assets.folderA.id],
newParentId: subfolder.id,
creatorId: user.id,
}),
).rejects.toThrow('Cannot move an asset into itself or its own descendant')
})
describe('fileCount verification', () => {
it('createAsset should increment parent fileCount', async () => {
const { user, assets, project } = await setupBasicAssets()
+14
View File
@@ -223,6 +223,20 @@ export class AssetService {
if (assetsToMove.length === 0) return
// Check if newParentId is equal to or a descendant of any asset being moved
const ancestors = await tx.$queryRaw<{ id: string }[]>`
WITH RECURSIVE ancestor AS (
SELECT id, parent_id FROM assets WHERE id = ${newParent.id}
UNION ALL
SELECT a.id, a.parent_id FROM assets a
INNER JOIN ancestor d ON a.id = d.parent_id
)
SELECT id FROM ancestor WHERE id IN (${Prisma.join(req.assetIds)}) LIMIT 1;
`
if (ancestors.length > 0) {
throw new Error('Cannot move an asset into itself or its own descendant')
}
if (newParent.type === AssetType.version_stack) {
for (const a of assetsToMove) {
if (a.type !== AssetType.file) {
@@ -0,0 +1,15 @@
-- Append 'delete_asset' to deniedTools of existing agents if not already present
UPDATE "agents"
SET "config" = jsonb_set(
"config"::jsonb,
'{deniedTools}',
CASE
WHEN "config"::jsonb ? 'deniedTools' AND jsonb_typeof("config"::jsonb->'deniedTools') = 'array' THEN
CASE
WHEN "config"::jsonb->'deniedTools' @> '["delete_asset"]'::jsonb THEN "config"::jsonb->'deniedTools'
ELSE ("config"::jsonb->'deniedTools') || '["delete_asset"]'::jsonb
END
ELSE
'["delete_asset"]'::jsonb
END
);
+2
View File
@@ -12,6 +12,8 @@ export type ThinkingLevel = z.infer<typeof thinkingLevelSchema>
export const agentPermissionSchema = z.enum(['owner', 'editor', 'reviewer'])
export type AgentPermission = z.infer<typeof agentPermissionSchema>
export const DEFAULT_DENIED_TOOLS = ['delete_asset'] as const
export const agentSkillSchema = z.object({
id: z.string().optional(),
skillId: z.string(),
@@ -88,5 +88,8 @@ describe('AgentFormDialog', () => {
expect(screen.getByText('Generate Video')).toBeDefined()
expect(screen.getByText('Sandboxed Terminal')).toBeDefined()
expect(screen.getByText('Read Asset')).toBeDefined()
expect(screen.getByText('Rename Asset')).toBeDefined()
expect(screen.getByText('Move Assets')).toBeDefined()
expect(screen.getByText('Delete Asset')).toBeDefined()
})
})
@@ -27,7 +27,13 @@ import { Check, ChevronDown, Loader2, Puzzle, Search, Server, Terminal, Zap } fr
import { useEffect, useMemo, useState } from 'react'
import { m } from '@/ui/paraglide/messages.js'
import { toast } from 'sonner'
import { AgentInfo, AgentType, ThinkingLevel, thinkingLevelSchema } from '@shumai/dtos'
import {
AgentInfo,
AgentType,
DEFAULT_DENIED_TOOLS,
ThinkingLevel,
thinkingLevelSchema,
} from '@shumai/dtos'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { Textarea } from '@/ui/components/ui/textarea'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
@@ -105,6 +111,21 @@ const BUILTIN_TOOLS = [
name: () => m.agent_tool_generate_video_name(),
description: () => m.agent_tool_generate_video_desc(),
},
{
id: 'rename_asset',
name: () => m.agent_tool_rename_asset_name(),
description: () => m.agent_tool_rename_asset_desc(),
},
{
id: 'move_assets',
name: () => m.agent_tool_move_assets_name(),
description: () => m.agent_tool_move_assets_desc(),
},
{
id: 'delete_asset',
name: () => m.agent_tool_delete_asset_name(),
description: () => m.agent_tool_delete_asset_desc(),
},
]
type AgentFormValues = z.infer<typeof agentFormSchema>
@@ -197,7 +218,7 @@ export function AgentFormDialog({
systemPrompt: initialValues?.systemPrompt || '',
skills: initialValues?.skills?.map((s) => s.skillId) || ([] as string[]),
mcpServerIds: initialValues?.mcpServerIds || ([] as string[]),
deniedTools: initialValues?.deniedTools || ([] as string[]),
deniedTools: initialValues?.deniedTools ?? [...DEFAULT_DENIED_TOOLS],
} as AgentFormValues,
validators: {
onChange: schema,
@@ -76,6 +76,9 @@ const STANDARD_TOOLS = [
{ value: 'create_version', label: () => m.agent_tool_create_version_name() },
{ value: 'generate_image', label: () => m.agent_tool_generate_image_name() },
{ value: 'generate_video', label: () => m.agent_tool_generate_video_name() },
{ value: 'rename_asset', label: () => m.agent_tool_rename_asset_name() },
{ value: 'move_assets', label: () => m.agent_tool_move_assets_name() },
{ value: 'delete_asset', label: () => m.agent_tool_delete_asset_name() },
]
/* eslint-disable @typescript-eslint/naming-convention */
+6
View File
@@ -533,6 +533,12 @@
"agent_tool_generate_image_desc": "Allows the agent to generate images from prompts and reference images using configured AI image models.",
"agent_tool_generate_video_name": "Generate Video",
"agent_tool_generate_video_desc": "Allows the agent to generate videos from text, images, or frame sequences using configured AI video models.",
"agent_tool_rename_asset_name": "Rename Asset",
"agent_tool_rename_asset_desc": "Allows the agent to rename an existing file or folder in Shumai.",
"agent_tool_move_assets_name": "Move Assets",
"agent_tool_move_assets_desc": "Allows the agent to move one or more assets to another folder in Shumai.",
"agent_tool_delete_asset_name": "Delete Asset",
"agent_tool_delete_asset_desc": "Allows the agent to delete a single file or folder in Shumai.",
"enabled": "Enabled",
"disabled": "Disabled",
"no_skills_available": "No skills available.",
+6
View File
@@ -533,6 +533,12 @@
"agent_tool_generate_image_desc": "允许智能体使用已配置的 AI 图片模型根据提示词和参考图片生成图片。",
"agent_tool_generate_video_name": "生成视频",
"agent_tool_generate_video_desc": "允许智能体使用已配置的 AI 视频模型根据提示词、图片或首尾帧生成视频。",
"agent_tool_rename_asset_name": "重命名资产",
"agent_tool_rename_asset_desc": "允许智能体在 Shumai 中重命名现有的文件或文件夹。",
"agent_tool_move_assets_name": "移动资产",
"agent_tool_move_assets_desc": "允许智能体将一个或多个资产移动到 Shumai 中的其他文件夹。",
"agent_tool_delete_asset_name": "删除资产",
"agent_tool_delete_asset_desc": "允许智能体在 Shumai 中删除单个文件或文件夹。",
"enabled": "已启用",
"disabled": "已禁用",
"no_skills_available": "暂无可用技能。",
+8 -1
View File
@@ -307,7 +307,14 @@ export const useChatbotStore = create<ChatbotState>((set) => ({
if (
entryObj.role === 'toolResult' &&
typeof entryObj.toolName === 'string' &&
['create_file', 'create_folder', 'create_version'].includes(entryObj.toolName) &&
[
'create_file',
'create_folder',
'create_version',
'rename_asset',
'move_assets',
'delete_asset',
].includes(entryObj.toolName) &&
!entryObj.isError
) {
onAssetMutation?.()