diff --git a/AGENTS.md b/AGENTS.md index 19480e16..14e0bb8b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -297,6 +297,7 @@ We use a custom workflow engine that supports both **Local** (polling-based) and - **Location**: Defined in `src/services/workflow/activities/.ts`. - **Export**: Export individual activity functions and re-export them in `src/services/workflow/activities/index.ts`. - **Implementation**: Activities _can_ and _should_ call other services (e.g., `aiService`, `transcodeService`) or interact with the database. +- **Database Access Restriction**: **Agent activities (or other non-database activities) are strictly prohibited from calling the database directly.** All database queries or updates must be isolated within dedicated database activities defined in `src/workflow/activities/db.ts` (running on `db_queue` / `TaskQueueDb`). Workflow functions coordinate execution by first invoking the database activity to resolve and store state, then passing the resolved data to the agent/non-database activity. ## Import conventions diff --git a/src/workflow/activities/agent.test.ts b/src/workflow/activities/agent.test.ts index 2f534eb2..2e5705ac 100644 --- a/src/workflow/activities/agent.test.ts +++ b/src/workflow/activities/agent.test.ts @@ -1,9 +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' -import type { SessionTreeEntry } from '@earendil-works/pi-agent-core' vi.mock('@/services/agent/agent', () => ({ agentService: { @@ -12,13 +9,11 @@ vi.mock('@/services/agent/agent', () => ({ })) describe('Agent Activities', () => { - setupTestDbHooks() - beforeEach(() => { vi.clearAllMocks() }) - it('should call aiChatActivity', async () => { + it('should call aiChatActivity and delegate to agentService', async () => { vi.mocked(agentService.chatWithAgent).mockResolvedValue({ text: 'AI response', usage: { inputTokens: 1, outputTokens: 1, model: 'gpt-4' }, @@ -45,145 +40,4 @@ describe('Agent Activities', () => { 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 user2 = await prisma.user.create({ - data: { name: 'Matt', email: 'matt@example.com' }, - }) - const agentUser = await prisma.user.create({ - data: { id: 'agent-user-id', name: 'Smart Agent', email: 'agent@example.com', type: 'agent' }, - }) - 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 (User) - const comment1 = await prisma.assetComment.create({ - data: { - assetId: file.id, - creatorId: user1.id, - message: `First comment message for <@${user2.id}>`, - }, - }) - - // Create existing comment 1.5 (Agent) - const commentAgent = await prisma.assetComment.create({ - data: { - assetId: file.id, - creatorId: agentUser.id, - message: 'I am helping', - }, - }) - - // 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 and commentAgent as context - const entries = await prisma.agentSessionEntry.findMany({ - where: { sessionId: createdSessionId }, - orderBy: { id: 'asc' }, - }) - - expect(entries.length).toBe(2) - - // Verify User Comment Entry - const entryData1 = entries[0].entry as unknown as SessionTreeEntry - expect(entryData1.id).toBeDefined() - expect(entryData1.id).not.toBe(comment1.id) - if (entryData1.type === 'message') { - const msg = entryData1.message as { role: 'user'; content: { type: 'text'; text: string }[] } - expect(msg.content[0].text).toBe('[User One]: First comment message for <@Matt>') - expect(msg.role).toBe('user') - } else { - throw new Error('Expected entry to be a message') - } - - // Verify Agent Comment Entry - const entryData2 = entries[1].entry as unknown as SessionTreeEntry - expect(entryData2.id).toBeDefined() - expect(entryData2.id).not.toBe(commentAgent.id) - if (entryData2.type === 'message') { - const msg = entryData2.message as { role: 'user'; content: { type: 'text'; text: string }[] } - expect(msg.content[0].text).toBe('[Agent Message][Smart Agent]: I am helping') - expect(msg.role).toBe('user') - } else { - throw new Error('Expected entry to be a message') - } - }) - - 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 34e9d2cd..262a97cb 100644 --- a/src/workflow/activities/agent.ts +++ b/src/workflow/activities/agent.ts @@ -1,8 +1,5 @@ import { agentService } from '@/services/agent/agent' import type { AutofillField } from '@/agent' -import { prisma } from '@/db' -import { ulid } from 'ulid' -import type { AgentMessage, SessionTreeEntry } from '@earendil-works/pi-agent-core' export interface AutofillAiParams { teamId: string @@ -23,188 +20,14 @@ export interface AiChatParams { projectId: string folderId: string agentsInstruction?: string - sessionId?: 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] - } - } - } - } - - // Resolve user mentions from IDs to names - const mentionRegex = /<@([^>]+)>/g - const mentionedUserIds = new Set() - for (const c of existingComments) { - if (c.message) { - const matches = [...c.message.matchAll(mentionRegex)] - for (const match of matches) { - mentionedUserIds.add(match[1]) - } - } - } - - const userIdToNameMap = new Map() - if (mentionedUserIds.size > 0) { - const resolvedUsers = await prisma.user.findMany({ - where: { - id: { in: Array.from(mentionedUserIds) }, - }, - select: { - id: true, - name: true, - }, - }) - for (const u of resolvedUsers) { - if (u.name) { - userIdToNameMap.set(u.id, u.name) - } - } - } - - // Save context as AgentSessionEntry records - let prevId: string | null = null - for (const c of existingComments) { - const isAgent = c.creator?.type === 'agent' || c.sessionId !== null - let messageContent = c.message || '' - - // Replace <@USER_ID> with <@USER_NAME> - messageContent = messageContent.replace(mentionRegex, (match, userId) => { - const resolvedName = userIdToNameMap.get(userId) - return resolvedName ? `<@${resolvedName}>` : match - }) - - if (isAgent) { - const agentName = c.creator?.name || 'Ai Agent' - messageContent = `[Agent Message][${agentName}]: ${messageContent}` - } else if (c.creator?.name) { - messageContent = `[${c.creator.name}]: ${messageContent}` - } - - const entryId = ulid() - const message: AgentMessage = { - role: 'user', - content: [{ type: 'text', text: messageContent }], - timestamp: c.createdAt.getTime(), - } - - const entryJson: SessionTreeEntry = { - type: 'message', - id: entryId, - parentId: prevId, - timestamp: c.createdAt.toISOString(), - message, - } - - await prisma.agentSessionEntry.create({ - data: { - id: entryId, - sessionId, - entry: entryJson, - }, - }) - prevId = entryId - } - - // Update leafId of the session - if (prevId) { - await prisma.agentSession.update({ - where: { id: sessionId }, - data: { leafId: prevId }, - }) - } - } + const sessionId = params.sessionId return agentService.chatWithAgent( params.teamId, @@ -216,98 +39,3 @@ export async function aiChatActivity(params: AiChatParams) { params.userId, ) } - -export async function deleteCommentActivity(commentId: string) { - return prisma.assetComment.delete({ - where: { id: commentId }, - }) -} - -export interface CreateCommentParams { - assetId: string - message: string - sessionId?: string | null - agentId?: string | null - replyToId?: string | null -} - -export async function createCommentActivity(params: CreateCommentParams) { - if (params.sessionId) { - const agentId = params.agentId && params.agentId !== 'default' ? params.agentId : 'default' - - // Fetch teamId from asset - const asset = await prisma.asset.findUnique({ - where: { id: params.assetId }, - include: { project: true }, - }) - if (!asset || !asset.project) throw new Error('asset or project not found') - const teamId = asset.project.teamId - - // 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, - type: 'chat', - config: { - provider: 'openai', - model: 'gpt-4', - }, - }, - }) - } - - // Ensure agent session exists - const sessionExists = await prisma.agentSession.findUnique({ where: { id: params.sessionId } }) - if (!sessionExists) { - await prisma.agentSession.create({ - data: { - id: params.sessionId, - agentId: agentId, - cwd: process.cwd(), - }, - }) - } - } - - return prisma.assetComment.create({ - data: { - assetId: params.assetId, - message: params.message, - sessionId: params.sessionId ?? null, - creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null, - replyToId: params.replyToId, - }, - }) -} - -export interface UpdateCommentParams { - commentId: string - message: string - sessionId?: string | null -} - -export async function updateCommentActivity(params: UpdateCommentParams) { - return prisma.assetComment.update({ - where: { id: params.commentId }, - data: { - message: params.message, - ...(params.sessionId !== undefined ? { sessionId: params.sessionId } : {}), - }, - }) -} diff --git a/src/workflow/activities/db.test.ts b/src/workflow/activities/db.test.ts new file mode 100644 index 00000000..9b0aca3d --- /dev/null +++ b/src/workflow/activities/db.test.ts @@ -0,0 +1,148 @@ +import { describe, it, expect } from 'vitest' +import { setupTestDbHooks } from '@/db-test-hooks' +import { prisma } from '@/db' +import { + createCommentActivity, + updateCommentActivity, + deleteCommentActivity, + initializeAgentSessionActivity, +} from './db' +import type { SessionTreeEntry } from '@earendil-works/pi-agent-core' + +describe('Database Activities', () => { + setupTestDbHooks() + + it('should support comment CRUD activities (create, update, delete)', async () => { + const team = await prisma.team.create({ data: { name: 't1' } }) + const user = 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: user.id, + status: 'uploaded', + }, + }) + + // 1. Create Comment + const comment = await createCommentActivity({ + assetId: file.id, + message: 'Initial comment', + }) + expect(comment.id).toBeDefined() + expect(comment.message).toBe('Initial comment') + + // 2. Update Comment + const updated = await updateCommentActivity({ + commentId: comment.id, + message: 'Updated comment', + }) + expect(updated.message).toBe('Updated comment') + + // 3. Delete Comment + await deleteCommentActivity(comment.id) + const found = await prisma.assetComment.findUnique({ + where: { id: comment.id }, + }) + expect(found).toBeNull() + }) + + it('should initialize a new session with chronological context, prefixed usernames, and resolved user mentions', 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 user2 = await prisma.user.create({ + data: { name: 'Matt', email: 'matt@example.com' }, + }) + const agentUser = await prisma.user.create({ + data: { id: 'agent-user-id', name: 'Smart Agent', email: 'agent@example.com', type: 'agent' }, + }) + 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 (User mentioning user2) + const comment1 = await prisma.assetComment.create({ + data: { + assetId: file.id, + creatorId: user1.id, + message: `First comment message for <@${user2.id}>`, + }, + }) + + // Create existing comment 1.5 (Agent) + const commentAgent = await prisma.assetComment.create({ + data: { + assetId: file.id, + creatorId: agentUser.id, + message: 'I am helping', + }, + }) + + // 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-user-id>', + }, + }) + + const sessionId = await initializeAgentSessionActivity({ + teamId: team.id, + agentId: 'agent-user-id', + userCommentId: comment2.id, + userId: user1.id, + }) + + expect(sessionId).toBeDefined() + + // Verify session entries were populated with comment1 and commentAgent as context + const entries = await prisma.agentSessionEntry.findMany({ + where: { sessionId }, + orderBy: { id: 'asc' }, + }) + + expect(entries.length).toBe(2) + + // Verify User Comment Entry with resolved mention and username prefix + const entryData1 = entries[0].entry as unknown as SessionTreeEntry + expect(entryData1.id).toBeDefined() + expect(entryData1.id).not.toBe(comment1.id) + if (entryData1.type === 'message') { + const msg = entryData1.message as { role: 'user'; content: { type: 'text'; text: string }[] } + expect(msg.content[0].text).toBe('[User One]: First comment message for <@Matt>') + expect(msg.role).toBe('user') + } else { + throw new Error('Expected entry to be a message') + } + + // Verify Agent Comment Entry + const entryData2 = entries[1].entry as unknown as SessionTreeEntry + expect(entryData2.id).toBeDefined() + expect(entryData2.id).not.toBe(commentAgent.id) + if (entryData2.type === 'message') { + const msg = entryData2.message as { role: 'user'; content: { type: 'text'; text: string }[] } + expect(msg.content[0].text).toBe('[Agent Message][Smart Agent]: I am helping') + expect(msg.role).toBe('user') + } else { + throw new Error('Expected entry to be a message') + } + }) +}) diff --git a/src/workflow/activities/db.ts b/src/workflow/activities/db.ts new file mode 100644 index 00000000..fc7411a7 --- /dev/null +++ b/src/workflow/activities/db.ts @@ -0,0 +1,281 @@ +import { prisma } from '@/db' +import { Prisma } from '@/generated/prisma/client' +import { ulid } from 'ulid' +import type { AgentMessage, SessionTreeEntry } from '@earendil-works/pi-agent-core' + +export interface InitializeAgentSessionParams { + teamId: string + agentId: string + userCommentId: string + userId?: string +} + +export async function initializeAgentSessionActivity( + params: InitializeAgentSessionParams, +): Promise { + 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(), + }, + }) + const 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 + }> = [] + + 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] + } + } + } + + // Resolve user mentions from IDs to names + const mentionRegex = /<@([^>]+)>/g + const mentionedUserIds = new Set() + for (const c of existingComments) { + if (c.message) { + const matches = [...c.message.matchAll(mentionRegex)] + for (const match of matches) { + mentionedUserIds.add(match[1]) + } + } + } + + const userIdToNameMap = new Map() + if (mentionedUserIds.size > 0) { + const resolvedUsers = await prisma.user.findMany({ + where: { + id: { in: Array.from(mentionedUserIds) }, + }, + select: { + id: true, + name: true, + }, + }) + for (const u of resolvedUsers) { + if (u.name) { + userIdToNameMap.set(u.id, u.name) + } + } + } + + // Save context as AgentSessionEntry records + let prevId: string | null = null + for (const c of existingComments) { + const isAgent = c.creator?.type === 'agent' || c.sessionId !== null + let messageContent = c.message || '' + + // Replace <@USER_ID> with <@USER_NAME> + messageContent = messageContent.replace(mentionRegex, (match, userId) => { + const resolvedName = userIdToNameMap.get(userId) + return resolvedName ? `<@${resolvedName}>` : match + }) + + if (isAgent) { + const agentName = c.creator?.name || 'Ai Agent' + messageContent = `[Agent Message][${agentName}]: ${messageContent}` + } else if (c.creator?.name) { + messageContent = `[${c.creator.name}]: ${messageContent}` + } + + const entryId = ulid() + const message: AgentMessage = { + role: 'user', + content: [{ type: 'text', text: messageContent }], + timestamp: c.createdAt.getTime(), + } + + const entryJson: SessionTreeEntry = { + type: 'message', + id: entryId, + parentId: prevId, + timestamp: c.createdAt.toISOString(), + message, + } + + await prisma.agentSessionEntry.create({ + data: { + id: entryId, + sessionId, + entry: entryJson as unknown as Prisma.InputJsonValue, + }, + }) + prevId = entryId + } + + // Update leafId of the session + if (prevId) { + await prisma.agentSession.update({ + where: { id: sessionId }, + data: { leafId: prevId }, + }) + } + + return sessionId +} + +export async function deleteCommentActivity(commentId: string) { + return prisma.assetComment.delete({ + where: { id: commentId }, + }) +} + +export interface CreateCommentParams { + assetId: string + message: string + sessionId?: string | null + agentId?: string | null + replyToId?: string | null +} + +export async function createCommentActivity(params: CreateCommentParams) { + if (params.sessionId) { + const agentId = params.agentId && params.agentId !== 'default' ? params.agentId : 'default' + + // Fetch teamId from asset + const asset = await prisma.asset.findUnique({ + where: { id: params.assetId }, + include: { project: true }, + }) + if (!asset || !asset.project) throw new Error('asset or project not found') + const teamId = asset.project.teamId + + // 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, + type: 'chat', + config: { + provider: 'openai', + model: 'gpt-4', + }, + }, + }) + } + + // Ensure agent session exists + const sessionExists = await prisma.agentSession.findUnique({ where: { id: params.sessionId } }) + if (!sessionExists) { + await prisma.agentSession.create({ + data: { + id: params.sessionId, + agentId: agentId, + cwd: process.cwd(), + }, + }) + } + } + + return prisma.assetComment.create({ + data: { + assetId: params.assetId, + message: params.message, + sessionId: params.sessionId ?? null, + creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null, + replyToId: params.replyToId, + }, + }) +} + +export interface UpdateCommentParams { + commentId: string + message: string + sessionId?: string | null +} + +export async function updateCommentActivity(params: UpdateCommentParams) { + return prisma.assetComment.update({ + where: { id: params.commentId }, + data: { + message: params.message, + ...(params.sessionId !== undefined ? { sessionId: params.sessionId } : {}), + }, + }) +} diff --git a/src/workflow/activities/index.ts b/src/workflow/activities/index.ts index 722d3071..bd05858c 100644 --- a/src/workflow/activities/index.ts +++ b/src/workflow/activities/index.ts @@ -2,10 +2,12 @@ import * as taskActivities from './task' import * as aiActivities from './ai' import * as transcodeActivities from '@/transcode/activities/transcode' import * as agentActivities from './agent' +import * as dbActivities from './db' export const activities = { ...taskActivities, ...aiActivities, ...transcodeActivities, ...agentActivities, + ...dbActivities, } diff --git a/src/workflow/workflows/ai-chat.test.ts b/src/workflow/workflows/ai-chat.test.ts index 85148f10..bbb40d87 100644 --- a/src/workflow/workflows/ai-chat.test.ts +++ b/src/workflow/workflows/ai-chat.test.ts @@ -32,6 +32,9 @@ describe('AIChat Workflow', () => { _activityName: 'getAgentWorkerQueueActivity', }), deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }), + initializeAgentSessionActivity: Object.assign(vi.fn(), { + _activityName: 'initializeAgentSessionActivity', + }), } beforeEach(() => { @@ -49,6 +52,7 @@ describe('AIChat Workflow', () => { }, ) mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue') + mockActivities.initializeAgentSessionActivity.mockResolvedValue('mock-session-id') }) it('should process AI chat successfully', async () => { diff --git a/src/workflow/workflows/ai-chat.ts b/src/workflow/workflows/ai-chat.ts index a79d868a..2e53e52f 100644 --- a/src/workflow/workflows/ai-chat.ts +++ b/src/workflow/workflows/ai-chat.ts @@ -17,6 +17,7 @@ export async function aiChat(task: WorkflowTask): Promise { updateTaskUsageActivity, getAgentWorkerQueueActivity, deleteCommentActivity, + initializeAgentSessionActivity, } = getActivities() let placeholderCommentId: string | undefined @@ -31,7 +32,7 @@ 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 + let sessionId = payload?.sessionId || payload?.session_id // 1. Get User Comment const userCommentId = payload?.userCommentId @@ -56,7 +57,17 @@ export async function aiChat(task: WorkflowTask): Promise { } const teamId = asset.project.teamId - // 4. Prepare Images (Attachments only) + // 4. Initialize Session if missing (Database Activity on db_queue) + if (!sessionId) { + sessionId = await executeActivity(TaskQueueDb, initializeAgentSessionActivity, { + teamId, + agentId: payload.agentId, + userCommentId, + userId: payload.userId, + }) + } + + // 5. Prepare Images (Attachments only) const attachmentImageUrls: string[] = [] // eslint-disable-next-line @typescript-eslint/no-explicit-any const userCommentWithAttachments = userComment as any @@ -82,7 +93,7 @@ export async function aiChat(task: WorkflowTask): Promise { 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 + // 6. Call AI Chat let folderId = '' if (asset.type === 'folder') { folderId = asset.id @@ -102,11 +113,10 @@ export async function aiChat(task: WorkflowTask): Promise { agentsInstruction: instruction, sessionId, userId: payload.userId, - userCommentId, explicitMention: payload?.explicitMention, }) - // 6. Update Placeholder Comment + // 7. Update Placeholder Comment if (placeholderCommentId) { if (aiResult.text.trim() === '__NO_REPLY__') { await executeActivity(TaskQueueDb, deleteCommentActivity, placeholderCommentId) @@ -119,7 +129,7 @@ export async function aiChat(task: WorkflowTask): Promise { } } - // 7. Update Usage + // 8. Update Usage if (aiResult.usage) { await executeActivity(TaskQueueDb, updateTaskUsageActivity, { taskId: task.id,