mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 04:14:30 +00:00
feat(agent): support 3D degree comments, markup annotations, and config3d in read_asset (#473)
* feat(agent): support AI embedding, autofill, and read_asset for 3D assets * feat(agent): support 3D degree comments, markup annotations, and config3d in read_asset * fix(agent): resolve 3D session annotations to turntable degree frame time
This commit is contained in:
@@ -4,6 +4,7 @@ import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { resolveAnnotationsById } from './annotation-resolver'
|
||||
import { DatabaseSessionStorage } from '../database-session-storage'
|
||||
import type { SessionTreeEntry } from '@earendil-works/pi-agent-core'
|
||||
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
|
||||
|
||||
describe('resolveAnnotationsById', () => {
|
||||
setupTestDbHooks()
|
||||
@@ -210,6 +211,89 @@ describe('resolveAnnotationsById', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('resolves annotations and degree position timestamp from 1-on-1 chat AgentSessionEntry for 3D assets', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'User 3D', email: 'user3d@test.com', password: 'pw' },
|
||||
})
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Team 3D' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Project 3D', teamId: team.id },
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'robot.glb',
|
||||
type: 'file',
|
||||
projectId: project.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
const agentUser = await prisma.user.create({
|
||||
data: { name: 'Agent 3D', email: 'agent3d@example.com', type: 'agent' },
|
||||
})
|
||||
const agent = await prisma.agent.create({
|
||||
data: {
|
||||
id: agentUser.id,
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'test-provider', model: 'test-model' },
|
||||
},
|
||||
})
|
||||
|
||||
const storage = await DatabaseSessionStorage.create({
|
||||
agentId: agent.id,
|
||||
userId: user.id,
|
||||
assetId: asset.id,
|
||||
})
|
||||
|
||||
storage.currentMessageContext = {
|
||||
currentAsset: {
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
type: 'file',
|
||||
path: asset.name,
|
||||
},
|
||||
position: { type: 'degree', degree: 45 },
|
||||
annotation: true,
|
||||
annotations: [
|
||||
{
|
||||
type: 'rectangle',
|
||||
x: 10,
|
||||
y: 20,
|
||||
width: 30,
|
||||
height: 40,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
const userEntry: SessionTreeEntry = {
|
||||
type: 'message',
|
||||
id: '01JTEST3DENTRY123456789',
|
||||
parentId: null,
|
||||
timestamp: new Date().toISOString(),
|
||||
message: {
|
||||
role: 'user',
|
||||
content: 'Check markup at 45 degrees',
|
||||
timestamp: Date.now(),
|
||||
},
|
||||
}
|
||||
|
||||
await storage.appendEntry(userEntry)
|
||||
|
||||
const result = await resolveAnnotationsById(asset.id, '01JTEST3DENTRY123456789')
|
||||
expect(result.timestamp).toBeCloseTo(degreeToSecond(45))
|
||||
expect(result.annotations).toEqual([
|
||||
{
|
||||
type: 'rectangle',
|
||||
x: 10,
|
||||
y: 20,
|
||||
width: 30,
|
||||
height: 40,
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('throws an error when AgentSessionEntry belongs to a different asset', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'User', email: 'user3@test.com', password: 'pw' },
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import type { ShumaiMessageContext } from '@shumai/dtos'
|
||||
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
|
||||
|
||||
export async function resolveAnnotationsById(
|
||||
assetId: string,
|
||||
@@ -44,7 +45,14 @@ export async function resolveAnnotationsById(
|
||||
const list = details?.annotations
|
||||
const annotations =
|
||||
Array.isArray(list) && list.length > 0 ? (list as unknown as PrismaJson.AnnotationList) : null
|
||||
const timestamp = details?.position?.type === 'time' ? details.position.seconds : null
|
||||
let timestamp: number | null = null
|
||||
if (details?.position?.type === 'time') {
|
||||
timestamp = details.position.seconds
|
||||
} else if (details?.position?.type === 'degree') {
|
||||
timestamp = degreeToSecond(details.position.degree)
|
||||
} else if (details?.position?.type === 'page') {
|
||||
timestamp = details.position.page
|
||||
}
|
||||
return { annotations, timestamp }
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import * as annotationResolver from './annotation-resolver'
|
||||
import { degreeToSecond } from '@shumai/core/src/utils/model3d'
|
||||
|
||||
vi.mock('@shumai/db', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@shumai/db')>()
|
||||
@@ -211,6 +212,476 @@ describe('readAssetTool', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('3D Assets', () => {
|
||||
it('should read 3D asset 4-views image and return image with quadrant layout description', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'model-1',
|
||||
name: 'robot.glb',
|
||||
mediaType: 'model/gltf-binary',
|
||||
storageKey: { key: 'raw/robot.glb' },
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
imageTranscodes: [{ key: 'proxy/views.webp' }],
|
||||
},
|
||||
} as unknown as Asset)
|
||||
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer: Buffer.from('fake-views-bytes'),
|
||||
contentType: 'image/webp',
|
||||
} as unknown as { buffer: Buffer; contentType: string })
|
||||
|
||||
const tool = createReadAssetTool('user-1')
|
||||
const result = await tool.execute('call-3d', {
|
||||
assetId: 'model-1',
|
||||
annotationId: null,
|
||||
imageConfig: null,
|
||||
videoConfig: null,
|
||||
docConfig: null,
|
||||
})
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'Read',
|
||||
type: 'asset',
|
||||
id: 'model-1',
|
||||
})
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'proxy/views.webp')
|
||||
|
||||
const textItem = result.content[0] as { type: 'text'; text: string }
|
||||
const imageItem = result.content[1] as { type: 'image'; data: string; mimeType: string }
|
||||
|
||||
expect(textItem.text).toContain('Orthogonal 4-view composite image')
|
||||
expect(textItem.text).toContain('Top-Left quadrant: Front view (0°)')
|
||||
expect(textItem.text).toContain('Top-Right quadrant: Right side view (90°)')
|
||||
expect(textItem.text).toContain('Bottom-Left quadrant: Back view (180°)')
|
||||
expect(textItem.text).toContain('Bottom-Right quadrant: Left side view (270°)')
|
||||
expect(imageItem.type).toBe('image')
|
||||
expect(imageItem.data).toBe(Buffer.from('fake-views-bytes').toString('base64'))
|
||||
expect(result.details.key).toBe('proxy/views.webp')
|
||||
})
|
||||
|
||||
it('should support s3KeyOnly mode for 3D assets', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'model-1',
|
||||
name: 'robot.glb',
|
||||
mediaType: 'model/gltf-binary',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
imageTranscodes: [{ key: 'proxy/views.webp' }],
|
||||
},
|
||||
} as unknown as Asset)
|
||||
|
||||
const tool = createReadAssetTool('user-1')
|
||||
const result = await tool.execute('call-3d-s3', {
|
||||
assetId: 'model-1',
|
||||
annotationId: null,
|
||||
s3KeyOnly: true,
|
||||
imageConfig: null,
|
||||
videoConfig: null,
|
||||
docConfig: null,
|
||||
})
|
||||
|
||||
expect(result.content).toHaveLength(1)
|
||||
const textItem = result.content[0] as { type: 'text'; text: string }
|
||||
expect(textItem.text).toContain('proxy/views.webp')
|
||||
expect(textItem.text).toContain('Front view (0°)')
|
||||
expect(result.details.key).toBe('proxy/views.webp')
|
||||
})
|
||||
|
||||
it('should throw error if videoConfig is passed for 3D assets', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'model-1',
|
||||
name: 'robot.glb',
|
||||
mediaType: 'model/gltf-binary',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
imageTranscodes: [{ key: 'proxy/views.webp' }],
|
||||
},
|
||||
} as unknown as Asset)
|
||||
|
||||
const tool = createReadAssetTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-3d-err', {
|
||||
assetId: 'model-1',
|
||||
annotationId: null,
|
||||
imageConfig: null,
|
||||
videoConfig: { start: 0, end: 4, count: 4 },
|
||||
docConfig: null,
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
"To inspect specific angles pass 'config3d: { degree: ... }'; do not pass videoConfig",
|
||||
)
|
||||
})
|
||||
|
||||
it('should throw error if 3D asset imageTranscodes is missing when overview is requested', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'model-1',
|
||||
name: 'robot.glb',
|
||||
mediaType: 'model/gltf-binary',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
imageTranscodes: [],
|
||||
},
|
||||
} as unknown as Asset)
|
||||
|
||||
const tool = createReadAssetTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-3d-err2', {
|
||||
assetId: 'model-1',
|
||||
annotationId: null,
|
||||
imageConfig: null,
|
||||
videoConfig: null,
|
||||
docConfig: null,
|
||||
}),
|
||||
).rejects.toThrow('4-views image (views.webp) is missing')
|
||||
})
|
||||
|
||||
it('should extract specific turntable frame when config3d.degree is provided', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'model-1',
|
||||
name: 'robot.glb',
|
||||
mediaType: 'model/gltf-binary',
|
||||
projectId: 'proj-1',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
videoTranscodes: [{ key: 'proxy/turntable.mp4' }],
|
||||
imageTranscodes: [{ key: 'proxy/views.webp' }],
|
||||
},
|
||||
} as unknown as Asset)
|
||||
|
||||
vi.mocked(prisma.workflowTask.create).mockResolvedValue({
|
||||
id: 'task-shot-3d',
|
||||
} as unknown as WorkflowTask)
|
||||
|
||||
vi.mocked(workflowService.executeWait).mockResolvedValue({
|
||||
id: 'task-shot-3d',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
output: {
|
||||
screenshots: [{ key: 'proxy/shot-45.webp', timestamp: 0.5833 }],
|
||||
},
|
||||
} as unknown as WorkflowTask)
|
||||
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer: Buffer.from('fake-shot-45-bytes'),
|
||||
contentType: 'image/webp',
|
||||
} as unknown as { buffer: Buffer; contentType: string })
|
||||
|
||||
const tool = createReadAssetTool('user-1')
|
||||
const result = await tool.execute('call-3d-degree', {
|
||||
assetId: 'model-1',
|
||||
annotationId: null,
|
||||
config3d: { degree: 45 },
|
||||
imageConfig: null,
|
||||
videoConfig: null,
|
||||
docConfig: null,
|
||||
})
|
||||
|
||||
expect(prisma.workflowTask.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
type: WorkflowTaskType.transcode_screenshot,
|
||||
assetId: 'model-1',
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
screenshot: {
|
||||
start: expect.any(Number),
|
||||
end: expect.any(Number),
|
||||
count: 1,
|
||||
commentTimestamp: expect.any(Number),
|
||||
annotations: undefined,
|
||||
},
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
const textItem = result.content[0] as { type: 'text'; text: string }
|
||||
const imageItem = result.content[1] as { type: 'image'; data: string; mimeType: string }
|
||||
|
||||
expect(textItem.text).toContain('view at 45°:')
|
||||
expect(imageItem.data).toBe(Buffer.from('fake-shot-45-bytes').toString('base64'))
|
||||
expect(result.details.key).toBe('proxy/shot-45.webp')
|
||||
})
|
||||
|
||||
it('should throw error when config3d.degree is not a multiple of 15 or out of range', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'model-1',
|
||||
name: 'robot.glb',
|
||||
mediaType: 'model/gltf-binary',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
videoTranscodes: [{ key: 'proxy/turntable.mp4' }],
|
||||
},
|
||||
} as unknown as Asset)
|
||||
|
||||
const tool = createReadAssetTool('user-1')
|
||||
|
||||
await expect(
|
||||
tool.execute('call-3d-invalid-deg', {
|
||||
assetId: 'model-1',
|
||||
annotationId: null,
|
||||
config3d: { degree: 40 },
|
||||
imageConfig: null,
|
||||
videoConfig: null,
|
||||
docConfig: null,
|
||||
}),
|
||||
).rejects.toThrow('Invalid turntable degree: 40')
|
||||
|
||||
await expect(
|
||||
tool.execute('call-3d-out-of-range', {
|
||||
assetId: 'model-1',
|
||||
annotationId: null,
|
||||
config3d: { degree: 360 },
|
||||
imageConfig: null,
|
||||
videoConfig: null,
|
||||
docConfig: null,
|
||||
}),
|
||||
).rejects.toThrow('Invalid turntable degree: 360')
|
||||
})
|
||||
|
||||
it('should extract frame with overlaid markups when annotationId is provided on 3D asset', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'model-1',
|
||||
name: 'robot.glb',
|
||||
mediaType: 'model/gltf-binary',
|
||||
projectId: 'proj-1',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
videoTranscodes: [{ key: 'proxy/turntable.mp4' }],
|
||||
},
|
||||
} as unknown as Asset)
|
||||
|
||||
vi.spyOn(annotationResolver, 'resolveAnnotationsById').mockResolvedValue({
|
||||
annotations: [
|
||||
{
|
||||
type: 'freehand',
|
||||
color: '#ff0000',
|
||||
points: [
|
||||
[0, 0],
|
||||
[10, 10],
|
||||
],
|
||||
},
|
||||
],
|
||||
timestamp: 0.5, // 0.5s = 45°
|
||||
})
|
||||
|
||||
vi.mocked(prisma.workflowTask.create).mockResolvedValue({
|
||||
id: 'task-shot-ann',
|
||||
} as unknown as WorkflowTask)
|
||||
|
||||
vi.mocked(workflowService.executeWait).mockResolvedValue({
|
||||
id: 'task-shot-ann',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
output: {
|
||||
screenshots: [{ key: 'proxy/shot-annotated.webp', timestamp: 0.5 }],
|
||||
},
|
||||
} as unknown as WorkflowTask)
|
||||
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer: Buffer.from('fake-shot-ann-bytes'),
|
||||
contentType: 'image/webp',
|
||||
} as unknown as { buffer: Buffer; contentType: string })
|
||||
|
||||
const tool = createReadAssetTool('user-1')
|
||||
const result = await tool.execute('call-3d-ann', {
|
||||
assetId: 'model-1',
|
||||
annotationId: 'comm-1',
|
||||
config3d: null,
|
||||
imageConfig: null,
|
||||
videoConfig: null,
|
||||
docConfig: null,
|
||||
})
|
||||
|
||||
expect(prisma.workflowTask.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
type: WorkflowTaskType.transcode_screenshot,
|
||||
assetId: 'model-1',
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
screenshot: {
|
||||
start: 0.5,
|
||||
end: 0.5,
|
||||
count: 1,
|
||||
commentTimestamp: 0.5,
|
||||
annotations: [
|
||||
{
|
||||
type: 'freehand',
|
||||
color: '#ff0000',
|
||||
points: [
|
||||
[0, 0],
|
||||
[10, 10],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
const textItem = result.content[0] as { type: 'text'; text: string }
|
||||
expect(textItem.text).toContain('view at 45° with visual markups overlaid:')
|
||||
expect(result.details.key).toBe('proxy/shot-annotated.webp')
|
||||
})
|
||||
|
||||
it('should extract turntable frame at resolved degree angle for 3D session annotations', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'model-1',
|
||||
name: 'robot.glb',
|
||||
mediaType: 'model/gltf-binary',
|
||||
projectId: 'proj-1',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
videoTranscodes: [{ key: 'proxy/turntable.mp4' }],
|
||||
},
|
||||
} as unknown as Asset)
|
||||
|
||||
const expectedTime = degreeToSecond(90)
|
||||
vi.spyOn(annotationResolver, 'resolveAnnotationsById').mockResolvedValue({
|
||||
annotations: [
|
||||
{
|
||||
type: 'box',
|
||||
color: '#00ff00',
|
||||
points: [
|
||||
[10, 20],
|
||||
[40, 60],
|
||||
],
|
||||
},
|
||||
],
|
||||
timestamp: expectedTime,
|
||||
})
|
||||
|
||||
vi.mocked(prisma.workflowTask.create).mockResolvedValue({
|
||||
id: 'task-shot-3d-session',
|
||||
} as unknown as WorkflowTask)
|
||||
|
||||
vi.mocked(workflowService.executeWait).mockResolvedValue({
|
||||
id: 'task-shot-3d-session',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
output: {
|
||||
screenshots: [{ key: 'proxy/shot-annotated-90.webp', timestamp: expectedTime }],
|
||||
},
|
||||
} as unknown as WorkflowTask)
|
||||
|
||||
vi.mocked(s3Service.getObject).mockResolvedValue({
|
||||
buffer: Buffer.from('fake-shot-90-bytes'),
|
||||
contentType: 'image/webp',
|
||||
} as unknown as { buffer: Buffer; contentType: string })
|
||||
|
||||
const tool = createReadAssetTool('user-1')
|
||||
const result = await tool.execute('call-3d-session-ann', {
|
||||
assetId: 'model-1',
|
||||
annotationId: 'session-entry-1',
|
||||
config3d: null,
|
||||
imageConfig: null,
|
||||
videoConfig: null,
|
||||
docConfig: null,
|
||||
})
|
||||
|
||||
expect(prisma.workflowTask.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
type: WorkflowTaskType.transcode_screenshot,
|
||||
assetId: 'model-1',
|
||||
payload: {
|
||||
projectId: 'proj-1',
|
||||
screenshot: {
|
||||
start: expectedTime,
|
||||
end: expectedTime,
|
||||
count: 1,
|
||||
commentTimestamp: expectedTime,
|
||||
annotations: [
|
||||
{
|
||||
type: 'box',
|
||||
color: '#00ff00',
|
||||
points: [
|
||||
[10, 20],
|
||||
[40, 60],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
const textItem = result.content[0] as { type: 'text'; text: string }
|
||||
expect(textItem.text).toContain('view at 90° with visual markups overlaid:')
|
||||
expect(result.details.key).toBe('proxy/shot-annotated-90.webp')
|
||||
})
|
||||
|
||||
it('should throw error if config3d.degree conflicts with annotation angle', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'model-1',
|
||||
name: 'robot.glb',
|
||||
mediaType: 'model/gltf-binary',
|
||||
projectId: 'proj-1',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
videoTranscodes: [{ key: 'proxy/turntable.mp4' }],
|
||||
},
|
||||
} as unknown as Asset)
|
||||
|
||||
vi.spyOn(annotationResolver, 'resolveAnnotationsById').mockResolvedValue({
|
||||
annotations: [
|
||||
{
|
||||
type: 'box',
|
||||
color: '#ff0000',
|
||||
points: [
|
||||
[0, 0],
|
||||
[10, 10],
|
||||
],
|
||||
},
|
||||
],
|
||||
timestamp: 0.5, // 45°
|
||||
})
|
||||
|
||||
const tool = createReadAssetTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-3d-conflict', {
|
||||
assetId: 'model-1',
|
||||
annotationId: 'comm-1',
|
||||
config3d: { degree: 90 }, // Conflicts with 45°
|
||||
imageConfig: null,
|
||||
videoConfig: null,
|
||||
docConfig: null,
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
'Annotation "comm-1" was drawn at 45°, but degree 90° was specified. Do not pass a conflicting degree with annotationId.',
|
||||
)
|
||||
})
|
||||
|
||||
it('should throw error if 3D asset turntable video is missing when angle inspection is requested', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
vi.mocked(prisma.asset.findUnique).mockResolvedValue({
|
||||
id: 'model-1',
|
||||
name: 'robot.glb',
|
||||
mediaType: 'model/gltf-binary',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
videoTranscodes: [],
|
||||
},
|
||||
} as unknown as Asset)
|
||||
|
||||
const tool = createReadAssetTool('user-1')
|
||||
await expect(
|
||||
tool.execute('call-3d-missing-turntable', {
|
||||
assetId: 'model-1',
|
||||
annotationId: null,
|
||||
config3d: { degree: 45 },
|
||||
imageConfig: null,
|
||||
videoConfig: null,
|
||||
docConfig: null,
|
||||
}),
|
||||
).rejects.toThrow('turntable video (turntable.mp4) is missing')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Video Assets', () => {
|
||||
it('should throw error if videoConfig is missing for video assets', async () => {
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
|
||||
@@ -7,6 +7,12 @@ import { workflowService } from '@shumai/workflow-core'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { resolveAnnotationsById } from './annotation-resolver'
|
||||
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { is3dModel } from '@shumai/core/src/utils/mime'
|
||||
import {
|
||||
isValidTurntableDegree,
|
||||
secondToDegree,
|
||||
degreeToSecond,
|
||||
} from '@shumai/core/src/utils/model3d'
|
||||
|
||||
export const readAssetSchema = Type.Object(
|
||||
{
|
||||
@@ -37,6 +43,31 @@ export const readAssetSchema = Type.Object(
|
||||
),
|
||||
Type.Null(),
|
||||
]),
|
||||
config3d: Type.Optional(
|
||||
Type.Union([
|
||||
Type.Object(
|
||||
{
|
||||
degree: Type.Optional(
|
||||
Type.Union([
|
||||
Type.Integer({
|
||||
minimum: 0,
|
||||
maximum: 345,
|
||||
description:
|
||||
'Turntable rotation degree (integer: 0, 15, 30, ..., 345 in 15° increments) to inspect a specific angle of a 3D model. Leave null/omitted to view the 4-view composite overview.',
|
||||
}),
|
||||
Type.Null(),
|
||||
]),
|
||||
),
|
||||
},
|
||||
{
|
||||
additionalProperties: false,
|
||||
description:
|
||||
'Configuration for 3D model assets. Pass null if inspecting another asset type. Optionally pass degree to inspect a specific turntable angle, or leave null/omitted to view the 4-view composite overview.',
|
||||
},
|
||||
),
|
||||
Type.Null(),
|
||||
]),
|
||||
),
|
||||
videoConfig: Type.Union([
|
||||
Type.Object(
|
||||
{
|
||||
@@ -167,12 +198,12 @@ export function createReadAssetTool(
|
||||
label: 'Read Asset',
|
||||
description:
|
||||
'Inspects and reads the content of an asset in the workspace. ' +
|
||||
'Supports visual analysis for images, video frame extraction, PDF page rendering, and direct text reading for text/markdown files. ' +
|
||||
'Pass assetId, and provide the specific config (imageConfig, videoConfig, or docConfig) while setting unused configs to null. ' +
|
||||
'Supports visual analysis for images, 3D models (overview or specific degree angle), video frame extraction, PDF page rendering, and direct text reading for text/markdown files. ' +
|
||||
'Pass assetId, and provide the specific config (imageConfig, config3d, videoConfig, or docConfig) while setting unused configs to null. ' +
|
||||
'Optionally provide annotationId to view visual markups drawn on the asset.',
|
||||
parameters: readAssetSchema,
|
||||
execute: async (_toolCallId, params) => {
|
||||
const { assetId, annotationId, s3KeyOnly, videoConfig, docConfig } = params
|
||||
const { assetId, annotationId, s3KeyOnly, config3d, videoConfig, docConfig } = params
|
||||
|
||||
if (agentType === 'autofill' && !userId) {
|
||||
if (!targetAssetId) {
|
||||
@@ -243,6 +274,209 @@ export function createReadAssetTool(
|
||||
const filename = asset.name?.toLowerCase() || ''
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Branch 0: 3D Assets (Orthogonal 4-View Composite Image or Degree Angle)
|
||||
// ----------------------------------------------------------------------
|
||||
const is3d = proxyType === '3d' || is3dModel(mediaType, filename)
|
||||
if (is3d) {
|
||||
if (videoConfig) {
|
||||
throw new Error(
|
||||
`Asset ${asset.id} is a 3D model. To inspect specific angles pass 'config3d: { degree: ... }'; do not pass videoConfig.`,
|
||||
)
|
||||
}
|
||||
|
||||
if (config3d?.degree !== undefined && config3d?.degree !== null) {
|
||||
if (!isValidTurntableDegree(config3d.degree)) {
|
||||
throw new Error(
|
||||
`Invalid turntable degree: ${config3d.degree}. Degree must be an integer multiple of 15 between 0 and 345 (e.g. 0, 15, 30, 45, ..., 345).`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
let annotations: PrismaJson.AnnotationList | null = null
|
||||
let commentTimestamp: number | null = null
|
||||
if (annotationId) {
|
||||
const resolved = await resolveAnnotationsById(asset.id, annotationId)
|
||||
annotations = resolved.annotations
|
||||
commentTimestamp = resolved.timestamp
|
||||
if (commentTimestamp !== null && commentTimestamp !== undefined) {
|
||||
const commentDegree = secondToDegree(commentTimestamp)
|
||||
if (
|
||||
config3d?.degree !== undefined &&
|
||||
config3d?.degree !== null &&
|
||||
config3d.degree !== commentDegree
|
||||
) {
|
||||
throw new Error(
|
||||
`Annotation "${annotationId}" was drawn at ${commentDegree}°, but degree ${config3d.degree}° was specified. Do not pass a conflicting degree with annotationId.`,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((config3d?.degree !== undefined && config3d?.degree !== null) || annotationId) {
|
||||
if (!mediaInfo?.videoTranscodes || mediaInfo.videoTranscodes.length === 0) {
|
||||
throw new Error(
|
||||
`Asset ${asset.id} is a 3D model, but its turntable video (turntable.mp4) is missing.`,
|
||||
)
|
||||
}
|
||||
|
||||
let targetDegree: number
|
||||
let targetSecond: number
|
||||
|
||||
if (config3d?.degree !== undefined && config3d?.degree !== null) {
|
||||
targetDegree = config3d.degree
|
||||
targetSecond = degreeToSecond(targetDegree)
|
||||
} else {
|
||||
targetSecond =
|
||||
commentTimestamp !== null && commentTimestamp !== undefined ? commentTimestamp : 0
|
||||
targetDegree = secondToDegree(targetSecond)
|
||||
}
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
projectId: asset.projectId || 'none',
|
||||
type: WorkflowTaskType.transcode_screenshot,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
payload: {
|
||||
projectId: asset.projectId || 'none',
|
||||
screenshot: {
|
||||
start: targetSecond,
|
||||
end: targetSecond,
|
||||
count: 1,
|
||||
commentTimestamp: targetSecond,
|
||||
annotations: annotations ?? undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const completedTask = await workflowService.executeWait(task)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- transcode screenshot output
|
||||
const output = completedTask.output as any
|
||||
const screenshots = output?.screenshots as
|
||||
| Array<{ key: string; timestamp: number }>
|
||||
| undefined
|
||||
|
||||
if (!screenshots || screenshots.length === 0) {
|
||||
throw new Error(
|
||||
`Failed to extract 3D turntable frame for asset ${asset.id} at ${targetDegree}°.`,
|
||||
)
|
||||
}
|
||||
|
||||
const shotKey = screenshots[0].key
|
||||
const downloadUrl = await s3Service.presign(
|
||||
bucket,
|
||||
shotKey,
|
||||
'GET',
|
||||
true,
|
||||
asset.name || undefined,
|
||||
)
|
||||
|
||||
const content: Array<TextContent | ImageContent> = []
|
||||
const hasMarkup = Boolean(annotations && annotations.length > 0)
|
||||
const textDescription = hasMarkup
|
||||
? `3D asset "${asset.name}" (ID: ${asset.id}, S3 Key: "${shotKey}") view at ${targetDegree}° with visual markups overlaid:`
|
||||
: `3D asset "${asset.name}" (ID: ${asset.id}, S3 Key: "${shotKey}") view at ${targetDegree}°:`
|
||||
|
||||
if (s3KeyOnly) {
|
||||
content.push({
|
||||
type: 'text',
|
||||
text: textDescription,
|
||||
})
|
||||
} else {
|
||||
const { buffer, contentType } = await s3Service.getObject(bucket, shotKey)
|
||||
const actualMimeType =
|
||||
contentType && contentType !== 'application/octet-stream' ? contentType : 'image/webp'
|
||||
content.push({
|
||||
type: 'text',
|
||||
text: textDescription,
|
||||
})
|
||||
content.push({
|
||||
type: 'image',
|
||||
data: buffer.toString('base64'),
|
||||
mimeType: actualMimeType,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
content,
|
||||
details: {
|
||||
assetId: asset.id,
|
||||
name: asset.name,
|
||||
mediaType: asset.mediaType,
|
||||
key: shotKey,
|
||||
downloadUrl,
|
||||
sourceKeys: [shotKey],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
if (!mediaInfo?.imageTranscodes || mediaInfo.imageTranscodes.length === 0) {
|
||||
throw new Error(
|
||||
`Asset ${asset.id} is a 3D model, but its 4-views image (views.webp) is missing.`,
|
||||
)
|
||||
}
|
||||
|
||||
const mediaKey = mediaInfo.imageTranscodes[0].key
|
||||
if (!mediaKey) {
|
||||
throw new Error(`Asset ${asset.id} is a 3D model, but its 4-views image key is missing.`)
|
||||
}
|
||||
|
||||
const keyToUse = mediaKey
|
||||
const mimeType = 'image/webp'
|
||||
|
||||
const downloadUrl = await s3Service.presign(
|
||||
bucket,
|
||||
keyToUse,
|
||||
'GET',
|
||||
true,
|
||||
asset.name || undefined,
|
||||
)
|
||||
|
||||
const content: Array<TextContent | ImageContent> = []
|
||||
const textDescription = [
|
||||
`3D asset "${asset.name}" (ID: ${asset.id}, MIME: ${mimeType}, S3 Key: "${keyToUse}"):`,
|
||||
'Orthogonal 4-view composite image (2x2 grid across 360° rotation):',
|
||||
'- Top-Left quadrant: Front view (0°)',
|
||||
'- Top-Right quadrant: Right side view (90°)',
|
||||
'- Bottom-Left quadrant: Back view (180°)',
|
||||
'- Bottom-Right quadrant: Left side view (270°)',
|
||||
].join('\n')
|
||||
|
||||
if (s3KeyOnly) {
|
||||
content.push({
|
||||
type: 'text',
|
||||
text: textDescription,
|
||||
})
|
||||
} else {
|
||||
const { buffer, contentType } = await s3Service.getObject(bucket, keyToUse)
|
||||
const actualMimeType =
|
||||
contentType && contentType !== 'application/octet-stream' ? contentType : mimeType
|
||||
content.push({
|
||||
type: 'text',
|
||||
text: textDescription,
|
||||
})
|
||||
content.push({
|
||||
type: 'image',
|
||||
data: buffer.toString('base64'),
|
||||
mimeType: actualMimeType,
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
content,
|
||||
details: {
|
||||
assetId: asset.id,
|
||||
name: asset.name,
|
||||
mediaType: asset.mediaType,
|
||||
key: keyToUse,
|
||||
downloadUrl,
|
||||
sourceKeys: [keyToUse],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Branch 1: Image Assets
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
@@ -129,6 +129,42 @@ describe('createReadThreadTool', () => {
|
||||
expect(textContent).toContain('- [Ai Agent] (id: reply-1, has_markup: false): Agent answer')
|
||||
})
|
||||
|
||||
it('should format 3d asset comment timestamps as degree: X°', async () => {
|
||||
vi.mocked(prisma.assetComment.findUnique).mockResolvedValue({
|
||||
id: 'root-3d',
|
||||
message: 'Notice this angle',
|
||||
creator: { name: 'Alice' },
|
||||
second: 0.5,
|
||||
annotation: [{ type: 'box' }],
|
||||
asset: {
|
||||
media: { proxyType: '3d' },
|
||||
mediaType: 'model/gltf-binary',
|
||||
name: 'robot.glb',
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
vi.mocked(prisma.assetComment.findMany).mockResolvedValue([
|
||||
{
|
||||
id: 'reply-3d-1',
|
||||
message: 'Looking at back side',
|
||||
creator: { name: 'Bob' },
|
||||
second: 2.0,
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
] as any)
|
||||
|
||||
const tool = createReadThreadTool()
|
||||
const result = await tool.execute('call-3d', { threadId: 'root-3d' })
|
||||
const textContent = (result.content[0] as { text: string }).text
|
||||
|
||||
expect(textContent).toContain(
|
||||
'Thread Root [Alice] (id: root-3d, degree: 45°, has_markup: true): Notice this angle',
|
||||
)
|
||||
expect(textContent).toContain(
|
||||
'- [Bob] (id: reply-3d-1, degree: 180°, has_markup: false): Looking at back side',
|
||||
)
|
||||
})
|
||||
|
||||
it('should describe threadId parameter as referencing <thread id="..." /> in <context>', () => {
|
||||
const tool = createReadThreadTool()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
import { Type } from 'typebox'
|
||||
import { type AgentTool } from '@earendil-works/pi-agent-core'
|
||||
import { secondToDegree } from '@shumai/core/src/utils/model3d'
|
||||
import { getProxyType } from '@shumai/core/src/utils/mime'
|
||||
|
||||
const readThreadSchema = Type.Object({
|
||||
threadId: Type.String({
|
||||
@@ -9,14 +11,21 @@ const readThreadSchema = Type.Object({
|
||||
}),
|
||||
})
|
||||
|
||||
function formatCommentMeta(c: {
|
||||
id: string
|
||||
second?: number | null
|
||||
annotation?: unknown
|
||||
}): string {
|
||||
function formatCommentMeta(
|
||||
c: {
|
||||
id: string
|
||||
second?: number | null
|
||||
annotation?: unknown
|
||||
},
|
||||
proxyType?: string,
|
||||
): string {
|
||||
const parts = [`id: ${c.id}`]
|
||||
if (c.second !== null && c.second !== undefined) {
|
||||
parts.push(`time: ${c.second}s`)
|
||||
if (proxyType === '3d') {
|
||||
parts.push(`degree: ${secondToDegree(c.second)}°`)
|
||||
} else {
|
||||
parts.push(`time: ${c.second}s`)
|
||||
}
|
||||
}
|
||||
const hasMarkup = Boolean(c.annotation && Array.isArray(c.annotation) && c.annotation.length > 0)
|
||||
parts.push(`has_markup: ${hasMarkup}`)
|
||||
@@ -34,7 +43,10 @@ export const createReadThreadTool = (): AgentTool<
|
||||
execute: async (_toolCallId, params) => {
|
||||
const rootComment = await prisma.assetComment.findUnique({
|
||||
where: { id: params.threadId },
|
||||
include: { creator: true },
|
||||
include: {
|
||||
creator: true,
|
||||
asset: { select: { media: true, mediaType: true, name: true } },
|
||||
},
|
||||
})
|
||||
|
||||
if (!rootComment) {
|
||||
@@ -61,9 +73,14 @@ export const createReadThreadTool = (): AgentTool<
|
||||
include: { creator: true },
|
||||
})
|
||||
|
||||
const proxyType =
|
||||
(rootComment.asset?.media as PrismaJson.MediaInfo | null)?.proxyType ||
|
||||
getProxyType(rootComment.asset?.mediaType, rootComment.asset?.name) ||
|
||||
undefined
|
||||
|
||||
const isRootAgent = rootComment.creator?.type === 'agent' || rootComment.sessionId !== null
|
||||
const rootAuthor = rootComment.creator?.name || (isRootAgent ? 'Ai Agent' : 'User')
|
||||
const rootMeta = formatCommentMeta(rootComment)
|
||||
const rootMeta = formatCommentMeta(rootComment, proxyType)
|
||||
let output = `Thread Root [${rootAuthor}] ${rootMeta}: ${rootComment.message || ''}\n\nReplies (${replies.length}):`
|
||||
|
||||
if (replies.length === 0) {
|
||||
@@ -72,7 +89,7 @@ export const createReadThreadTool = (): AgentTool<
|
||||
for (const reply of replies) {
|
||||
const isAgent = reply.creator?.type === 'agent' || reply.sessionId !== null
|
||||
const author = reply.creator?.name || (isAgent ? 'Ai Agent' : 'User')
|
||||
const replyMeta = formatCommentMeta(reply)
|
||||
const replyMeta = formatCommentMeta(reply, proxyType)
|
||||
output += `\n- [${author}] ${replyMeta}: ${reply.message || ''}`
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user