mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 17:37:15 +00:00
feat: move MCP to /mcp and add teammate operations (#500)
* feat(operations): move MCP to /mcp and add search, comment, metadata, version, and upload operations - Serve the MCP server at /mcp instead of /api/mcp - Add search_assets, copy_assets, get_folder_instructions, list_comments, create_comment, resolve_comment, list_metadata_fields, update_asset_metadata, create_version_stack, list_versions, and remove_version on the agent, MCP, and CLI - Add create_file and create_version (agent, MCP) with Creation Context metadata, and complete_upload (MCP) for presigned two-step uploads - Replace the native agent create_file/create_version tools with Operation-backed ones - Route the comment-complete, metadata, copy, version stack, and AGENTS.md read REST endpoints through their Operations * docs(readme): add built-in MCP server and CLI to features list
This commit is contained in:
@@ -397,8 +397,9 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
async copyAssets(req: CopyAssetsRequest): Promise<void> {
|
||||
await this.prismaClient.$transaction(async (tx) => {
|
||||
/** Copies assets into a folder. Returns the IDs of the copies, in the order of `assetIds`. */
|
||||
async copyAssets(req: CopyAssetsRequest): Promise<string[]> {
|
||||
return this.prismaClient.$transaction(async (tx) => {
|
||||
const newParent = await tx.asset.findUnique({
|
||||
where: { id: req.newParentId },
|
||||
include: { project: { include: { team: true } } },
|
||||
@@ -448,6 +449,7 @@ export class AssetService {
|
||||
let firstSortIndex = firstFile?.sortIndex || null
|
||||
|
||||
let totalSize = 0
|
||||
const copiedIds: string[] = new Array(req.assetIds.length)
|
||||
for (let i = req.assetIds.length - 1; i >= 0; i--) {
|
||||
const assetId = req.assetIds[i]
|
||||
const asset = assetsToCopy.find((a) => a.id === assetId)!
|
||||
@@ -461,6 +463,7 @@ export class AssetService {
|
||||
req.creatorId,
|
||||
req.withComments,
|
||||
)
|
||||
copiedIds[i] = copiedAsset.id
|
||||
totalSize += Number(copiedAsset.sizeByte)
|
||||
firstSortIndex = newSortIndex
|
||||
}
|
||||
@@ -472,6 +475,7 @@ export class AssetService {
|
||||
},
|
||||
})
|
||||
await this.updateAncestorsSize(tx, newParent.id, totalSize)
|
||||
return copiedIds
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1144,12 +1148,17 @@ export class AssetService {
|
||||
* Lightweight lookup of an asset's type and team/project, without building a full AssetInfo
|
||||
* (no presigned URLs). Use it to capture context before a mutation such as a delete.
|
||||
*/
|
||||
async getAssetMeta(
|
||||
assetId: string,
|
||||
): Promise<{ id: string; name: string; type: AssetType; teamId: string; projectId?: string }> {
|
||||
async getAssetMeta(assetId: string): Promise<{
|
||||
id: string
|
||||
name: string
|
||||
type: AssetType
|
||||
parentId: string | null
|
||||
teamId: string
|
||||
projectId?: string
|
||||
}> {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
select: { id: true, name: true, type: true },
|
||||
select: { id: true, name: true, type: true, parentId: true },
|
||||
})
|
||||
if (!asset) {
|
||||
throw new HTTPException(404, { message: 'Asset not found' })
|
||||
@@ -1158,6 +1167,20 @@ export class AssetService {
|
||||
return { ...asset, teamId, projectId }
|
||||
}
|
||||
|
||||
/**
|
||||
* The asset whose file is stored under `key`, with its creator. Used to make finishing an
|
||||
* upload idempotent: the same uploaded object is never attached to two assets.
|
||||
*/
|
||||
async findAssetByStorageKey(
|
||||
key: string,
|
||||
): Promise<{ id: string; creatorId: string | null } | null> {
|
||||
return this.prismaClient.asset.findFirst({
|
||||
where: { storageKey: { key } },
|
||||
select: { id: true, creatorId: true },
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
}
|
||||
|
||||
async resolveTargetAssetId(assetId: string): Promise<string> {
|
||||
const asset = await this.prismaClient.asset.findUnique({
|
||||
where: { id: assetId },
|
||||
@@ -1734,7 +1757,16 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
async createComment(req: CreateCommentRequest): Promise<CommentInfo> {
|
||||
/**
|
||||
* Creates a comment or reply. Mentions of agents (`<@agentId>`) start a chat with them
|
||||
* unless `triggerAgents` is false, which keeps an agent's own comments from starting
|
||||
* further agent runs.
|
||||
*/
|
||||
async createComment(
|
||||
req: CreateCommentRequest,
|
||||
options: { triggerAgents?: boolean } = {},
|
||||
): Promise<CommentInfo> {
|
||||
const triggerAgents = options.triggerAgents ?? true
|
||||
let commentId = ''
|
||||
const resolvedAssetId = await this.resolveLatestVersionId(req.assetId)
|
||||
|
||||
@@ -1783,6 +1815,8 @@ export class AssetService {
|
||||
}
|
||||
}
|
||||
|
||||
if (!triggerAgents) return
|
||||
|
||||
// Parse bot mentions
|
||||
const botMentionMatches = [...req.message.matchAll(/<@([^>]+)>/g)]
|
||||
const mentionedAgentIds = new Set(botMentionMatches.map((match) => match[1]))
|
||||
@@ -2083,7 +2117,10 @@ export class AssetService {
|
||||
orderBy: { id: 'asc' },
|
||||
})
|
||||
},
|
||||
async () => this.prismaClient.assetComment.count({ where: { assetId, replyToId: null } }),
|
||||
async () =>
|
||||
this.prismaClient.assetComment.count({
|
||||
where: { assetId: resolvedAssetId, replyToId: null },
|
||||
}),
|
||||
params,
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { CommentInfo } from '@shumai/dtos'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
|
||||
export interface PostCommentParams {
|
||||
assetId: string
|
||||
userId: string
|
||||
message: string
|
||||
replyToId?: string
|
||||
/** Markup drawn on the frame or page (web app only). */
|
||||
annotations?: unknown
|
||||
/** Timecode in seconds (or the encoded viewing angle for 3D models). */
|
||||
second?: number
|
||||
attachmentIds?: string[]
|
||||
/** Whether mentions of agents start a chat with them (default true). */
|
||||
triggerAgents?: boolean
|
||||
}
|
||||
|
||||
export class CommentService {
|
||||
/**
|
||||
* Posts a comment or reply and notifies the people involved: team members for a new
|
||||
* comment, the thread's author for a reply, and anyone mentioned.
|
||||
*/
|
||||
async postComment(params: PostCommentParams): Promise<CommentInfo> {
|
||||
const comment = await assetService.createComment(
|
||||
{
|
||||
assetId: params.assetId,
|
||||
userId: params.userId,
|
||||
replyToId: params.replyToId,
|
||||
message: params.message,
|
||||
annotations: params.annotations,
|
||||
second: params.second,
|
||||
attachmentIds: params.attachmentIds ?? [],
|
||||
},
|
||||
{ triggerAgents: params.triggerAgents },
|
||||
)
|
||||
|
||||
const context = await assetService.getAssetContext(params.assetId)
|
||||
|
||||
let targetUserId: string | undefined
|
||||
if (params.replyToId) {
|
||||
const parentComment = await assetService.getComment(params.replyToId).catch(() => null)
|
||||
if (parentComment?.creator?.id) {
|
||||
targetUserId = parentComment.creator.id
|
||||
}
|
||||
}
|
||||
|
||||
// Delivery happens in the background; this only schedules it.
|
||||
await notificationService.create({
|
||||
type: params.replyToId ? 'reply_created' : 'comment_created',
|
||||
teamId: context.teamId,
|
||||
creatorId: params.userId,
|
||||
assetId: params.assetId,
|
||||
userId: targetUserId,
|
||||
commentMessage: params.message,
|
||||
})
|
||||
|
||||
return comment
|
||||
}
|
||||
}
|
||||
|
||||
export const commentService = new CommentService()
|
||||
@@ -0,0 +1,35 @@
|
||||
import { copyAssets } from '@shumai/operations'
|
||||
import { AuditAction } from '@shumai/dtos'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { asBadRequest } from '../errors'
|
||||
import { implementOperation } from '../implement'
|
||||
|
||||
export const copyAssetsOp = implementOperation(copyAssets, {
|
||||
authz: (input) => [
|
||||
{ permission: Permission.Edit, type: ResourceType.Asset, id: input.newParentId },
|
||||
...[...new Set(input.assetIds)].map((id) => ({
|
||||
permission: Permission.Read,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})),
|
||||
],
|
||||
execute: async (input, ctx) => {
|
||||
const copiedAssetIds = await asBadRequest(() =>
|
||||
assetService.copyAssets({
|
||||
assetIds: input.assetIds,
|
||||
newParentId: input.newParentId,
|
||||
withComments: input.withComments ?? false,
|
||||
creatorId: ctx.userId,
|
||||
}),
|
||||
)
|
||||
return { copiedAssetIds, newParentId: input.newParentId }
|
||||
},
|
||||
// One entry per source asset, recorded in the destination's team and project.
|
||||
audit: (input) =>
|
||||
input.assetIds.map((assetId) => ({
|
||||
action: AuditAction.asset_copy,
|
||||
itemId: assetId,
|
||||
contextAssetId: input.newParentId,
|
||||
})),
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
import { getFolderInstructions } from '@shumai/operations'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { asBadRequest } from '../errors'
|
||||
import { implementOperation } from '../implement'
|
||||
|
||||
export const getFolderInstructionsOp = implementOperation(getFolderInstructions, {
|
||||
authz: (input) => [{ permission: Permission.Read, type: ResourceType.Asset, id: input.folderId }],
|
||||
execute: async (input) => ({
|
||||
folderId: input.folderId,
|
||||
content: await asBadRequest(() => assetService.getAgentsMd(input.folderId)),
|
||||
}),
|
||||
})
|
||||
@@ -0,0 +1,39 @@
|
||||
import { DEFAULT_PAGE_SIZE, searchAssets } from '@shumai/operations'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { searchService } from '@shumai/core/src/search/search'
|
||||
import { asBadRequest } from '../errors'
|
||||
import { implementOperation } from '../implement'
|
||||
import { toAssetSummary } from './to-asset-summary'
|
||||
|
||||
export const searchAssetsOp = implementOperation(searchAssets, {
|
||||
authz: (input) => [{ permission: Permission.Read, type: ResourceType.Asset, id: input.parent }],
|
||||
execute: async (input) => {
|
||||
const semantic = Boolean(input.query && input.semantic)
|
||||
const conditions = (input.conditions ?? []).map((c) => ({ ...c, value: c.value ?? null }))
|
||||
// Name search is a `name contains` condition (always combined with AND); only
|
||||
// semantic search uses the query text itself.
|
||||
if (input.query && !semantic) {
|
||||
conditions.push({ field: 'name', operator: 'contains', value: input.query })
|
||||
}
|
||||
const result = await asBadRequest(() =>
|
||||
searchService.search(input.parent, {
|
||||
query: semantic ? input.query : undefined,
|
||||
isSemantic: semantic,
|
||||
assetType: input.type,
|
||||
recursively: input.recursive ?? true,
|
||||
conditions,
|
||||
operator: input.matchAny ? 'OR' : 'AND',
|
||||
first: input.first ?? DEFAULT_PAGE_SIZE,
|
||||
after: input.after,
|
||||
}),
|
||||
)
|
||||
return {
|
||||
data: result.data.map(toAssetSummary),
|
||||
pageInfo: {
|
||||
hasNextPage: Boolean(result.pageInfo.cursor),
|
||||
endCursor: result.pageInfo.cursor ?? null,
|
||||
},
|
||||
total: result.pageInfo.total ?? result.data.length,
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,545 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
import { prisma, type User } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { AuditAction } from '@shumai/dtos'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import {
|
||||
copyAssetsOp,
|
||||
createCommentOp,
|
||||
createFolderOp,
|
||||
createVersionStackOp,
|
||||
getFolderInstructionsOp,
|
||||
listCommentsOp,
|
||||
listMetadataFieldsOp,
|
||||
listVersionsOp,
|
||||
removeVersionOp,
|
||||
resolveCommentOp,
|
||||
searchAssetsOp,
|
||||
updateAssetMetadataOp,
|
||||
} from './index'
|
||||
import { runOperation } from './run'
|
||||
import type { OperationContext } from './context'
|
||||
|
||||
/**
|
||||
* Real-database tests for the search, copy, folder instruction, comment, metadata, and version
|
||||
* Operations: success, permission denial without side effects, and audit entries.
|
||||
*/
|
||||
describe('collaboration Operations', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let owner: User
|
||||
let reviewer: User
|
||||
let outsider: User
|
||||
let teamId: string
|
||||
let projectId: string
|
||||
let rootFolderId: string
|
||||
|
||||
const as = (user: User, via: OperationContext['via'] = 'mcp', agentId?: string) => ({
|
||||
userId: user.id,
|
||||
via,
|
||||
agentId,
|
||||
})
|
||||
|
||||
/** A file without a preview type, so creating it doesn't start transcoding. */
|
||||
async function createFile(name: string, parentId = rootFolderId) {
|
||||
const asset = await assetService.createFile({
|
||||
parentId,
|
||||
name,
|
||||
key: `files/test/${name}-${Math.random().toString(36).slice(2)}`,
|
||||
sizeByte: 10,
|
||||
contentType: 'application/octet-stream',
|
||||
creatorId: owner.id,
|
||||
})
|
||||
return asset.id
|
||||
}
|
||||
|
||||
async function auditRows(action: AuditAction) {
|
||||
return prisma.auditLog.findMany({ where: { action, teamId }, orderBy: { id: 'asc' } })
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
owner = await prisma.user.create({
|
||||
data: { name: 'Owner', email: 'collab-owner@test.com', password: 'pw' },
|
||||
})
|
||||
reviewer = await prisma.user.create({
|
||||
data: { name: 'Reviewer', email: 'collab-reviewer@test.com', password: 'pw' },
|
||||
})
|
||||
outsider = await prisma.user.create({
|
||||
data: { name: 'Outsider', email: 'collab-outsider@test.com', password: 'pw' },
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 'Collab Team' } })
|
||||
teamId = team.id
|
||||
await prisma.teamMember.create({ data: { teamId, userId: owner.id, role: 'owner' } })
|
||||
await prisma.teamMember.create({ data: { teamId, userId: reviewer.id, role: 'reviewer' } })
|
||||
const project = await projectService.createProject(owner, { teamId, name: 'Collab Project' })
|
||||
projectId = project.id
|
||||
rootFolderId = project.rootFolder!
|
||||
})
|
||||
|
||||
describe('search_assets', () => {
|
||||
it('finds files by name in subfolders and pages through results', async () => {
|
||||
const sub = await runOperation(createFolderOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
name: 'shots',
|
||||
})
|
||||
await createFile('sunset-a.bin', sub.id)
|
||||
await createFile('sunset-b.bin', rootFolderId)
|
||||
await createFile('night.bin', rootFolderId)
|
||||
|
||||
const page1 = await runOperation(searchAssetsOp, as(reviewer), {
|
||||
parent: rootFolderId,
|
||||
query: 'sunset',
|
||||
first: 1,
|
||||
})
|
||||
expect(page1.total).toBe(2)
|
||||
expect(page1.data).toHaveLength(1)
|
||||
expect(page1.pageInfo.hasNextPage).toBe(true)
|
||||
|
||||
const page2 = await runOperation(searchAssetsOp, as(reviewer), {
|
||||
parent: rootFolderId,
|
||||
query: 'sunset',
|
||||
first: 1,
|
||||
after: page1.pageInfo.endCursor!,
|
||||
})
|
||||
const names = [...page1.data, ...page2.data].map((a) => a.name).sort()
|
||||
expect(names).toEqual(['sunset-a.bin', 'sunset-b.bin'])
|
||||
})
|
||||
|
||||
it('searches only the folder itself when recursive is false', async () => {
|
||||
const sub = await runOperation(createFolderOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
name: 'shots',
|
||||
})
|
||||
await createFile('sunset-a.bin', sub.id)
|
||||
|
||||
const result = await runOperation(searchAssetsOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
query: 'sunset',
|
||||
recursive: false,
|
||||
})
|
||||
expect(result.data).toEqual([])
|
||||
})
|
||||
|
||||
it('filters by metadata conditions', async () => {
|
||||
const field = await metadataService.createProjectField(projectId, {
|
||||
config: { name: 'Approved', type: 'toggle' },
|
||||
description: '',
|
||||
})
|
||||
const approved = await createFile('approved.bin')
|
||||
await createFile('pending.bin')
|
||||
await metadataService.updateAssetMetadata(approved, [{ key: field.key, value: true }])
|
||||
|
||||
const result = await runOperation(searchAssetsOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
conditions: [{ field: field.key, operator: 'eq', value: true }],
|
||||
})
|
||||
expect(result.data.map((a) => a.id)).toEqual([approved])
|
||||
})
|
||||
|
||||
it('reports an unsupported operator for a field as a bad request', async () => {
|
||||
await expect(
|
||||
runOperation(searchAssetsOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
conditions: [{ field: 'name', operator: 'gt', value: 'a' }],
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
})
|
||||
|
||||
it('rejects a non-member', async () => {
|
||||
await expect(
|
||||
runOperation(searchAssetsOp, as(outsider), { parent: rootFolderId, query: 'x' }),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('copy_assets', () => {
|
||||
it('copies assets, returns the copies in order, and audits each source', async () => {
|
||||
const dest = await runOperation(createFolderOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
name: 'dest',
|
||||
})
|
||||
const a = await createFile('a.bin')
|
||||
const b = await createFile('b.bin')
|
||||
|
||||
const result = await runOperation(copyAssetsOp, as(owner), {
|
||||
assetIds: [a, b],
|
||||
newParentId: dest.id,
|
||||
})
|
||||
|
||||
expect(result.newParentId).toBe(dest.id)
|
||||
expect(result.copiedAssetIds).toHaveLength(2)
|
||||
const copies = await prisma.asset.findMany({
|
||||
where: { id: { in: result.copiedAssetIds } },
|
||||
})
|
||||
const byId = new Map(copies.map((c) => [c.id, c]))
|
||||
expect(result.copiedAssetIds.map((id) => byId.get(id)?.name)).toEqual(['a.bin', 'b.bin'])
|
||||
expect(copies.every((c) => c.parentId === dest.id && c.creatorId === owner.id)).toBe(true)
|
||||
|
||||
const audits = await auditRows(AuditAction.asset_copy)
|
||||
expect(audits.map((r) => r.itemId).sort()).toEqual([a, b].sort())
|
||||
expect(audits.every((r) => r.teamId === teamId && r.projectId === projectId)).toBe(true)
|
||||
expect(audits.every((r) => r.via === 'mcp')).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects a reviewer without copying', async () => {
|
||||
const a = await createFile('a.bin')
|
||||
|
||||
await expect(
|
||||
runOperation(copyAssetsOp, as(reviewer), { assetIds: [a], newParentId: rootFolderId }),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
expect(await prisma.asset.count({ where: { name: 'a.bin', projectId } })).toBe(1)
|
||||
expect(await auditRows(AuditAction.asset_copy)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('reports copying a folder into itself as a bad request', async () => {
|
||||
const folder = await runOperation(createFolderOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
name: 'loop',
|
||||
})
|
||||
await expect(
|
||||
runOperation(copyAssetsOp, as(owner), { assetIds: [folder.id], newParentId: folder.id }),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('get_folder_instructions', () => {
|
||||
it("returns the folder's AGENTS.md, or null", async () => {
|
||||
const folder = await runOperation(createFolderOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
name: 'deliverables',
|
||||
})
|
||||
await expect(
|
||||
runOperation(getFolderInstructionsOp, as(reviewer), { folderId: folder.id }),
|
||||
).resolves.toEqual({ folderId: folder.id, content: null })
|
||||
|
||||
await assetService.updateAgentsMd(folder.id, '# Name files <shot>_v<n>')
|
||||
await expect(
|
||||
runOperation(getFolderInstructionsOp, as(reviewer), { folderId: folder.id }),
|
||||
).resolves.toEqual({ folderId: folder.id, content: '# Name files <shot>_v<n>' })
|
||||
})
|
||||
|
||||
it('rejects a file as a bad request and a non-member as forbidden', async () => {
|
||||
const file = await createFile('a.bin')
|
||||
await expect(
|
||||
runOperation(getFolderInstructionsOp, as(owner), { folderId: file }),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
await expect(
|
||||
runOperation(getFolderInstructionsOp, as(outsider), { folderId: rootFolderId }),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('comments', () => {
|
||||
it('lets a reviewer comment, reply, list, and resolve, with audit entries', async () => {
|
||||
const file = await createFile('cut.bin')
|
||||
|
||||
const comment = await runOperation(createCommentOp, as(reviewer), {
|
||||
assetId: file,
|
||||
message: 'Too dark at the start',
|
||||
second: 2.5,
|
||||
})
|
||||
expect(comment).toEqual({ id: expect.any(String), assetId: file, replyToId: null })
|
||||
|
||||
const reply = await runOperation(createCommentOp, as(owner, 'agent', undefined), {
|
||||
assetId: file,
|
||||
message: 'Brightened in v2',
|
||||
replyToId: comment.id,
|
||||
})
|
||||
expect(reply.replyToId).toBe(comment.id)
|
||||
|
||||
const listed = await runOperation(listCommentsOp, as(reviewer), { assetId: file })
|
||||
expect(listed.total).toBe(1)
|
||||
expect(listed.data).toEqual([
|
||||
expect.objectContaining({
|
||||
id: comment.id,
|
||||
message: 'Too dark at the start',
|
||||
author: { id: reviewer.id, name: 'Reviewer' },
|
||||
second: 2.5,
|
||||
resolved: false,
|
||||
replies: [
|
||||
expect.objectContaining({
|
||||
id: reply.id,
|
||||
message: 'Brightened in v2',
|
||||
author: { id: owner.id, name: 'Owner' },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
])
|
||||
|
||||
await expect(
|
||||
runOperation(resolveCommentOp, as(reviewer), { commentId: comment.id }),
|
||||
).resolves.toEqual({ commentId: comment.id, resolved: true })
|
||||
await expect(
|
||||
runOperation(resolveCommentOp, as(reviewer), { commentId: comment.id, reopen: true }),
|
||||
).resolves.toEqual({ commentId: comment.id, resolved: false })
|
||||
|
||||
const created = await auditRows(AuditAction.comment_create)
|
||||
expect(created.map((r) => r.itemId)).toEqual([comment.id, reply.id])
|
||||
expect(created.every((r) => r.teamId === teamId && r.projectId === projectId)).toBe(true)
|
||||
const completed = await auditRows(AuditAction.comment_complete)
|
||||
expect(completed).toHaveLength(2)
|
||||
expect(completed[0]).toMatchObject({ itemId: comment.id, userId: reviewer.id, via: 'mcp' })
|
||||
})
|
||||
|
||||
it('notifies the team about a new comment', async () => {
|
||||
const file = await createFile('cut.bin')
|
||||
await runOperation(createCommentOp, as(reviewer), { assetId: file, message: 'Nice' })
|
||||
|
||||
await expect
|
||||
.poll(() => prisma.notification.count({ where: { type: 'comment_created', teamId } }))
|
||||
.toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('does not start agent runs from comments written by the built-in agent', async () => {
|
||||
const file = await createFile('cut.bin')
|
||||
await runOperation(createCommentOp, as(owner, 'agent'), {
|
||||
assetId: file,
|
||||
message: '<@default> please review',
|
||||
})
|
||||
expect(await prisma.workflowTask.count({ where: { type: 'chat', projectId } })).toBe(0)
|
||||
|
||||
await runOperation(createCommentOp, as(owner, 'mcp'), {
|
||||
assetId: file,
|
||||
message: '<@default> please review',
|
||||
})
|
||||
expect(await prisma.workflowTask.count({ where: { type: 'chat', projectId } })).toBe(1)
|
||||
})
|
||||
|
||||
it('lists the comments of a version stack, counting them on its latest version', async () => {
|
||||
const v2 = await createFile('v2.bin')
|
||||
const v1 = await createFile('v1.bin')
|
||||
const stack = await runOperation(createVersionStackOp, as(owner), { fileIds: [v2, v1] })
|
||||
await runOperation(createCommentOp, as(owner), { assetId: stack.id, message: 'On v2' })
|
||||
|
||||
const listed = await runOperation(listCommentsOp, as(owner), { assetId: stack.id })
|
||||
expect(listed.data.map((c) => c.message)).toEqual(['On v2'])
|
||||
expect(listed.total).toBe(1)
|
||||
})
|
||||
|
||||
it('rejects commenting without access, and replies to threads the caller cannot see', async () => {
|
||||
const file = await createFile('cut.bin')
|
||||
await expect(
|
||||
runOperation(createCommentOp, as(outsider), { assetId: file, message: 'hi' }),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
expect(await prisma.assetComment.count({ where: { assetId: file } })).toBe(0)
|
||||
|
||||
// A thread in another team's project
|
||||
const otherTeam = await prisma.team.create({ data: { name: 'Other' } })
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: otherTeam.id, userId: outsider.id, role: 'owner' },
|
||||
})
|
||||
const otherProject = await projectService.createProject(outsider, {
|
||||
teamId: otherTeam.id,
|
||||
name: 'Other Project',
|
||||
})
|
||||
const otherFile = await assetService.createFile({
|
||||
parentId: otherProject.rootFolder!,
|
||||
name: 'secret.bin',
|
||||
key: 'files/test/secret.bin',
|
||||
sizeByte: 1,
|
||||
contentType: 'application/octet-stream',
|
||||
creatorId: outsider.id,
|
||||
})
|
||||
const otherThread = await runOperation(createCommentOp, as(outsider), {
|
||||
assetId: otherFile.id,
|
||||
message: 'private',
|
||||
})
|
||||
|
||||
await expect(
|
||||
runOperation(createCommentOp, as(owner), {
|
||||
assetId: file,
|
||||
message: 'sneaky',
|
||||
replyToId: otherThread.id,
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
expect(await prisma.assetComment.count({ where: { message: 'sneaky', assetId: file } })).toBe(
|
||||
0,
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects resolving a comment without access, and 404s an unknown one', async () => {
|
||||
const file = await createFile('cut.bin')
|
||||
const comment = await runOperation(createCommentOp, as(owner), {
|
||||
assetId: file,
|
||||
message: 'x',
|
||||
})
|
||||
await expect(
|
||||
runOperation(resolveCommentOp, as(outsider), { commentId: comment.id }),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
const row = await prisma.assetComment.findUniqueOrThrow({ where: { id: comment.id } })
|
||||
expect(row.isCompleted).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('metadata', () => {
|
||||
it('lists fields with choices and the Creation Context flag', async () => {
|
||||
const status = await metadataService.createProjectField(projectId, {
|
||||
config: {
|
||||
name: 'Review',
|
||||
type: 'select',
|
||||
select: { options: [{ id: 'approved', displayName: 'Approved', color: '#fff' }] },
|
||||
},
|
||||
description: 'Review status',
|
||||
})
|
||||
const prompt = await metadataService.createProjectField(projectId, {
|
||||
config: { name: 'Prompt', type: 'text', autofillSource: 'CREATION_CONTEXT' },
|
||||
description: '',
|
||||
})
|
||||
|
||||
const { fields } = await runOperation(listMetadataFieldsOp, as(reviewer), { projectId })
|
||||
|
||||
expect(fields).toContainEqual({
|
||||
key: status.key,
|
||||
name: 'Review',
|
||||
type: 'select',
|
||||
description: 'Review status',
|
||||
readOnly: false,
|
||||
creationContext: false,
|
||||
options: [{ id: 'approved', name: 'Approved' }],
|
||||
})
|
||||
expect(fields).toContainEqual(
|
||||
expect.objectContaining({ key: prompt.key, creationContext: true }),
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a non-member listing fields', async () => {
|
||||
await expect(
|
||||
runOperation(listMetadataFieldsOp, as(outsider), { projectId }),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
})
|
||||
|
||||
it('sets values, adds a new select option, and audits a file update', async () => {
|
||||
const review = await metadataService.createProjectField(projectId, {
|
||||
config: { name: 'Review', type: 'select', select: { options: [] } },
|
||||
description: '',
|
||||
})
|
||||
const notes = await metadataService.createProjectField(projectId, {
|
||||
config: { name: 'Notes', type: 'text' },
|
||||
description: '',
|
||||
})
|
||||
const file = await createFile('a.bin')
|
||||
|
||||
const result = await runOperation(updateAssetMetadataOp, as(owner, 'agent', undefined), {
|
||||
assetId: file,
|
||||
values: { [review.key]: { newOption: { value: 'Approved' } }, [notes.key]: 'Looks good' },
|
||||
})
|
||||
|
||||
expect(result).toEqual({ assetId: file, updatedKeys: [review.key, notes.key] })
|
||||
const values = await prisma.assetMetadataValue.findMany({ where: { assetId: file } })
|
||||
expect(values.find((v) => v.fieldKey === review.key)?.stringValue).toBe('approved')
|
||||
expect(values.find((v) => v.fieldKey === notes.key)?.stringValue).toBe('Looks good')
|
||||
|
||||
const [audit] = await auditRows(AuditAction.file_update)
|
||||
expect(audit).toMatchObject({ itemId: file, teamId, projectId, via: 'agent' })
|
||||
})
|
||||
|
||||
it('rejects unknown and read-only fields before writing anything', async () => {
|
||||
const notes = await metadataService.createProjectField(projectId, {
|
||||
config: { name: 'Notes', type: 'text' },
|
||||
description: '',
|
||||
})
|
||||
await prisma.metadataField.update({ where: { key: notes.key }, data: { readOnly: true } })
|
||||
const file = await createFile('a.bin')
|
||||
|
||||
await expect(
|
||||
runOperation(updateAssetMetadataOp, as(owner), {
|
||||
assetId: file,
|
||||
values: { nope: 'x' },
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
await expect(
|
||||
runOperation(updateAssetMetadataOp, as(owner), {
|
||||
assetId: file,
|
||||
values: { [notes.key]: 'x' },
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 422 })
|
||||
expect(await prisma.assetMetadataValue.count({ where: { assetId: file } })).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects a reviewer without writing', async () => {
|
||||
const notes = await metadataService.createProjectField(projectId, {
|
||||
config: { name: 'Notes', type: 'text' },
|
||||
description: '',
|
||||
})
|
||||
const file = await createFile('a.bin')
|
||||
|
||||
await expect(
|
||||
runOperation(updateAssetMetadataOp, as(reviewer), {
|
||||
assetId: file,
|
||||
values: { [notes.key]: 'x' },
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
expect(await prisma.assetMetadataValue.count({ where: { assetId: file } })).toBe(0)
|
||||
expect(await auditRows(AuditAction.file_update)).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('version stacks', () => {
|
||||
it('stacks files, lists versions latest first, and unstacks one', async () => {
|
||||
const v2 = await createFile('cut_v2.bin')
|
||||
const v1 = await createFile('cut_v1.bin')
|
||||
|
||||
const stack = await runOperation(createVersionStackOp, as(owner), { fileIds: [v2, v1] })
|
||||
expect(stack).toMatchObject({ type: 'version_stack', projectId })
|
||||
|
||||
const { versions } = await runOperation(listVersionsOp, as(reviewer), { stackId: stack.id })
|
||||
expect(versions.map((v) => [v.id, v.version, v.current])).toEqual([
|
||||
[v2, 2, true],
|
||||
[v1, 1, false],
|
||||
])
|
||||
|
||||
await expect(runOperation(removeVersionOp, as(owner), { versionId: v1 })).resolves.toEqual({
|
||||
versionId: v1,
|
||||
stackId: stack.id,
|
||||
})
|
||||
const removed = await prisma.asset.findUniqueOrThrow({ where: { id: v1 } })
|
||||
expect(removed.parentId).toBe(rootFolderId)
|
||||
expect(removed.isDeleted).toBe(false)
|
||||
|
||||
const [created] = await auditRows(AuditAction.version_stack_create)
|
||||
expect(created).toMatchObject({ itemId: stack.id, teamId, projectId, via: 'mcp' })
|
||||
const [updated] = await auditRows(AuditAction.version_stack_update)
|
||||
expect(updated).toMatchObject({ itemId: stack.id, teamId, projectId })
|
||||
})
|
||||
|
||||
it('rejects stacking files from different folders as a bad request', async () => {
|
||||
const sub = await runOperation(createFolderOp, as(owner), { parent: rootFolderId, name: 's' })
|
||||
const a = await createFile('a.bin')
|
||||
const b = await createFile('b.bin', sub.id)
|
||||
|
||||
await expect(
|
||||
runOperation(createVersionStackOp, as(owner), { fileIds: [a, b] }),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
expect(await prisma.asset.count({ where: { type: 'version_stack', projectId } })).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects a reviewer stacking or unstacking without changes', async () => {
|
||||
const v2 = await createFile('v2.bin')
|
||||
const v1 = await createFile('v1.bin')
|
||||
|
||||
await expect(
|
||||
runOperation(createVersionStackOp, as(reviewer), { fileIds: [v2, v1] }),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
expect(await prisma.asset.count({ where: { type: 'version_stack', projectId } })).toBe(0)
|
||||
|
||||
const stack = await runOperation(createVersionStackOp, as(owner), { fileIds: [v2, v1] })
|
||||
await expect(
|
||||
runOperation(removeVersionOp, as(reviewer), { versionId: v1 }),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
const row = await prisma.asset.findUniqueOrThrow({ where: { id: v1 } })
|
||||
expect(row.parentId).toBe(stack.id)
|
||||
})
|
||||
|
||||
it('reports a file outside a stack and a non-stack as bad requests', async () => {
|
||||
const file = await createFile('lonely.bin')
|
||||
await expect(
|
||||
runOperation(removeVersionOp, as(owner), { versionId: file }),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
await expect(
|
||||
runOperation(listVersionsOp, as(owner), { stackId: file }),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import { createComment } from '@shumai/operations'
|
||||
import { AuditAction } from '@shumai/dtos'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { commentService } from '@shumai/core/src/comment/comment'
|
||||
import { implementOperation } from '../implement'
|
||||
|
||||
export const createCommentOp = implementOperation(createComment, {
|
||||
// Commenting needs Read on the file, as in the web app; a reply also needs access to the
|
||||
// thread it replies to.
|
||||
authz: (input) => [
|
||||
{ permission: Permission.Read, type: ResourceType.Asset, id: input.assetId },
|
||||
...(input.replyToId
|
||||
? [{ permission: Permission.Read, type: ResourceType.Comment, id: input.replyToId }]
|
||||
: []),
|
||||
],
|
||||
execute: async (input, ctx) => {
|
||||
const comment = await commentService.postComment({
|
||||
assetId: input.assetId,
|
||||
userId: ctx.userId,
|
||||
message: input.message,
|
||||
replyToId: input.replyToId,
|
||||
second: input.second,
|
||||
// Mentions in comments written by Shumai's own agent must not start more agent runs.
|
||||
triggerAgents: ctx.via !== 'agent',
|
||||
})
|
||||
return { id: comment.id, assetId: comment.assetId, replyToId: input.replyToId ?? null }
|
||||
},
|
||||
audit: (input, output) => [
|
||||
{ action: AuditAction.comment_create, itemId: output.id, contextAssetId: input.assetId },
|
||||
],
|
||||
})
|
||||
@@ -0,0 +1,47 @@
|
||||
import { DEFAULT_PAGE_SIZE, listComments, type CommentThread } from '@shumai/operations'
|
||||
import type { CommentInfo } from '@shumai/dtos'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { implementOperation } from '../implement'
|
||||
|
||||
/** Placeholder reply that anchors an agent chat session to a thread; not a real comment. */
|
||||
const CHAT_PLACEHOLDER = '__CHAT__'
|
||||
|
||||
function toCommentFields(comment: CommentInfo) {
|
||||
return {
|
||||
id: comment.id,
|
||||
message: comment.message ?? '',
|
||||
author: { id: comment.creator.id, name: comment.creator.name },
|
||||
second: comment.second,
|
||||
hasMarkup: Array.isArray(comment.annotations) && comment.annotations.length > 0,
|
||||
attachmentCount: comment.attachments.length,
|
||||
createdAt: comment.createdAt,
|
||||
}
|
||||
}
|
||||
|
||||
export function toCommentThread(comment: CommentInfo): CommentThread {
|
||||
return {
|
||||
...toCommentFields(comment),
|
||||
resolved: comment.isCompleted,
|
||||
replies: comment.replies.filter((r) => r.message !== CHAT_PLACEHOLDER).map(toCommentFields),
|
||||
}
|
||||
}
|
||||
|
||||
export const listCommentsOp = implementOperation(listComments, {
|
||||
authz: (input) => [{ permission: Permission.Read, type: ResourceType.Asset, id: input.assetId }],
|
||||
execute: async (input, ctx) => {
|
||||
const result = await assetService.listComments(
|
||||
input.assetId,
|
||||
{ first: input.first ?? DEFAULT_PAGE_SIZE, after: input.after },
|
||||
ctx.userId,
|
||||
)
|
||||
return {
|
||||
data: result.data.map(toCommentThread),
|
||||
pageInfo: {
|
||||
hasNextPage: Boolean(result.pageInfo.cursor),
|
||||
endCursor: result.pageInfo.cursor ?? null,
|
||||
},
|
||||
total: result.pageInfo.total ?? result.data.length,
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { resolveComment } from '@shumai/operations'
|
||||
import { AuditAction } from '@shumai/dtos'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { implementOperation } from '../implement'
|
||||
|
||||
export const resolveCommentOp = implementOperation(resolveComment, {
|
||||
authz: (input) => [
|
||||
{ permission: Permission.Read, type: ResourceType.Comment, id: input.commentId },
|
||||
],
|
||||
// The comment's file, for the audit entry.
|
||||
prepare: async (input) => {
|
||||
const comment = await assetService.getComment(input.commentId).catch(() => null)
|
||||
if (!comment) throw new HTTPException(404, { message: 'Comment not found' })
|
||||
return { assetId: comment.assetId }
|
||||
},
|
||||
execute: async (input, ctx) => {
|
||||
const updated = await assetService.completeComment(input.commentId, !input.reopen, ctx.userId)
|
||||
return { commentId: updated.id, resolved: updated.isCompleted }
|
||||
},
|
||||
audit: (input, _output, _ctx, comment) => [
|
||||
{
|
||||
action: AuditAction.comment_complete,
|
||||
itemId: input.commentId,
|
||||
contextAssetId: comment.assetId,
|
||||
},
|
||||
],
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
|
||||
/**
|
||||
* Runs a service call whose plain `Error`s describe invalid input (e.g. "file is not in the
|
||||
* stack") and reports them as 400 Bad Request instead of a server error. Other errors, such as
|
||||
* `HTTPException`s and database errors, pass through unchanged.
|
||||
*/
|
||||
export async function asBadRequest<T>(fn: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await fn()
|
||||
} catch (err) {
|
||||
if (err instanceof Error && err.constructor === Error) {
|
||||
throw new HTTPException(400, { message: err.message })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
/** A 400 Bad Request with a message for the caller. */
|
||||
export function badRequest(message: string): HTTPException {
|
||||
return new HTTPException(400, { message })
|
||||
}
|
||||
@@ -10,9 +10,11 @@ export {
|
||||
} from './implement'
|
||||
export { runOperation } from './run'
|
||||
export { getOperation, getOperationsForSurface, operations } from './registry'
|
||||
export { copyAssetsOp } from './asset/copy-assets'
|
||||
export { createFolderOp } from './asset/create-folder'
|
||||
export { deleteAssetOp } from './asset/delete-asset'
|
||||
export { downloadAssetOp } from './asset/download-asset'
|
||||
export { getFolderInstructionsOp } from './asset/get-folder-instructions'
|
||||
export { listAssetsOp } from './asset/list-assets'
|
||||
export { moveAssetsOp } from './asset/move-assets'
|
||||
export {
|
||||
@@ -22,4 +24,16 @@ export {
|
||||
waitBudgetMs,
|
||||
} from './asset/read-asset'
|
||||
export { renameAssetOp } from './asset/rename-asset'
|
||||
export { searchAssetsOp } from './asset/search-assets'
|
||||
export { createCommentOp } from './comment/create-comment'
|
||||
export { listCommentsOp } from './comment/list-comments'
|
||||
export { resolveCommentOp } from './comment/resolve-comment'
|
||||
export { listMetadataFieldsOp } from './metadata/list-metadata-fields'
|
||||
export { updateAssetMetadataOp } from './metadata/update-asset-metadata'
|
||||
export { listProjectsOp } from './project/list-projects'
|
||||
export { completeUploadOp } from './upload/complete-upload'
|
||||
export { createFileOp } from './upload/create-file'
|
||||
export { createVersionOp } from './upload/create-version'
|
||||
export { createVersionStackOp } from './version/create-version-stack'
|
||||
export { listVersionsOp } from './version/list-versions'
|
||||
export { removeVersionOp } from './version/remove-version'
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { listMetadataFields, type MetadataFieldSummary } from '@shumai/operations'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { implementOperation } from '../implement'
|
||||
|
||||
interface FieldRecord {
|
||||
key: string
|
||||
readOnly: boolean
|
||||
description: string | null
|
||||
config: PrismaJson.FieldConfig | null
|
||||
}
|
||||
|
||||
export function toMetadataFieldSummary(field: FieldRecord): MetadataFieldSummary {
|
||||
const config = field.config
|
||||
const choices =
|
||||
config?.type === 'select'
|
||||
? config.select?.options
|
||||
: config?.type === 'selectMulti'
|
||||
? config.selectMulti?.options
|
||||
: undefined
|
||||
return {
|
||||
key: field.key,
|
||||
name: config?.name ?? field.key,
|
||||
type: config?.type ?? 'text',
|
||||
description: field.description ?? '',
|
||||
readOnly: field.readOnly,
|
||||
creationContext: config?.autofillSource === 'CREATION_CONTEXT',
|
||||
...(choices ? { options: choices.map((o) => ({ id: o.id, name: o.displayName })) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
export const listMetadataFieldsOp = implementOperation(listMetadataFields, {
|
||||
authz: (input) => [
|
||||
{ permission: Permission.Read, type: ResourceType.Project, id: input.projectId },
|
||||
],
|
||||
execute: async (input, ctx) => {
|
||||
const fields = await metadataService.listProjectFields(ctx.userId, input.projectId)
|
||||
return { fields: fields.map((f) => toMetadataFieldSummary(f.field)) }
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { updateAssetMetadata } from '@shumai/operations'
|
||||
import { AuditAction } from '@shumai/dtos'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { notificationService } from '@shumai/core/src/notification/notification'
|
||||
import { asBadRequest, badRequest } from '../errors'
|
||||
import { implementOperation } from '../implement'
|
||||
|
||||
export const updateAssetMetadataOp = implementOperation(updateAssetMetadata, {
|
||||
authz: (input) => [{ permission: Permission.Edit, type: ResourceType.Asset, id: input.assetId }],
|
||||
// Check every key before writing anything: unknown keys would otherwise fail halfway.
|
||||
prepare: async (input) => {
|
||||
const keys = Object.keys(input.values)
|
||||
if (keys.length === 0) throw badRequest('values must set at least one field')
|
||||
|
||||
const asset = await assetService.getAssetMeta(input.assetId)
|
||||
if (!asset.projectId) throw badRequest('This asset does not belong to a project')
|
||||
|
||||
const fields = new Map(
|
||||
(await metadataService.listProjectFields(null, asset.projectId)).map((f) => [
|
||||
f.field.key,
|
||||
f.field,
|
||||
]),
|
||||
)
|
||||
const unknown = keys.filter((key) => !fields.has(key))
|
||||
if (unknown.length > 0) {
|
||||
throw badRequest(
|
||||
`Unknown metadata field(s): ${unknown.join(', ')}. Use list_metadata_fields to get the field keys.`,
|
||||
)
|
||||
}
|
||||
const readOnly = keys.filter((key) => fields.get(key)?.readOnly)
|
||||
if (readOnly.length > 0) {
|
||||
throw new HTTPException(422, { message: `Field ${readOnly.join(', ')} is read-only` })
|
||||
}
|
||||
return asset
|
||||
},
|
||||
execute: async (input, ctx, asset) => {
|
||||
const updates = Object.entries(input.values).map(([key, value]) => ({ key, value }))
|
||||
await asBadRequest(() => metadataService.updateAssetMetadata(input.assetId, updates))
|
||||
|
||||
if ('status' in input.values) {
|
||||
await notificationService.create({
|
||||
type: 'metadata_field_updated_status',
|
||||
teamId: asset.teamId,
|
||||
creatorId: ctx.userId,
|
||||
assetId: input.assetId,
|
||||
})
|
||||
}
|
||||
return { assetId: input.assetId, updatedKeys: updates.map((u) => u.key) }
|
||||
},
|
||||
audit: (input, _output, _ctx, asset) => [
|
||||
{
|
||||
action: asset.type === 'folder' ? AuditAction.folder_update : AuditAction.file_update,
|
||||
itemId: input.assetId,
|
||||
teamId: asset.teamId,
|
||||
projectId: asset.projectId,
|
||||
},
|
||||
],
|
||||
})
|
||||
@@ -285,6 +285,7 @@ describe('asset and project Operations', () => {
|
||||
id: folder.id,
|
||||
name: 'meta',
|
||||
type: 'folder',
|
||||
parentId: rootFolderId,
|
||||
teamId,
|
||||
projectId,
|
||||
})
|
||||
|
||||
@@ -1,13 +1,27 @@
|
||||
import type { OperationName, Surface } from '@shumai/operations'
|
||||
import { copyAssetsOp } from './asset/copy-assets'
|
||||
import { createFolderOp } from './asset/create-folder'
|
||||
import { deleteAssetOp } from './asset/delete-asset'
|
||||
import { downloadAssetOp } from './asset/download-asset'
|
||||
import { getFolderInstructionsOp } from './asset/get-folder-instructions'
|
||||
import { listAssetsOp } from './asset/list-assets'
|
||||
import { moveAssetsOp } from './asset/move-assets'
|
||||
import { getAssetRenderOp, readAssetOp } from './asset/read-asset'
|
||||
import { renameAssetOp } from './asset/rename-asset'
|
||||
import { searchAssetsOp } from './asset/search-assets'
|
||||
import { createCommentOp } from './comment/create-comment'
|
||||
import { listCommentsOp } from './comment/list-comments'
|
||||
import { resolveCommentOp } from './comment/resolve-comment'
|
||||
import type { Operation } from './implement'
|
||||
import { listMetadataFieldsOp } from './metadata/list-metadata-fields'
|
||||
import { updateAssetMetadataOp } from './metadata/update-asset-metadata'
|
||||
import { listProjectsOp } from './project/list-projects'
|
||||
import { completeUploadOp } from './upload/complete-upload'
|
||||
import { createFileOp } from './upload/create-file'
|
||||
import { createVersionOp } from './upload/create-version'
|
||||
import { createVersionStackOp } from './version/create-version-stack'
|
||||
import { listVersionsOp } from './version/list-versions'
|
||||
import { removeVersionOp } from './version/remove-version'
|
||||
|
||||
type ImplementedName<TOps extends readonly Operation[]> = TOps[number]['definition']['name']
|
||||
type MissingNames<TOps extends readonly Operation[]> = Exclude<OperationName, ImplementedName<TOps>>
|
||||
@@ -29,13 +43,27 @@ function defineRegistry<const TOps extends readonly Operation[]>(
|
||||
export const operations = defineRegistry([
|
||||
listProjectsOp,
|
||||
listAssetsOp,
|
||||
searchAssetsOp,
|
||||
createFolderOp,
|
||||
renameAssetOp,
|
||||
moveAssetsOp,
|
||||
copyAssetsOp,
|
||||
deleteAssetOp,
|
||||
readAssetOp,
|
||||
getAssetRenderOp,
|
||||
downloadAssetOp,
|
||||
getFolderInstructionsOp,
|
||||
createFileOp,
|
||||
createVersionOp,
|
||||
completeUploadOp,
|
||||
listCommentsOp,
|
||||
createCommentOp,
|
||||
resolveCommentOp,
|
||||
listMetadataFieldsOp,
|
||||
updateAssetMetadataOp,
|
||||
createVersionStackOp,
|
||||
listVersionsOp,
|
||||
removeVersionOp,
|
||||
] as const)
|
||||
|
||||
const operationsByName = new Map<string, Operation>()
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { prisma, type User } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { AuditAction } from '@shumai/dtos'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { projectService } from '@shumai/core/src/project/project'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { pendingUploadService } from '@shumai/core/src/upload/pending-upload'
|
||||
import { completeUploadOp, createFileOp, createFolderOp, createVersionOp } from './index'
|
||||
import { runOperation } from './run'
|
||||
import type { OperationContext } from './context'
|
||||
|
||||
/** Real-database and real-storage tests for create_file, create_version, and complete_upload. */
|
||||
describe('upload Operations', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
const bucket = 'shumai-test-upload-ops'
|
||||
const originalBucket = process.env.S3_BUCKET
|
||||
|
||||
let owner: User
|
||||
let reviewer: User
|
||||
let teamId: string
|
||||
let projectId: string
|
||||
let rootFolderId: string
|
||||
|
||||
const as = (user: User, via: OperationContext['via'] = 'mcp', agentId?: string) => ({
|
||||
userId: user.id,
|
||||
via,
|
||||
agentId,
|
||||
})
|
||||
|
||||
/** Uploads bytes the way a client would after create_file / create_version. */
|
||||
async function upload(uploadId: string, user: User, content = 'hello world') {
|
||||
const { key } = pendingUploadService.read(uploadId, user.id)
|
||||
await s3Service.putObject(bucket, key, Buffer.from(content), Buffer.byteLength(content))
|
||||
return key
|
||||
}
|
||||
|
||||
async function auditRows(action: AuditAction) {
|
||||
return prisma.auditLog.findMany({ where: { action, teamId }, orderBy: { id: 'asc' } })
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.S3_BUCKET = bucket
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
if (originalBucket === undefined) delete process.env.S3_BUCKET
|
||||
else process.env.S3_BUCKET = originalBucket
|
||||
await s3Service.deletePrefix(bucket, '').catch(() => undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
beforeEach(async () => {
|
||||
owner = await prisma.user.create({
|
||||
data: { name: 'Owner', email: 'upload-owner@test.com', password: 'pw' },
|
||||
})
|
||||
reviewer = await prisma.user.create({
|
||||
data: { name: 'Reviewer', email: 'upload-reviewer@test.com', password: 'pw' },
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 'Upload Team' } })
|
||||
teamId = team.id
|
||||
await prisma.teamMember.create({ data: { teamId, userId: owner.id, role: 'owner' } })
|
||||
await prisma.teamMember.create({ data: { teamId, userId: reviewer.id, role: 'reviewer' } })
|
||||
const project = await projectService.createProject(owner, { teamId, name: 'Upload Project' })
|
||||
projectId = project.id
|
||||
rootFolderId = project.rootFolder!
|
||||
})
|
||||
|
||||
describe('create_file + complete_upload', () => {
|
||||
it('creates nothing until the upload completes, then creates the file once', async () => {
|
||||
const started = await runOperation(createFileOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
name: 'notes.bin',
|
||||
})
|
||||
|
||||
expect(started).toEqual({
|
||||
uploadId: expect.any(String),
|
||||
uploadUrl: expect.stringContaining('/api/upload/local?'),
|
||||
method: 'PUT',
|
||||
expiresAt: expect.any(String),
|
||||
})
|
||||
expect(new Date(started.expiresAt).getTime()).toBeGreaterThan(Date.now())
|
||||
expect(await prisma.asset.count({ where: { name: 'notes.bin', projectId } })).toBe(0)
|
||||
|
||||
// Completing before the bytes are uploaded fails and can be retried
|
||||
await expect(
|
||||
runOperation(completeUploadOp, as(owner), { uploadId: started.uploadId }),
|
||||
).rejects.toMatchObject({ status: 409 })
|
||||
|
||||
const key = await upload(started.uploadId, owner)
|
||||
const file = await runOperation(completeUploadOp, as(owner), {
|
||||
uploadId: started.uploadId,
|
||||
})
|
||||
|
||||
expect(file).toEqual({
|
||||
id: expect.any(String),
|
||||
name: 'notes.bin',
|
||||
type: 'file',
|
||||
size: 11,
|
||||
projectId,
|
||||
})
|
||||
const row = await prisma.asset.findUniqueOrThrow({
|
||||
where: { id: file.id },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
expect(row).toMatchObject({ parentId: rootFolderId, creatorId: owner.id })
|
||||
expect(row.storageKey?.key).toBe(key)
|
||||
|
||||
const [audit] = await auditRows(AuditAction.file_create)
|
||||
expect(audit).toMatchObject({ itemId: file.id, teamId, projectId, via: 'mcp' })
|
||||
|
||||
// Completing again returns the same file without another asset or audit entry
|
||||
const again = await runOperation(completeUploadOp, as(owner), {
|
||||
uploadId: started.uploadId,
|
||||
})
|
||||
expect(again.id).toBe(file.id)
|
||||
expect(await prisma.asset.count({ where: { name: 'notes.bin', projectId } })).toBe(1)
|
||||
expect(await auditRows(AuditAction.file_create)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('records Creation Context metadata and attributes the file to the agent', async () => {
|
||||
const prompt = await metadataService.createProjectField(projectId, {
|
||||
config: { name: 'Prompt', type: 'text', autofillSource: 'CREATION_CONTEXT' },
|
||||
description: '',
|
||||
})
|
||||
const agentUser = await prisma.user.create({
|
||||
data: { name: 'Bot', type: 'agent', email: 'upload-bot@test.com' },
|
||||
})
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: agentUser.id,
|
||||
teamId,
|
||||
type: 'chat',
|
||||
config: { provider: 'test', model: 'test' },
|
||||
},
|
||||
})
|
||||
|
||||
const started = await runOperation(createFileOp, as(owner, 'agent', agent.id), {
|
||||
parent: rootFolderId,
|
||||
name: 'gen.bin',
|
||||
metadata: { [prompt.key]: 'a red fox' },
|
||||
})
|
||||
// The built-in agent writes straight to storage, so it gets the key
|
||||
expect(started.key).toMatch(/^files\/.+\/gen\.bin$/)
|
||||
|
||||
await upload(started.uploadId, owner)
|
||||
const file = await runOperation(completeUploadOp, as(owner, 'agent', agent.id), {
|
||||
uploadId: started.uploadId,
|
||||
})
|
||||
|
||||
const row = await prisma.asset.findUniqueOrThrow({ where: { id: file.id } })
|
||||
expect(row.agentId).toBe(agent.id)
|
||||
const value = await prisma.assetMetadataValue.findFirstOrThrow({
|
||||
where: { assetId: file.id, fieldKey: prompt.key },
|
||||
})
|
||||
expect(value.stringValue).toBe('a red fox')
|
||||
const [audit] = await auditRows(AuditAction.file_create)
|
||||
expect(audit).toMatchObject({ itemId: file.id, agentId: agent.id, via: 'agent' })
|
||||
})
|
||||
|
||||
it('rejects metadata that is not a Creation Context field before uploading', async () => {
|
||||
const notes = await metadataService.createProjectField(projectId, {
|
||||
config: { name: 'Notes', type: 'text' },
|
||||
description: '',
|
||||
})
|
||||
|
||||
await expect(
|
||||
runOperation(createFileOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
name: 'a.bin',
|
||||
metadata: { [notes.key]: 'x' },
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 400, message: expect.stringContaining(notes.key) })
|
||||
})
|
||||
|
||||
it('rejects a parent that is not a folder', async () => {
|
||||
const started = await runOperation(createFileOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
name: 'a.bin',
|
||||
})
|
||||
await upload(started.uploadId, owner)
|
||||
const file = await runOperation(completeUploadOp, as(owner), { uploadId: started.uploadId })
|
||||
|
||||
await expect(
|
||||
runOperation(createFileOp, as(owner), { parent: file.id, name: 'b.bin' }),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
})
|
||||
|
||||
it('rejects a reviewer without starting an upload', async () => {
|
||||
const presign = vi.spyOn(s3Service, 'presign')
|
||||
await expect(
|
||||
runOperation(createFileOp, as(reviewer), { parent: rootFolderId, name: 'nope.bin' }),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
expect(presign).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('stops an upload if the user lost access before completing it', async () => {
|
||||
const folder = await runOperation(createFolderOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
name: 'inbox',
|
||||
})
|
||||
const editor = await prisma.user.create({
|
||||
data: { name: 'Editor', email: 'upload-editor@test.com', password: 'pw' },
|
||||
})
|
||||
await prisma.teamMember.create({ data: { teamId, userId: editor.id, role: 'editor' } })
|
||||
const started = await runOperation(createFileOp, as(editor), {
|
||||
parent: folder.id,
|
||||
name: 'late.bin',
|
||||
})
|
||||
await upload(started.uploadId, editor)
|
||||
|
||||
await prisma.teamMember.update({
|
||||
where: { teamIdUserId: { teamId, userId: editor.id } },
|
||||
data: { role: 'reviewer' },
|
||||
})
|
||||
|
||||
await expect(
|
||||
runOperation(completeUploadOp, as(editor), { uploadId: started.uploadId }),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
expect(await prisma.asset.count({ where: { name: 'late.bin', projectId } })).toBe(0)
|
||||
})
|
||||
|
||||
it('only lets the user who started an upload complete it', async () => {
|
||||
const started = await runOperation(createFileOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
name: 'mine.bin',
|
||||
})
|
||||
await upload(started.uploadId, owner)
|
||||
|
||||
await expect(
|
||||
runOperation(completeUploadOp, as(reviewer), { uploadId: started.uploadId }),
|
||||
).rejects.toMatchObject({ status: 403 })
|
||||
expect(await prisma.asset.count({ where: { name: 'mine.bin', projectId } })).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects a tampered or expired upload ID', async () => {
|
||||
const started = await runOperation(createFileOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
name: 'a.bin',
|
||||
})
|
||||
const [payload, signature] = started.uploadId.split('.')
|
||||
const forged = Buffer.from(
|
||||
JSON.stringify({
|
||||
...JSON.parse(Buffer.from(payload, 'base64url').toString()),
|
||||
parentId: 'elsewhere',
|
||||
}),
|
||||
).toString('base64url')
|
||||
|
||||
await expect(
|
||||
runOperation(completeUploadOp, as(owner), { uploadId: `${forged}.${signature}` }),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
await expect(
|
||||
runOperation(completeUploadOp, as(owner), { uploadId: 'not-an-upload' }),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
|
||||
vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 2 * 60 * 60 * 1000)
|
||||
await expect(
|
||||
runOperation(completeUploadOp, as(owner), { uploadId: started.uploadId }),
|
||||
).rejects.toMatchObject({ status: 400, message: expect.stringContaining('expired') })
|
||||
})
|
||||
})
|
||||
|
||||
describe('create_version + complete_upload', () => {
|
||||
it('adds the upload as the current version of a file', async () => {
|
||||
const first = await runOperation(createFileOp, as(owner), {
|
||||
parent: rootFolderId,
|
||||
name: 'cut_v1.bin',
|
||||
})
|
||||
await upload(first.uploadId, owner)
|
||||
const v1 = await runOperation(completeUploadOp, as(owner), { uploadId: first.uploadId })
|
||||
|
||||
const second = await runOperation(createVersionOp, as(owner), {
|
||||
parent: v1.id,
|
||||
name: 'cut_v2.bin',
|
||||
})
|
||||
await upload(second.uploadId, owner, 'version two')
|
||||
const v2 = await runOperation(completeUploadOp, as(owner), { uploadId: second.uploadId })
|
||||
|
||||
expect(v2).toMatchObject({ name: 'cut_v2.bin', type: 'file', size: 11 })
|
||||
const stackId = (await prisma.asset.findUniqueOrThrow({ where: { id: v2.id } })).parentId!
|
||||
const stack = await prisma.asset.findUniqueOrThrow({ where: { id: stackId } })
|
||||
expect(stack.type).toBe('version_stack')
|
||||
expect(await assetService.resolveLatestVersionId(stackId)).toBe(v2.id)
|
||||
expect(await auditRows(AuditAction.file_create)).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('rejects a folder as the parent', async () => {
|
||||
await expect(
|
||||
runOperation(createVersionOp, as(owner), { parent: rootFolderId, name: 'v.bin' }),
|
||||
).rejects.toMatchObject({ status: 400 })
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { completeUpload } from '@shumai/operations'
|
||||
import { AuditAction } from '@shumai/dtos'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { pendingUploadService } from '@shumai/core/src/upload/pending-upload'
|
||||
import { asBadRequest } from '../errors'
|
||||
import { implementOperation } from '../implement'
|
||||
import { toAssetSummary } from '../asset/to-asset-summary'
|
||||
|
||||
export const completeUploadOp = implementOperation(completeUpload, {
|
||||
// The upload ID is signed and names its parent; Edit on it is still checked here, so
|
||||
// losing access between starting and finishing an upload stops it.
|
||||
authz: (input, ctx) => {
|
||||
const pending = pendingUploadService.read(input.uploadId, ctx.userId)
|
||||
return [{ permission: Permission.Edit, type: ResourceType.Asset, id: pending.parentId }]
|
||||
},
|
||||
prepare: async (input, ctx) => {
|
||||
const pending = pendingUploadService.read(input.uploadId, ctx.userId)
|
||||
// Completing the same upload again returns the file it already created.
|
||||
const existing = await assetService.findAssetByStorageKey(pending.key)
|
||||
if (existing && existing.creatorId !== ctx.userId) {
|
||||
throw new HTTPException(409, { message: 'This upload was already used.' })
|
||||
}
|
||||
return { pending, existingId: existing?.id }
|
||||
},
|
||||
execute: async (_input, ctx, { pending, existingId }) => {
|
||||
if (existingId) {
|
||||
return toAssetSummary(await assetService.getAsset({ assetId: existingId }))
|
||||
}
|
||||
|
||||
const size = await pendingUploadService.uploadedSize(pending.key)
|
||||
if (size === null) {
|
||||
throw new HTTPException(409, {
|
||||
message:
|
||||
'The file has not been uploaded yet: PUT its bytes to uploadUrl first, then call complete_upload again.',
|
||||
})
|
||||
}
|
||||
|
||||
const params = {
|
||||
parentId: pending.parentId,
|
||||
name: pending.name,
|
||||
key: pending.key,
|
||||
sizeByte: size,
|
||||
contentType: pending.contentType,
|
||||
creatorId: ctx.userId,
|
||||
agentId: ctx.agentId,
|
||||
metadata: pending.metadata,
|
||||
}
|
||||
const asset = await asBadRequest(() =>
|
||||
pending.kind === 'file'
|
||||
? assetService.createFile(params)
|
||||
: assetService.createVersion(params),
|
||||
)
|
||||
return toAssetSummary(asset)
|
||||
},
|
||||
audit: (_input, output, _ctx, { existingId }) =>
|
||||
existingId
|
||||
? []
|
||||
: [{ action: AuditAction.file_create, itemId: output.id, contextAssetId: output.id }],
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
import { createFile } from '@shumai/operations'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { badRequest } from '../errors'
|
||||
import { implementOperation } from '../implement'
|
||||
import { assertCreationMetadata, startUpload } from './start-upload'
|
||||
|
||||
export const createFileOp = implementOperation(createFile, {
|
||||
authz: (input) => [{ permission: Permission.Edit, type: ResourceType.Asset, id: input.parent }],
|
||||
prepare: async (input, ctx) => {
|
||||
const parent = await assetService.getAssetMeta(input.parent)
|
||||
if (parent.type !== 'folder' && parent.type !== 'root') {
|
||||
throw badRequest(
|
||||
'parent must be a folder. To upload a new version of a file, use create_version.',
|
||||
)
|
||||
}
|
||||
await assertCreationMetadata(ctx.userId, parent.projectId, input.metadata)
|
||||
},
|
||||
execute: (input, ctx) => startUpload('file', input, ctx),
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
import { createVersion } from '@shumai/operations'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { badRequest } from '../errors'
|
||||
import { implementOperation } from '../implement'
|
||||
import { assertCreationMetadata, startUpload } from './start-upload'
|
||||
|
||||
export const createVersionOp = implementOperation(createVersion, {
|
||||
authz: (input) => [{ permission: Permission.Edit, type: ResourceType.Asset, id: input.parent }],
|
||||
prepare: async (input, ctx) => {
|
||||
const parent = await assetService.getAssetMeta(input.parent)
|
||||
if (parent.type !== 'file' && parent.type !== 'version_stack') {
|
||||
throw badRequest(
|
||||
'parent must be a file or a version stack. To upload a new file, use create_file.',
|
||||
)
|
||||
}
|
||||
await assertCreationMetadata(ctx.userId, parent.projectId, input.metadata)
|
||||
},
|
||||
execute: (input, ctx) => startUpload('version', input, ctx),
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { StartedUploadOutput } from '@shumai/operations'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import {
|
||||
pendingUploadService,
|
||||
type PendingUploadKind,
|
||||
} from '@shumai/core/src/upload/pending-upload'
|
||||
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import type { OperationContext } from '../context'
|
||||
import { badRequest } from '../errors'
|
||||
|
||||
interface StartUploadInput {
|
||||
parent: string
|
||||
name: string
|
||||
contentType?: string
|
||||
metadata?: Record<string, unknown>
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that `metadata` only sets the project's Creation Context fields, so a bad key fails
|
||||
* before anything is uploaded rather than when the upload is completed.
|
||||
*/
|
||||
export async function assertCreationMetadata(
|
||||
userId: string,
|
||||
projectId: string | undefined,
|
||||
metadata: Record<string, unknown> | undefined,
|
||||
): Promise<void> {
|
||||
const keys = Object.keys(metadata ?? {})
|
||||
if (keys.length === 0) return
|
||||
if (!projectId) throw badRequest('metadata is only supported for files in a project')
|
||||
|
||||
const fields = await metadataService.listProjectFields(userId, projectId)
|
||||
const allowed = fields
|
||||
.filter((f) => f.field.config?.autofillSource === 'CREATION_CONTEXT')
|
||||
.map((f) => f.field.key)
|
||||
const invalid = keys.filter((key) => !allowed.includes(key))
|
||||
if (invalid.length > 0) {
|
||||
throw badRequest(
|
||||
`metadata only accepts the project's Creation Context fields; not allowed: ${invalid.join(', ')}. ` +
|
||||
(allowed.length > 0
|
||||
? `Allowed: ${allowed.join(', ')} (see list_metadata_fields).`
|
||||
: 'This project has none, so omit metadata.'),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Starts an upload and returns where to send the bytes and how to finish it. */
|
||||
export async function startUpload(
|
||||
kind: PendingUploadKind,
|
||||
input: StartUploadInput,
|
||||
ctx: OperationContext,
|
||||
): Promise<StartedUploadOutput> {
|
||||
const name = sanitizeFilename(input.name)
|
||||
const started = await pendingUploadService.start({
|
||||
kind,
|
||||
userId: ctx.userId,
|
||||
parentId: input.parent,
|
||||
name,
|
||||
contentType: input.contentType ?? getFileMimeType(null, name),
|
||||
metadata: input.metadata,
|
||||
})
|
||||
return {
|
||||
uploadId: started.uploadId,
|
||||
uploadUrl: started.uploadUrl,
|
||||
method: 'PUT',
|
||||
expiresAt: started.expiresAt.toISOString(),
|
||||
// Shumai's built-in agent writes the file straight to storage from its sandbox.
|
||||
...(ctx.via === 'agent' ? { key: started.key } : {}),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { createVersionStack } from '@shumai/operations'
|
||||
import { AuditAction } from '@shumai/dtos'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { versionStackService } from '@shumai/core/src/versionStack/versionStack'
|
||||
import { asBadRequest, badRequest } from '../errors'
|
||||
import { implementOperation } from '../implement'
|
||||
import { toAssetSummary } from '../asset/to-asset-summary'
|
||||
|
||||
export const createVersionStackOp = implementOperation(createVersionStack, {
|
||||
authz: (input) =>
|
||||
[...new Set(input.fileIds)].map((id) => ({
|
||||
permission: Permission.Edit,
|
||||
type: ResourceType.Asset,
|
||||
id,
|
||||
})),
|
||||
// The stack belongs to the files' project.
|
||||
prepare: async (input) => {
|
||||
if (new Set(input.fileIds).size !== input.fileIds.length) {
|
||||
throw badRequest('fileIds must not contain the same file twice')
|
||||
}
|
||||
const first = await assetService.getAssetMeta(input.fileIds[0])
|
||||
if (!first.projectId) throw badRequest('The files do not belong to a project')
|
||||
return { projectId: first.projectId }
|
||||
},
|
||||
execute: async (input, ctx, { projectId }) => {
|
||||
const stack = await asBadRequest(() =>
|
||||
versionStackService.createVersionStack({
|
||||
fileIds: input.fileIds,
|
||||
projectId,
|
||||
creatorId: ctx.userId,
|
||||
}),
|
||||
)
|
||||
return toAssetSummary(await assetService.getAsset({ assetId: stack.id }))
|
||||
},
|
||||
audit: (_input, output) => [
|
||||
{ action: AuditAction.version_stack_create, itemId: output.id, contextAssetId: output.id },
|
||||
],
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { listVersions } from '@shumai/operations'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { implementOperation } from '../implement'
|
||||
|
||||
export const listVersionsOp = implementOperation(listVersions, {
|
||||
authz: (input) => [{ permission: Permission.Read, type: ResourceType.Asset, id: input.stackId }],
|
||||
prepare: async (input) => {
|
||||
const stack = await assetService.getAssetMeta(input.stackId)
|
||||
if (stack.type !== 'version_stack') {
|
||||
throw new HTTPException(400, {
|
||||
message: 'This asset is not a version stack. Pass the ID of a version stack.',
|
||||
})
|
||||
}
|
||||
},
|
||||
execute: async (input) => {
|
||||
// Sorted latest first: the first entry is the current version.
|
||||
const versions = await assetService.getStackVersions(input.stackId)
|
||||
return {
|
||||
versions: versions.map((v, index) => ({
|
||||
id: v.id,
|
||||
version: v.version,
|
||||
name: v.name,
|
||||
current: index === 0,
|
||||
createdAt: v.createdAt,
|
||||
creator: v.creator ? { id: v.creator.id, name: v.creator.name } : null,
|
||||
agent: v.agent ?? null,
|
||||
})),
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import { removeVersion } from '@shumai/operations'
|
||||
import { AuditAction } from '@shumai/dtos'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
import { Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { versionStackService } from '@shumai/core/src/versionStack/versionStack'
|
||||
import { asBadRequest, badRequest } from '../errors'
|
||||
import { implementOperation } from '../implement'
|
||||
|
||||
export const removeVersionOp = implementOperation(removeVersion, {
|
||||
// Editing the version means editing its stack: both are in the same project.
|
||||
authz: (input) => [
|
||||
{ permission: Permission.Edit, type: ResourceType.Asset, id: input.versionId },
|
||||
],
|
||||
prepare: async (input) => {
|
||||
const version = await assetService.getAssetMeta(input.versionId)
|
||||
const stack = version.parentId ? await assetService.getAssetMeta(version.parentId) : null
|
||||
if (stack?.type !== 'version_stack') throw badRequest('This file is not in a version stack')
|
||||
return { stackId: stack.id }
|
||||
},
|
||||
execute: async (input, _ctx, { stackId }) => {
|
||||
await asBadRequest(() =>
|
||||
versionStackService.removeVersionFromStack({ stackId, fileId: input.versionId }),
|
||||
)
|
||||
return { versionId: input.versionId, stackId }
|
||||
},
|
||||
audit: (input, output) => [
|
||||
{
|
||||
action: AuditAction.version_stack_update,
|
||||
itemId: output.stackId,
|
||||
contextAssetId: input.versionId,
|
||||
},
|
||||
],
|
||||
})
|
||||
@@ -0,0 +1,130 @@
|
||||
import * as crypto from 'crypto'
|
||||
import { HTTPException } from 'hono/http-exception'
|
||||
import { ulid } from 'ulid'
|
||||
import { UPLOAD_TTL_SECONDS } from '@shumai/operations'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
|
||||
/** What an upload creates once its file is in storage: a new file, or a new version of one. */
|
||||
export type PendingUploadKind = 'file' | 'version'
|
||||
|
||||
/** An upload that was started but not finished yet. Carried by its signed upload ID. */
|
||||
export interface PendingUpload {
|
||||
kind: PendingUploadKind
|
||||
/** The user who started it; only they can finish it. */
|
||||
userId: string
|
||||
/** The folder (file uploads) or the file / version stack (version uploads). */
|
||||
parentId: string
|
||||
name: string
|
||||
/** Storage key the file is uploaded to. */
|
||||
key: string
|
||||
contentType: string
|
||||
/** Creation Context metadata to record on the new file. */
|
||||
metadata?: Record<string, unknown>
|
||||
/** Expiry, in milliseconds since the epoch. */
|
||||
expiresAt: number
|
||||
}
|
||||
|
||||
export interface StartedUpload {
|
||||
/** Opaque, signed ID that finishes the upload. */
|
||||
uploadId: string
|
||||
/** Presigned URL to PUT the file's bytes to. */
|
||||
uploadUrl: string
|
||||
key: string
|
||||
expiresAt: Date
|
||||
}
|
||||
|
||||
const SIGNING_CONTEXT = 'shumai-pending-upload:v1'
|
||||
|
||||
function signingSecret(): string {
|
||||
return process.env.BETTER_AUTH_SECRET || 'shumai-local-storage-secret'
|
||||
}
|
||||
|
||||
function sign(payload: string): string {
|
||||
return crypto
|
||||
.createHmac('sha256', signingSecret())
|
||||
.update(`${SIGNING_CONTEXT}:${payload}`)
|
||||
.digest('base64url')
|
||||
}
|
||||
|
||||
function invalid(): HTTPException {
|
||||
return new HTTPException(400, {
|
||||
message: 'Invalid upload ID: pass the uploadId returned by create_file or create_version.',
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Two-step uploads for clients that send file bytes themselves (e.g. MCP clients): `start`
|
||||
* returns a presigned URL and a signed upload ID; once the bytes are uploaded, `read` checks
|
||||
* the ID so the caller can create the asset. Nothing is written to the database until then,
|
||||
* so abandoned uploads leave no half-created assets behind.
|
||||
*/
|
||||
export class PendingUploadService {
|
||||
/** How long the upload URL and the upload ID stay valid. */
|
||||
readonly ttlSeconds = UPLOAD_TTL_SECONDS
|
||||
|
||||
async start(params: Omit<PendingUpload, 'key' | 'expiresAt'>): Promise<StartedUpload> {
|
||||
const key = `files/${ulid()}/${sanitizeFilename(params.name)}`
|
||||
const expiresAt = Date.now() + this.ttlSeconds * 1000
|
||||
const uploadUrl = await s3Service.presign(
|
||||
this.bucket(),
|
||||
key,
|
||||
'PUT',
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
this.ttlSeconds,
|
||||
)
|
||||
const pending: PendingUpload = { ...params, key, expiresAt }
|
||||
const payload = Buffer.from(JSON.stringify(pending)).toString('base64url')
|
||||
return {
|
||||
uploadId: `${payload}.${sign(payload)}`,
|
||||
uploadUrl,
|
||||
key,
|
||||
expiresAt: new Date(expiresAt),
|
||||
}
|
||||
}
|
||||
|
||||
/** Verifies an upload ID for `userId` and returns the upload it describes. */
|
||||
read(uploadId: string, userId: string): PendingUpload {
|
||||
const [payload, signature, ...rest] = uploadId.split('.')
|
||||
if (!payload || !signature || rest.length > 0) throw invalid()
|
||||
const expected = Buffer.from(sign(payload))
|
||||
const actual = Buffer.from(signature)
|
||||
if (expected.length !== actual.length || !crypto.timingSafeEqual(expected, actual)) {
|
||||
throw invalid()
|
||||
}
|
||||
|
||||
let pending: PendingUpload
|
||||
try {
|
||||
pending = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as PendingUpload
|
||||
} catch {
|
||||
throw invalid()
|
||||
}
|
||||
if (pending.userId !== userId) {
|
||||
throw new HTTPException(403, { message: 'This upload was started by another user.' })
|
||||
}
|
||||
if (Date.now() > pending.expiresAt) {
|
||||
throw new HTTPException(400, {
|
||||
message: 'This upload has expired. Start a new one with create_file or create_version.',
|
||||
})
|
||||
}
|
||||
return pending
|
||||
}
|
||||
|
||||
/** Size of the uploaded file, or null when nothing has been uploaded to the key yet. */
|
||||
async uploadedSize(key: string): Promise<number | null> {
|
||||
try {
|
||||
const info = await s3Service.headObject(this.bucket(), key)
|
||||
return info.size
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
private bucket(): string {
|
||||
return process.env.S3_BUCKET || 'shumai'
|
||||
}
|
||||
}
|
||||
|
||||
export const pendingUploadService = new PendingUploadService()
|
||||
Reference in New Issue
Block a user