diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index 451a76c6..d93b341c 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -118,7 +118,7 @@ If you need to create files in the local filesystem (for example, a temporary fi When creating a file or version, you may attach metadata (for example, the AI model or prompt used to generate the asset). The allowed field keys and value types are declared directly in the 'metadata' parameter of the 'create_file' and 'create_version' tools. # Message Context & Tools -User messages may contain a block detailing the user, active asset location, playback position, and attachments. Use the asset IDs from when invoking tools (e.g. 'analyze_image', 'screenshot', 'read_pdf_pages', 'download_asset', 'list_assets'). When an tag is present, it indicates the user has drawn visual markups on the asset at the specified position.` +User messages may contain a block detailing the user, active asset location, playback position, and attachments. Use the asset IDs from when invoking tools (e.g. 'analyze_image', 'screenshot', 'read_pdf_pages', 'download_asset', 'list_assets'). When an tag is present, it indicates the user has drawn visual markups on the asset at the specified position. When calling 'screenshot', 'analyze_image', or 'read_pdf_pages', pass the 'annotationId' parameter with that ID to view the image with the visual markups overlaid.` if (agent.soul) { systemPrompt = `${systemPrompt}\n\nAgent Personality and Core Instructions:\n${agent.soul}` @@ -824,6 +824,7 @@ export async function initializeAgentSessionActivity(params: { } const commentDetails: ShumaiMessageContext = { + id: c.id, ...(userObj ? { user: userObj } : {}), ...(position ? { position } : {}), ...(annotation diff --git a/packages/agent/src/context/serialize-context.test.ts b/packages/agent/src/context/serialize-context.test.ts index 2e6496a0..1c72c542 100644 --- a/packages/agent/src/context/serialize-context.test.ts +++ b/packages/agent/src/context/serialize-context.test.ts @@ -330,5 +330,25 @@ describe('serializeContextToXml', () => { expect(serializeContextToXml(context2)).toContain('duration_seconds="14.00"') expect(serializeContextToXml(context2)).toContain('seconds="5.5000"') }) + + it('serializes annotation tag with id when context.id is provided', () => { + const context: ShumaiMessageContext = { + id: '01JABCDEF1234567890', + annotation: true, + } + expect(serializeContextToXml(context)).toBe( + '\n \n', + ) + }) + + it('escapes special XML characters in annotation id', () => { + const context: ShumaiMessageContext = { + id: 'test&"123"', + annotation: true, + } + expect(serializeContextToXml(context)).toBe( + '\n \n', + ) + }) }) }) diff --git a/packages/agent/src/database-session-storage.test.ts b/packages/agent/src/database-session-storage.test.ts index 7967f61a..e3bb27aa 100644 --- a/packages/agent/src/database-session-storage.test.ts +++ b/packages/agent/src/database-session-storage.test.ts @@ -470,12 +470,12 @@ describe('DatabaseSessionStorage', () => { providers: mockProviders, }) - // 4. Assert that the tools were instantiated using the new comment ID and user ID - expect(createAnalyzeImageToolSpy).toHaveBeenCalledWith(user.id, 'new-comment-456') - expect(createScreenshotToolSpy).toHaveBeenCalledWith(user.id, 'new-comment-456') + // 4. Assert that the tools were instantiated using user ID + expect(createAnalyzeImageToolSpy).toHaveBeenCalledWith(user.id) + expect(createScreenshotToolSpy).toHaveBeenCalledWith(user.id) }) - it('should use the current comment ID for media tools in subsequent turns (video)', async () => { + it('should instantiate media tools with user ID in subsequent turns (video)', async () => { const { agent, user, team } = await setupTestData() // Create a project and asset to satisfy FK constraints @@ -524,9 +524,9 @@ describe('DatabaseSessionStorage', () => { providers: mockProviders, }) - // 4. Assert that the tools were instantiated using the new comment ID and user ID - expect(createScreenshotToolSpy).toHaveBeenCalledWith(user.id, 'new-comment-456') - expect(createAnalyzeImageToolSpy).toHaveBeenCalledWith(user.id, 'new-comment-456') + // 4. Assert that the tools were instantiated using user ID + expect(createScreenshotToolSpy).toHaveBeenCalledWith(user.id) + expect(createAnalyzeImageToolSpy).toHaveBeenCalledWith(user.id) }) describe('P1 Bug Reproductions', () => { diff --git a/packages/agent/src/database-session-storage.ts b/packages/agent/src/database-session-storage.ts index 26880b79..8f08ca61 100644 --- a/packages/agent/src/database-session-storage.ts +++ b/packages/agent/src/database-session-storage.ts @@ -132,7 +132,10 @@ export class DatabaseSessionStorage implements SessionStorage { assetComment: { findUnique: vi.fn(), }, + agentSessionEntry: { + findUnique: vi.fn(), + }, workflowTask: { create: vi.fn(), }, @@ -58,7 +62,7 @@ describe('analyzeImageTool', () => { vi.clearAllMocks() }) - it('should check user permissions and fetch the image from S3 when comment has no annotations', async () => { + it('should check user permissions and fetch the image from S3 when annotationId is omitted', async () => { vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user-1' } as User) vi.mocked(authzService.hasPermission).mockResolvedValue() @@ -69,18 +73,12 @@ describe('analyzeImageTool', () => { media: null, } as unknown as Asset) - vi.mocked(prisma.assetComment.findUnique).mockResolvedValue({ - id: 'comment-1', - assetId: 'asset-1', - annotation: null, - } as unknown as AssetComment) - vi.mocked(s3Service.getObject).mockResolvedValue({ buffer: Buffer.from('fake-image-bytes'), contentType: 'image/png', } as unknown as { buffer: Buffer; contentType: string }) - const tool = createAnalyzeImageTool('user-1', 'comment-1') + const tool = createAnalyzeImageTool('user-1') const result = await tool.execute('call-1', { assetId: 'asset-1' }) expect(authzService.hasPermission).toHaveBeenCalledWith({ @@ -99,7 +97,10 @@ describe('analyzeImageTool', () => { expect(prisma.workflowTask.create).not.toHaveBeenCalled() }) - it('should trigger overlay transcode workflow when comment has annotations', async () => { + it('should trigger overlay transcode workflow when annotationId matches AssetComment with annotations', async () => { + vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user-1' } as User) + vi.mocked(authzService.hasPermission).mockResolvedValue() + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ id: 'asset-1', projectId: 'project-1', @@ -139,8 +140,8 @@ describe('analyzeImageTool', () => { contentType: 'image/webp', } as unknown as { buffer: Buffer; contentType: string }) - const tool = createAnalyzeImageTool('user-1', 'comment-1') - const result = await tool.execute('call-1', { assetId: 'asset-1' }) + const tool = createAnalyzeImageTool('user-1') + const result = await tool.execute('call-1', { assetId: 'asset-1', annotationId: 'comment-1' }) expect(prisma.workflowTask.create).toHaveBeenCalledWith({ data: { @@ -172,4 +173,90 @@ describe('analyzeImageTool', () => { ) expect(result.details.sourceKeys).toEqual(['annotated-image.webp']) }) + + it('should trigger overlay transcode workflow when annotationId matches AgentSessionEntry (1-on-1 chat mode)', async () => { + vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user-1' } as User) + vi.mocked(authzService.hasPermission).mockResolvedValue() + + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'asset-1', + projectId: 'project-1', + storageKey: { key: 'raw-image.png' }, + media: null, + } as unknown as Asset) + + vi.mocked(prisma.assetComment.findUnique).mockResolvedValue(null) + vi.mocked(prisma.agentSessionEntry.findUnique).mockResolvedValue({ + id: 'entry-1', + assetId: 'asset-1', + data: { + details: { + annotations: [{ type: 'arrow', x1: 5, y1: 5, x2: 20, y2: 20 }], + }, + }, + } as unknown as AgentSessionEntry) + + vi.mocked(prisma.workflowTask.create).mockResolvedValue({ + id: 'task-1', + } as unknown as WorkflowTask) + + vi.mocked(workflowService.executeWait).mockResolvedValue({ + id: 'task-1', + status: WorkflowTaskStatus.completed, + output: { key: 'chat-annotated-image.webp' }, + } as unknown as WorkflowTask) + + vi.mocked(s3Service.getObject).mockResolvedValue({ + buffer: Buffer.from('fake-chat-annotated-bytes'), + contentType: 'image/webp', + } as unknown as { buffer: Buffer; contentType: string }) + + const tool = createAnalyzeImageTool('user-1') + const result = await tool.execute('call-2', { assetId: 'asset-1', annotationId: 'entry-1' }) + + expect(prisma.workflowTask.create).toHaveBeenCalledWith({ + data: { + assetId: 'asset-1', + projectId: 'project-1', + type: 'transcode_image_annotation', + status: 'pending', + payload: { + projectId: 'project-1', + imageAnnotation: { + annotations: [{ type: 'arrow', x1: 5, y1: 5, x2: 20, y2: 20 }], + }, + }, + }, + }) + + expect(result.details.sourceKeys).toEqual(['chat-annotated-image.webp']) + }) + + it('should throw an error when annotationId belongs to a different asset', async () => { + vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user-1' } as User) + vi.mocked(authzService.hasPermission).mockResolvedValue() + + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'asset-1', + projectId: 'project-1', + storageKey: { key: 'raw-image.png' }, + media: null, + } as unknown as Asset) + + vi.mocked(prisma.assetComment.findUnique).mockResolvedValue({ + id: 'comment-on-other-asset', + assetId: 'asset-999', + annotation: [{ type: 'arrow' }], + } as unknown as AssetComment) + + const tool = createAnalyzeImageTool('user-1') + await expect( + tool.execute('call-mismatch', { + assetId: 'asset-1', + annotationId: 'comment-on-other-asset', + }), + ).rejects.toThrow( + 'Annotation "comment-on-other-asset" belongs to asset "asset-999", not target asset "asset-1".', + ) + }) }) diff --git a/packages/agent/src/tools/analyze-image.ts b/packages/agent/src/tools/analyze-image.ts index 46da5b51..472d277d 100644 --- a/packages/agent/src/tools/analyze-image.ts +++ b/packages/agent/src/tools/analyze-image.ts @@ -5,17 +5,21 @@ import { prisma, WorkflowTaskType, WorkflowTaskStatus, type User } from '@shumai import { s3Service } from '@shumai/core/src/s3/s3' import { workflowService } from '@shumai/workflow-core' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' +import { resolveAnnotationsById } from './annotation-resolver' const analyzeImageSchema = Type.Object({ assetId: Type.String({ description: 'The asset ID of the image to analyze. This parameter is required.', }), + annotationId: Type.Optional( + Type.String({ + description: + 'The ID of the comment or message entry from whose visual markup should be overlaid on the image.', + }), + ), }) -export function createAnalyzeImageTool( - userId: string, - userCommentId?: string | null, -): AgentTool { +export function createAnalyzeImageTool(userId: string): AgentTool { return { name: 'analyze_image', label: 'Analyze Image', @@ -70,19 +74,8 @@ export function createAnalyzeImageTool( throw new Error('No media content found for this asset.') } - // Check if trigger comment has draw annotations for this asset - let annotations: unknown = null - if (userCommentId) { - const comment = await prisma.assetComment.findUnique({ - where: { id: userCommentId }, - }) - if (comment && comment.assetId === assetId && comment.annotation) { - const list = comment.annotation - if (Array.isArray(list) && list.length > 0) { - annotations = list - } - } - } + // Resolve annotations dynamically by annotationId + const { annotations } = await resolveAnnotationsById(assetId, params.annotationId) let keyToUse = mediaKey @@ -97,7 +90,7 @@ export function createAnalyzeImageTool( payload: { projectId: asset.projectId || 'none', imageAnnotation: { - annotations: annotations as PrismaJson.AnnotationList, + annotations, }, }, }, diff --git a/packages/agent/src/tools/annotation-resolver.test.ts b/packages/agent/src/tools/annotation-resolver.test.ts new file mode 100644 index 00000000..2ea0e0df --- /dev/null +++ b/packages/agent/src/tools/annotation-resolver.test.ts @@ -0,0 +1,270 @@ +import { describe, it, expect, beforeEach } from 'vitest' +import { prisma } from '@shumai/db' +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' + +describe('resolveAnnotationsById', () => { + setupTestDbHooks() + + beforeEach(() => { + // DB hooks automatically manage transactions + }) + + it('returns null annotations and null timestamp when annotationId is undefined or empty', async () => { + const result1 = await resolveAnnotationsById('asset-1', undefined) + expect(result1).toEqual({ annotations: null, timestamp: null }) + + const result2 = await resolveAnnotationsById('asset-1', '') + expect(result2).toEqual({ annotations: null, timestamp: null }) + }) + + it('resolves annotations and timestamp from AssetComment (Comments Mode)', async () => { + const user = await prisma.user.create({ + data: { name: 'Comment Author', email: 'author@test.com', password: 'pw' }, + }) + const team = await prisma.team.create({ + data: { name: 'Test Team' }, + }) + const project = await prisma.project.create({ + data: { name: 'Test Project', teamId: team.id }, + }) + const asset = await prisma.asset.create({ + data: { + name: 'video.mp4', + type: 'file', + projectId: project.id, + status: 'uploaded', + }, + }) + + const comment = await prisma.assetComment.create({ + data: { + assetId: asset.id, + creatorId: user.id, + message: 'Look at the highlighted area', + second: 18.5, + annotation: [ + { + type: 'line', + color: '#ff0000', + points: [ + [10, 10], + [50, 50], + ], + }, + ], + }, + }) + + const result = await resolveAnnotationsById(asset.id, comment.id) + expect(result.timestamp).toBe(18.5) + expect(result.annotations).toEqual([ + { + type: 'line', + color: '#ff0000', + points: [ + [10, 10], + [50, 50], + ], + }, + ]) + }) + + it('throws an error when AssetComment belongs to a different asset', async () => { + const user = await prisma.user.create({ + data: { name: 'Author', email: 'author2@test.com', password: 'pw' }, + }) + const team = await prisma.team.create({ + data: { name: 'Team' }, + }) + const project = await prisma.project.create({ + data: { name: 'Project', teamId: team.id }, + }) + const assetA = await prisma.asset.create({ + data: { name: 'videoA.mp4', type: 'file', projectId: project.id, status: 'uploaded' }, + }) + const assetB = await prisma.asset.create({ + data: { name: 'videoB.mp4', type: 'file', projectId: project.id, status: 'uploaded' }, + }) + + const commentB = await prisma.assetComment.create({ + data: { + assetId: assetB.id, + creatorId: user.id, + message: 'Comment on B', + annotation: [ + { + type: 'box', + color: '#ff0000', + points: [ + [0, 0], + [10, 10], + ], + }, + ], + }, + }) + + await expect(resolveAnnotationsById(assetA.id, commentB.id)).rejects.toThrow( + `Annotation "${commentB.id}" belongs to asset "${assetB.id}", not target asset "${assetA.id}".`, + ) + }) + + it('resolves annotations and timestamp from AgentSessionEntry (1-on-1 Chat Mode)', async () => { + const user = await prisma.user.create({ + data: { name: 'Chat User', email: 'chatuser@test.com', password: 'pw' }, + }) + const team = await prisma.team.create({ + data: { name: 'Chat Team' }, + }) + const project = await prisma.project.create({ + data: { name: 'Chat Project', teamId: team.id }, + }) + const asset = await prisma.asset.create({ + data: { + name: 'chat-video.mp4', + type: 'file', + projectId: project.id, + status: 'uploaded', + }, + }) + const agentUser = await prisma.user.create({ + data: { name: 'Chat Bot User', email: 'bot@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' }, + }, + }) + + // Create session storage + const storage = await DatabaseSessionStorage.create({ + agentId: agent.id, + userId: user.id, + assetId: asset.id, + }) + + // Set active message context with markup annotations and position + storage.currentMessageContext = { + currentAsset: { + id: asset.id, + name: asset.name, + type: 'file', + path: asset.name, + }, + position: { type: 'time', seconds: 12.34 }, + annotation: true, + annotations: [ + { + type: 'rectangle', + x: 100, + y: 200, + width: 50, + height: 50, + }, + ], + } + + // User sends a message -> DatabaseSessionStorage.appendEntry is called + const userEntry: SessionTreeEntry = { + type: 'message', + id: '01JTESTENTRY1234567890', + parentId: null, + timestamp: new Date().toISOString(), + message: { + role: 'user', + content: 'Check this rectangle markup on video', + timestamp: Date.now(), + }, + } + + await storage.appendEntry(userEntry) + + // Verify DatabaseSessionStorage persisted entry with details.id = entry.id + const dbEntry = await prisma.agentSessionEntry.findUnique({ + where: { id: '01JTESTENTRY1234567890' }, + }) + expect(dbEntry).toBeDefined() + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const details = (dbEntry?.data as any)?.details + expect(details.id).toBe('01JTESTENTRY1234567890') + expect(details.position).toEqual({ type: 'time', seconds: 12.34 }) + expect(details.annotations).toHaveLength(1) + + // Now resolveAnnotationsById directly with the entry id and matching asset.id + const result = await resolveAnnotationsById(asset.id, '01JTESTENTRY1234567890') + expect(result.timestamp).toBe(12.34) + expect(result.annotations).toEqual([ + { + type: 'rectangle', + x: 100, + y: 200, + width: 50, + height: 50, + }, + ]) + }) + + 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' }, + }) + const team = await prisma.team.create({ + data: { name: 'Team' }, + }) + const project = await prisma.project.create({ + data: { name: 'Project', teamId: team.id }, + }) + const assetA = await prisma.asset.create({ + data: { name: 'chatA.mp4', type: 'file', projectId: project.id, status: 'uploaded' }, + }) + const assetB = await prisma.asset.create({ + data: { name: 'chatB.mp4', type: 'file', projectId: project.id, status: 'uploaded' }, + }) + const agentUser = await prisma.user.create({ + data: { name: 'Bot User', email: 'bot2@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: assetB.id, + }) + storage.currentMessageContext = { + currentAsset: { id: assetB.id, name: assetB.name, type: 'file', path: assetB.name }, + annotation: true, + annotations: [{ type: 'box' }], + } + const userEntry: SessionTreeEntry = { + type: 'message', + id: '01JENTRYONASSETB123456', + parentId: null, + timestamp: new Date().toISOString(), + message: { role: 'user', content: 'Markup on B', timestamp: Date.now() }, + } + await storage.appendEntry(userEntry) + + await expect(resolveAnnotationsById(assetA.id, '01JENTRYONASSETB123456')).rejects.toThrow( + `Annotation "01JENTRYONASSETB123456" belongs to asset "${assetB.id}", not target asset "${assetA.id}".`, + ) + }) + + it('throws an error if annotationId does not match any record', async () => { + await expect(resolveAnnotationsById('asset-1', 'non_existent_id')).rejects.toThrow( + 'Annotation with ID "non_existent_id" not found.', + ) + }) +}) diff --git a/packages/agent/src/tools/annotation-resolver.ts b/packages/agent/src/tools/annotation-resolver.ts new file mode 100644 index 00000000..b4201700 --- /dev/null +++ b/packages/agent/src/tools/annotation-resolver.ts @@ -0,0 +1,52 @@ +import { prisma } from '@shumai/db' +import type { ShumaiMessageContext } from '@shumai/dtos' + +export async function resolveAnnotationsById( + assetId: string, + annotationId?: string, +): Promise<{ annotations: PrismaJson.AnnotationList | null; timestamp: number | null }> { + if (!annotationId) { + return { annotations: null, timestamp: null } + } + + // 1. Check AssetComment table (Comments Mode) + const comment = await prisma.assetComment.findUnique({ + where: { id: annotationId }, + select: { assetId: true, annotation: true, second: true }, + }) + if (comment) { + if (comment.assetId !== assetId) { + throw new Error( + `Annotation "${annotationId}" belongs to asset "${comment.assetId}", not target asset "${assetId}".`, + ) + } + const list = comment.annotation + const annotations = + Array.isArray(list) && list.length > 0 ? (list as PrismaJson.AnnotationList) : null + return { annotations, timestamp: comment.second } + } + + // 2. Check AgentSessionEntry table (1-on-1 Chat Mode) + const entry = await prisma.agentSessionEntry.findUnique({ + where: { id: annotationId }, + select: { assetId: true, data: true }, + }) + if (entry) { + const details = (entry.data as Record | null)?.details as + | ShumaiMessageContext + | undefined + const entryAssetId = entry.assetId || details?.currentAsset?.id + if (entryAssetId && entryAssetId !== assetId) { + throw new Error( + `Annotation "${annotationId}" belongs to asset "${entryAssetId}", not target asset "${assetId}".`, + ) + } + 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 + return { annotations, timestamp } + } + + throw new Error(`Annotation with ID "${annotationId}" not found.`) +} diff --git a/packages/agent/src/tools/read-pdf-pages.test.ts b/packages/agent/src/tools/read-pdf-pages.test.ts index 5b084cb2..9f8743d9 100644 --- a/packages/agent/src/tools/read-pdf-pages.test.ts +++ b/packages/agent/src/tools/read-pdf-pages.test.ts @@ -5,6 +5,7 @@ import { WorkflowTaskStatus, type Asset, type AssetComment, + type AgentSessionEntry, type User, type WorkflowTask, } from '@shumai/db' @@ -26,6 +27,9 @@ vi.mock('@shumai/db', async (importOriginal) => { assetComment: { findUnique: vi.fn(), }, + agentSessionEntry: { + findUnique: vi.fn(), + }, workflowTask: { create: vi.fn(), }, @@ -59,7 +63,7 @@ describe('readPdfPagesTool', () => { vi.mocked(authzService.hasPermission).mockResolvedValue() }) - it('should trigger pdfPages transcode workflow and return image outputs', async () => { + it('should trigger pdfPages transcode workflow and return image outputs with annotation from AssetComment', async () => { vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user-1' } as User) vi.mocked(prisma.asset.findUnique).mockResolvedValue({ @@ -106,8 +110,13 @@ describe('readPdfPagesTool', () => { } as unknown as { buffer: Buffer; contentType: string } }) - const tool = createReadPdfPagesTool('user-1', 'comment-1') - const result = await tool.execute('call-1', { assetId: 'asset-1', start: 1, end: 2 }) + const tool = createReadPdfPagesTool('user-1') + const result = await tool.execute('call-1', { + assetId: 'asset-1', + start: 1, + end: 2, + annotationId: 'comment-1', + }) expect(authzService.hasPermission).toHaveBeenCalledWith({ user: { id: 'user-1' }, @@ -151,6 +160,101 @@ describe('readPdfPagesTool', () => { expect(result.details.sourceKeys).toEqual(['pdf_pages/page_1.webp', 'pdf_pages/page_2.webp']) }) + it('should trigger pdfPages transcode workflow with annotations from AgentSessionEntry (1-on-1 chat mode)', async () => { + vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user-1' } as User) + + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'asset-1', + projectId: 'project-1', + media: { proxyType: 'pdf' }, + } as unknown as Asset) + + vi.mocked(prisma.assetComment.findUnique).mockResolvedValue(null) + vi.mocked(prisma.agentSessionEntry.findUnique).mockResolvedValue({ + id: 'entry-1', + assetId: 'asset-1', + data: { + details: { + position: { type: 'page', page: 3 }, + annotations: [{ type: 'highlight', page: 3 }], + }, + }, + } as unknown as AgentSessionEntry) + + vi.mocked(prisma.workflowTask.create).mockResolvedValue({ + id: 'task-1', + } as unknown as WorkflowTask) + + vi.mocked(workflowService.executeWait).mockResolvedValue({ + id: 'task-1', + status: WorkflowTaskStatus.completed, + output: { + pages: [{ key: 'pdf_pages/page_3.webp', page: 3 }], + }, + } as unknown as WorkflowTask) + + vi.mocked(s3Service.getObject).mockImplementation(async (_bucket: string, key: string) => { + return { + buffer: Buffer.from(`fake-bytes-for-${key}`), + contentType: 'image/webp', + } as unknown as { buffer: Buffer; contentType: string } + }) + + const tool = createReadPdfPagesTool('user-1') + await tool.execute('call-2', { + assetId: 'asset-1', + start: 1, + end: 3, + annotationId: 'entry-1', + }) + + expect(prisma.workflowTask.create).toHaveBeenCalledWith({ + data: { + assetId: 'asset-1', + projectId: 'project-1', + type: 'transcode_pdf_pages', + status: 'pending', + payload: { + projectId: 'project-1', + pdfPages: { + start: 1, + end: 3, + commentTimestamp: null, + annotations: [{ type: 'highlight', page: 3 }], + }, + }, + }, + }) + }) + + it('should throw an error when annotationId belongs to a different asset', async () => { + vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user-1' } as User) + + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'asset-1', + projectId: 'project-1', + media: { proxyType: 'pdf' }, + } as unknown as Asset) + + vi.mocked(prisma.assetComment.findUnique).mockResolvedValue({ + id: 'comment-on-other-asset', + assetId: 'asset-pdf-2', + annotation: [{ type: 'highlight' }], + } as unknown as AssetComment) + + const tool = createReadPdfPagesTool('user-1') + await expect( + tool.execute('call-mismatch', { + assetId: 'asset-1', + start: 1, + end: 3, + annotationId: 'comment-on-other-asset', + }), + ).rejects.toThrow( + 'Annotation "comment-on-other-asset" belongs to asset "asset-pdf-2", not target asset "asset-1".', + ) + }) + it('should throw error if start page is less than 1', async () => { const tool = createReadPdfPagesTool('user-1') await expect(tool.execute('call-1', { assetId: 'asset-1', start: 0, end: 5 })).rejects.toThrow( @@ -160,50 +264,38 @@ describe('readPdfPagesTool', () => { it('should throw error if start page is greater than end page', async () => { const tool = createReadPdfPagesTool('user-1') - await expect(tool.execute('call-1', { assetId: 'asset-1', start: 5, end: 2 })).rejects.toThrow( - 'Invalid page range: start page (5) must be less than or equal to end page (2).', + await expect(tool.execute('call-1', { assetId: 'asset-1', start: 6, end: 5 })).rejects.toThrow( + 'Invalid page range: start page (6) must be less than or equal to end page (5).', ) }) - it('should throw error if page range exceeds maximum limit of 20', async () => { + it('should throw error if requested page range exceeds maximum limit of 20', async () => { const tool = createReadPdfPagesTool('user-1') - await expect(tool.execute('call-1', { assetId: 'asset-1', start: 1, end: 25 })).rejects.toThrow( - 'Page range (25 pages requested) exceeds the maximum limit of 20 pages per request.', + await expect(tool.execute('call-1', { assetId: 'asset-1', start: 1, end: 22 })).rejects.toThrow( + 'Page range (22 pages requested) exceeds the maximum limit of 20 pages per request.', ) }) - it('should throw error if asset not found', async () => { + it('should throw error if asset is not found', async () => { + vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user-1' } as User) vi.mocked(prisma.asset.findUnique).mockResolvedValue(null) const tool = createReadPdfPagesTool('user-1') - await expect(tool.execute('call-1', { assetId: 'asset-1', start: 1, end: 3 })).rejects.toThrow( - 'Asset with ID asset-1 not found.', - ) + await expect( + tool.execute('call-1', { assetId: 'non-existent', start: 1, end: 2 }), + ).rejects.toThrow('Asset with ID non-existent not found.') }) - it('should throw error if proxyType is not pdf', async () => { + it('should throw error if asset is not a PDF proxyType', async () => { + vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user-1' } as User) vi.mocked(prisma.asset.findUnique).mockResolvedValue({ - id: 'asset-1', - projectId: 'project-1', - media: { proxyType: 'image' }, + id: 'asset-video', + media: { proxyType: 'video' }, } as unknown as Asset) const tool = createReadPdfPagesTool('user-1') - await expect(tool.execute('call-1', { assetId: 'asset-1', start: 1, end: 3 })).rejects.toThrow( - 'Asset asset-1 is not a PDF or document.', - ) - }) - - it('should throw error if proxyType is null/undefined (unprocessed)', async () => { - vi.mocked(prisma.asset.findUnique).mockResolvedValue({ - id: 'asset-1', - projectId: 'project-1', - media: null, - } as unknown as Asset) - - const tool = createReadPdfPagesTool('user-1') - await expect(tool.execute('call-1', { assetId: 'asset-1', start: 1, end: 3 })).rejects.toThrow( - 'Asset asset-1 is not a PDF or document.', - ) + await expect( + tool.execute('call-1', { assetId: 'asset-video', start: 1, end: 2 }), + ).rejects.toThrow('Asset asset-video is not a PDF or document.') }) }) diff --git a/packages/agent/src/tools/read-pdf-pages.ts b/packages/agent/src/tools/read-pdf-pages.ts index d9cad2bb..f1ba9c09 100644 --- a/packages/agent/src/tools/read-pdf-pages.ts +++ b/packages/agent/src/tools/read-pdf-pages.ts @@ -5,6 +5,7 @@ import { prisma, WorkflowTaskType, WorkflowTaskStatus, type User } from '@shumai import { s3Service } from '@shumai/core/src/s3/s3' import { workflowService } from '@shumai/workflow-core' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' +import { resolveAnnotationsById } from './annotation-resolver' const readPdfPagesSchema = Type.Object({ assetId: Type.String({ @@ -12,12 +13,15 @@ const readPdfPagesSchema = Type.Object({ }), start: Type.Number({ description: 'Start page number (1-based index)' }), end: Type.Number({ description: 'End page number (1-based index)' }), + annotationId: Type.Optional( + Type.String({ + description: + 'The ID of the comment or message entry from whose visual markup should be overlaid on the rendered PDF pages.', + }), + ), }) -export function createReadPdfPagesTool( - userId: string, - userCommentId?: string | null, -): AgentTool { +export function createReadPdfPagesTool(userId: string): AgentTool { return { name: 'read_pdf_pages', label: 'Read PDF Pages', @@ -79,23 +83,11 @@ export function createReadPdfPagesTool( throw new Error(`Asset ${targetAssetId} is not a PDF or document.`) } - // Fetch trigger comment details for comment page and annotations - let commentTimestamp: number | null = null - let annotations: unknown = null - if (userCommentId) { - const comment = await prisma.assetComment.findUnique({ - where: { id: userCommentId }, - }) - if (comment && comment.assetId === targetAssetId) { - commentTimestamp = comment.second !== null ? comment.second : null - if (comment.annotation) { - const list = comment.annotation - if (Array.isArray(list) && list.length > 0) { - annotations = list - } - } - } - } + // Resolve annotations dynamically by annotationId + const { annotations, timestamp: commentTimestamp } = await resolveAnnotationsById( + targetAssetId, + params.annotationId, + ) // Trigger transcode workflow to render PDF pages const task = await prisma.workflowTask.create({ @@ -110,7 +102,7 @@ export function createReadPdfPagesTool( start: params.start, end: params.end, commentTimestamp, - annotations: annotations as PrismaJson.AnnotationList, + annotations, }, }, }, diff --git a/packages/agent/src/tools/read-thread.test.ts b/packages/agent/src/tools/read-thread.test.ts index 6dd3ed91..a4fbb6f3 100644 --- a/packages/agent/src/tools/read-thread.test.ts +++ b/packages/agent/src/tools/read-thread.test.ts @@ -51,6 +51,8 @@ describe('createReadThreadTool', () => { id: 'root-1', message: 'Initial top-level question', creator: { name: 'Alice' }, + second: 12.5, + annotation: [{ type: 'box' }], // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any) vi.mocked(prisma.assetComment.findMany).mockResolvedValue([]) @@ -59,7 +61,9 @@ describe('createReadThreadTool', () => { const result = await tool.execute('call-2', { threadId: 'root-1' }) const textContent = (result.content[0] as { text: string }).text - expect(textContent).toContain('Thread Root [Alice] (root-1): Initial top-level question') + expect(textContent).toContain( + 'Thread Root [Alice] (id: root-1, time: 12.5s, has_markup: true): Initial top-level question', + ) expect(textContent).toContain('(No replies in this thread yet)') }) @@ -75,6 +79,8 @@ describe('createReadThreadTool', () => { id: 'reply-1', message: 'First reply to thread', creator: { name: 'Bob' }, + second: 15.0, + annotation: [{ type: 'line' }], }, { id: 'reply-2', @@ -88,9 +94,15 @@ describe('createReadThreadTool', () => { const result = await tool.execute('call-3', { threadId: 'root-1' }) const textContent = (result.content[0] as { text: string }).text - expect(textContent).toContain('Thread Root [Alice] (root-1): Initial top-level question') - expect(textContent).toContain('- [Bob]: First reply to thread') - expect(textContent).toContain('- [Charlie]: Second reply to thread') + expect(textContent).toContain( + 'Thread Root [Alice] (id: root-1, has_markup: false): Initial top-level question', + ) + expect(textContent).toContain( + '- [Bob] (id: reply-1, time: 15s, has_markup: true): First reply to thread', + ) + expect(textContent).toContain( + '- [Charlie] (id: reply-2, has_markup: false): Second reply to thread', + ) }) it('should label agent replies as [Ai Agent] when creator is null but sessionId exists', async () => { @@ -114,7 +126,7 @@ describe('createReadThreadTool', () => { const result = await tool.execute('call-agent', { threadId: 'root-1' }) const textContent = (result.content[0] as { text: string }).text - expect(textContent).toContain('- [Ai Agent]: Agent answer') + expect(textContent).toContain('- [Ai Agent] (id: reply-1, has_markup: false): Agent answer') }) it('should describe threadId parameter as referencing in ', () => { diff --git a/packages/agent/src/tools/read-thread.ts b/packages/agent/src/tools/read-thread.ts index c4dafba2..4a258c95 100644 --- a/packages/agent/src/tools/read-thread.ts +++ b/packages/agent/src/tools/read-thread.ts @@ -9,6 +9,20 @@ const readThreadSchema = Type.Object({ }), }) +function formatCommentMeta(c: { + id: string + second?: number | null + annotation?: unknown +}): string { + const parts = [`id: ${c.id}`] + if (c.second !== null && c.second !== undefined) { + parts.push(`time: ${c.second}s`) + } + const hasMarkup = Boolean(c.annotation && Array.isArray(c.annotation) && c.annotation.length > 0) + parts.push(`has_markup: ${hasMarkup}`) + return `(${parts.join(', ')})` +} + export const createReadThreadTool = (): AgentTool< typeof readThreadSchema, { threadId: string } @@ -49,7 +63,8 @@ export const createReadThreadTool = (): AgentTool< const isRootAgent = rootComment.creator?.type === 'agent' || rootComment.sessionId !== null const rootAuthor = rootComment.creator?.name || (isRootAgent ? 'Ai Agent' : 'User') - let output = `Thread Root [${rootAuthor}] (${rootComment.id}): ${rootComment.message || ''}\n\nReplies (${replies.length}):` + const rootMeta = formatCommentMeta(rootComment) + let output = `Thread Root [${rootAuthor}] ${rootMeta}: ${rootComment.message || ''}\n\nReplies (${replies.length}):` if (replies.length === 0) { output += '\n(No replies in this thread yet)' @@ -57,7 +72,8 @@ 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') - output += `\n- [${author}]: ${reply.message || ''}` + const replyMeta = formatCommentMeta(reply) + output += `\n- [${author}] ${replyMeta}: ${reply.message || ''}` } } diff --git a/packages/agent/src/tools/screenshot.test.ts b/packages/agent/src/tools/screenshot.test.ts index 7c704851..1fab9864 100644 --- a/packages/agent/src/tools/screenshot.test.ts +++ b/packages/agent/src/tools/screenshot.test.ts @@ -5,6 +5,7 @@ import { WorkflowTaskStatus, type Asset, type AssetComment, + type AgentSessionEntry, type User, type WorkflowTask, } from '@shumai/db' @@ -26,6 +27,9 @@ vi.mock('@shumai/db', async (importOriginal) => { assetComment: { findUnique: vi.fn(), }, + agentSessionEntry: { + findUnique: vi.fn(), + }, workflowTask: { create: vi.fn(), }, @@ -58,7 +62,7 @@ describe('screenshotTool', () => { vi.clearAllMocks() }) - it('should trigger screenshot transcode workflow and return image outputs', async () => { + it('should trigger screenshot transcode workflow with annotations when annotationId matches AssetComment', async () => { vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user-1' } as User) vi.mocked(authzService.hasPermission).mockResolvedValue() @@ -105,8 +109,14 @@ describe('screenshotTool', () => { } as unknown as { buffer: Buffer; contentType: string } }) - const tool = createScreenshotTool('user-1', 'comment-1') - const result = await tool.execute('call-1', { assetId: 'asset-1', start: 0, end: 10, count: 2 }) + const tool = createScreenshotTool('user-1') + const result = await tool.execute('call-1', { + assetId: 'asset-1', + start: 0, + end: 10, + count: 2, + annotationId: 'comment-1', + }) expect(authzService.hasPermission).toHaveBeenCalledWith({ user: { id: 'user-1' }, @@ -153,4 +163,158 @@ describe('screenshotTool', () => { ) expect(result.details.sourceKeys).toEqual(['screenshots/shot1.webp', 'screenshots/shot2.webp']) }) + + it('should trigger screenshot transcode workflow with annotations when annotationId matches AgentSessionEntry (1-on-1 chat)', async () => { + vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user-1' } as User) + vi.mocked(authzService.hasPermission).mockResolvedValue() + + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'asset-1', + projectId: 'project-1', + } as unknown as Asset) + + vi.mocked(prisma.assetComment.findUnique).mockResolvedValue(null) + vi.mocked(prisma.agentSessionEntry.findUnique).mockResolvedValue({ + id: 'entry-1', + assetId: 'asset-1', + data: { + details: { + position: { type: 'time', seconds: 7.25 }, + annotations: [{ type: 'rectangle', x: 10, y: 20, width: 30, height: 40 }], + }, + }, + } as unknown as AgentSessionEntry) + + vi.mocked(prisma.workflowTask.create).mockResolvedValue({ + id: 'task-1', + } as unknown as WorkflowTask) + + vi.mocked(workflowService.executeWait).mockResolvedValue({ + id: 'task-1', + status: WorkflowTaskStatus.completed, + output: { + screenshots: [{ key: 'screenshots/shot-chat.webp', timestamp: 7.25 }], + }, + } as unknown as WorkflowTask) + + vi.mocked(s3Service.getObject).mockImplementation(async (_bucket: string, key: string) => { + return { + buffer: Buffer.from(`fake-bytes-for-${key}`), + contentType: 'image/webp', + } as unknown as { buffer: Buffer; contentType: string } + }) + + const tool = createScreenshotTool('user-1') + await tool.execute('call-2', { + assetId: 'asset-1', + start: 5, + end: 10, + count: 1, + annotationId: 'entry-1', + }) + + expect(prisma.workflowTask.create).toHaveBeenCalledWith({ + data: { + assetId: 'asset-1', + projectId: 'project-1', + type: 'transcode_screenshot', + status: 'pending', + payload: { + projectId: 'project-1', + screenshot: { + start: 5, + end: 10, + count: 1, + commentTimestamp: 7.25, + annotations: [{ type: 'rectangle', x: 10, y: 20, width: 30, height: 40 }], + }, + }, + }, + }) + }) + + it('should throw an error when annotationId belongs to a different asset', async () => { + vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user-1' } as User) + vi.mocked(authzService.hasPermission).mockResolvedValue() + + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'asset-1', + projectId: 'project-1', + } as unknown as Asset) + + vi.mocked(prisma.assetComment.findUnique).mockResolvedValue({ + id: 'comment-on-other-asset', + assetId: 'asset-2', + annotation: [{ type: 'arrow' }], + } as unknown as AssetComment) + + const tool = createScreenshotTool('user-1') + await expect( + tool.execute('call-mismatch', { + assetId: 'asset-1', + start: 0, + end: 5, + count: 1, + annotationId: 'comment-on-other-asset', + }), + ).rejects.toThrow( + 'Annotation "comment-on-other-asset" belongs to asset "asset-2", not target asset "asset-1".', + ) + }) + + it('should take unannotated screenshots when annotationId is omitted', async () => { + vi.mocked(prisma.user.findUnique).mockResolvedValue({ id: 'user-1' } as User) + vi.mocked(authzService.hasPermission).mockResolvedValue() + + vi.mocked(prisma.asset.findUnique).mockResolvedValue({ + id: 'asset-1', + projectId: 'project-1', + } as unknown as Asset) + + vi.mocked(prisma.workflowTask.create).mockResolvedValue({ + id: 'task-1', + } as unknown as WorkflowTask) + + vi.mocked(workflowService.executeWait).mockResolvedValue({ + id: 'task-1', + status: WorkflowTaskStatus.completed, + output: { + screenshots: [{ key: 'screenshots/shot-clean.webp', timestamp: 0.0 }], + }, + } as unknown as WorkflowTask) + + vi.mocked(s3Service.getObject).mockImplementation(async (_bucket: string, key: string) => { + return { + buffer: Buffer.from(`fake-bytes-for-${key}`), + contentType: 'image/webp', + } as unknown as { buffer: Buffer; contentType: string } + }) + + const tool = createScreenshotTool('user-1') + await tool.execute('call-3', { + assetId: 'asset-1', + start: 0, + end: 5, + count: 1, + }) + + expect(prisma.workflowTask.create).toHaveBeenCalledWith({ + data: { + assetId: 'asset-1', + projectId: 'project-1', + type: 'transcode_screenshot', + status: 'pending', + payload: { + projectId: 'project-1', + screenshot: { + start: 0, + end: 5, + count: 1, + commentTimestamp: null, + annotations: null, + }, + }, + }, + }) + }) }) diff --git a/packages/agent/src/tools/screenshot.ts b/packages/agent/src/tools/screenshot.ts index d0905ee0..9bf750c8 100644 --- a/packages/agent/src/tools/screenshot.ts +++ b/packages/agent/src/tools/screenshot.ts @@ -5,6 +5,7 @@ import { prisma, WorkflowTaskType, WorkflowTaskStatus, type User } from '@shumai import { s3Service } from '@shumai/core/src/s3/s3' import { workflowService } from '@shumai/workflow-core' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' +import { resolveAnnotationsById } from './annotation-resolver' const screenshotSchema = Type.Object({ assetId: Type.String({ @@ -13,12 +14,15 @@ const screenshotSchema = Type.Object({ start: Type.Number({ description: 'Start time in seconds' }), end: Type.Number({ description: 'End time in seconds' }), count: Type.Number({ description: 'Number of screenshots to take' }), + annotationId: Type.Optional( + Type.String({ + description: + 'The ID of the comment or message entry from whose visual markup should be overlaid on the screenshot.', + }), + ), }) -export function createScreenshotTool( - userId: string, - userCommentId?: string | null, -): AgentTool { +export function createScreenshotTool(userId: string): AgentTool { return { name: 'screenshot', label: 'Take Video Screenshots', @@ -47,23 +51,11 @@ export function createScreenshotTool( throw new Error(`Asset with ID ${assetId} not found.`) } - // Fetch trigger comment details for timestamp and annotations - let commentTimestamp: number | null = null - let annotations: unknown = null - if (userCommentId) { - const comment = await prisma.assetComment.findUnique({ - where: { id: userCommentId }, - }) - if (comment && comment.assetId === assetId) { - commentTimestamp = comment.second !== null ? comment.second : null - if (comment.annotation) { - const list = comment.annotation - if (Array.isArray(list) && list.length > 0) { - annotations = list - } - } - } - } + // Resolve annotations dynamically by annotationId + const { annotations, timestamp: commentTimestamp } = await resolveAnnotationsById( + assetId, + params.annotationId, + ) // Trigger transcode workflow to take screenshots const task = await prisma.workflowTask.create({ @@ -79,7 +71,7 @@ export function createScreenshotTool( end: params.end, count: params.count, commentTimestamp, - annotations: annotations as PrismaJson.AnnotationList, + annotations, }, }, }, diff --git a/packages/agent/src/workflows/agent-chat.test.ts b/packages/agent/src/workflows/agent-chat.test.ts index 77f7fd36..39a90531 100644 --- a/packages/agent/src/workflows/agent-chat.test.ts +++ b/packages/agent/src/workflows/agent-chat.test.ts @@ -766,4 +766,44 @@ describe('Agent Chat Workflow', () => { }), ) }) + + it('should include userCommentId as id in comment messageContext', async () => { + mockActivities.getCommentActivity.mockResolvedValue({ + id: 'comment-with-id-123', + creatorId: 'user-c1', + message: 'Check this out', + replyToId: null, + second: 5.0, + annotation: [{ type: 'arrow' }], + attachments: [], + }) + + const task = await prisma.workflowTask.create({ + data: { + type: 'chat', + status: 'pending', + assetId: 'a1', + payload: { + projectId: 'p1', + agent: { + agentId: 'b1', + userCommentId: 'comment-with-id-123', + }, + }, + }, + }) + + await agentChat(task) + + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith( + expect.objectContaining({ + messageContext: expect.objectContaining({ + id: 'comment-with-id-123', + position: { type: 'time', seconds: 5.0 }, + annotation: true, + annotations: [{ type: 'arrow' }], + }), + }), + ) + }) }) diff --git a/packages/agent/src/workflows/agent-chat.ts b/packages/agent/src/workflows/agent-chat.ts index 2ccd8977..40ea7756 100644 --- a/packages/agent/src/workflows/agent-chat.ts +++ b/packages/agent/src/workflows/agent-chat.ts @@ -298,6 +298,7 @@ export async function agentChat(task: WorkflowTask): Promise { // Build structured ShumaiMessageContext const messageContext: ShumaiMessageContext = { + ...(userCommentId ? { id: userCommentId } : {}), ...(userInfo ? { user: { id: targetUserId!, name: userInfo.name, role: userInfo.role } } : {}), diff --git a/packages/dtos/src/chat.ts b/packages/dtos/src/chat.ts index 7ef50f03..1159ba5a 100644 --- a/packages/dtos/src/chat.ts +++ b/packages/dtos/src/chat.ts @@ -87,6 +87,7 @@ export const shumaiThreadContextSchema = z.object({ export type ShumaiThreadContext = z.infer export const shumaiMessageContextSchema = z.object({ + id: z.string().optional(), user: z .object({ id: z.string(), diff --git a/packages/dtos/src/context.ts b/packages/dtos/src/context.ts index 4bd95c82..2570f0e9 100644 --- a/packages/dtos/src/context.ts +++ b/packages/dtos/src/context.ts @@ -107,9 +107,13 @@ export function serializeContextToXml(context?: ShumaiMessageContext | null): st } } - // 4. + // 4. if (context.annotation) { - lines.push(' ') + if (context.id !== undefined) { + lines.push(` `) + } else { + lines.push(' ') + } } // 5. ...