From 979e4711c5ae97f614c521e902a2e2eaee827594 Mon Sep 17 00:00:00 2001 From: yiling Date: Thu, 21 May 2026 22:51:40 +0800 Subject: [PATCH] feat(agent): add agent chat context session routing and thread support --- src/services/asset/asset.test.ts | 126 +++++++++++++++++++++ src/services/asset/asset.ts | 48 +++++++- src/workflow/activities/agent.test.ts | 111 ++++++++++++++++++- src/workflow/activities/agent.ts | 147 ++++++++++++++++++++++++- src/workflow/workflows/ai-chat.test.ts | 101 +++++++++++++++++ src/workflow/workflows/ai-chat.ts | 32 ++++-- 6 files changed, 548 insertions(+), 17 deletions(-) diff --git a/src/services/asset/asset.test.ts b/src/services/asset/asset.test.ts index 5eaa641c..b83a6af7 100644 --- a/src/services/asset/asset.test.ts +++ b/src/services/asset/asset.test.ts @@ -658,6 +658,132 @@ describe('AssetService', () => { expect(tasks.some((t) => (t.payload as any).agentId === 'default')).toBe(true) }) + it('implements agent comment interaction rules (Rule 1, 2, 3)', async () => { + const { user, project } = await setupBasicAssets() + const file = await prisma.asset.create({ + data: { + name: 'rules-file', + type: AssetType.file, + projectId: project.id, + creatorId: user.id, + status: 'uploaded', + }, + }) + + const botUser = await prisma.user.create({ + data: { + name: 'Bot Agent', + type: 'agent', + email: 'rule-bot@shumai.ai', + }, + }) + const agent = await prisma.agent.create({ + data: { + id: botUser.id, + teamId: project.teamId, + type: 'chat', + config: { + provider: 'google', + model: 'gemini-pro', + }, + }, + }) + + // Rule 1: user mentions agent in chat, and it's not in a reply + const c1 = await assetService.createComment({ + assetId: file.id, + userId: user.id, + message: `Rule 1 test: Hello <@${agent.id}>`, + attachmentIds: [], + }) + + const tasksRule1 = await prisma.workflowTask.findMany({ + where: { assetId: file.id, payload: { path: ['userCommentId'], equals: c1.id } }, + }) + expect(tasksRule1.length).toBe(1) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const p1 = tasksRule1[0].payload as any + expect(p1.agentId).toBe(agent.id) + expect(p1.sessionId).toBeUndefined() + expect(p1.explicitMention).toBe(true) + + // Rule 2: user mentions agent in reply, and root is not an agent comment + const reply1 = await assetService.createComment({ + assetId: file.id, + userId: user.id, + message: `Rule 2 reply: <@${agent.id}>`, + replyToId: c1.id, + attachmentIds: [], + }) + + const tasksRule2 = await prisma.workflowTask.findMany({ + where: { assetId: file.id, payload: { path: ['userCommentId'], equals: reply1.id } }, + }) + expect(tasksRule2.length).toBe(1) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const p2 = tasksRule2[0].payload as any + expect(p2.agentId).toBe(agent.id) + expect(p2.sessionId).toBeUndefined() + expect(p2.explicitMention).toBe(true) + + // Create an agent session first for the foreign key constraint + await prisma.agentSession.create({ + data: { + id: 'test-session-rule3', + agentId: botUser.id, + cwd: process.cwd(), + }, + }) + + // Create an agent root comment with sessionId + const agentRoot = await prisma.assetComment.create({ + data: { + assetId: file.id, + creatorId: botUser.id, + message: 'Agent root comment', + sessionId: 'test-session-rule3', + }, + }) + + // Rule 3a: any user creates a reply, root is agent comment, no explicit mention + const reply3a = await assetService.createComment({ + assetId: file.id, + userId: user.id, + message: 'Rule 3a: reply without mention', + replyToId: agentRoot.id, + attachmentIds: [], + }) + + const tasksRule3a = await prisma.workflowTask.findMany({ + where: { assetId: file.id, payload: { path: ['userCommentId'], equals: reply3a.id } }, + }) + expect(tasksRule3a.length).toBe(1) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const p3a = tasksRule3a[0].payload as any + expect(p3a.agentId).toBe(botUser.id) + expect(p3a.sessionId).toBe('test-session-rule3') + expect(p3a.explicitMention).toBe(false) + + // Rule 3b: any user creates a reply, root is agent comment, explicitly mentions agent + const reply3b = await assetService.createComment({ + assetId: file.id, + userId: user.id, + message: `Rule 3b: reply with mention <@${botUser.id}>`, + replyToId: agentRoot.id, + attachmentIds: [], + }) + + const tasksRule3b = await prisma.workflowTask.findMany({ + where: { assetId: file.id, payload: { path: ['userCommentId'], equals: reply3b.id } }, + }) + expect(tasksRule3b.length).toBe(1) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const p3b = tasksRule3b[0].payload as any + expect(p3b.agentId).toBe(botUser.id) + expect(p3b.sessionId).toBe('test-session-rule3') + expect(p3b.explicitMention).toBe(true) + }) + it('updates asset order correctly', async () => { const { user, project } = await setupBasicAssets() diff --git a/src/services/asset/asset.ts b/src/services/asset/asset.ts index 12be021f..71341db9 100644 --- a/src/services/asset/asset.ts +++ b/src/services/asset/asset.ts @@ -797,12 +797,48 @@ export class AssetService { } } - // Detect bot mentions - const botMentionMatches = req.message.matchAll(/<@([^>]+)>/g) - for (const match of botMentionMatches) { - const agentId = match[1] - let foundAgent = false + // Parse bot mentions + const botMentionMatches = [...req.message.matchAll(/<@([^>]+)>/g)] + const mentionedAgentIds = new Set(botMentionMatches.map((match) => match[1])) + const handledAgentIds = new Set() + if (req.replyToId && a.project) { + const rootComment = await tx.assetComment.findUnique({ + where: { id: req.replyToId }, + include: { creator: true }, + }) + const rootSessionId = rootComment?.sessionId + const isRootAgent = + !!rootComment && (!!rootSessionId || rootComment.creator?.type === 'agent') + const rootAgentId = rootComment?.creatorId + + if (isRootAgent && rootAgentId) { + const explicitMention = mentionedAgentIds.has(rootAgentId) + await tx.workflowTask.create({ + data: { + assetId: a.id, + type: 'chat', + status: 'pending', + teamId: a.project.team.id, + projectId: a.project.id, + payload: { + userCommentId: comment.id, + agentId: rootAgentId, + projectId: a.project.id, + sessionId: rootSessionId || undefined, + explicitMention, + }, + }, + }) + handledAgentIds.add(rootAgentId) + } + } + + // Handle any other explicitly mentioned agents + for (const agentId of mentionedAgentIds) { + if (handledAgentIds.has(agentId)) continue + + let foundAgent = false if (agentId === 'default') { foundAgent = true } else { @@ -822,9 +858,11 @@ export class AssetService { userCommentId: comment.id, agentId: agentId, projectId: a.project.id, + explicitMention: true, }, }, }) + handledAgentIds.add(agentId) } } }) diff --git a/src/workflow/activities/agent.test.ts b/src/workflow/activities/agent.test.ts index 9b1945b2..362e9804 100644 --- a/src/workflow/activities/agent.test.ts +++ b/src/workflow/activities/agent.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' import { setupTestDbHooks } from '@/db-test-hooks' +import { prisma } from '@/db' import { aiChatActivity } from './agent' import { agentService } from '@/services/agent/agent' @@ -30,6 +31,7 @@ describe('Agent Activities', () => { imageUrls: [], projectId: 'p1', folderId: 'f1', + sessionId: 'mock-session-id', }) expect(agentService.chatWithAgent).toHaveBeenCalledWith( @@ -38,8 +40,115 @@ describe('Agent Activities', () => { 'Hi', [], '', - undefined, + 'mock-session-id', undefined, ) }) + + it('should initialize a new session with chronological context (Rule 1 and Rule 2) and prefix username', async () => { + const team = await prisma.team.create({ data: { name: 't1' } }) + const user1 = await prisma.user.create({ + data: { name: 'User One', email: 'user1@example.com' }, + }) + const project = await prisma.project.create({ + data: { name: 'p1', teamId: team.id }, + }) + const file = await prisma.asset.create({ + data: { + name: 'test-file', + type: 'file', + projectId: project.id, + creatorId: user1.id, + status: 'uploaded', + }, + }) + + // Create existing comment 1 + const comment1 = await prisma.assetComment.create({ + data: { + assetId: file.id, + creatorId: user1.id, + message: 'First comment message', + }, + }) + + // Create triggering comment 2 (Rule 1: no reply, mentions agent) + const comment2 = await prisma.assetComment.create({ + data: { + assetId: file.id, + creatorId: user1.id, + message: 'Hello <@agent-id>', + }, + }) + + vi.mocked(agentService.chatWithAgent).mockResolvedValue({ + text: 'AI response', + usage: { inputTokens: 1, outputTokens: 1, model: 'gpt-4' }, + sessionId: 'generated-session-id', + }) + + await aiChatActivity({ + teamId: team.id, + agentId: 'agent-id', + message: 'Hello <@agent-id>', + imageUrls: [], + projectId: project.id, + folderId: file.id, + userCommentId: comment2.id, + }) + + // Verify chatWithAgent was called with a brand new sessionId (a ULID) + expect(agentService.chatWithAgent).toHaveBeenCalled() + const callArgs = vi.mocked(agentService.chatWithAgent).mock.calls[0] + const createdSessionId = callArgs[5] + expect(createdSessionId).toBeDefined() + expect(createdSessionId).not.toBe('generated-session-id') + + // Verify session entries were populated with comment1 as context + const entries = await prisma.agentSessionEntry.findMany({ + where: { sessionId: createdSessionId }, + orderBy: { id: 'asc' }, + }) + + expect(entries.length).toBe(1) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const entryData = entries[0].entry as any + expect(entryData.id).toBe(comment1.id) + expect(entryData.message.content[0].text).toBe('[User One]: First comment message') + expect(entryData.message.role).toBe('user') + }) + + it('should support deleteCommentActivity', async () => { + const team = await prisma.team.create({ data: { name: 't1' } }) + const user1 = await prisma.user.create({ + data: { name: 'User One', email: 'user1-delete@example.com' }, + }) + const project = await prisma.project.create({ + data: { name: 'p1', teamId: team.id }, + }) + const file = await prisma.asset.create({ + data: { + name: 'test-file', + type: 'file', + projectId: project.id, + creatorId: user1.id, + status: 'uploaded', + }, + }) + const comment = await prisma.assetComment.create({ + data: { + assetId: file.id, + creatorId: user1.id, + message: 'To be deleted', + }, + }) + + const { deleteCommentActivity } = await import('./agent') + await deleteCommentActivity(comment.id) + + const found = await prisma.assetComment.findUnique({ + where: { id: comment.id }, + }) + expect(found).toBeNull() + }) }) diff --git a/src/workflow/activities/agent.ts b/src/workflow/activities/agent.ts index 5c1a0b32..2344de37 100644 --- a/src/workflow/activities/agent.ts +++ b/src/workflow/activities/agent.ts @@ -23,21 +23,166 @@ export interface AiChatParams { agentsInstruction?: string sessionId?: string userId?: string + userCommentId?: string + explicitMention?: boolean } export async function aiChatActivity(params: AiChatParams) { const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim() + let sessionId = params.sessionId + + if (!sessionId) { + const agentId = params.agentId === 'default' ? 'default' : params.agentId + + // Ensure user exists for agent + const userExists = await prisma.user.findUnique({ where: { id: agentId } }) + if (!userExists) { + await prisma.user.create({ + data: { + id: agentId, + name: 'Ai Agent', + email: `${agentId}@shumai.ai`, + type: 'agent', + }, + }) + } + + // Ensure agent exists + const agentExists = await prisma.agent.findUnique({ where: { id: agentId } }) + if (!agentExists) { + await prisma.agent.create({ + data: { + id: agentId, + teamId: params.teamId, + type: 'chat', + config: { + provider: 'openai', + model: 'gpt-4', + }, + }, + }) + } + + // Create a new AgentSession + const newSession = await prisma.agentSession.create({ + data: { + agentId, + userId: params.userId || null, + cwd: process.cwd(), + }, + }) + sessionId = newSession.id + + // Fetch existing comments as context + let existingComments: Array<{ + id: string + message: string | null + createdAt: Date + creatorId: string | null + creator: { type: string; name: string } | null + sessionId: string | null + }> = [] + + if (params.userCommentId) { + const userComment = await prisma.assetComment.findUnique({ + where: { id: params.userCommentId }, + include: { creator: true }, + }) + + if (userComment) { + if (!userComment.replyToId) { + // Rule 1: outside of a reply, add all other comments on that asset + existingComments = await prisma.assetComment.findMany({ + where: { + assetId: userComment.assetId, + id: { not: userComment.id }, + }, + orderBy: { id: 'asc' }, + include: { creator: true }, + }) + } else { + // Rule 2: in a reply, add root comment + all other replies to it + const rootComment = await prisma.assetComment.findUnique({ + where: { id: userComment.replyToId }, + include: { creator: true }, + }) + if (rootComment) { + const replies = await prisma.assetComment.findMany({ + where: { + replyToId: rootComment.id, + id: { not: userComment.id }, + }, + orderBy: { id: 'asc' }, + include: { creator: true }, + }) + existingComments = [rootComment, ...replies] + } + } + } + } + + // Save context as AgentSessionEntry records + let prevId: string | null = null + for (const c of existingComments) { + const isAgent = c.creator?.type === 'agent' || c.sessionId !== null + const role = isAgent ? 'assistant' : 'user' + let messageContent = c.message || '' + + // Prepend user name to user messages to ensure agent knows who sent what + if (!isAgent && c.creator?.name) { + messageContent = `[${c.creator.name}]: ${messageContent}` + } + + const entryId = c.id + const entryJson = { + type: 'message', + id: entryId, + parentId: prevId, + timestamp: c.createdAt.toISOString(), + message: { + role, + content: [{ type: 'text', text: messageContent }], + timestamp: c.createdAt.getTime(), + }, + } + + await prisma.agentSessionEntry.create({ + data: { + id: entryId, + sessionId, + // eslint-disable-next-line @typescript-eslint/no-explicit-any -- entryJson conforms to the internal PiSessionEntry/SessionTreeEntry JSON schema which uses generic json types + entry: entryJson as any, + }, + }) + prevId = entryId + } + + // Update leafId of the session + if (prevId) { + await prisma.agentSession.update({ + where: { id: sessionId }, + data: { leafId: prevId }, + }) + } + } + return agentService.chatWithAgent( params.teamId, params.agentId, cleanMessage, params.imageUrls, params.agentsInstruction || '', - params.sessionId, + sessionId, params.userId, ) } +export async function deleteCommentActivity(commentId: string) { + return prisma.assetComment.delete({ + where: { id: commentId }, + }) +} + export interface CreateCommentParams { assetId: string message: string diff --git a/src/workflow/workflows/ai-chat.test.ts b/src/workflow/workflows/ai-chat.test.ts index 7a0228b4..85148f10 100644 --- a/src/workflow/workflows/ai-chat.test.ts +++ b/src/workflow/workflows/ai-chat.test.ts @@ -31,6 +31,7 @@ describe('AIChat Workflow', () => { getAgentWorkerQueueActivity: Object.assign(vi.fn(), { _activityName: 'getAgentWorkerQueueActivity', }), + deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }), } beforeEach(() => { @@ -219,4 +220,104 @@ describe('AIChat Workflow', () => { output: { error: 'DB Down' }, }) }) + + it('should pass explicitMention payload parameter and format instruction when true', async () => { + const task: WorkflowTask = { + id: 'task-explicit', + assetId: 'asset-1', + type: WorkflowTaskType.chat, + status: WorkflowTaskStatus.pending, + output: null, + payload: { + userCommentId: 'comment-1', + agentId: 'bot-1', + explicitMention: true, + }, + createdAt: new Date(), + updatedAt: new Date(), + heartbeat: null, + teamId: 'team-1', + projectId: 'proj-1', + uid: 'task-uid-explicit', + model: null, + inputTokens: 0, + outputTokens: 0, + } + + mockActivities.getAssetActivity.mockResolvedValue({ + id: 'asset-1', + project: { teamId: 'team-1', id: 'proj-1' }, + }) + + mockActivities.getCommentActivity.mockResolvedValue({ + id: 'comment-1', + message: 'Hello AI', + }) + + mockActivities.createCommentActivity.mockResolvedValue({ + id: 'placeholder-1', + }) + + mockActivities.aiChatActivity.mockResolvedValue({ + text: 'Hello Human', + usage: { inputTokens: 5, outputTokens: 5, model: 'gpt-4' }, + }) + + await aiChat(task) + + expect(mockActivities.aiChatActivity).toHaveBeenCalledWith( + expect.objectContaining({ + explicitMention: true, + agentsInstruction: expect.stringContaining('MUST reply to this message'), + }), + ) + }) + + it('should delete placeholder comment when AI response is __NO_REPLY__', async () => { + const task: WorkflowTask = { + id: 'task-no-reply', + assetId: 'asset-1', + type: WorkflowTaskType.chat, + status: WorkflowTaskStatus.pending, + output: null, + payload: { + userCommentId: 'comment-1', + agentId: 'bot-1', + explicitMention: false, + }, + createdAt: new Date(), + updatedAt: new Date(), + heartbeat: null, + teamId: 'team-1', + projectId: 'proj-1', + uid: 'task-uid-no-reply', + model: null, + inputTokens: 0, + outputTokens: 0, + } + + mockActivities.getAssetActivity.mockResolvedValue({ + id: 'asset-1', + project: { teamId: 'team-1', id: 'proj-1' }, + }) + + mockActivities.getCommentActivity.mockResolvedValue({ + id: 'comment-1', + message: 'Hello AI', + }) + + mockActivities.createCommentActivity.mockResolvedValue({ + id: 'placeholder-delete-me', + }) + + mockActivities.aiChatActivity.mockResolvedValue({ + text: ' __NO_REPLY__ ', + usage: { inputTokens: 5, outputTokens: 5, model: 'gpt-4' }, + }) + + await aiChat(task) + + expect(mockActivities.deleteCommentActivity).toHaveBeenCalledWith('placeholder-delete-me') + expect(mockActivities.updateCommentActivity).not.toHaveBeenCalled() + }) }) diff --git a/src/workflow/workflows/ai-chat.ts b/src/workflow/workflows/ai-chat.ts index 0e49a1eb..a79d868a 100644 --- a/src/workflow/workflows/ai-chat.ts +++ b/src/workflow/workflows/ai-chat.ts @@ -16,6 +16,7 @@ export async function aiChat(task: WorkflowTask): Promise { updateCommentActivity, updateTaskUsageActivity, getAgentWorkerQueueActivity, + deleteCommentActivity, } = getActivities() let placeholderCommentId: string | undefined @@ -30,6 +31,8 @@ export async function aiChat(task: WorkflowTask): Promise { // eslint-disable-next-line @typescript-eslint/no-explicit-any const payload = task.payload as any + const sessionId = payload?.sessionId || payload?.session_id + // 1. Get User Comment const userCommentId = payload?.userCommentId if (!userCommentId) throw new Error('userCommentId missing in payload') @@ -40,7 +43,7 @@ export async function aiChat(task: WorkflowTask): Promise { const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, { assetId: task.assetId, message: '__CHAT__', - sessionId: payload?.session_id || 'pending', + sessionId: sessionId || 'pending', agentId: payload?.agentId, replyToId: userComment.replyToId ?? userComment.id, }) @@ -73,6 +76,12 @@ export async function aiChat(task: WorkflowTask): Promise { 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?.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__.` + } + // 5. Call AI Chat let folderId = '' if (asset.type === 'folder') { @@ -91,20 +100,23 @@ export async function aiChat(task: WorkflowTask): Promise { projectId: payload.projectId, folderId, agentsInstruction: instruction, - sessionId: payload.session_id, + sessionId, userId: payload.userId, + userCommentId, + explicitMention: payload?.explicitMention, }) // 6. Update Placeholder Comment if (placeholderCommentId) { - await executeActivity(TaskQueueDb, updateCommentActivity, { - commentId: placeholderCommentId, - message: aiResult.text, - sessionId: aiResult.sessionId, - }) - - // Also store sessionId in comment's metadata if we had such a field, - // but for now we just return it in task status. + if (aiResult.text.trim() === '__NO_REPLY__') { + await executeActivity(TaskQueueDb, deleteCommentActivity, placeholderCommentId) + } else { + await executeActivity(TaskQueueDb, updateCommentActivity, { + commentId: placeholderCommentId, + message: aiResult.text, + sessionId: aiResult.sessionId, + }) + } } // 7. Update Usage