import type { ToolRegistration } from '@earendil-works/pi-durable' import { Harness, createRegistry } from '@earendil-works/pi-durable' import { BACKGROUND_CONTEXT } from '@earendil-works/chord/context' import { createModels } from '@earendil-works/pi-ai' import { agentSessionService } from '@shumai/core/src/agent/session-service' import { invokeTool } from '@shumai/core/src/agent/tool-test-utils' import { logger } from '@shumai/core/src/logger' import { getShumaiMessage } from '@shumai/dtos' import { DBOS, DBOSError, runInLocalTaskContext, triggerLocalCancel } from '@shumai/workflow-core' import { beforeEach, describe, expect, it, vi } from 'vitest' import * as piAgent from '../runtime' import * as commentContext from '../comment-context' import { mockAgentSession } from '../testing/native-runtime' import { agentChatActivity, type AgentExecutionContext, autofillAiActivity, createCommentActivity, deleteCommentActivity, formatProjectContextPrompt, generateSessionNameActivity, type GenerateSessionNameParams, getAgentAutofillContextActivity, getAgentChatContextActivity, getAssetActivity, getAssetPathContextActivity, getAssetPathHierarchyActivity, getCommentActivity, getProjectAutofillFieldsActivity, getUserTeamInfoActivity, initializeAgentSessionActivity, updateAssetMetadataActivity, updateCommentActivity, } from './agent' import { type Asset, AssetStatus, AssetType, prisma, type Project, type Team, type User, } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' vi.mock('../runtime', async () => { const actual = await vi.importActual('../runtime') return { ...actual, createAgentSession: vi.fn(), fieldsToTypeBoxSchema: vi.fn(), } }) describe('Agent Activities', () => { beforeEach(() => { vi.clearAllMocks() vi.spyOn(agentSessionService, 'getEntries').mockResolvedValue([]) vi.spyOn(commentContext, 'synchronizeCommentContext').mockResolvedValue() }) it('should call agentChatActivity and prompt the harness', async () => { const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockResolvedValue({ content: [{ type: 'text', text: 'AI response' }], usage: { input: 10, output: 20 }, }), } const mockSession = { getEntries: vi.fn().mockResolvedValue([]), getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), } vi.mocked(piAgent.createAgentSession).mockResolvedValue( mockAgentSession(mockHarness, mockSession), ) const context = { agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } }, dbProviders: [], teamSkills: [], allowedDomains: [], } as unknown as AgentExecutionContext const res = await agentChatActivity({ teamId: 't1', agentId: 'b1', message: 'Hi', imageUrls: [], projectId: 'p1', folderId: 'f1', sessionId: 'mock-session-id', context, }) expect(res.text).toBe('AI response') expect(res.usage.inputTokens).toBe(10) expect(res.usage.outputTokens).toBe(20) expect(piAgent.createAgentSession).toHaveBeenCalled() }) it('reports committed native model usage', async () => { const usage = { input: 150, output: 75, cacheRead: 25, totalTokens: 225, cost: { total: 0.0015 }, } const model = { prompt: vi.fn().mockResolvedValue({ content: [{ type: 'text', text: 'Response' }], usage }), } vi.mocked(piAgent.createAgentSession).mockResolvedValue(mockAgentSession(model)) const context = { agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } }, dbProviders: [], teamSkills: [], allowedDomains: [], } as unknown as AgentExecutionContext const response = await agentChatActivity({ teamId: 'team123', agentId: 'b1', message: 'Hi', imageUrls: [], projectId: 'p1', folderId: 'f1', sessionId: 'mock-session-id', context, }) expect(response.usage).toMatchObject({ inputTokens: 150, outputTokens: 75, cacheReadTokens: 25, cost: 0.0015, }) expect(response.usage.totalTokens).toBe(225) }) it('should register local cancellation handler and call harness.abort when cancelled in local mode', async () => { let resolvePrompt!: (value: { content: Array<{ type: string; text: string } | { type: string }> usage: { input: number; output: number } stopReason?: string errorMessage?: string }) => void const promptPromise = new Promise[0]>((resolve) => { resolvePrompt = resolve }) const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockReturnValue(promptPromise), abort: vi.fn(), } const mockSession = { getEntries: vi.fn().mockResolvedValue([]), getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), } vi.mocked(piAgent.createAgentSession).mockResolvedValue( mockAgentSession(mockHarness, mockSession), ) const context = { agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } }, dbProviders: [], teamSkills: [], allowedDomains: [], } as unknown as AgentExecutionContext const executionPromise = agentChatActivity({ taskId: 'task-123', teamId: 't1', agentId: 'b1', message: 'Hi', imageUrls: [], projectId: 'p1', folderId: 'f1', sessionId: 'mock-session-id', context, }) // Yield to let the asynchronous setup register the cancel handler await new Promise((resolve) => setTimeout(resolve, 50)) // Simulate user cancellation const cancelled = triggerLocalCancel('task-123') expect(cancelled).toBe(true) expect(mockHarness.abort).toHaveBeenCalled() // Resolve the prompt promise to allow the activity to finish clean resolvePrompt({ content: [{ type: 'text', text: 'AI response' }], usage: { input: 10, output: 20 }, }) await executionPromise }) it('should listen to abort signal and call harness.abort when cancelled', async () => { let resolvePrompt!: (value: { content: Array<{ type: string; text: string } | { type: string }> usage: { input: number; output: number } stopReason?: string errorMessage?: string }) => void const promptPromise = new Promise[0]>((resolve) => { resolvePrompt = resolve }) const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockReturnValue(promptPromise), abort: vi.fn(), } const mockSession = { getEntries: vi.fn().mockResolvedValue([]), getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), } vi.mocked(piAgent.createAgentSession).mockResolvedValue( mockAgentSession(mockHarness, mockSession), ) const context = { agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } }, dbProviders: [], teamSkills: [], allowedDomains: [], } as unknown as AgentExecutionContext const taskId = 'test-abort-task' const abortController = new AbortController() await runInLocalTaskContext({ taskId, abortController }, async () => { const executionPromise = agentChatActivity({ taskId, teamId: 't1', agentId: 'b1', message: 'Hi', imageUrls: [], projectId: 'p1', folderId: 'f1', sessionId: 'mock-session-id', context, }) // Yield to let the asynchronous setup add the abort event listener await new Promise((resolve) => setTimeout(resolve, 50)) abortController.abort() expect(mockHarness.abort).toHaveBeenCalled() // Resolve the prompt promise to allow the activity to finish clean resolvePrompt({ content: [{ type: 'text', text: 'AI response' }], usage: { input: 10, output: 20 }, }) await executionPromise }) }) it('rejects a failed native answer instead of completing the workflow', async () => { const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockResolvedValue({ content: [], usage: { input: 0, output: 0 }, stopReason: 'error', errorMessage: 'API key not valid', }), } const mockSession = { getEntries: vi.fn().mockResolvedValue([]), getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), } vi.mocked(piAgent.createAgentSession).mockResolvedValue( mockAgentSession(mockHarness, mockSession), ) const context = { agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } }, dbProviders: [], teamSkills: [], allowedDomains: [], } as unknown as AgentExecutionContext await expect( agentChatActivity({ teamId: 't1', agentId: 'b1', message: 'Hi', imageUrls: [], projectId: 'p1', folderId: 'f1', sessionId: 'mock-session-id', context, }), ).rejects.toThrow('API key not valid') }) it('should pass thinkingLevel from agent config to createAgentSession', async () => { const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockResolvedValue({ content: [], usage: { input: 0, output: 0 }, }), getThinkingLevel: vi.fn().mockReturnValue('high'), } const mockSession = { getEntries: vi.fn().mockResolvedValue([]), getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), } vi.mocked(piAgent.createAgentSession).mockResolvedValue( mockAgentSession(mockHarness, mockSession), ) const context = { agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' }, config: { thinkingLevel: 'high' }, }, dbProviders: [], teamSkills: [], allowedDomains: [], } as unknown as AgentExecutionContext await agentChatActivity({ teamId: 't1', agentId: 'b1', message: 'Hi', imageUrls: [], projectId: 'p1', folderId: 'f1', sessionId: 'mock-session-id', context, }) expect(piAgent.createAgentSession).toHaveBeenCalledWith( expect.objectContaining({ thinkingLevel: 'high', }), ) }) it('should call autofillAiActivity and run autofill tool', async () => { const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockResolvedValue({ content: [{ type: 'text', text: 'Captured' }], usage: { input: 5, output: 5 }, }), } const mockSession = { getEntries: vi.fn().mockResolvedValue([]), getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), } vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: unknown) => { const params = config as { customTools: ToolRegistration[] } const tool = params.customTools.find((t) => t.name === 'autofill_metadata') if (tool) { await invokeTool(tool, '1', { f1: 'val' }) } return mockAgentSession(mockHarness, mockSession) }) const context = { agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } }, dbProviders: [], teamSkills: [], allowedDomains: [], } as unknown as AgentExecutionContext const res = await autofillAiActivity({ teamId: 't1', images: [], fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }], context, }) expect(res.text).toBe('{"f1":"val"}') expect(res.usage.inputTokens).toBe(5) }) it('should use the base autofill prompt without any creation-context injection', async () => { const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockResolvedValue({ content: [{ type: 'text', text: 'Captured' }], usage: { input: 5, output: 5 }, }), } const mockSession = { getEntries: vi.fn().mockResolvedValue([]), getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), } let capturedSystemPrompt = '' vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: unknown) => { const params = config as { systemPrompt?: string customTools: ToolRegistration[] } capturedSystemPrompt = params.systemPrompt ?? '' const tool = params.customTools.find((t) => t.name === 'autofill_metadata') if (tool) { await invokeTool(tool, '1', { f1: 'val' }) } return mockAgentSession(mockHarness, mockSession) }) const context = { agent: { id: 'b1', type: 'autofill', provider: { name: 'google' }, modelRef: { modelId: 'gemini' }, }, dbProviders: [], teamSkills: [], allowedDomains: [], } as unknown as AgentExecutionContext await autofillAiActivity({ teamId: 't1', assetId: 'a1', assetName: 'test.mp4', mediaType: 'video/mp4', duration: 30.5, images: [], fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }], context, }) const capturedPrompt = mockHarness.prompt.mock.calls[0]?.[0] ?? '' expect(capturedPrompt).toContain('You are tasked with analyzing the asset "test.mp4"') expect(capturedPrompt).toContain('Call the "read_asset" tool with assetId: "a1"') expect(capturedPrompt).toContain( 'Video duration: 30.5s. Recommended inspection: call read_asset with videoConfig: { start: 0, end: 30.5, count: 10 }.', ) expect(capturedPrompt).toContain( 'call the "autofill_metadata" tool to provide the extracted metadata values.', ) expect(capturedPrompt).toContain( 'If "read_asset" fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content.', ) expect(capturedPrompt).not.toContain('') expect(capturedSystemPrompt).toContain( "If 'read_asset' fails or returns an error, do not autofill any metadata and report to the user directly. Do not try anything fancy, for example downloading the file or using python/ffmpeg to extract content.", ) }) it('should include PDF page count recommendations in autofill prompt when present', async () => { const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockResolvedValue({ content: [{ type: 'text', text: 'Captured' }], usage: { input: 5, output: 5 }, }), } const mockSession = { getEntries: vi.fn().mockResolvedValue([]), getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), } vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: unknown) => { const params = config as { customTools: ToolRegistration[] } const tool = params.customTools.find((t) => t.name === 'autofill_metadata') if (tool) { await invokeTool(tool, '1', { f1: 'val' }) } return mockAgentSession(mockHarness, mockSession) }) const context = { agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } }, dbProviders: [], teamSkills: [], allowedDomains: [], } as unknown as AgentExecutionContext await autofillAiActivity({ teamId: 't1', assetId: 'pdf-1', assetName: 'report.pdf', mediaType: 'application/pdf', pageCount: 15, images: [], fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }], context, }) const capturedPrompt = mockHarness.prompt.mock.calls[0]?.[0] ?? '' expect(capturedPrompt).toContain('You are tasked with analyzing the asset "report.pdf"') expect(capturedPrompt).toContain( 'Document pages: 15. Recommended inspection: call read_asset with docConfig: { mode: "pages", startPage: 1, endPage: 15 } or mode: "text".', ) }) it('should ignore inappropriate mediaType recommendations in autofillAiActivity', async () => { const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockResolvedValue({ content: [{ type: 'text', text: 'Captured' }], usage: { input: 5, output: 5 }, }), } const mockSession = { getEntries: vi.fn().mockResolvedValue([]), getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), } vi.mocked(piAgent.createAgentSession).mockImplementation(async (config: unknown) => { const params = config as { customTools: ToolRegistration[] } const tool = params.customTools.find((t) => t.name === 'autofill_metadata') if (tool) { await invokeTool(tool, '1', { f1: 'val' }) } return mockAgentSession(mockHarness, mockSession) }) const context = { agent: { id: 'b1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } }, dbProviders: [], teamSkills: [], allowedDomains: [], } as unknown as AgentExecutionContext // For a video asset, pageCount should NOT produce Document pages recommendation await autofillAiActivity({ teamId: 't1', assetId: 'video-1', assetName: 'video.mp4', mediaType: 'video/mp4', duration: 10.1, pageCount: 300, images: [], fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }], context, }) const videoPrompt = mockHarness.prompt.mock.calls[0]?.[0] ?? '' expect(videoPrompt).toContain('Video duration: 10.1s') expect(videoPrompt).not.toContain('Document pages') // For a PDF asset, duration should NOT produce Video duration recommendation await autofillAiActivity({ teamId: 't1', assetId: 'pdf-2', assetName: 'document.pdf', mediaType: 'application/pdf', duration: 10.1, pageCount: 50, images: [], fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }], context, }) const pdfPrompt = mockHarness.prompt.mock.calls[1]?.[0] ?? '' expect(pdfPrompt).toContain('Document pages: 50') expect(pdfPrompt).not.toContain('Video duration') // For a 3D asset, should produce 3D Model recommendation await autofillAiActivity({ teamId: 't1', assetId: 'model-3', assetName: 'robot.glb', mediaType: 'model/gltf-binary', images: [], fields: [{ id: 'f1', config: { name: 'F1', type: 'text' } }], context, }) const modelPrompt = mockHarness.prompt.mock.calls[2]?.[0] ?? '' expect(modelPrompt).toContain('3D Model: This asset has an orthogonal 4-view composite image') expect(modelPrompt).toContain( 'Front view at top-left, Right side view at top-right, Back view at bottom-left, Left side view at bottom-right', ) }) }) describe('Agent Database Activities Integration', () => { setupTestDbHooks() // Space out comment creations: ULID ids have 1ms timestamp granularity, so // back-to-back creates landing in the same millisecond sort by random suffix // and can break the id-ordered DAG spine in initializeAgentSessionActivity. const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) let team: Team let user: User let project: Project let asset: Asset 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', () => { const synchronize = async (sessionId: string, userCommentId: string) => agentSessionService.withWriter(sessionId, async (storage) => { const harness = await Harness.open( storage, { models: createModels(), registry: createRegistry() }, BACKGROUND_CONTEXT, ) try { await commentContext.synchronizeCommentContext({ conversation: await harness.root(BACKGROUND_CONTEXT), sessionId, userCommentId, teamId: team.id, agentId: 'test-agent-id', }) } finally { await harness.close(BACKGROUND_CONTEXT) } }) it('copies independent context with authors, mentions, attachments and media positions', async () => { await prisma.asset.update({ where: { id: asset.id }, data: { media: { proxyType: '3d', duration: 0, filesize: 0, frames: 0, imageTranscodes: [], videoTranscodes: [], finishedAt: '', metadata: null, original: null, }, }, }) const attachment = await prisma.asset.create({ data: { name: 'doc.pdf', type: 'file', status: 'uploaded', mediaType: 'application/pdf', projectId: project.id, }, }) const first = await prisma.assetComment.create({ data: { assetId: asset.id, message: `Hello <@${user.id}>`, creatorId: user.id, second: 1 }, }) await prisma.assetCommentAttachment.create({ data: { commentId: first.id, assetId: attachment.id }, }) await sleep(2) const second = await prisma.assetComment.create({ data: { assetId: asset.id, message: 'Next', creatorId: user.id }, }) await sleep(2) const third = await prisma.assetComment.create({ data: { assetId: asset.id, message: 'Third', creatorId: user.id }, }) const initialize = async (id: string) => { const sessionId = await initializeAgentSessionActivity({ teamId: team.id, agentId: 'test-agent-id', userCommentId: id, userId: user.id, }) await synchronize(sessionId, id) return sessionId } const secondSession = await initialize(second.id) const thirdSession = await initialize(third.id) expect(secondSession).not.toBe(thirdSession) const entries = await agentSessionService.getEntries(secondSession) const message = entries .map(getShumaiMessage) .find((data) => data?.sourceCommentId === first.id) expect(message).toMatchObject({ displayText: `Hello <@${user.name}>`, context: { user: { name: user.name, role: 'owner' }, position: { type: 'degree' }, attachedFiles: [{ id: attachment.id, mimeType: 'application/pdf' }], }, }) expect(entries.filter((e) => e.kind === 'shumai.message')).toHaveLength(1) expect( (await agentSessionService.getEntries(thirdSession)).filter( (e) => e.kind === 'shumai.message', ), ).toHaveLength(2) expect( await prisma.agentSession.count({ where: { assetId: asset.id, userCommentId: null } }), ).toBe(0) expect(await prisma.agentSessionEntry.count()).toBe(0) // Repeated initialization is idempotent, and deleting another session cannot remove copied context. await initialize(second.id) await prisma.agentSession.delete({ where: { id: thirdSession } }) expect(await agentSessionService.getEntries(secondSession)).toEqual(entries) }) it('copies thread replies without the triggering comment, placeholders or duplicate agent answers', async () => { const root = await prisma.assetComment.create({ data: { assetId: asset.id, message: 'Question', creatorId: user.id }, }) await prisma.assetComment.create({ data: { assetId: asset.id, message: '__CHAT__', replyToId: root.id }, }) await sleep(2) const reply = await prisma.assetComment.create({ data: { assetId: asset.id, message: 'Earlier reply', creatorId: user.id, replyToId: root.id, }, }) await sleep(2) const current = await prisma.assetComment.create({ data: { assetId: asset.id, message: 'Trigger', creatorId: user.id, replyToId: root.id }, }) const sessionId = await initializeAgentSessionActivity({ teamId: team.id, agentId: 'test-agent-id', userCommentId: current.id, userId: user.id, }) await synchronize(sessionId, current.id) const records = (await agentSessionService.getEntries(sessionId)) .map(getShumaiMessage) .filter(Boolean) expect(records.map((record) => record?.sourceCommentId)).toEqual([root.id, reply.id]) expect(records[0]?.context?.thread).toEqual({ id: root.id, replyCount: 2 }) await initializeAgentSessionActivity({ teamId: team.id, agentId: 'test-agent-id', userCommentId: current.id, }) await synchronize(sessionId, current.id) expect( (await agentSessionService.getEntries(sessionId)).map(getShumaiMessage).filter(Boolean), ).toEqual(records) }) it('should return user name and role for team member', async () => { const info = await getUserTeamInfoActivity({ userId: user.id, teamId: team.id, }) expect(info).toBeDefined() expect(info?.name).toBe(user.name) expect(info?.role).toBe('owner') }) }) 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() }) it('should create comment even if cancelled with DBOSWorkflowCancelledError (runOnCancel: true)', async () => { const realCancelErr = new DBOSError.DBOSWorkflowCancelledError('test-workflow-id') const isWithinWorkflowSpy = vi.spyOn(DBOS, 'isWithinWorkflow').mockReturnValue(true) const runStepSpy = vi.spyOn(DBOS, 'runStep').mockRejectedValue(realCancelErr) const comment = await createCommentActivity({ assetId: asset.id, message: 'Autofill failed: workflow cancelled', agentId: 'default', }) expect(comment.id).toBeDefined() expect(comment.message).toBe('Autofill failed: workflow cancelled') const savedComment = await prisma.assetComment.findUnique({ where: { id: comment.id } }) expect(savedComment).not.toBeNull() expect(savedComment?.message).toBe('Autofill failed: workflow cancelled') isWithinWorkflowSpy.mockRestore() runStepSpy.mockRestore() }) }) 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-completions', 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', }, }) // Create two team skills, only one of which is enabled for the agent const enabledSkill = await prisma.skill.create({ data: { name: 'Enabled Chat Skill', assetId: 'asset-enabled', hash: 'enabled-hash', teamId: team.id, }, }) const disabledSkill = await prisma.skill.create({ data: { name: 'Disabled Chat Skill', assetId: 'asset-disabled', hash: 'disabled-hash', teamId: team.id, }, }) 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', }, skills: { create: [{ skillId: enabledSkill.id }], }, }, }) const chatCtx = await getAgentChatContextActivity({ teamId: team.id, agentId: agent.id, }) expect(chatCtx.agent.id).toBe(agent.id) expect(chatCtx.dbProviders[0].name).toBe('openai') // Only the enabled skill must be advertised, and disabled team skills excluded expect(chatCtx.teamSkills.map((s) => s.id)).toEqual([enabledSkill.id]) expect(chatCtx.enabledSkillIds).toEqual([enabledSkill.id]) expect(chatCtx.teamSkills.map((s) => s.id)).not.toContain(disabledSkill.id) // Test permission enforcement in getAgentChatContextActivity // Create owner-only agent const ownerAgentUser = await prisma.user.create({ data: { name: 'Owner Bot', email: `ownerbot-${Date.now()}@shumai.ai`, type: 'agent' }, }) const ownerAgent = await prisma.agent.create({ data: { id: ownerAgentUser.id, teamId: team.id, type: 'chat', permission: 'owner', providerId: provider.id, modelId: model.id, config: { provider: 'openai', model: 'gpt-4' }, }, }) // Create owner and reviewer members const ownerUser = await prisma.user.create({ data: { name: 'Owner User', email: `owner-${Date.now()}@shumai.ai` }, }) await prisma.teamMember.create({ data: { teamId: team.id, userId: ownerUser.id, role: 'owner' }, }) const reviewerUser = await prisma.user.create({ data: { name: 'Reviewer User', email: `reviewer-${Date.now()}@shumai.ai` }, }) await prisma.teamMember.create({ data: { teamId: team.id, userId: reviewerUser.id, role: 'reviewer' }, }) // Owner should succeed const ownerCtx = await getAgentChatContextActivity({ teamId: team.id, agentId: ownerAgent.id, userId: ownerUser.id, }) expect(ownerCtx.agent.id).toBe(ownerAgent.id) // Reviewer should fail with non-retryable ApplicationFailure await expect( getAgentChatContextActivity({ teamId: team.id, agentId: ownerAgent.id, userId: reviewerUser.id, }), ).rejects.toThrow('Permission denied') // 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', }, skills: { create: [{ skillId: enabledSkill.id }], }, }, }) const autofillCtx = await getAgentAutofillContextActivity({ teamId: team.id, }) expect(autofillCtx.agent.id).toBe(autofillAgent.id) // Only the enabled skill must be advertised for the autofill agent as well expect(autofillCtx.teamSkills.map((s) => s.id)).toEqual([enabledSkill.id]) expect(autofillCtx.enabledSkillIds).toEqual([enabledSkill.id]) expect(autofillCtx.teamSkills.map((s) => s.id)).not.toContain(disabledSkill.id) }) it('should return an empty enabled skill list when the agent has no skills enabled', async () => { const provider = await prisma.provider.create({ data: { teamId: team.id, name: 'openai-noskill', config: { api: 'openai-completions', 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 }, }, }, }) await prisma.skill.create({ data: { name: 'Team Wide Skill', assetId: 'asset-team', hash: 'team-hash', teamId: team.id, }, }) const agentUser = await prisma.user.create({ data: { name: 'No Skill Agent User', email: 'noskillagent@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-noskill', model: 'gpt-4', }, }, }) const chatCtx = await getAgentChatContextActivity({ teamId: team.id, agentId: agent.id, }) // Team-wide skill exists but is not enabled for this agent expect(chatCtx.teamSkills).toEqual([]) expect(chatCtx.enabledSkillIds).toEqual([]) }) }) 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) }) it('should resolve version stack asset to its latest version file', async () => { const stack = await prisma.asset.create({ data: { name: 'Stack', type: AssetType.version_stack, status: AssetStatus.uploaded, projectId: project.id, }, }) await prisma.asset.create({ data: { name: 'v1.png', type: AssetType.file, mediaType: 'image/png', status: AssetStatus.uploaded, projectId: project.id, parentId: stack.id, sortIndex: 'a1', }, }) const v2 = await prisma.asset.create({ data: { name: 'v2.png', type: AssetType.file, mediaType: 'image/png', status: AssetStatus.uploaded, projectId: project.id, parentId: stack.id, sortIndex: 'a0', }, }) const fetchedAsset = await getAssetActivity(stack.id) expect(fetchedAsset?.id).toBe(v2.id) expect(fetchedAsset?.name).toBe('v2.png') }) }) 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).toBe('RootFolder/SubFolder/TargetImage.webp') const hierarchy = await getAssetPathHierarchyActivity(targetAsset.id) expect(hierarchy.path).toBe('RootFolder/SubFolder/TargetImage.webp') expect(hierarchy.ancestors).toEqual([ { id: rootFolder.id, name: 'RootFolder' }, { id: subfolder.id, name: 'SubFolder' }, ]) }) }) 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, config: { name: 'Title Extractor', type: 'text', autofillSource: 'CONTENT' }, }, }) 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('generateSessionNameActivity', () => { it('should generate and save session name for chat sessions', async () => { await prisma.team.create({ data: { id: 't1', name: 'Test Team' }, }) const user = await prisma.user.create({ data: { id: 'u1', name: 'Test User', email: 'u1@test.com' }, }) const agentUser = await prisma.user.create({ data: { id: 'agent-123', name: 'Chat Agent User', email: 'agent@shumai.ai', type: 'agent', }, }) const agent = await prisma.agent.create({ data: { id: agentUser.id, teamId: 't1', type: 'chat', config: { provider: 'openai', model: 'gpt-4' }, }, }) await prisma.agentSession.create({ data: { id: 'session-123', agentId: 'agent-123', userId: user.id, cwd: process.cwd(), type: 'chat', name: null, }, }) const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockResolvedValue({ content: [{ type: 'text', text: ' "Summarized Chat Title" ' }], }), } vi.mocked(piAgent.createAgentSession).mockResolvedValue(mockAgentSession(mockHarness, {})) await generateSessionNameActivity({ teamId: 't1', agentId: 'agent-123', prompt: 'hello world prompt', sessionId: 'session-123', context: { agent: { ...agent, provider: { name: 'openai' }, modelRef: { id: 'm1', providerName: 'openai', modelId: 'gpt-4', name: 'GPT-4', config: {}, createdAt: new Date(), updatedAt: new Date(), }, } as unknown as GenerateSessionNameParams['context']['agent'], dbProviders: [ { name: 'openai', config: { api: 'openai-responses', apiKey: 'fake-key' }, models: [ { modelId: 'gpt-4', name: 'GPT-4', config: { reasoning: false, input: ['text'], contextWindow: 4096, maxTokens: 4096, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, }, }, ], }, ], }, }) expect(piAgent.createAgentSession).toHaveBeenCalledWith( expect.objectContaining({ disableTools: true, }), ) const updatedSession = await prisma.agentSession.findUnique({ where: { id: 'session-123' }, }) expect(updatedSession?.name).toBe('Summarized Chat Title') expect(mockHarness.prompt).toHaveBeenCalledWith( 'Generate a short 2 to 4 word title for a session starting with this message:\n\n\nhello world prompt\n', { images: [] }, ) // Verify that transient naming session was cleaned up (deleted) const namingSessions = await prisma.agentSession.findMany({ where: { type: 'naming' }, }) expect(namingSessions).toHaveLength(0) }) it('should skip name generation for comment sessions or if name is already set', async () => { await prisma.team.create({ data: { id: 't1', name: 'Test Team' }, }) const user = await prisma.user.create({ data: { id: 'u1', name: 'Test User', email: 'u1@test.com' }, }) const agentUser = await prisma.user.create({ data: { id: 'agent-123', name: 'Chat Agent User', email: 'agent2@shumai.ai', type: 'agent', }, }) await prisma.agent.create({ data: { id: agentUser.id, teamId: 't1', type: 'chat', config: { provider: 'openai', model: 'gpt-4' }, }, }) await prisma.agentSession.create({ data: { id: 'session-comment', agentId: 'agent-123', userId: user.id, cwd: process.cwd(), type: 'comment', name: null, }, }) await prisma.agentSession.create({ data: { id: 'session-named', agentId: 'agent-123', userId: user.id, cwd: process.cwd(), type: 'chat', name: 'Existing Name', }, }) vi.mocked(piAgent.createAgentSession).mockClear() await generateSessionNameActivity({ teamId: 't1', agentId: 'agent-123', prompt: 'hello comment', sessionId: 'session-comment', context: { agent: {} as unknown as GenerateSessionNameParams['context']['agent'], dbProviders: [], }, }) await generateSessionNameActivity({ teamId: 't1', agentId: 'agent-123', prompt: 'hello named', sessionId: 'session-named', context: { agent: {} as unknown as GenerateSessionNameParams['context']['agent'], dbProviders: [], }, }) expect(piAgent.createAgentSession).not.toHaveBeenCalled() }) it('should log error and not update session name when LLM returns an error', async () => { const errorSpy = vi.spyOn(logger, 'error') await prisma.team.create({ data: { id: 't1', name: 'Test Team' }, }) const user = await prisma.user.create({ data: { id: 'u1', name: 'Test User', email: 'u1@test.com' }, }) const agentUser = await prisma.user.create({ data: { id: 'agent-123', name: 'Chat Agent User', email: 'agent@shumai.ai', type: 'agent', }, }) const agent = await prisma.agent.create({ data: { id: agentUser.id, teamId: 't1', type: 'chat', config: { provider: 'openai', model: 'gpt-4' }, }, }) await prisma.agentSession.create({ data: { id: 'session-err', agentId: 'agent-123', userId: user.id, cwd: process.cwd(), type: 'chat', name: null, }, }) const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockResolvedValue({ content: [{ type: 'text', text: '' }], stopReason: 'error', errorMessage: 'Rate limit exceeded (429)', }), } vi.mocked(piAgent.createAgentSession).mockResolvedValue(mockAgentSession(mockHarness, {})) await generateSessionNameActivity({ teamId: 't1', agentId: 'agent-123', prompt: 'hello error', sessionId: 'session-err', context: { agent: { ...agent, provider: { name: 'openai' }, modelRef: { id: 'm1', providerName: 'openai', modelId: 'gpt-4', name: 'GPT-4', config: {}, createdAt: new Date(), updatedAt: new Date(), }, } as unknown as GenerateSessionNameParams['context']['agent'], dbProviders: [ { name: 'openai', config: { api: 'openai-responses', apiKey: 'fake-key' }, models: [], }, ], }, }) expect(errorSpy).toHaveBeenCalledWith( expect.objectContaining({ sessionId: 'session-err', stopReason: 'error', errorMessage: 'Rate limit exceeded (429)', }), 'Failed to generate session name: LLM returned an error', ) const sessionAfter = await prisma.agentSession.findUnique({ where: { id: 'session-err' }, }) expect(sessionAfter?.name).toBeNull() errorSpy.mockRestore() }) it('should pass thinkingLevel from agent.config to createAgentSession', async () => { await prisma.team.create({ data: { id: 't-thinking', name: 'Thinking Team' }, }) const user = await prisma.user.create({ data: { id: 'u-thinking', name: 'Thinking User', email: 'u-thinking@test.com' }, }) const agentUser = await prisma.user.create({ data: { id: 'agent-thinking', name: 'Thinking Agent User', email: 'agent-thinking@shumai.ai', type: 'agent', }, }) const agent = await prisma.agent.create({ data: { id: agentUser.id, teamId: 't-thinking', type: 'chat', config: { provider: 'openai', model: 'gpt-4', thinkingLevel: 'low' }, }, }) await prisma.agentSession.create({ data: { id: 'session-thinking', agentId: agent.id, userId: user.id, cwd: process.cwd(), type: 'chat', name: null, }, }) const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockResolvedValue({ content: [{ type: 'text', text: 'Thinking Title' }], }), } vi.mocked(piAgent.createAgentSession).mockResolvedValue(mockAgentSession(mockHarness, {})) await generateSessionNameActivity({ teamId: 't-thinking', agentId: agent.id, prompt: 'test prompt', sessionId: 'session-thinking', context: { agent: { ...agent, provider: { name: 'openai' }, modelRef: { id: 'm1', providerName: 'openai', modelId: 'gpt-4', name: 'GPT-4', config: {}, createdAt: new Date(), updatedAt: new Date(), }, } as unknown as GenerateSessionNameParams['context']['agent'], dbProviders: [ { name: 'openai', config: { api: 'openai-responses', apiKey: 'fake-key' }, models: [], }, ], }, }) expect(piAgent.createAgentSession).toHaveBeenCalledWith( expect.objectContaining({ thinkingLevel: 'low', disableTools: true, }), ) }) }) describe('Nested AGENTS.md prompt injection', () => { beforeEach(() => { vi.spyOn(commentContext, 'synchronizeCommentContext').mockResolvedValue() }) it('formatProjectContextPrompt formats context files into XML project_context block', () => { expect(formatProjectContextPrompt([])).toBe('') const formatted = formatProjectContextPrompt([ { path: '/AGENTS.md', content: 'Root rules' }, { path: '/subfolder/AGENTS.md', content: 'Subfolder rules' }, ]) expect(formatted).toBe( '\n\n\n\nProject-specific instructions and guidelines:\n\n\nRoot rules\n\n\n\nSubfolder rules\n\n\n', ) }) it('agentChatActivity injects nested AGENTS.md instructions into systemPrompt', async () => { const user = await prisma.user.create({ data: { name: 'User_Chat_Md', email: `chat-md-${Date.now()}@example.com` }, }) const team = await prisma.team.create({ data: { name: 'Team_Chat_Md_' + Date.now() }, }) const project = await prisma.project.create({ data: { name: 'Project_Chat_Md', teamId: team.id }, }) const rootFolder = await prisma.asset.create({ data: { name: 'Root', type: AssetType.root, projectId: project.id, status: AssetStatus.uploaded, }, }) await prisma.assetAgentMd.create({ data: { assetId: rootFolder.id, content: '# Root Policy', }, }) const subfolder = await prisma.asset.create({ data: { name: 'subfolder', type: AssetType.folder, parentId: rootFolder.id, projectId: project.id, status: AssetStatus.uploaded, }, }) await prisma.assetAgentMd.create({ data: { assetId: subfolder.id, content: '# Subfolder Policy', }, }) const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockResolvedValue({ content: [{ type: 'text', text: 'Chat reply' }], usage: { input: 10, output: 20 }, }), } const mockSession = { getEntries: vi.fn().mockResolvedValue([]), getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), } vi.mocked(piAgent.createAgentSession).mockResolvedValue( mockAgentSession(mockHarness, mockSession), ) const context = { agent: { id: 'agent-1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } }, dbProviders: [], teamSkills: [], allowedDomains: [], } as unknown as AgentExecutionContext await agentChatActivity({ teamId: team.id, agentId: 'agent-1', message: 'Hello', imageUrls: [], projectId: project.id, folderId: subfolder.id, assetId: subfolder.id, sessionId: 'mock-session-id', userId: user.id, context, }) expect(piAgent.createAgentSession).toHaveBeenCalledWith( expect.objectContaining({ systemPrompt: expect.stringContaining(''), }), ) const lastCall = vi.mocked(piAgent.createAgentSession).mock.calls.at(-1) const systemPromptArg = lastCall?.[0].systemPrompt as string expect(systemPromptArg).toContain( '\n# Root Policy\n', ) expect(systemPromptArg).toContain( '\n# Subfolder Policy\n', ) }) it('agentChatActivity injects # Comment Threads into systemPrompt when userCommentId is present', async () => { const user = await prisma.user.create({ data: { name: 'User_Comment_Prompt', email: `comment-prompt-${Date.now()}@example.com` }, }) const team = await prisma.team.create({ data: { name: 'Team_Comment_Prompt_' + Date.now() }, }) const project = await prisma.project.create({ data: { name: 'Project_Comment_Prompt', teamId: team.id }, }) const asset = await prisma.asset.create({ data: { name: 'Asset_1', type: AssetType.file, projectId: project.id, status: AssetStatus.uploaded, }, }) const comment = await prisma.assetComment.create({ data: { assetId: asset.id, message: 'Question', creatorId: user.id, }, }) const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockResolvedValue({ content: [{ type: 'text', text: 'Chat reply' }], usage: { input: 10, output: 20 }, }), } const mockSession = { getEntries: vi.fn().mockResolvedValue([]), getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), } vi.mocked(piAgent.createAgentSession).mockResolvedValue( mockAgentSession(mockHarness, mockSession), ) const context = { agent: { id: 'agent-1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } }, dbProviders: [], teamSkills: [], allowedDomains: [], } as unknown as AgentExecutionContext await agentChatActivity({ teamId: team.id, agentId: 'agent-1', message: 'Hello', imageUrls: [], projectId: project.id, folderId: asset.id, assetId: asset.id, sessionId: 'mock-session-id', userCommentId: comment.id, userId: user.id, context, }) const lastCall = vi.mocked(piAgent.createAgentSession).mock.calls.at(-1) const systemPromptArg = lastCall?.[0].systemPrompt as string expect(systemPromptArg).toContain('# Comment Threads') expect(systemPromptArg).toContain('') expect(systemPromptArg).toContain('read_thread') }) it('agentChatActivity injects # 3D Model Inspection into systemPrompt', async () => { const user = await prisma.user.create({ data: { name: 'User_3d_Prompt', email: `prompt-3d-${Date.now()}@example.com` }, }) const team = await prisma.team.create({ data: { name: 'Team_3d_Prompt_' + Date.now() }, }) const project = await prisma.project.create({ data: { name: 'Project_3d_Prompt', teamId: team.id }, }) const asset = await prisma.asset.create({ data: { name: 'robot.glb', type: 'file', status: 'processed', mediaType: 'model/gltf-binary', media: { proxyType: '3d', duration: 0, filesize: 0, frames: 0, imageTranscodes: [], videoTranscodes: [], finishedAt: '', metadata: null, original: null, } as unknown as PrismaJson.MediaInfo, projectId: project.id, }, }) const comment = await prisma.assetComment.create({ data: { assetId: asset.id, creatorId: user.id, message: 'Check this 3d model', }, }) const mockSession = { id: 'mock-session-id', subscribe: vi.fn(), getEntries: vi.fn().mockResolvedValue([]), getStorage: vi.fn().mockReturnValue({ sessionId: 'mock-session-id' }), } const mockHarness = { subscribe: vi.fn(), prompt: vi.fn().mockResolvedValue({ content: [{ type: 'text', text: 'Response' }], usage: { input: 10, output: 20 }, }), } vi.mocked(piAgent.createAgentSession).mockResolvedValue( mockAgentSession(mockHarness, mockSession), ) const context = { agent: { id: 'agent-1', provider: { name: 'google' }, modelRef: { modelId: 'gemini' } }, dbProviders: [], teamSkills: [], allowedDomains: [], } as unknown as AgentExecutionContext await agentChatActivity({ teamId: team.id, agentId: 'agent-1', message: 'Hello', imageUrls: [], projectId: project.id, folderId: asset.id, assetId: asset.id, sessionId: 'mock-session-id', userCommentId: comment.id, userId: user.id, context, }) const lastCall = vi.mocked(piAgent.createAgentSession).mock.calls.at(-1) const systemPromptArg = lastCall?.[0].systemPrompt as string expect(systemPromptArg).toContain('# 3D Model Inspection') expect(systemPromptArg).toContain('media_type="3d"') expect(systemPromptArg).toContain('config3d') expect(systemPromptArg).toContain('') }) }) })