feat(chatbot): decouple chatbot sessions from AssetComment table

This commit is contained in:
yiling
2026-07-07 11:12:15 +08:00
parent ccf742e158
commit 63590d5329
4 changed files with 99 additions and 91 deletions
+44 -32
View File
@@ -46,26 +46,42 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
// 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<void> {
// 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<void> {
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<void> {
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<void> {
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,
})
+39 -28
View File
@@ -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 () => {
+14 -31
View File
@@ -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,
+2
View File
@@ -288,6 +288,8 @@ declare global {
sessionId?: string
userCommentId?: string
explicitMention?: boolean
prompt?: string
imageUrls?: string[]
}
// ----------------------------------------------------------------------