From 63590d53297de72a91658d382fe329c9b168e064 Mon Sep 17 00:00:00 2001 From: yiling Date: Tue, 7 Jul 2026 11:12:15 +0800 Subject: [PATCH] feat(chatbot): decouple chatbot sessions from AssetComment table --- packages/agent/src/workflows/agent-chat.ts | 76 +++++++++++++--------- packages/core/src/chat/chat.test.ts | 67 +++++++++++-------- packages/core/src/chat/chat.ts | 45 ++++--------- packages/db/src/prisma-json-types.ts | 2 + 4 files changed, 99 insertions(+), 91 deletions(-) diff --git a/packages/agent/src/workflows/agent-chat.ts b/packages/agent/src/workflows/agent-chat.ts index 5face496..48e183a7 100644 --- a/packages/agent/src/workflows/agent-chat.ts +++ b/packages/agent/src/workflows/agent-chat.ts @@ -46,26 +46,42 @@ export async function agentChat(task: WorkflowTask): Promise { // 1. Get User Comment const userCommentId = payload.agent?.userCommentId - if (!userCommentId) { - throw ApplicationFailure.create({ - message: 'userCommentId missing in payload', - nonRetryable: true, - }) - } - const userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId) - if (!userComment) { - throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true }) - } + let prompt = '' + let attachmentImageUrls: string[] = [] + let commentTimestamp: number | undefined - // 2. Create Placeholder Comment - const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, { - assetId: task.assetId, - message: '__CHAT__', - sessionId: sessionId || 'pending', - agentId: agentId, - replyToId: userComment.replyToId ?? userComment.id, - }) - placeholderCommentId = placeholder.id + if (userCommentId) { + const userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId) + if (!userComment) { + throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true }) + } + prompt = userComment.message || '' + if (userComment.second !== null && userComment.second !== undefined) { + commentTimestamp = userComment.second + } + + // 2. Create Placeholder Comment + const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, { + assetId: task.assetId, + message: '__CHAT__', + sessionId: sessionId || 'pending', + agentId: agentId, + replyToId: userComment.replyToId ?? userComment.id, + }) + placeholderCommentId = placeholder.id + + // 5. Prepare Images (Attachments only) + if (userComment.attachments) { + for (const att of userComment.attachments) { + if (att.asset?.mediaType?.startsWith('image/') && att.asset?.storageKey?.key) { + attachmentImageUrls.push(att.asset.storageKey.key) + } + } + } + } else { + prompt = payload.agent?.prompt || '' + attachmentImageUrls = payload.agent?.imageUrls || [] + } // 3. Get Asset const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId) @@ -76,6 +92,12 @@ export async function agentChat(task: WorkflowTask): Promise { // 4. Initialize Session if missing if (!sessionId) { + if (!userCommentId) { + throw ApplicationFailure.create({ + message: 'sessionId is required when userCommentId is missing', + nonRetryable: true, + }) + } sessionId = await executeActivity(agentWorkerQueue, initializeAgentSessionActivity, { teamId, agentId: agentId, @@ -90,16 +112,6 @@ export async function agentChat(task: WorkflowTask): Promise { agentId: agentId, }) - // 5. Prepare Images (Attachments only) - const attachmentImageUrls: string[] = [] - if (userComment?.attachments) { - for (const att of userComment.attachments) { - if (att.asset?.mediaType?.startsWith('image/') && att.asset?.storageKey?.key) { - attachmentImageUrls.push(att.asset.storageKey.key) - } - } - } - const pathContext = await executeActivity( agentWorkerQueue, getAssetPathContextActivity, @@ -113,7 +125,7 @@ export async function agentChat(task: WorkflowTask): Promise { const instruction = new AgentChatPromptBuilder(asset.id) .withPathContext(pathContext) .withAssetDetails(asset.name, asset.mediaType, duration) - .withCommentTimestamp(userComment.second) + .withCommentTimestamp(commentTimestamp) .withExplicitMention(payload.agent?.explicitMention) .build() @@ -128,14 +140,14 @@ export async function agentChat(task: WorkflowTask): Promise { const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, { teamId, agentId: agentId, - message: userComment.message || '', + message: prompt, imageUrls: attachmentImageUrls, projectId: payload.projectId, folderId, agentsInstruction: instruction, sessionId, userId: payload.agent?.userId, - userCommentId, + userCommentId: userCommentId || undefined, explicitMention: payload.agent?.explicitMention, context, }) diff --git a/packages/core/src/chat/chat.test.ts b/packages/core/src/chat/chat.test.ts index 43951b6b..c11b930a 100644 --- a/packages/core/src/chat/chat.test.ts +++ b/packages/core/src/chat/chat.test.ts @@ -70,13 +70,11 @@ describe('ChatService', () => { expect(session?.userId).toBe(user.id) expect(session?.assetId).toBe(rootFolder.id) - // Verify comment is created + // Verify no comment is created const comment = await prisma.assetComment.findFirst({ where: { sessionId }, }) - expect(comment).toBeDefined() - expect(comment?.message).toBe('hello world') - expect(comment?.creatorId).toBe(user.id) + expect(comment).toBeNull() // Verify session entry is created const entry = await prisma.agentSessionEntry.findFirst({ @@ -87,13 +85,16 @@ describe('ChatService', () => { const payload = entry?.entry as any expect(payload.message.content[0].text).toBe('hello world') - // Verify WorkflowTask is created + // Verify WorkflowTask is created with correct payload const task = await prisma.workflowTask.findUnique({ where: { id: taskId }, }) expect(task).toBeDefined() expect(task?.type).toBe('chat') expect(task?.status).toBe('pending') + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const taskPayload = task?.payload as any + expect(taskPayload?.agent?.prompt).toBe('hello world') }) it('should continue an existing chat session', async () => { @@ -128,14 +129,14 @@ describe('ChatService', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((entries[1].entry as any).message.content[0].text).toBe('second message') - // Verify reply comment - const comments = await prisma.assetComment.findMany({ - where: { sessionId }, - orderBy: { id: 'asc' }, + // Verify WorkflowTask is created with correct payload + const task = await prisma.workflowTask.findUnique({ + where: { id: nextTaskId }, }) - expect(comments).toHaveLength(2) - expect(comments[0].replyToId).toBeNull() - expect(comments[1].replyToId).toBe(comments[0].id) + expect(task).toBeDefined() + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const taskPayload = task?.payload as any + expect(taskPayload?.agent?.prompt).toBe('second message') }) it('should inject context of referenced assets and attached files', async () => { @@ -151,34 +152,44 @@ describe('ChatService', () => { }, }) - const textFile = await prisma.asset.create({ + const storageKey = await prisma.storageKey.create({ data: { - name: 'doc.txt', - type: 'file', - mediaType: 'text/plain', - status: 'processed', - projectId: project.id, - parentId: childFolder.id, + key: 'doc_s3_key', }, }) - const { sessionId } = await chatService.startOrContinueChat(user, { + const textFile = await prisma.asset.create({ + data: { + name: 'doc.jpg', + type: 'file', + mediaType: 'image/jpeg', + status: 'processed', + projectId: project.id, + parentId: childFolder.id, + storageKeyId: storageKey.id, + }, + }) + + const { taskId } = await chatService.startOrContinueChat(user, { textPrompt: 'process file', projectId: project.id, assetIds: [childFolder.id], attachedFiles: [textFile.id], }) - const comment = await prisma.assetComment.findFirst({ - where: { sessionId }, + const task = await prisma.workflowTask.findUnique({ + where: { id: taskId }, }) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const taskPayload = task?.payload as any - expect(comment?.message).toContain('[Context: Attached Files & Referenced Assets]') - expect(comment?.message).toContain('doc.txt') - expect(comment?.message).toContain('child_folder') - expect(comment?.message).toContain('text/plain') - expect(comment?.message).toContain('child_folder/doc.txt') - expect(comment?.message).toContain('process file') + expect(taskPayload?.agent?.prompt).toContain('[Context: Attached Files & Referenced Assets]') + expect(taskPayload?.agent?.prompt).toContain('doc.jpg') + expect(taskPayload?.agent?.prompt).toContain('child_folder') + expect(taskPayload?.agent?.prompt).toContain('image/jpeg') + expect(taskPayload?.agent?.prompt).toContain('child_folder/doc.jpg') + expect(taskPayload?.agent?.prompt).toContain('process file') + expect(taskPayload?.agent?.imageUrls).toContain('doc_s3_key') }) it('should list sessions of a user', async () => { diff --git a/packages/core/src/chat/chat.ts b/packages/core/src/chat/chat.ts index 8d2db667..5690f1ad 100644 --- a/packages/core/src/chat/chat.ts +++ b/packages/core/src/chat/chat.ts @@ -194,6 +194,17 @@ export class ChatService { const finalPrompt = `${contextPrompt}${textPrompt || ''}` + const resolvedImageUrls: string[] = [] + for (const fileId of attachedFiles) { + const file = await this.prismaClient.asset.findUnique({ + where: { id: fileId }, + include: { storageKey: true }, + }) + if (file && file.mediaType?.startsWith('image/') && file.storageKey?.key) { + resolvedImageUrls.push(file.storageKey.key) + } + } + // 4. Create database records in a transaction return await this.prismaClient.$transaction(async (tx) => { const asset = await tx.asset.findUnique({ @@ -254,35 +265,6 @@ export class ChatService { activeSessionId = newSession.id } - // Create comment representing the user's message - const replyToId = passedSessionId ? existingSession?.userCommentId : undefined - const comment = await tx.assetComment.create({ - data: { - assetId: asset.id, - creatorId: user.id, - message: finalPrompt, - sessionId: activeSessionId, - replyToId: replyToId || null, - }, - }) - - // Link attachment assets if provided - if (attachedFiles.length > 0) { - for (const fileId of attachedFiles) { - const fileAsset = await tx.asset.findUnique({ - where: { id: fileId }, - }) - if (fileAsset) { - await tx.assetCommentAttachment.create({ - data: { - assetId: fileAsset.id, - commentId: comment.id, - }, - }) - } - } - } - // Append entry for user's message const parentId = passedSessionId ? existingSession?.leafId : null const entryId = ulid() @@ -311,7 +293,6 @@ export class ChatService { where: { id: activeSessionId }, data: { leafId: entryId, - ...(!passedSessionId ? { userCommentId: comment.id } : {}), }, }) @@ -326,7 +307,9 @@ export class ChatService { payload: { projectId, agent: { - userCommentId: comment.id, + prompt: finalPrompt, + imageUrls: resolvedImageUrls, + explicitMention: true, agentId, sessionId: activeSessionId, userId: user.id, diff --git a/packages/db/src/prisma-json-types.ts b/packages/db/src/prisma-json-types.ts index 717a4343..72b1d0a3 100644 --- a/packages/db/src/prisma-json-types.ts +++ b/packages/db/src/prisma-json-types.ts @@ -288,6 +288,8 @@ declare global { sessionId?: string userCommentId?: string explicitMention?: boolean + prompt?: string + imageUrls?: string[] } // ----------------------------------------------------------------------