diff --git a/packages/agent/src/activities/agent.test.ts b/packages/agent/src/activities/agent.test.ts index fb27c0ab..19254f49 100644 --- a/packages/agent/src/activities/agent.test.ts +++ b/packages/agent/src/activities/agent.test.ts @@ -17,6 +17,7 @@ import { executeAgentToolActivity, generateSessionNameActivity, type GenerateSessionNameParams, + getUserTeamInfoActivity, } from './agent' import * as piAgent from '../index' import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core' @@ -548,9 +549,19 @@ describe('Agent Database Activities Integration', () => { // 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`, + `[${user.name} (owner)]: Hello <@${user.name}> check this`, ) }) + + 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', () => { diff --git a/packages/agent/src/activities/agent.ts b/packages/agent/src/activities/agent.ts index 46350680..c7c8ee63 100644 --- a/packages/agent/src/activities/agent.ts +++ b/packages/agent/src/activities/agent.ts @@ -338,15 +338,58 @@ export interface AgentChatParams { attachedAssets?: Array<{ id: string; name: string; type: string }> } +export async function getUserTeamInfoActivity(params: { + userId?: string + teamId: string +}): Promise<{ name: string; role: string } | null> { + if (!params.userId) return null + const [user, member] = await Promise.all([ + prisma.user.findUnique({ + where: { id: params.userId }, + select: { name: true }, + }), + prisma.teamMember.findUnique({ + where: { teamIdUserId: { teamId: params.teamId, userId: params.userId } }, + select: { role: true }, + }), + ]) + if (!user) return null + return { + name: user.name || 'Unknown User', + role: member?.role || 'user', + } +} + export async function agentChatActivity(params: AgentChatParams) { const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim() const sessionId = params.sessionId + let prompt = cleanMessage + if (params.userCommentId) { + let targetUserId = params.userId + if (!targetUserId) { + const comment = await prisma.assetComment.findUnique({ + where: { id: params.userCommentId }, + select: { creatorId: true }, + }) + targetUserId = comment?.creatorId || undefined + } + if (targetUserId) { + const userInfo = await getUserTeamInfoActivity({ + userId: targetUserId, + teamId: params.teamId, + }) + if (userInfo) { + prompt = `[${userInfo.name} (${userInfo.role})]: ${cleanMessage}` + } + } + } + return executeAgentPrompt({ taskId: params.taskId, teamId: params.teamId, agentId: params.agentId, - prompt: cleanMessage, + prompt, images: params.imageUrls, agentsInstruction: params.agentsInstruction || '', sessionId, @@ -531,6 +574,27 @@ export async function initializeAgentSessionActivity(params: { } } + const userRoleMap = new Map() + const humanCreatorIds = Array.from( + new Set( + existingComments + .filter((c) => c.creator?.type !== 'agent' && c.creatorId) + .map((c) => c.creatorId!), + ), + ) + if (humanCreatorIds.length > 0) { + const members = await prisma.teamMember.findMany({ + where: { + teamId: params.teamId, + userId: { in: humanCreatorIds }, + }, + select: { userId: true, role: true }, + }) + for (const m of members) { + userRoleMap.set(m.userId, m.role) + } + } + // Save context as AgentSessionEntry records let prevId: string | null = null for (const c of existingComments) { @@ -547,7 +611,8 @@ export async function initializeAgentSessionActivity(params: { const agentName = c.creator?.name || 'Ai Agent' messageContent = `[Agent Message][${agentName}]: ${messageContent}` } else if (c.creator?.name) { - messageContent = `[${c.creator.name}]: ${messageContent}` + const role = (c.creatorId ? userRoleMap.get(c.creatorId) : undefined) || 'user' + messageContent = `[${c.creator.name} (${role})]: ${messageContent}` } const entryId = ulid() diff --git a/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts b/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts index 0c26a7e3..e5aee67e 100644 --- a/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts +++ b/packages/agent/src/workflows/agent-chat-prompt-builder.test.ts @@ -164,4 +164,11 @@ describe('AgentChatPromptBuilder', () => { expect(result).toContain('File Name: new-folder') expect(result).toContain('Asset Path Context:\nprojects/my-proj/new-folder') }) + + it('should build prompt with user info when provided and not continuation', () => { + const builder = new AgentChatPromptBuilder('a1').withUserInfo('Alice', 'owner') + const result = builder.build() + + expect(result).toContain('User Info:\nName: Alice\nRole: owner') + }) }) diff --git a/packages/agent/src/workflows/agent-chat-prompt-builder.ts b/packages/agent/src/workflows/agent-chat-prompt-builder.ts index db7ff3f6..73668a02 100644 --- a/packages/agent/src/workflows/agent-chat-prompt-builder.ts +++ b/packages/agent/src/workflows/agent-chat-prompt-builder.ts @@ -17,6 +17,7 @@ export class AgentChatPromptBuilder { private explicitMention = false private attachedFiles: string[] = [] private referencedAssets: string[] = [] + private userInfo?: { name: string; role: string } private isContinuation = false private hasAssetChanged = false @@ -25,6 +26,13 @@ export class AgentChatPromptBuilder { this.assetId = assetId } + withUserInfo(name?: string, role?: string): this { + if (name) { + this.userInfo = { name, role: role || 'user' } + } + return this + } + withContinuation(isContinuation: boolean): this { this.isContinuation = isContinuation return this @@ -178,6 +186,10 @@ export class AgentChatPromptBuilder { 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__.` } + if (this.userInfo) { + instruction += `\n\nUser Info:\nName: ${this.userInfo.name}\nRole: ${this.userInfo.role}` + } + return instruction } } diff --git a/packages/agent/src/workflows/agent-chat.test.ts b/packages/agent/src/workflows/agent-chat.test.ts index 180a29b2..23d1797b 100644 --- a/packages/agent/src/workflows/agent-chat.test.ts +++ b/packages/agent/src/workflows/agent-chat.test.ts @@ -49,12 +49,16 @@ describe('Agent Chat Workflow', () => { generateSessionNameActivity: Object.assign(vi.fn(), { _activityName: 'generateSessionNameActivity', }), + getUserTeamInfoActivity: Object.assign(vi.fn(), { + _activityName: 'getUserTeamInfoActivity', + }), } mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue') mockActivities.updateTaskStatusActivity.mockResolvedValue({}) mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' }) mockActivities.generateSessionNameActivity.mockResolvedValue(undefined) + mockActivities.getUserTeamInfoActivity.mockResolvedValue({ name: 'Test User', role: 'owner' }) mockActivities.getAssetActivity.mockResolvedValue({ id: 'a1', project: { teamId: 't1' }, @@ -567,4 +571,37 @@ describe('Agent Chat Workflow', () => { }), ) }) + + it('should inject user info for 1-on-1 new chat sessions', async () => { + const task = await prisma.workflowTask.create({ + data: { + type: 'chat', + status: 'pending', + assetId: 'a1', + payload: { + projectId: 'p1', + agent: { + prompt: 'Hello agent from 1-on-1 chat', + sessionId: 'session-new-1-on-1', + agentId: 'b1', + userId: 'user-alice', + isNewChat: true, + }, + }, + }, + }) + + await agentChat(task) + + expect(mockActivities.getUserTeamInfoActivity).toHaveBeenCalledWith({ + userId: 'user-alice', + teamId: 't1', + }) + + expect(mockActivities.agentChatActivity).toHaveBeenCalledWith( + expect.objectContaining({ + agentsInstruction: expect.stringContaining('User Info:\nName: Test User\nRole: owner'), + }), + ) + }) }) diff --git a/packages/agent/src/workflows/agent-chat.ts b/packages/agent/src/workflows/agent-chat.ts index 572e5675..032df514 100644 --- a/packages/agent/src/workflows/agent-chat.ts +++ b/packages/agent/src/workflows/agent-chat.ts @@ -18,6 +18,7 @@ export async function agentChat(task: WorkflowTask): Promise { initializeAgentSessionActivity, getAssetPathContextActivity, generateSessionNameActivity, + getUserTeamInfoActivity, } = getActivities() let placeholderCommentId: string | undefined @@ -162,8 +163,16 @@ export async function agentChat(task: WorkflowTask): Promise { } } + let userInfo: { name: string; role: string } | null = null + if (!userCommentId && isNewChat && payload.agent?.userId) { + userInfo = await executeActivity(agentWorkerQueue, getUserTeamInfoActivity, { + userId: payload.agent.userId, + teamId, + }) + } + const proxyType = (asset.media as PrismaJson.MediaInfo | null)?.proxyType - const instruction = new AgentChatPromptBuilder(asset.id) + const promptBuilder = new AgentChatPromptBuilder(asset.id) .withContinuation(!isNewChat) .withAssetChanged(payload.agent?.hasAssetChanged) .withPathContext(pathContext) @@ -172,7 +181,12 @@ export async function agentChat(task: WorkflowTask): Promise { .withExplicitMention(payload.agent?.explicitMention) .withAttachedFiles(attachedFileDetailsList) .withReferencedAssets(referencedAssetDetailsList) - .build() + + if (userInfo) { + promptBuilder.withUserInfo(userInfo.name, userInfo.role) + } + + const instruction = promptBuilder.build() // 6. Call AI Chat let folderId = ''