Files
shumai/packages/api/src/project.test.ts
T
Yiling-J c55804a548 feat(operations): add create_project operation across agent, mcp, and cli (#529)
* feat(operations): add create_project operation across agent, mcp, and cli

* fix(api): remove legacy team creation endpoint

* fix(api): preserve ProjectInfo response on POST /teams/:teamId/projects
2026-11-13 11:43:08 +08:00

478 lines
14 KiB
TypeScript

import { describe, expect, it, vi, beforeEach } from 'vitest'
import { Hono, type Context, type Next } from 'hono'
import projectRoute from './project'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { projectService } from '@shumai/core/src/project/project'
import { assetService } from '@shumai/core/src/asset/asset'
import type { ProjectInfo } from '@shumai/dtos'
import {
copyAssetsOp,
createProjectOp,
moveAssetsOp,
runOperation,
} from '@shumai/core/src/operations'
vi.mock('./middleware/auth', () => ({
authMiddleware: async (
c: Context<{ Variables: { user: { id: string; name: string } } }>,
next: Next,
) => {
c.set('user', { id: 'user1', name: 'Test User' })
await next()
},
}))
vi.mock('@shumai/core/src/authz/authz')
vi.mock('@shumai/core/src/project/project', () => ({
projectService: {
createProject: vi.fn(),
updateProject: vi.fn(),
getProject: vi.fn(),
getProjectTeam: vi.fn().mockResolvedValue('t1'),
deleteProject: vi.fn(),
listProjects: vi.fn(),
getUserProjects: vi.fn(),
listProjectMembers: vi.fn(),
addProjectMember: vi.fn(),
updateMemberRole: vi.fn(),
removeMember: vi.fn(),
getProjectMe: vi.fn(),
},
}))
vi.mock('@shumai/core/src/asset/asset')
vi.mock('@shumai/core/src/operations', async (importOriginal) => ({
...(await importOriginal<typeof import('@shumai/core/src/operations')>()),
runOperation: vi.fn(),
}))
vi.mock('@shumai/core/src/auditLog/auditLog', () => ({
auditLogService: {
logAction: vi.fn().mockResolvedValue({}),
listAuditLogs: vi.fn().mockResolvedValue({ nodes: [], pageInfo: {}, total: 0 }),
},
}))
describe('project api', () => {
const app = new Hono<{ Variables: { user: { id: string; name: string } } }>()
.use('*', async (c, next) => {
c.set('user', { id: 'user1', name: 'Test User' })
await next()
})
.route('/', projectRoute)
beforeEach(() => {
vi.restoreAllMocks()
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
})
it('GET /teams/:teamId/projects', async () => {
vi.mocked(projectService.listProjects).mockResolvedValue({
data: [{ id: 'foo', name: 'foo.png', rootFolder: 'uid' }] as any, // eslint-disable-line @typescript-eslint/no-explicit-any
pageInfo: { total: 100, cursor: 'abc' },
})
const res = await app.request('/teams/t/projects?page_size=10')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.data).toHaveLength(1)
expect(json.pageInfo.total).toBe(100)
expect(json.data[0].id).toBe('foo')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Team,
id: 't',
})
})
it('GET /teams/:teamId/projects with previewFormat=jpeg', async () => {
vi.mocked(projectService.listProjects).mockResolvedValue({
data: [{ id: 'p1', name: 'p1', rootFolder: 'r1', coverImage: 'http://s3/p1.jpeg' }] as any, // eslint-disable-line @typescript-eslint/no-explicit-any
pageInfo: { total: 1, cursor: 'abc' },
})
const res = await app.request('/teams/t/projects?previewFormat=jpeg')
expect(res.status).toBe(200)
expect(projectService.listProjects).toHaveBeenCalledWith(
expect.objectContaining({
teamId: 't',
previewFormat: 'jpeg',
}),
)
})
it('POST /teams/:teamId/projects runs create_project and returns ProjectInfo', async () => {
vi.mocked(runOperation).mockResolvedValue({
id: 'foo',
name: 'foo.png',
teamId: 't',
rootFolderId: 'root1',
})
const projectInfo: ProjectInfo = {
id: 'foo',
name: 'foo.png',
teamId: 't',
rootFolder: 'root1',
coverImage: 'http://s3/bucket/key',
coverImageKey: 'key',
enableNotification: true,
updatedAt: '2026-01-01T00:00:00.000Z',
}
vi.mocked(projectService.getProject).mockResolvedValue(projectInfo)
const res = await app.request('/teams/t/projects', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'foo.png', coverImageKey: 'key' }),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual(projectInfo)
expect(runOperation).toHaveBeenCalledWith(
createProjectOp,
{ userId: 'user1', via: 'api' },
{ teamId: 't', name: 'foo.png', coverImageKey: 'key', enableNotification: true },
)
expect(projectService.getProject).toHaveBeenCalledWith('foo')
})
it('PUT /projects/:projectId', async () => {
vi.mocked(projectService.updateProject).mockResolvedValue({
id: 'foo',
name: 'updated',
coverImage: 'http://s3/bucket/key',
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const res = await app.request('/projects/foo', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'updated' }),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.name).toBe('updated')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Edit,
type: ResourceType.Project,
id: 'foo',
})
})
it('GET /projects/:projectId', async () => {
vi.mocked(projectService.getProject).mockResolvedValue({
id: 'p',
name: 'foo.png',
rootFolder: 'root_folder_id',
} as any) // eslint-disable-line @typescript-eslint/no-explicit-any
const res = await app.request('/projects/p')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.rootFolder).toBe('root_folder_id')
expect(json.id).toBe('p')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Project,
id: 'p',
})
})
it('GET /projects/:projectId/team', async () => {
vi.mocked(projectService.getProjectTeam).mockResolvedValue('teamId')
const res = await app.request('/projects/p/team')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.teamId).toBe('teamId')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Project,
id: 'p',
})
})
it('POST /projects/:projectId/reparent runs move_assets', async () => {
vi.mocked(runOperation).mockResolvedValue({
movedAssetIds: ['asset_1', 'asset_2'],
newParentId: 'new_parent_id',
})
const res = await app.request('/projects/p/reparent', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
newParentId: 'new_parent_id',
assetIds: ['asset_1', 'asset_2'],
}),
})
expect(res.status).toBe(204)
expect(runOperation).toHaveBeenCalledWith(
moveAssetsOp,
{ userId: 'user1', via: 'api' },
{ assetIds: ['asset_1', 'asset_2'], newParentId: 'new_parent_id' },
)
})
it('POST /projects/:projectId/copy runs copy_assets', async () => {
vi.mocked(runOperation).mockResolvedValue({
copiedAssetIds: ['copy_1'],
newParentId: 'new_parent_id',
})
const res = await app.request('/projects/p/copy', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
newParentId: 'new_parent_id',
assetIds: ['asset_1'],
}),
})
expect(res.status).toBe(204)
expect(runOperation).toHaveBeenCalledWith(
copyAssetsOp,
{ userId: 'user1', via: 'api' },
{ assetIds: ['asset_1'], newParentId: 'new_parent_id', withComments: false },
)
})
it('POST /projects/:projectId/empty-trash', async () => {
vi.mocked(assetService.emptyTrash).mockResolvedValue(undefined)
const res = await app.request('/projects/p1/empty-trash', {
method: 'POST',
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual({ success: true })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Admin,
type: ResourceType.Project,
id: 'p1',
})
expect(assetService.emptyTrash).toHaveBeenCalledWith('p1')
})
it('GET /projects/:projectId/members', async () => {
vi.mocked(projectService.listProjectMembers).mockResolvedValue([
{
id: 'user1',
name: 'Test User',
role: 'editor',
type: 'human',
},
])
const res = await app.request('/projects/p1/members')
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual([
{
id: 'user1',
name: 'Test User',
role: 'editor',
type: 'human',
},
])
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Project,
id: 'p1',
})
expect(projectService.listProjectMembers).toHaveBeenCalledWith({
projectId: 'p1',
includeAgents: false,
requesterUserId: 'user1',
})
})
it('GET /projects/:projectId/members?includeAgents=true', async () => {
vi.mocked(projectService.listProjectMembers).mockResolvedValue([
{
id: 'user1',
name: 'Test User',
role: 'editor',
type: 'human',
},
{
id: 'agent1',
name: 'Agent Bot',
role: 'bot',
type: 'agent',
},
])
const res = await app.request('/projects/p1/members?includeAgents=true')
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toHaveLength(2)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Project,
id: 'p1',
})
expect(projectService.listProjectMembers).toHaveBeenCalledWith({
projectId: 'p1',
includeAgents: true,
requesterUserId: 'user1',
})
})
it('POST /projects/:projectId/members', async () => {
vi.mocked(projectService.addProjectMember).mockResolvedValue(undefined)
const res = await app.request('/projects/p1/members', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: 'user2', role: 'editor' }),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual({ success: true })
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Admin,
type: ResourceType.Project,
id: 'p1',
})
expect(projectService.addProjectMember).toHaveBeenCalledWith({
projectId: 'p1',
userId: 'user2',
role: 'editor',
})
})
it('GET /projects/:projectId/me', async () => {
vi.mocked(projectService.getProjectMe).mockResolvedValue({
id: 'user1',
name: 'Test User',
role: 'editor',
})
const res = await app.request('/projects/p1/me')
expect(res.status).toBe(200)
const json = await res.json()
expect(json).toEqual({
id: 'user1',
name: 'Test User',
role: 'editor',
})
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Project,
id: 'p1',
})
expect(projectService.getProjectMe).toHaveBeenCalledWith('p1', 'user1')
})
it('GET /projects', async () => {
vi.mocked(projectService.getUserProjects).mockResolvedValue([
{
id: 'proj1',
name: 'My Project',
teamId: 'team1',
rootFolder: 'folder1',
enableNotification: true,
updatedAt: '2026-06-21T00:00:00.000Z',
},
] as unknown as ProjectInfo[])
const res = await app.request('/projects?first=10')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.data).toHaveLength(1)
expect(json.data[0]).toEqual({
id: 'proj1',
name: 'My Project',
teamId: 'team1',
rootFolder: 'folder1',
enableNotification: true,
updatedAt: '2026-06-21T00:00:00.000Z',
})
expect(projectService.getUserProjects).toHaveBeenCalledWith('user1', 10)
})
it('GET /projects with previewFormat=jpeg', async () => {
vi.mocked(projectService.getUserProjects).mockResolvedValue([
{
id: 'proj1',
name: 'My Project',
teamId: 'team1',
rootFolder: 'folder1',
coverImage: 'http://s3/proj1.jpeg',
enableNotification: true,
updatedAt: '2026-06-21T00:00:00.000Z',
},
] as unknown as ProjectInfo[])
const res = await app.request('/projects?first=10&previewFormat=jpeg')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.data[0].coverImage).toBe('http://s3/proj1.jpeg')
expect(projectService.getUserProjects).toHaveBeenCalledWith('user1', 10, 'jpeg')
})
it('GET /projects/:projectId/recents', async () => {
vi.mocked(assetService.listRecents).mockResolvedValue({
data: [{ id: 'file1', name: 'video.mp4', type: 'file' }] as any, // eslint-disable-line @typescript-eslint/no-explicit-any
pageInfo: { total: 1 },
})
const res = await app.request('/projects/p1/recents?first=20')
expect(res.status).toBe(200)
const json = await res.json()
expect(json.data).toHaveLength(1)
expect(json.data[0].id).toBe('file1')
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Project,
id: 'p1',
})
expect(assetService.listRecents).toHaveBeenCalledWith('user1', 'p1', { first: 20 })
})
it('POST /projects/:projectId/recents/view', async () => {
vi.mocked(assetService.recordRecentView).mockResolvedValue(undefined)
const res = await app.request('/projects/p1/recents/view', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ assetId: 'file1' }),
})
expect(res.status).toBe(200)
const json = await res.json()
expect(json.success).toBe(true)
expect(authzService.hasPermission).toHaveBeenCalledWith({
user: expect.anything(),
permission: Permission.Read,
type: ResourceType.Project,
id: 'p1',
})
expect(assetService.recordRecentView).toHaveBeenCalledWith('user1', 'p1', 'file1')
})
})