From 729d16d3eec8d41116dde8d5c80b6dd9111227bc Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 3 Jun 2026 15:48:25 +0800 Subject: [PATCH 1/3] test(agent): write solid tests for agent workflows and activities --- packages/agent/src/activities/agent.test.ts | 547 +++++++++++++++++- packages/agent/src/activities/ai.test.ts | 278 ++++++++- .../src/workflows/agent-autofill.test.ts | 209 ++++++- .../agent/src/workflows/agent-chat.test.ts | 294 +++++++++- .../src/workflows/agent-embedding.test.ts | 150 ++++- .../src/workflows/agent-tool-call.test.ts | 140 +++++ .../query-embedding-for-search.test.ts | 145 +++++ 7 files changed, 1723 insertions(+), 40 deletions(-) create mode 100644 packages/agent/src/workflows/agent-tool-call.test.ts create mode 100644 packages/agent/src/workflows/query-embedding-for-search.test.ts diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index 77a250cb..1c0cc9ba 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -1,8 +1,28 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { agentChatActivity, autofillAiActivity, type AgentExecutionContext } from './agent' +import { + agentChatActivity, + autofillAiActivity, + type AgentExecutionContext, + initializeAgentSessionActivity, + deleteCommentActivity, + createCommentActivity, + updateCommentActivity, + getAgentChatContextActivity, + getAgentAutofillContextActivity, + getAssetActivity, + getCommentActivity, + getProjectAutofillFieldsActivity, + updateAssetMetadataActivity, + getAssetPathContextActivity, + executeAgentToolActivity, +} from './agent' import * as piAgent from '../index' import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core' import { type DatabaseSessionMetadata } from '../database-session-storage' +import { prisma, AssetType, AssetStatus } from '@shumai/db' +import { setupTestDbHooks } from '@shumai/db/test' +import { authzService } from '@shumai/core/src/authz/authz' +import { uploadService } from '@shumai/core/src/upload/upload' vi.mock('../index', async () => { const actual = await vi.importActual('../index') @@ -112,7 +132,6 @@ describe('Agent Activities', () => { } vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: unknown) => { - // Simulate tool execution const params = config as { customTools: Array<{ name: string @@ -147,3 +166,527 @@ describe('Agent Activities', () => { expect(res.usage.inputTokens).toBe(5) }) }) + +describe('Agent Database Activities Integration', () => { + setupTestDbHooks() + + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests + let team: any + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests + let user: any + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests + let project: any + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests + let asset: any + + beforeEach(async () => { + vi.restoreAllMocks() + + team = await prisma.team.create({ + data: { name: 'Test Team' }, + }) + + user = await prisma.user.create({ + data: { + name: 'Test Human', + email: 'human@shumai.ai', + type: 'human', + }, + }) + + project = await prisma.project.create({ + data: { + name: 'Test Project', + teamId: team.id, + }, + }) + + asset = await prisma.asset.create({ + data: { + name: 'file.png', + type: AssetType.file, + status: AssetStatus.uploaded, + projectId: project.id, + }, + }) + + await prisma.teamMember.create({ + data: { + teamId: team.id, + userId: user.id, + role: 'owner', + scope: 'team', + }, + }) + }) + + describe('initializeAgentSessionActivity', () => { + it('should initialize a session, create agent/user records if missing, and store existing comments context', async () => { + // Create first comment so it acts as context + await prisma.assetComment.create({ + data: { + assetId: asset.id, + message: 'Hello <@' + user.id + '> check this', + creatorId: user.id, + }, + }) + + // Create second comment that user responds with, triggering session initialization + const userComment = await prisma.assetComment.create({ + data: { + assetId: asset.id, + message: 'Reply comment', + creatorId: user.id, + }, + }) + + const sessionId = await initializeAgentSessionActivity({ + teamId: team.id, + agentId: 'test-agent-id', + userCommentId: userComment.id, + userId: user.id, + }) + + expect(sessionId).toBeDefined() + + // Verify agent user created + const agentUser = await prisma.user.findUnique({ where: { id: 'test-agent-id' } }) + expect(agentUser).toBeDefined() + expect(agentUser?.type).toBe('agent') + + // Verify agentSession created + const agentSession = await prisma.agentSession.findUnique({ + where: { id: sessionId }, + include: { entries: true }, + }) + expect(agentSession).toBeDefined() + expect(agentSession?.leafId).toBeDefined() + + // Verify historical comment is converted and saved to entries (mentions replaced, prefixes added) + expect(agentSession?.entries.length).toBe(1) + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- entry is stored as Json in DB and needs casting to check properties + const parsedEntry = agentSession?.entries[0].entry as any + expect(parsedEntry.message.content[0].text).toContain( + `[${user.name}]: Hello <@${user.name}> check this`, + ) + }) + }) + + describe('Comment Operations', () => { + it('should create, update, and delete comments correctly', async () => { + const comment = await createCommentActivity({ + assetId: asset.id, + message: 'Drafting response', + agentId: 'default', + }) + + expect(comment.id).toBeDefined() + expect(comment.message).toBe('Drafting response') + + const updated = await updateCommentActivity({ + commentId: comment.id, + message: 'Final response', + }) + expect(updated.message).toBe('Final response') + + await deleteCommentActivity(comment.id) + const deleted = await prisma.assetComment.findUnique({ where: { id: comment.id } }) + expect(deleted).toBeNull() + }) + }) + + describe('Context Retrievals', () => { + it('should retrieve Agent chat and autofill contexts correctly', async () => { + const provider = await prisma.provider.create({ + data: { + teamId: team.id, + name: 'openai', + config: { + api: 'openai', + apiKey: 'mock-key', + }, + }, + }) + + const model = await prisma.model.create({ + data: { + providerId: provider.id, + modelId: 'gpt-4', + name: 'GPT 4', + config: { + reasoning: false, + input: ['text'], + contextWindow: 8192, + maxTokens: 2048, + cost: { input: 0.01, output: 0.03, cacheRead: 0, cacheWrite: 0 } + }, + }, + }) + + // Create User to map Agent 1-to-1 + const agentUser = await prisma.user.create({ + data: { + id: 'chat-agent-id', + name: 'Chat Agent User', + email: 'chatagent@shumai.ai', + type: 'agent', + }, + }) + + const agent = await prisma.agent.create({ + data: { + id: agentUser.id, + teamId: team.id, + type: 'chat', + providerId: provider.id, + modelId: model.id, + config: { + provider: 'openai', + model: 'gpt-4', + }, + }, + }) + + const chatCtx = await getAgentChatContextActivity({ + teamId: team.id, + agentId: agent.id, + }) + + expect(chatCtx.agent.id).toBe(agent.id) + expect(chatCtx.dbProviders[0].name).toBe('openai') + + // Create User for autofill agent + const autofillUser = await prisma.user.create({ + data: { + name: 'Autofill Agent User', + email: 'autofillagent@shumai.ai', + type: 'agent', + }, + }) + + const autofillAgent = await prisma.agent.create({ + data: { + id: autofillUser.id, + teamId: team.id, + type: 'autofill', + enabled: true, + providerId: provider.id, + modelId: model.id, + config: { + provider: 'openai', + model: 'gpt-4', + }, + }, + }) + + const autofillCtx = await getAgentAutofillContextActivity({ + teamId: team.id, + }) + + expect(autofillCtx.agent.id).toBe(autofillAgent.id) + }) + }) + + describe('Asset and Comment Fetching', () => { + it('should retrieve asset and comment correctly', async () => { + const fetchedAsset = await getAssetActivity(asset.id) + expect(fetchedAsset?.id).toBe(asset.id) + + const comment = await createCommentActivity({ + assetId: asset.id, + message: 'draft comment', + }) + const fetchedComment = await getCommentActivity(comment.id) + expect(fetchedComment?.id).toBe(comment.id) + }) + }) + + describe('getAssetPathContextActivity', () => { + it('should build correct asset path context from root to asset', async () => { + const rootFolder = await prisma.asset.create({ + data: { + name: 'RootFolder', + type: AssetType.folder, + status: AssetStatus.uploaded, + projectId: project.id, + }, + }) + + const subfolder = await prisma.asset.create({ + data: { + name: 'SubFolder', + type: AssetType.folder, + status: AssetStatus.uploaded, + projectId: project.id, + parentId: rootFolder.id, + }, + }) + + const targetAsset = await prisma.asset.create({ + data: { + name: 'TargetImage.webp', + type: AssetType.file, + status: AssetStatus.uploaded, + projectId: project.id, + parentId: subfolder.id, + }, + }) + + const pathCtx = await getAssetPathContextActivity(targetAsset.id) + expect(pathCtx).toContain('Path: RootFolder/SubFolder/TargetImage.webp') + expect(pathCtx).toContain(`name: RootFolder, id: ${rootFolder.id}`) + expect(pathCtx).toContain(`name: SubFolder, id: ${subfolder.id}`) + expect(pathCtx).toContain(`name: TargetImage.webp, id: ${targetAsset.id}`) + }) + }) + + describe('getProjectAutofillFieldsActivity & updateAssetMetadataActivity', () => { + it('should get fields and update metadata', async () => { + // Create team field + await prisma.metadataField.create({ + data: { + key: 'field_key_1', + scope: 'TEAM', + teamId: team.id, + aiAutofill: true, + config: { name: 'Title Extractor', type: 'text' }, + }, + }) + + const fields = await getProjectAutofillFieldsActivity(project.id) + expect(fields.length).toBe(1) + expect(fields[0].key).toBe('field_key_1') + + await updateAssetMetadataActivity({ + assetId: asset.id, + metadata: [{ key: 'field_key_1', value: 'Hello Web' }], + }) + + const updatedVal = await prisma.assetMetadataValue.findFirst({ + where: { assetId: asset.id, fieldKey: 'field_key_1' }, + }) + expect(updatedVal?.stringValue).toBe('Hello Web') + }) + }) + + describe('executeAgentToolActivity', () => { + beforeEach(() => { + vi.spyOn(authzService, 'hasPermission').mockResolvedValue() + vi.spyOn(uploadService, 'triggerPostUploadWorkflows').mockResolvedValue() + }) + + describe('list_assets', () => { + it('should list assets inside a folder with cursor pagination', async () => { + const folder = await prisma.asset.create({ + data: { + name: 'WorkspaceFolder', + type: AssetType.folder, + status: AssetStatus.uploaded, + projectId: project.id, + }, + }) + + await prisma.asset.create({ + data: { + name: 'file1.txt', + type: AssetType.file, + status: AssetStatus.uploaded, + projectId: project.id, + parentId: folder.id, + }, + }) + + await prisma.asset.create({ + data: { + name: 'subfolder1', + type: AssetType.folder, + status: AssetStatus.uploaded, + projectId: project.id, + parentId: folder.id, + }, + }) + + const res = await executeAgentToolActivity({ + taskId: 'task-1', + toolName: 'list_assets', + args: { parent: folder.id, page: 1, pageSize: 1 }, + userId: user.id, + }) + + expect(res.assets.length).toBe(1) + expect(res.pageInfo.cursor).toBeDefined() + }) + }) + + describe('create_folder', () => { + it('should create folder and increment parent fileCount', async () => { + const folder = await prisma.asset.create({ + data: { + name: 'WorkspaceFolder', + type: AssetType.folder, + status: AssetStatus.uploaded, + projectId: project.id, + fileCount: 0, + }, + }) + + const res = await executeAgentToolActivity({ + taskId: 'task-1', + toolName: 'create_folder', + args: { parent: folder.id, name: 'subfolder' }, + userId: user.id, + }) + + expect(res.name).toBe('subfolder') + expect(res.type).toBe('folder') + + const parentFolder = await prisma.asset.findUnique({ where: { id: folder.id } }) + expect(parentFolder?.fileCount).toBe(1) + }) + }) + + describe('create_file', () => { + it('should create file, increment parent fileCount, and update parent sizes', async () => { + const folder = await prisma.asset.create({ + data: { + name: 'WorkspaceFolder', + type: AssetType.folder, + status: AssetStatus.uploaded, + projectId: project.id, + fileCount: 0, + sizeByte: 0, + }, + }) + + const res = await executeAgentToolActivity({ + taskId: 'task-1', + toolName: 'create_file', + args: { + parent: folder.id, + s3Key: 'uploads/testfile.txt', + name: 'testfile.txt', + size: 500, + contentType: 'text/plain', + }, + userId: user.id, + }) + + expect(res.name).toBe('testfile.txt') + expect(res.size).toBe(500) + + const parentFolder = await prisma.asset.findUnique({ where: { id: folder.id } }) + expect(parentFolder?.fileCount).toBe(1) + expect(parentFolder?.sizeByte).toBe(500) + expect(uploadService.triggerPostUploadWorkflows).toHaveBeenCalled() + }) + }) + + describe('create_version', () => { + it('should create a version stack when parent is a regular file', async () => { + const folder = await prisma.asset.create({ + data: { + name: 'WorkspaceFolder', + type: AssetType.folder, + status: AssetStatus.uploaded, + projectId: project.id, + fileCount: 1, + sizeByte: 200, + }, + }) + + const fileAsset = await prisma.asset.create({ + data: { + name: 'v1.txt', + type: AssetType.file, + status: AssetStatus.uploaded, + projectId: project.id, + parentId: folder.id, + sizeByte: 200, + }, + }) + + const res = await executeAgentToolActivity({ + taskId: 'task-1', + toolName: 'create_version', + args: { + parent: fileAsset.id, + s3Key: 'uploads/v2.txt', + name: 'v2.txt', + size: 300, + contentType: 'text/plain', + }, + userId: user.id, + }) + + expect(res.name).toBe('v2.txt') + expect(res.size).toBe(300) + + // Check version stack was created + const stack = await prisma.asset.findFirst({ + where: { type: AssetType.version_stack, projectId: project.id }, + include: { children: true }, + }) + + expect(stack).not.toBeNull() + expect(stack?.children.length).toBe(2) // v1.txt and v2.txt should both be inside the stack + }) + + it('should add to version stack when parent is already inside a version stack', async () => { + const folder = await prisma.asset.create({ + data: { + name: 'WorkspaceFolder', + type: AssetType.folder, + status: AssetStatus.uploaded, + projectId: project.id, + }, + }) + + const stack = await prisma.asset.create({ + data: { + name: 'VersionStack', + type: AssetType.version_stack, + status: AssetStatus.uploaded, + projectId: project.id, + parentId: folder.id, + fileCount: 1, + sizeByte: 100, + }, + }) + + const existingFileVersion = await prisma.asset.create({ + data: { + name: 'v1.txt', + type: AssetType.file, + status: AssetStatus.uploaded, + projectId: project.id, + parentId: stack.id, + sizeByte: 100, + }, + }) + + const res = await executeAgentToolActivity({ + taskId: 'task-1', + toolName: 'create_version', + args: { + parent: existingFileVersion.id, + s3Key: 'uploads/v2.txt', + name: 'v2.txt', + size: 250, + contentType: 'text/plain', + }, + userId: user.id, + }) + + expect(res.name).toBe('v2.txt') + + const updatedStack = await prisma.asset.findUnique({ + where: { id: stack.id }, + include: { children: true }, + }) + + expect(updatedStack?.fileCount).toBe(2) + expect(updatedStack?.sizeByte).toBe(350) + }) + }) + }) +}) diff --git a/packages/agent/src/activities/ai.test.ts b/packages/agent/src/activities/ai.test.ts index 53741b25..d5848ba9 100644 --- a/packages/agent/src/activities/ai.test.ts +++ b/packages/agent/src/activities/ai.test.ts @@ -1,6 +1,33 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { generateEmbeddingActivity } from './ai' +import { + generateEmbeddingActivity, + generateTextEmbeddingActivity, + extractAiMetadataActivity, + getEmbeddingContextActivity, + saveAssetEmbeddingsActivity, +} from './ai' import { s3Service } from '@shumai/core/src/s3/s3' +import { transcodeService } from '@shumai/transcode' +import { prisma, AssetType, AssetStatus } from '@shumai/db' +import { setupTestDbHooks } from '@shumai/db/test' +import * as fs from 'fs' + +vi.mock('fs', async (importOriginal) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- importOriginal returns the raw fs module, typed dynamically as any here + const actual = await importOriginal() + const mockRead = vi.fn((path, options) => { + if (typeof path === 'string' && (path.includes('video-chunk') || path.includes('out1.webp'))) { + return Buffer.from('chunk-data') + } + return actual.readFileSync(path, options) + }) + return { + ...actual, + writeFileSync: vi.fn(), + readFileSync: mockRead, + unlinkSync: vi.fn(), + } +}) vi.mock('@shumai/core/src/s3/s3', () => ({ s3Service: { @@ -11,6 +38,30 @@ vi.mock('@shumai/core/src/s3/s3', () => ({ }, })) +vi.mock('@shumai/transcode', () => ({ + transcodeService: { + extractVideoFrames: vi.fn(), + }, +})) + +vi.mock('child_process', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock functions dynamically return varying types based on test command calls + const execMock: any = vi.fn((cmd: any, cb: any) => { + cb(null, '120.0\n', '') + }) + // Setup custom promisify behavior to return { stdout, stderr } + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock functions dynamically return varying types based on test command calls + execMock[Symbol.for('nodejs.util.promisify.custom')] = vi.fn(async (cmd: any) => { + if (cmd.includes('ffprobe')) { + return { stdout: '120.0\n', stderr: '' } + } + return { stdout: '', stderr: '' } + }) + return { + exec: execMock, + } +}) + const mockEmbedContent = vi.fn().mockResolvedValue({ embeddings: [ { @@ -21,7 +72,7 @@ const mockEmbedContent = vi.fn().mockResolvedValue({ vi.mock('@google/genai', () => { return { - // eslint-disable-next-line @typescript-eslint/naming-convention + // eslint-disable-next-line @typescript-eslint/naming-convention -- matches external library GoogleGenAI export naming convention GoogleGenAI: class { models = { embedContent: mockEmbedContent, @@ -30,7 +81,7 @@ vi.mock('@google/genai', () => { } }) -describe('AI Activities', () => { +describe('AI Activities Unit Tests', () => { beforeEach(() => { vi.clearAllMocks() process.env.GEMINI_API_KEY = 'test-key' @@ -40,8 +91,7 @@ describe('AI Activities', () => { vi.mocked(s3Service.getObject).mockResolvedValue({ buffer: Buffer.from('test-image'), contentType: 'image/png', - // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock getObject return value needs broad any casting - } as any) + } as unknown as { buffer: Buffer; contentType: string }) const context = { agent: { config: { provider: 'google', model: 'gemini' } }, @@ -58,4 +108,222 @@ describe('AI Activities', () => { expect(res.embeddings[0].embedding).toEqual([0.1, 0.2, 0.3]) expect(s3Service.getObject).toHaveBeenCalledWith('shumai', 'test.png') }) + + it('should generate video embedding in chunks', async () => { + vi.mocked(s3Service.getObject).mockResolvedValue({ + buffer: Buffer.from('test-video'), + contentType: 'video/mp4', + } as unknown as { buffer: Buffer; contentType: string }) + + const context = { + agent: { config: { provider: 'google', model: 'gemini' } }, + asset: { id: 'a2', mediaType: 'video/mp4', storageKey: { key: 'test.mp4' } }, + } + + const res = await generateEmbeddingActivity({ + teamId: 't1', + assetId: 'a2', + context, + }) + + // Duration is 120s, chunks are 60s, so it should generate 2 chunks (0-60, 60-120) + expect(res.embeddings.length).toBe(2) + expect(res.embeddings[0]).toEqual({ embedding: [0.1, 0.2, 0.3], startTime: 0, endTime: 60 }) + expect(res.embeddings[1]).toEqual({ embedding: [0.1, 0.2, 0.3], startTime: 60, endTime: 120 }) + + expect(vi.mocked(fs.writeFileSync)).toHaveBeenCalled() + expect(vi.mocked(fs.readFileSync)).toHaveBeenCalled() + expect(vi.mocked(fs.unlinkSync)).toHaveBeenCalled() + }) + + it('should generate text embedding successfully', async () => { + const res = await generateTextEmbeddingActivity({ + text: 'Search query', + teamId: 't1', + }) + + expect(res.embedding).toEqual([0.1, 0.2, 0.3]) + expect(mockEmbedContent).toHaveBeenCalledWith( + expect.objectContaining({ + model: 'gemini-embedding-2', + contents: [ + expect.objectContaining({ + parts: [{ text: 'Search query' }], + }), + ], + }), + ) + }) + + describe('extractAiMetadataActivity', () => { + it('should return existing images if they are already in S3 storage', async () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock returned object cast as any due to partial implementation + vi.mocked(s3Service.headObject).mockResolvedValue({} as any) + vi.mocked(s3Service.listObjects).mockResolvedValue([ + 'project/ai_metadata/1.webp', + 'project/ai_metadata/2.webp', + ]) + + const res = await extractAiMetadataActivity({ + assetKey: 'project/video.mp4', + filePath: '/tmp/video.mp4', + type: 'autofill', + isImage: false, + }) + + expect(res).toEqual(['project/ai_metadata/1.webp', 'project/ai_metadata/2.webp']) + expect(s3Service.headObject).toHaveBeenCalledWith('shumai', 'project/ai_metadata/1.webp') + expect(transcodeService.extractVideoFrames).not.toHaveBeenCalled() + }) + + it('should extract frames and upload to S3 if not already present', async () => { + vi.mocked(s3Service.headObject).mockRejectedValue(new Error('Not Found')) + vi.mocked(transcodeService.extractVideoFrames).mockResolvedValue(['/tmp/out1.webp']) + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock returned object cast as any due to partial implementation + vi.mocked(s3Service.putObject).mockResolvedValue({} as any) + + const res = await extractAiMetadataActivity({ + assetKey: 'project/video.mp4', + filePath: '/tmp/video.mp4', + type: 'autofill', + isImage: false, + }) + + expect(res).toEqual(['project/ai_metadata/out1.webp']) + expect(transcodeService.extractVideoFrames).toHaveBeenCalledWith({ + inputFile: '/tmp/video.mp4', + outputDir: '/tmp', + numFrames: 30, + frameHeight: 720, + isImage: false, + }) + expect(s3Service.putObject).toHaveBeenCalledWith( + 'shumai', + 'project/ai_metadata/out1.webp', + expect.any(Buffer), + expect.any(Number), + 'image/webp', + ) + }) + }) +}) + +describe('AI Database Activities Integration', () => { + setupTestDbHooks() + + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests + let team: any + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests + let user: any + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests + let asset: any + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests + let storageKey: any + + beforeEach(async () => { + vi.restoreAllMocks() + + team = await prisma.team.create({ + data: { name: 'AI Team' }, + }) + + user = await prisma.user.create({ + data: { + name: 'AI Agent User', + email: 'aiagent@shumai.ai', + type: 'agent', + }, + }) + + // Add user as a member of the team + await prisma.teamMember.create({ + data: { + teamId: team.id, + userId: user.id, + role: 'editor', + }, + }) + + storageKey = await prisma.storageKey.create({ + data: { + key: 'media/video.mp4', + }, + }) + + asset = await prisma.asset.create({ + data: { + name: 'video.mp4', + type: AssetType.file, + status: AssetStatus.uploaded, + mediaType: 'video/mp4', + storageKeyId: storageKey.id, + }, + }) + }) + + describe('getEmbeddingContextActivity', () => { + it('should retrieve embedding context and throw if embedding agent not configured/enabled', async () => { + // Expect throw since agent not created yet + await expect( + getEmbeddingContextActivity({ teamId: team.id, assetId: asset.id }), + ).rejects.toThrow('embedding feature is disabled or agent not found') + + // Create embedding agent + await prisma.agent.create({ + data: { + id: user.id, // match user.id + teamId: team.id, + type: 'embedding', + enabled: true, + config: { + provider: 'openai', + model: 'gpt-4', + }, + }, + }) + + const ctx = await getEmbeddingContextActivity({ + teamId: team.id, + assetId: asset.id, + }) + + expect(ctx.agent.id).toBe(user.id) + expect(ctx.asset.id).toBe(asset.id) + expect(ctx.asset.mediaType).toBe('video/mp4') + }) + }) + + describe('saveAssetEmbeddingsActivity', () => { + it('should save embeddings with start and end times to the database', async () => { + const embeddings = [ + { + embedding: Array(1536).fill(0.01), + startTime: 0.0, + endTime: 60.0, + }, + { + embedding: Array(1536).fill(0.02), + }, + ] + + await saveAssetEmbeddingsActivity({ + assetId: asset.id, + embeddings, + }) + + // Query raw embeddings from DB + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- db query output is a raw postgres result array typed as any + const dbEmbeddings: any[] = await prisma.$queryRaw` + SELECT id, asset_id as "assetId", start_time as "startTime", end_time as "endTime" + FROM asset_embeddings + WHERE asset_id = ${asset.id} + ORDER BY start_time ASC NULLS LAST + ` + + expect(dbEmbeddings.length).toBe(2) + expect(dbEmbeddings[0].startTime).toBe(0.0) + expect(dbEmbeddings[0].endTime).toBe(60.0) + expect(dbEmbeddings[1].startTime).toBeNull() + }) + }) }) diff --git a/packages/agent/src/workflows/agent-autofill.test.ts b/packages/agent/src/workflows/agent-autofill.test.ts index 6016a3cf..2988298c 100644 --- a/packages/agent/src/workflows/agent-autofill.test.ts +++ b/packages/agent/src/workflows/agent-autofill.test.ts @@ -16,12 +16,13 @@ vi.mock('@shumai/workflow-core', async () => { describe('Agent Autofill Workflow', () => { setupTestDbHooks() + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities holds mock functions cast to expected types + let mockActivities: any + beforeEach(() => { vi.clearAllMocks() - }) - it('should run agent autofill workflow successfully', async () => { - const mockActivities = { + mockActivities = { updateTaskStatusActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskStatusActivity', }), @@ -54,6 +55,9 @@ describe('Agent Autofill Workflow', () => { cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }), } + mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue') + mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue') + mockActivities.updateTaskStatusActivity.mockResolvedValue({}) mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' }) mockActivities.getAssetActivity.mockResolvedValue({ id: 'a1', @@ -61,21 +65,19 @@ describe('Agent Autofill Workflow', () => { project: { id: 'p1', teamId: 't1' }, mediaType: 'image/png', }) - mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue') mockActivities.downloadMediaToTmpActivity.mockResolvedValue({ filePath: '/tmp/test.png', - tmpDir: '/tmp', + tmpDir: '/tmp/test-dir', }) - mockActivities.extractAiMetadataActivity.mockResolvedValue(['/tmp/1.webp']) + mockActivities.extractAiMetadataActivity.mockResolvedValue(['/tmp/test-dir/1.webp']) mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([ - { id: 'f1', key: 'f1', config: { name: 'F1', type: 'text' } }, + { key: 'title', config: { name: 'Title', type: 'text' }, description: 'The title' }, ]) mockActivities.getAgentAutofillContextActivity.mockResolvedValue({ agent: { id: 'b1' } }) - mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue') mockActivities.autofillAiActivity.mockResolvedValue({ - text: '{"f1":"val"}', + text: '{"title":"Extracted Title"}', sessionId: 'session-123', - usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' }, + usage: { inputTokens: 10, outputTokens: 15, model: 'gemini-model' }, }) // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types @@ -84,6 +86,110 @@ describe('Agent Autofill Workflow', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities return (act as any)(...args) }) + }) + + it('should run agent autofill workflow successfully', async () => { + const task = await prisma.workflowTask.create({ + data: { + type: 'ai_metadata_autofill', + status: 'pending', + assetId: 'a1', + payload: { + projectId: 'p1', + agent: { sessionId: 's1', agentId: 'agent-1' }, + }, + }, + }) + + await agentAutofillMedia(task) + + // Verify queue discovery + expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled() + expect(mockActivities.getTranscodeWorkerQueueActivity).toHaveBeenCalled() + + // Verify task processing status + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'processing', + }) + + // Verify placeholder comment created + expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({ + assetId: 'a1', + message: '__AUTOFILL__', + sessionId: 's1', + agentId: 'agent-1', + }) + + // Verify download, extraction and fields fetched + expect(mockActivities.downloadMediaToTmpActivity).toHaveBeenCalledWith({ + assetKey: 'asset-key', + }) + expect(mockActivities.extractAiMetadataActivity).toHaveBeenCalledWith({ + assetKey: 'asset-key', + filePath: '/tmp/test.png', + type: 'autofill', + isImage: true, + }) + expect(mockActivities.getProjectAutofillFieldsActivity).toHaveBeenCalledWith('p1') + expect(mockActivities.getAgentAutofillContextActivity).toHaveBeenCalledWith({ + teamId: 't1', + }) + + // Verify AI autofill called with mapped fields + expect(mockActivities.autofillAiActivity).toHaveBeenCalledWith({ + teamId: 't1', + images: ['/tmp/test-dir/1.webp'], + fields: [ + { + id: 'title', + config: { name: 'Title', type: 'text' }, + description: 'The title', + }, + ], + context: { agent: { id: 'b1' } }, + }) + + // Verify task usage update + expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({ + taskId: task.id, + inputTokens: 10, + outputTokens: 15, + model: 'gemini-model', + }) + + // Verify metadata updated on asset + expect(mockActivities.updateAssetMetadataActivity).toHaveBeenCalledWith({ + assetId: 'a1', + metadata: [ + { + key: 'title', + value: 'Extracted Title', + }, + ], + }) + + // Verify placeholder comment updated + expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({ + commentId: 'comment-placeholder-id', + message: 'Autofill completed successfully.', + sessionId: 'session-123', + }) + + // Verify cleanup was called + expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({ + tmpDir: '/tmp/test-dir', + }) + + // Verify completed task status + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'completed', + }) + }) + + it('should complete early if no image files could be extracted', async () => { + mockActivities.extractAiMetadataActivity.mockResolvedValue([]) const task = await prisma.workflowTask.create({ data: { @@ -95,7 +201,86 @@ describe('Agent Autofill Workflow', () => { await agentAutofillMedia(task) - expect(mockActivities.getAgentAutofillContextActivity).toHaveBeenCalled() - expect(mockActivities.autofillAiActivity).toHaveBeenCalled() + expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({ + commentId: 'comment-placeholder-id', + message: 'Autofill completed: No images could be extracted for analysis.', + }) + + expect(mockActivities.autofillAiActivity).not.toHaveBeenCalled() + expect(mockActivities.updateAssetMetadataActivity).not.toHaveBeenCalled() + + // Verify cleanup still runs + expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({ + tmpDir: '/tmp/test-dir', + }) + + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'completed', + }) + }) + + it('should complete early if no autofill fields are defined in the project', async () => { + mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([]) + + const task = await prisma.workflowTask.create({ + data: { + type: 'ai_metadata_autofill', + status: 'pending', + assetId: 'a1', + }, + }) + + await agentAutofillMedia(task) + + expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({ + commentId: 'comment-placeholder-id', + message: 'Autofill completed: No autofill fields defined in project.', + }) + + expect(mockActivities.autofillAiActivity).not.toHaveBeenCalled() + expect(mockActivities.updateAssetMetadataActivity).not.toHaveBeenCalled() + + // Verify cleanup still runs + expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({ + tmpDir: '/tmp/test-dir', + }) + + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'completed', + }) + }) + + it('should handle failures, update placeholder with error, set status to failed, and cleanup tmp directory', async () => { + mockActivities.getProjectAutofillFieldsActivity.mockRejectedValue(new Error('DB failure')) + + const task = await prisma.workflowTask.create({ + data: { + type: 'ai_metadata_autofill', + status: 'pending', + assetId: 'a1', + }, + }) + + await expect(agentAutofillMedia(task)).rejects.toThrow('DB failure') + + // Verify placeholder updated with error + expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({ + commentId: 'comment-placeholder-id', + message: 'Autofill failed: DB failure', + }) + + // Verify task failed status + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'failed', + output: { error: 'DB failure' }, + }) + + // Verify cleanup still runs in finally block + expect(mockActivities.cleanupTmpDirActivity).toHaveBeenCalledWith({ + tmpDir: '/tmp/test-dir', + }) }) }) diff --git a/packages/agent/src/workflows/agent-chat.test.ts b/packages/agent/src/workflows/agent-chat.test.ts index 7e876e53..f17c9c37 100644 --- a/packages/agent/src/workflows/agent-chat.test.ts +++ b/packages/agent/src/workflows/agent-chat.test.ts @@ -16,12 +16,13 @@ vi.mock('@shumai/workflow-core', async () => { describe('Agent Chat Workflow', () => { setupTestDbHooks() + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities holds mock functions cast to expected types + let mockActivities: any + beforeEach(() => { vi.clearAllMocks() - }) - it('should run agent chat workflow successfully', async () => { - const mockActivities = { + mockActivities = { updateTaskStatusActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskStatusActivity', }), @@ -46,23 +47,28 @@ describe('Agent Chat Workflow', () => { }), } + mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue') + mockActivities.updateTaskStatusActivity.mockResolvedValue({}) + mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' }) + mockActivities.getAssetActivity.mockResolvedValue({ + id: 'a1', + project: { teamId: 't1' }, + type: 'file', + parentId: 'parent-folder-id', + }) mockActivities.getCommentActivity.mockResolvedValue({ id: 'c1', - message: 'hello', + message: 'hello agent', replyToId: null, + attachments: [], }) - mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' }) - mockActivities.getAssetActivity.mockResolvedValue({ id: 'a1', project: { teamId: 't1' } }) mockActivities.initializeAgentSessionActivity.mockResolvedValue('session-123') mockActivities.getAgentChatContextActivity.mockResolvedValue({ agent: { id: 'b1' } }) - mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue') - mockActivities.getAssetPathContextActivity.mockResolvedValue( - 'Path: foo/bar/z.png\n\nname: foo, id: foo-id', - ) + mockActivities.getAssetPathContextActivity.mockResolvedValue('Path: folder/subfolder/file.png') mockActivities.agentChatActivity.mockResolvedValue({ - text: 'arr matey!', + text: 'Hello user, how can I help you?', sessionId: 'session-123', - usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' }, + usage: { inputTokens: 10, outputTokens: 20, model: 'gemini-model' }, }) // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types @@ -71,6 +77,175 @@ describe('Agent Chat Workflow', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities return (act as any)(...args) }) + }) + + it('should run agent chat workflow successfully with default configurations', async () => { + const task = await prisma.workflowTask.create({ + data: { + type: 'chat', + status: 'pending', + assetId: 'a1', + payload: { + projectId: 'p1', + agent: { userCommentId: 'c1', agentId: 'b1', explicitMention: true }, + }, + }, + }) + + await agentChat(task) + + // Verify queue discovery + expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled() + + // Verify task status processing + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'processing', + }) + + // Verify comment context fetched + expect(mockActivities.getCommentActivity).toHaveBeenCalledWith('c1') + + // Verify placeholder comment created + expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({ + assetId: 'a1', + message: '__CHAT__', + sessionId: 'pending', + agentId: 'b1', + replyToId: 'c1', + }) + + // Verify session initialized since sessionId was missing + expect(mockActivities.initializeAgentSessionActivity).toHaveBeenCalledWith({ + teamId: 't1', + agentId: 'b1', + userCommentId: 'c1', + userId: undefined, + }) + + // Verify agent instruction composition + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith( + expect.objectContaining({ + teamId: 't1', + agentId: 'b1', + message: 'hello agent', + agentsInstruction: expect.stringContaining('explicitly mentioned you'), + sessionId: 'session-123', + folderId: 'parent-folder-id', + }), + ) + + // Verify comment update + expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({ + commentId: 'comment-placeholder-id', + message: 'Hello user, how can I help you?', + sessionId: 'session-123', + }) + + // Verify task usage update + expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({ + taskId: task.id, + inputTokens: 10, + outputTokens: 20, + model: 'gemini-model', + }) + + // Verify task completed status + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'completed', + output: { sessionId: 'session-123' }, + }) + }) + + it('should skip session initialization if sessionId is already provided', async () => { + const task = await prisma.workflowTask.create({ + data: { + type: 'chat', + status: 'pending', + assetId: 'a1', + payload: { + projectId: 'p1', + agent: { userCommentId: 'c1', agentId: 'b1', sessionId: 'existing-session-456' }, + }, + }, + }) + + await agentChat(task) + + expect(mockActivities.initializeAgentSessionActivity).not.toHaveBeenCalled() + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith( + expect.objectContaining({ + sessionId: 'existing-session-456', + }), + ) + }) + + it('should delete placeholder comment and finish when AI responds with __NO_REPLY__', async () => { + mockActivities.agentChatActivity.mockResolvedValue({ + text: '__NO_REPLY__', + sessionId: 'session-123', + }) + + const task = await prisma.workflowTask.create({ + data: { + type: 'chat', + status: 'pending', + assetId: 'a1', + payload: { + projectId: 'p1', + agent: { userCommentId: 'c1', agentId: 'b1', explicitMention: false }, + }, + }, + }) + + await agentChat(task) + + // Verify instruction contains not explicitly mentioned instructions + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith( + expect.objectContaining({ + agentsInstruction: expect.stringContaining('did not explicitly mention you'), + }), + ) + + // Verify placeholder comment is deleted + expect(mockActivities.deleteCommentActivity).toHaveBeenCalledWith('comment-placeholder-id') + expect(mockActivities.updateCommentActivity).not.toHaveBeenCalled() + + // Verify task still completes successfully + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'completed', + output: { sessionId: 'session-123' }, + }) + }) + + it('should collect S3 keys for image attachments from the user comment', async () => { + mockActivities.getCommentActivity.mockResolvedValue({ + id: 'c1', + message: 'look at this', + replyToId: null, + attachments: [ + { + asset: { + mediaType: 'image/png', + storageKey: { key: 'attachments/image1.png' }, + }, + }, + { + asset: { + mediaType: 'video/mp4', // non-image, should be ignored + storageKey: { key: 'attachments/video.mp4' }, + }, + }, + { + asset: { + mediaType: 'image/jpeg', + storageKey: { key: 'attachments/image2.jpg' }, + }, + }, + ], + }) const task = await prisma.workflowTask.create({ data: { @@ -86,7 +261,98 @@ describe('Agent Chat Workflow', () => { await agentChat(task) - expect(mockActivities.getAgentChatContextActivity).toHaveBeenCalled() - expect(mockActivities.agentChatActivity).toHaveBeenCalled() + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith( + expect.objectContaining({ + imageUrls: ['attachments/image1.png', 'attachments/image2.jpg'], + }), + ) + }) + + it('should format instructions with asset media info when available', async () => { + mockActivities.getAssetActivity.mockResolvedValue({ + id: 'a1', + project: { teamId: 't1' }, + type: 'file', + media: { + duration: 10, + height: 1080, + width: 1920, + }, + }) + + const task = await prisma.workflowTask.create({ + data: { + type: 'chat', + status: 'pending', + assetId: 'a1', + payload: { + projectId: 'p1', + agent: { userCommentId: 'c1', agentId: 'b1' }, + }, + }, + }) + + await agentChat(task) + + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith( + expect.objectContaining({ + agentsInstruction: expect.stringContaining('Asset Media Info:'), + }), + ) + }) + + it('should handle errors gracefully by updating the placeholder comment with error message and marking task as failed', async () => { + mockActivities.agentChatActivity.mockRejectedValue(new Error('AI error: API limit reached')) + + const task = await prisma.workflowTask.create({ + data: { + type: 'chat', + status: 'pending', + assetId: 'a1', + payload: { + projectId: 'p1', + agent: { userCommentId: 'c1', agentId: 'b1' }, + }, + }, + }) + + await expect(agentChat(task)).rejects.toThrow('AI error: API limit reached') + + // Verify placeholder updated with formatted error message + expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({ + commentId: 'comment-placeholder-id', + message: 'AI error: API limit reached', + }) + + // Verify status updated to failed + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'failed', + output: { error: 'AI error: API limit reached' }, + }) + }) + + it('should handle generic errors in error handling block', async () => { + mockActivities.agentChatActivity.mockRejectedValue(new Error('Some DB connection error')) + + const task = await prisma.workflowTask.create({ + data: { + type: 'chat', + status: 'pending', + assetId: 'a1', + payload: { + projectId: 'p1', + agent: { userCommentId: 'c1', agentId: 'b1' }, + }, + }, + }) + + await expect(agentChat(task)).rejects.toThrow('Some DB connection error') + + // Verify placeholder updated with generic error message + expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({ + commentId: 'comment-placeholder-id', + message: 'Sorry, I encountered an error while processing your request.', + }) }) }) diff --git a/packages/agent/src/workflows/agent-embedding.test.ts b/packages/agent/src/workflows/agent-embedding.test.ts index dbaba91f..57441d7d 100644 --- a/packages/agent/src/workflows/agent-embedding.test.ts +++ b/packages/agent/src/workflows/agent-embedding.test.ts @@ -16,12 +16,13 @@ vi.mock('@shumai/workflow-core', async () => { describe('Agent Embedding Workflow', () => { setupTestDbHooks() + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities holds mock functions cast to expected types + let mockActivities: any + beforeEach(() => { vi.clearAllMocks() - }) - it('should run agent embedding workflow successfully', async () => { - const mockActivities = { + mockActivities = { updateTaskStatusActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskStatusActivity', }), @@ -42,13 +43,14 @@ describe('Agent Embedding Workflow', () => { }), } + mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue') + mockActivities.updateTaskStatusActivity.mockResolvedValue({}) mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' }) mockActivities.getEmbeddingContextActivity.mockResolvedValue({ agent: { id: 'b1' }, asset: { id: 'a1' }, dbProvider: { name: 'google' }, }) - mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue') mockActivities.generateEmbeddingActivity.mockResolvedValue({ embeddings: [{ embedding: [0.1, 0.2] }], usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' }, @@ -60,6 +62,109 @@ describe('Agent Embedding Workflow', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities return (act as any)(...args) }) + }) + + it('should run agent embedding workflow successfully', async () => { + const task = await prisma.workflowTask.create({ + data: { + type: 'ai_embedding', + status: 'pending', + assetId: 'a1', + teamId: 't1', + payload: { + projectId: 'p1', + agent: { sessionId: 's1', agentId: 'agent-1' }, + }, + }, + }) + + await agentEmbeddingMedia(task) + + // Verify queue discovery + expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled() + + // Verify task processing status + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'processing', + }) + + // Verify placeholder comment created + expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({ + assetId: 'a1', + message: '__EMBEDDING__', + sessionId: 's1', + agentId: 'agent-1', + }) + + // Verify context fetching + expect(mockActivities.getEmbeddingContextActivity).toHaveBeenCalledWith({ + teamId: 't1', + assetId: 'a1', + }) + + // Verify embedding generation + expect(mockActivities.generateEmbeddingActivity).toHaveBeenCalledWith({ + teamId: 't1', + assetId: 'a1', + context: { + agent: { id: 'b1' }, + asset: { id: 'a1' }, + dbProvider: { name: 'google' }, + }, + }) + + // Verify embeddings saved + expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalledWith({ + assetId: 'a1', + embeddings: [{ embedding: [0.1, 0.2] }], + }) + + // Verify usage update + expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({ + taskId: task.id, + inputTokens: 5, + outputTokens: 5, + model: 'gpt', + }) + + // Verify placeholder comment updated + expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({ + commentId: 'comment-placeholder-id', + message: 'Embedding completed successfully.', + }) + + // Verify completed task status + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'completed', + }) + }) + + it('should throw if task has no teamId', async () => { + const task = await prisma.workflowTask.create({ + data: { + type: 'ai_embedding', + status: 'pending', + assetId: 'a1', + }, + }) + + await expect(agentEmbeddingMedia(task)).rejects.toThrow('Task has no teamId') + + // Verify status updated to failed + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'failed', + output: { error: 'Task has no teamId' }, + }) + }) + + it('should skip saving embeddings if none are returned', async () => { + mockActivities.generateEmbeddingActivity.mockResolvedValue({ + embeddings: [], + usage: null, + }) const task = await prisma.workflowTask.create({ data: { @@ -72,8 +177,39 @@ describe('Agent Embedding Workflow', () => { await agentEmbeddingMedia(task) - expect(mockActivities.getEmbeddingContextActivity).toHaveBeenCalled() - expect(mockActivities.generateEmbeddingActivity).toHaveBeenCalled() - expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalled() + expect(mockActivities.saveAssetEmbeddingsActivity).not.toHaveBeenCalled() + expect(mockActivities.updateTaskUsageActivity).not.toHaveBeenCalled() + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'completed', + }) + }) + + it('should handle failures, update placeholder with error, and set status to failed', async () => { + mockActivities.generateEmbeddingActivity.mockRejectedValue(new Error('AI Service Unavailable')) + + const task = await prisma.workflowTask.create({ + data: { + type: 'ai_embedding', + status: 'pending', + assetId: 'a1', + teamId: 't1', + }, + }) + + await expect(agentEmbeddingMedia(task)).rejects.toThrow('AI Service Unavailable') + + // Verify placeholder updated with error + expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({ + commentId: 'comment-placeholder-id', + message: 'Embedding failed: AI Service Unavailable', + }) + + // Verify status updated to failed + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'failed', + output: { error: 'AI Service Unavailable' }, + }) }) }) diff --git a/packages/agent/src/workflows/agent-tool-call.test.ts b/packages/agent/src/workflows/agent-tool-call.test.ts new file mode 100644 index 00000000..928fb46b --- /dev/null +++ b/packages/agent/src/workflows/agent-tool-call.test.ts @@ -0,0 +1,140 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { agentToolCall } from './agent-tool-call' +import { prisma } from '@shumai/db' +import { setupTestDbHooks } from '@shumai/db/test' +import * as workflowUtils from '@shumai/workflow-core' + +vi.mock('@shumai/workflow-core', async () => { + const actual = await vi.importActual('@shumai/workflow-core') + return { + ...actual, + getActivities: vi.fn(), + executeActivity: vi.fn(), + } +}) + +describe('Agent Tool Call Workflow', () => { + setupTestDbHooks() + + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities holds mock functions cast to expected types + let mockActivities: any + + beforeEach(() => { + vi.clearAllMocks() + + mockActivities = { + updateTaskStatusActivity: Object.assign(vi.fn(), { + _activityName: 'updateTaskStatusActivity', + }), + executeAgentToolActivity: Object.assign(vi.fn(), { + _activityName: 'executeAgentToolActivity', + }), + getAgentWorkerQueueActivity: Object.assign(vi.fn(), { + _activityName: 'getAgentWorkerQueueActivity', + }), + } + + mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue') + mockActivities.updateTaskStatusActivity.mockResolvedValue({}) + mockActivities.executeAgentToolActivity.mockResolvedValue({ success: true, count: 42 }) + + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types + vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any) + vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities + return (act as any)(...args) + }) + }) + + it('should run agent tool call workflow successfully', async () => { + const task = await prisma.workflowTask.create({ + data: { + type: 'agent_tool_call', + status: 'pending', + assetId: 'a1', + payload: { + projectId: 'p1', + agentToolCall: { + toolName: 'list_assets', + args: { parent: 'folder-123' }, + userId: 'user-456', + }, + }, + }, + }) + + await agentToolCall(task) + + // Verify queue discovery + expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled() + + // Verify task processing status + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'processing', + }) + + // Verify tool execution + expect(mockActivities.executeAgentToolActivity).toHaveBeenCalledWith({ + taskId: task.id, + toolName: 'list_assets', + args: { parent: 'folder-123' }, + userId: 'user-456', + }) + + // Verify task completed status with output + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'completed', + output: { success: true, count: 42 }, + }) + }) + + it('should throw if payload or agentToolCall is missing', async () => { + const task = await prisma.workflowTask.create({ + data: { + type: 'agent_tool_call', + status: 'pending', + assetId: 'a1', + }, + }) + + await expect(agentToolCall(task)).rejects.toThrow('Task payload or agentToolCall is missing') + + // Verify status updated to failed + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'failed', + output: { error: 'Task payload or agentToolCall is missing' }, + }) + }) + + it('should handle tool execution failures by updating task to failed and throwing', async () => { + mockActivities.executeAgentToolActivity.mockRejectedValue(new Error('Authz failure')) + + const task = await prisma.workflowTask.create({ + data: { + type: 'agent_tool_call', + status: 'pending', + assetId: 'a1', + payload: { + projectId: 'p1', + agentToolCall: { + toolName: 'create_folder', + args: { parent: 'folder-123', name: 'new-folder' }, + userId: 'user-456', + }, + }, + }, + }) + + await expect(agentToolCall(task)).rejects.toThrow('Authz failure') + + // Verify task status failed + expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'failed', + output: { error: 'Authz failure' }, + }) + }) +}) diff --git a/packages/agent/src/workflows/query-embedding-for-search.test.ts b/packages/agent/src/workflows/query-embedding-for-search.test.ts new file mode 100644 index 00000000..619a8b2b --- /dev/null +++ b/packages/agent/src/workflows/query-embedding-for-search.test.ts @@ -0,0 +1,145 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { queryEmbeddingForSearch } from './query-embedding-for-search' +import { prisma } from '@shumai/db' +import { setupTestDbHooks } from '@shumai/db/test' +import * as workflowUtils from '@shumai/workflow-core' + +vi.mock('@shumai/workflow-core', async () => { + const actual = await vi.importActual('@shumai/workflow-core') + return { + ...actual, + getActivities: vi.fn(), + executeActivity: vi.fn(), + } +}) + +describe('Query Embedding For Search Workflow', () => { + setupTestDbHooks() + + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities holds mock functions cast to expected types + let mockActivities: any + + beforeEach(() => { + vi.clearAllMocks() + + mockActivities = { + updateWorkflowTaskActivity: Object.assign(vi.fn(), { + _activityName: 'updateWorkflowTaskActivity', + }), + generateTextEmbeddingActivity: Object.assign(vi.fn(), { + _activityName: 'generateTextEmbeddingActivity', + }), + getAgentWorkerQueueActivity: Object.assign(vi.fn(), { + _activityName: 'getAgentWorkerQueueActivity', + }), + } + + mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue') + mockActivities.updateWorkflowTaskActivity.mockResolvedValue({}) + mockActivities.generateTextEmbeddingActivity.mockResolvedValue({ + embedding: [0.1, 0.2, 0.3], + usage: { inputTokens: 4, outputTokens: 0, model: 'gemini-embedding-2' }, + }) + + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types + vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any) + vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities + return (act as any)(...args) + }) + }) + + it('should run query embedding workflow successfully', async () => { + const task = await prisma.workflowTask.create({ + data: { + type: 'query_embedding_for_search', + status: 'pending', + teamId: 't1', + assetId: 'a1', + payload: { + projectId: 'p1', + queryEmbeddingForSearch: { + text: 'search query', + }, + }, + }, + }) + + await queryEmbeddingForSearch(task) + + // Verify queue discovery + expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled() + + // Verify task processing status + expect(mockActivities.updateWorkflowTaskActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'processing', + heartbeat: true, + }) + + // Verify embedding generation + expect(mockActivities.generateTextEmbeddingActivity).toHaveBeenCalledWith({ + text: 'search query', + teamId: 't1', + }) + + // Verify completed status and details + expect(mockActivities.updateWorkflowTaskActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'completed', + output: { embedding: [0.1, 0.2, 0.3] }, + inputTokens: 4, + outputTokens: 0, + model: 'gemini-embedding-2', + }) + }) + + it('should throw immediately if text is missing', async () => { + const task = await prisma.workflowTask.create({ + data: { + type: 'query_embedding_for_search', + status: 'pending', + teamId: 't1', + assetId: 'a1', + }, + }) + + await expect(queryEmbeddingForSearch(task)).rejects.toThrow( + 'Missing text in query_embedding_for_search task payload', + ) + + // Should not call any activities because it throws before queue discovery + expect(mockActivities.getAgentWorkerQueueActivity).not.toHaveBeenCalled() + expect(mockActivities.updateWorkflowTaskActivity).not.toHaveBeenCalled() + }) + + it('should handle activity failure and update task status to failed', async () => { + mockActivities.generateTextEmbeddingActivity.mockRejectedValue( + new Error('Embedding API failed'), + ) + + const task = await prisma.workflowTask.create({ + data: { + type: 'query_embedding_for_search', + status: 'pending', + teamId: 't1', + assetId: 'a1', + payload: { + projectId: 'p1', + queryEmbeddingForSearch: { + text: 'search query', + }, + }, + }, + }) + + await expect(queryEmbeddingForSearch(task)).rejects.toThrow('Embedding API failed') + + // Verify it updates task to failed + expect(mockActivities.updateWorkflowTaskActivity).toHaveBeenCalledWith({ + taskId: task.id, + status: 'failed', + output: { error: 'Embedding API failed' }, + }) + }) +}) From 6a903478e18fcbcf121deb7758732a30a1dbb587 Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 3 Jun 2026 16:02:06 +0800 Subject: [PATCH 2/3] test(agent): verify prompt builder instructions exactly in agent-chat workflow tests --- packages/agent/src/activities/agent.test.ts | 2 +- .../agent-chat-prompt-builder.test.ts | 77 +++++++++++++++++++ .../workflows/agent-chat-prompt-builder.ts | 56 ++++++++++++++ .../agent/src/workflows/agent-chat.test.ts | 39 +++++++++- packages/agent/src/workflows/agent-chat.ts | 22 ++---- 5 files changed, 176 insertions(+), 20 deletions(-) create mode 100644 packages/agent/src/workflows/agent-chat-prompt-builder.test.ts create mode 100644 packages/agent/src/workflows/agent-chat-prompt-builder.ts diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index 1c0cc9ba..d0bf368c 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -318,7 +318,7 @@ describe('Agent Database Activities Integration', () => { input: ['text'], contextWindow: 8192, maxTokens: 2048, - cost: { input: 0.01, output: 0.03, cacheRead: 0, cacheWrite: 0 } + cost: { input: 0.01, output: 0.03, cacheRead: 0, cacheWrite: 0 }, }, }, }) diff --git a/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts b/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts new file mode 100644 index 00000000..dad572b2 --- /dev/null +++ b/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts @@ -0,0 +1,77 @@ +import { describe, it, expect } from 'vitest' +import { + AgentChatPromptBuilder, + PROMPT_ASSET_BASE, + PROMPT_PATH_CONTEXT, + PROMPT_MEDIA_INFO, + PROMPT_MEDIA_TOOL_INSTRUCTION, + PROMPT_EXPLICIT_MENTION, + PROMPT_IMPLICIT_MENTION, +} from './agent-chat-prompt-builder' + +describe('AgentChatPromptBuilder', () => { + it('should build prompt with baseline configurations (implicit mention)', () => { + const builder = new AgentChatPromptBuilder('a1') + const result = builder.build() + + const expected = + PROMPT_ASSET_BASE('a1') + PROMPT_MEDIA_TOOL_INSTRUCTION + PROMPT_IMPLICIT_MENTION + + expect(result).toBe(expected) + }) + + it('should build prompt with explicit mention', () => { + const builder = new AgentChatPromptBuilder('a1').withExplicitMention(true) + const result = builder.build() + + const expected = + PROMPT_ASSET_BASE('a1') + PROMPT_MEDIA_TOOL_INSTRUCTION + PROMPT_EXPLICIT_MENTION + + expect(result).toBe(expected) + }) + + it('should build prompt with path context', () => { + const builder = new AgentChatPromptBuilder('a1').withPathContext('folder/sub/file.png') + const result = builder.build() + + const expected = + PROMPT_ASSET_BASE('a1') + + PROMPT_PATH_CONTEXT('folder/sub/file.png') + + PROMPT_MEDIA_TOOL_INSTRUCTION + + PROMPT_IMPLICIT_MENTION + + expect(result).toBe(expected) + }) + + it('should build prompt with media info', () => { + const media = { duration: 10, format: 'mp4' } + const builder = new AgentChatPromptBuilder('a1').withMediaInfo(media) + const result = builder.build() + + const expected = + PROMPT_ASSET_BASE('a1') + + PROMPT_MEDIA_INFO(JSON.stringify(media, null, 2)) + + PROMPT_MEDIA_TOOL_INSTRUCTION + + PROMPT_IMPLICIT_MENTION + + expect(result).toBe(expected) + }) + + it('should build prompt with all fields combined', () => { + const media = { width: 1920, height: 1080 } + const builder = new AgentChatPromptBuilder('a1') + .withExplicitMention(true) + .withPathContext('src/main.ts') + .withMediaInfo(media) + const result = builder.build() + + const expected = + PROMPT_ASSET_BASE('a1') + + PROMPT_PATH_CONTEXT('src/main.ts') + + PROMPT_MEDIA_INFO(JSON.stringify(media, null, 2)) + + PROMPT_MEDIA_TOOL_INSTRUCTION + + PROMPT_EXPLICIT_MENTION + + expect(result).toBe(expected) + }) +}) diff --git a/packages/agent/src/workflows/agent-chat-prompt-builder.ts b/packages/agent/src/workflows/agent-chat-prompt-builder.ts new file mode 100644 index 00000000..a53b0ae7 --- /dev/null +++ b/packages/agent/src/workflows/agent-chat-prompt-builder.ts @@ -0,0 +1,56 @@ +export const PROMPT_ASSET_BASE = (assetId: string) => + `The user is discussing an asset with ID: ${assetId}.` + +export const PROMPT_PATH_CONTEXT = (pathContext: string) => + `\n\nAsset Path Context:\n${pathContext}` + +export const PROMPT_MEDIA_INFO = (mediaJson: string) => `\n\nAsset Media Info:\n${mediaJson}` + +export const PROMPT_MEDIA_TOOL_INSTRUCTION = `\n\nIf you need to view the asset's media content (frames/images/video), call the 'analyze_asset_media' tool by passing the appropriate 'key' from the Asset Media Info above. Choose the most suitable format based on your capabilities and the user's request (e.g., use a poster or sprite for quick visual checks, or a transcode/raw file for detailed analysis).` + +export const PROMPT_EXPLICIT_MENTION = `\n\nThe user explicitly mentioned you in their message. You MUST reply to this message.` + +export const PROMPT_IMPLICIT_MENTION = `\n\nThe user did not explicitly mention you, but is replying in a thread where you are the participant. Let's decide if you should reply or not. If the user is not directly addressing you or doesn't need a response from you, you may choose to not reply. To choose not to reply, respond with exactly and only the text: __NO_REPLY__.` + +export class AgentChatPromptBuilder { + private assetId: string + private pathContext?: string + private mediaInfo?: unknown + private explicitMention = false + + constructor(assetId: string) { + this.assetId = assetId + } + + withPathContext(pathContext?: string): this { + this.pathContext = pathContext + return this + } + + withMediaInfo(mediaInfo?: unknown): this { + this.mediaInfo = mediaInfo + return this + } + + withExplicitMention(explicitMention?: boolean): this { + this.explicitMention = !!explicitMention + return this + } + + build(): string { + let instruction = PROMPT_ASSET_BASE(this.assetId) + if (this.pathContext) { + instruction += PROMPT_PATH_CONTEXT(this.pathContext) + } + if (this.mediaInfo) { + instruction += PROMPT_MEDIA_INFO(JSON.stringify(this.mediaInfo, null, 2)) + } + instruction += PROMPT_MEDIA_TOOL_INSTRUCTION + if (this.explicitMention) { + instruction += PROMPT_EXPLICIT_MENTION + } else { + instruction += PROMPT_IMPLICIT_MENTION + } + return instruction + } +} diff --git a/packages/agent/src/workflows/agent-chat.test.ts b/packages/agent/src/workflows/agent-chat.test.ts index f17c9c37..76bdf71e 100644 --- a/packages/agent/src/workflows/agent-chat.test.ts +++ b/packages/agent/src/workflows/agent-chat.test.ts @@ -3,6 +3,7 @@ import { agentChat } from './agent-chat' import { prisma } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' import * as workflowUtils from '@shumai/workflow-core' +import { AgentChatPromptBuilder } from './agent-chat-prompt-builder' vi.mock('@shumai/workflow-core', async () => { const actual = await vi.importActual('@shumai/workflow-core') @@ -124,12 +125,17 @@ describe('Agent Chat Workflow', () => { }) // Verify agent instruction composition + const expectedInstruction1 = new AgentChatPromptBuilder('a1') + .withPathContext('Path: folder/subfolder/file.png') + .withExplicitMention(true) + .build() + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith( expect.objectContaining({ teamId: 't1', agentId: 'b1', message: 'hello agent', - agentsInstruction: expect.stringContaining('explicitly mentioned you'), + agentsInstruction: expectedInstruction1, sessionId: 'session-123', folderId: 'parent-folder-id', }), @@ -174,9 +180,15 @@ describe('Agent Chat Workflow', () => { await agentChat(task) expect(mockActivities.initializeAgentSessionActivity).not.toHaveBeenCalled() + const expectedInstruction2 = new AgentChatPromptBuilder('a1') + .withPathContext('Path: folder/subfolder/file.png') + .withExplicitMention(false) + .build() + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith( expect.objectContaining({ sessionId: 'existing-session-456', + agentsInstruction: expectedInstruction2, }), ) }) @@ -202,9 +214,14 @@ describe('Agent Chat Workflow', () => { await agentChat(task) // Verify instruction contains not explicitly mentioned instructions + const expectedInstruction3 = new AgentChatPromptBuilder('a1') + .withPathContext('Path: folder/subfolder/file.png') + .withExplicitMention(false) + .build() + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith( expect.objectContaining({ - agentsInstruction: expect.stringContaining('did not explicitly mention you'), + agentsInstruction: expectedInstruction3, }), ) @@ -261,9 +278,15 @@ describe('Agent Chat Workflow', () => { await agentChat(task) + const expectedInstruction4 = new AgentChatPromptBuilder('a1') + .withPathContext('Path: folder/subfolder/file.png') + .withExplicitMention(false) + .build() + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith( expect.objectContaining({ imageUrls: ['attachments/image1.png', 'attachments/image2.jpg'], + agentsInstruction: expectedInstruction4, }), ) }) @@ -294,9 +317,19 @@ describe('Agent Chat Workflow', () => { await agentChat(task) + const expectedInstruction5 = new AgentChatPromptBuilder('a1') + .withPathContext('Path: folder/subfolder/file.png') + .withMediaInfo({ + duration: 10, + height: 1080, + width: 1920, + }) + .withExplicitMention(false) + .build() + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith( expect.objectContaining({ - agentsInstruction: expect.stringContaining('Asset Media Info:'), + agentsInstruction: expectedInstruction5, }), ) }) diff --git a/packages/agent/src/workflows/agent-chat.ts b/packages/agent/src/workflows/agent-chat.ts index 9271d470..d7cf1f90 100644 --- a/packages/agent/src/workflows/agent-chat.ts +++ b/packages/agent/src/workflows/agent-chat.ts @@ -1,6 +1,7 @@ import { ApplicationFailure } from '@temporalio/workflow' import type { WorkflowTask } from '@shumai/db' import { executeActivity, getActivities, TaskQueueAgent } from '@shumai/workflow-core' +import { AgentChatPromptBuilder } from './agent-chat-prompt-builder' export async function agentChat(task: WorkflowTask): Promise { const { @@ -105,22 +106,11 @@ export async function agentChat(task: WorkflowTask): Promise { task.assetId, ) - let instruction = `The user is discussing an asset with ID: ${asset.id}.` - if (pathContext) { - instruction += `\n\nAsset Path Context:\n${pathContext}` - } - - if (asset.media) { - instruction += `\n\nAsset Media Info:\n${JSON.stringify(asset.media, null, 2)}` - } - - instruction += `\n\nIf you need to view the asset's media content (frames/images/video), call the 'analyze_asset_media' tool by passing the appropriate 'key' from the Asset Media Info above. Choose the most suitable format based on your capabilities and the user's request (e.g., use a poster or sprite for quick visual checks, or a transcode/raw file for detailed analysis).` - - if (payload.agent?.explicitMention) { - instruction += `\n\nThe user explicitly mentioned you in their message. You MUST reply to this message.` - } else { - instruction += `\n\nThe user did not explicitly mention you, but is replying in a thread where you are the participant. Let's decide if you should reply or not. If the user is not directly addressing you or doesn't need a response from you, you may choose to not reply. To choose not to reply, respond with exactly and only the text: __NO_REPLY__.` - } + const instruction = new AgentChatPromptBuilder(asset.id) + .withPathContext(pathContext) + .withMediaInfo(asset.media) + .withExplicitMention(payload.agent?.explicitMention) + .build() // 6. Call AI Chat let folderId = '' From 6dc060b04f2d0d1e117ba9479f015247fb49d65f Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 3 Jun 2026 16:17:25 +0800 Subject: [PATCH 3/3] refactor(agent): use concrete Prisma model types in agent database activity tests --- packages/agent/src/activities/agent.test.ts | 22 ++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index d0bf368c..3706837f 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -19,7 +19,15 @@ import { import * as piAgent from '../index' import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core' import { type DatabaseSessionMetadata } from '../database-session-storage' -import { prisma, AssetType, AssetStatus } from '@shumai/db' +import { + prisma, + AssetType, + AssetStatus, + type Team, + type User, + type Project, + type Asset, +} from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' import { authzService } from '@shumai/core/src/authz/authz' import { uploadService } from '@shumai/core/src/upload/upload' @@ -170,14 +178,10 @@ describe('Agent Activities', () => { describe('Agent Database Activities Integration', () => { setupTestDbHooks() - // eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests - let team: any - // eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests - let user: any - // eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests - let project: any - // eslint-disable-next-line @typescript-eslint/no-explicit-any -- variables hold Prisma model output types that are difficult to type explicitly in tests - let asset: any + let team: Team + let user: User + let project: Project + let asset: Asset beforeEach(async () => { vi.restoreAllMocks()