feat(chatbot): delegate context prompt building to AgentChatPromptBuilder in workflow

This commit is contained in:
yiling
2026-07-07 11:42:40 +08:00
parent 7b6db5b56c
commit e4c1830e02
7 changed files with 143 additions and 38 deletions
@@ -73,4 +73,15 @@ describe('AgentChatPromptBuilder', () => {
expect(result).toContain("call the 'screenshot' tool")
expect(result).toContain('The user explicitly mentioned you')
})
it('should build prompt with attached files and referenced assets', () => {
const builder = new AgentChatPromptBuilder('a1')
.withAttachedFiles(['- file1.txt', '- file2.png'])
.withReferencedAssets(['- folder1', '- file3.mp4'])
const result = builder.build()
expect(result).toContain('[Context: Attached Files & Referenced Assets]')
expect(result).toContain('Attached Files:\n- file1.txt\n- file2.png')
expect(result).toContain('Referenced Workspace Assets:\n- folder1\n- file3.mp4')
})
})
@@ -22,11 +22,27 @@ export class AgentChatPromptBuilder {
private commentTimestamp?: number
private pathContext?: string
private explicitMention = false
private attachedFiles: string[] = []
private referencedAssets: string[] = []
constructor(assetId: string) {
this.assetId = assetId
}
withAttachedFiles(files?: string[]): this {
if (files) {
this.attachedFiles = files
}
return this
}
withReferencedAssets(assets?: string[]): this {
if (assets) {
this.referencedAssets = assets
}
return this
}
withPathContext(pathContext?: string): this {
this.pathContext = pathContext
return this
@@ -70,6 +86,16 @@ export class AgentChatPromptBuilder {
instruction += `\n\nAsset Path Context:\n${this.pathContext}`
}
if (this.attachedFiles.length > 0 || this.referencedAssets.length > 0) {
instruction += `\n\n[Context: Attached Files & Referenced Assets]`
if (this.attachedFiles.length > 0) {
instruction += `\nAttached Files:\n${this.attachedFiles.join('\n')}`
}
if (this.referencedAssets.length > 0) {
instruction += `\nReferenced Workspace Assets:\n${this.referencedAssets.join('\n')}`
}
}
if (this.mediaType) {
const type = getSimpleMediaType(this.mediaType)
if (type === 'image') {
@@ -397,4 +397,72 @@ describe('Agent Chat Workflow', () => {
message: 'Sorry, I encountered an error while processing your request.',
})
})
it('should execute direct-context chatbot flow resolving file metadata and skipping comment placeholder', async () => {
mockActivities.getAssetActivity.mockImplementation(async (id: string) => {
if (id === 'file-attachment-1') {
return { id: 'file-attachment-1', name: 'attachment.png', type: 'file', mediaType: 'image/png', projectId: 'p1' }
}
if (id === 'referenced-asset-1') {
return { id: 'referenced-asset-1', name: 'ref-folder', type: 'folder', mediaType: null, projectId: 'p1' }
}
return { id, name: 'test-file.png', type: 'file', mediaType: 'image/png', projectId: 'p1', project: { teamId: 't1' } }
})
mockActivities.getAssetPathContextActivity.mockImplementation(async (id: string) => {
if (id === 'file-attachment-1') return 'attachment.png'
if (id === 'referenced-asset-1') return 'ref-folder'
return 'folder/subfolder/file.png'
})
const task = await prisma.workflowTask.create({
data: {
type: 'chat',
status: 'pending',
assetId: 'a1',
payload: {
projectId: 'p1',
agent: {
agentId: 'b1',
sessionId: 'session-direct-123',
prompt: 'chatbot prompt',
attachedFiles: ['file-attachment-1'],
assetIds: ['referenced-asset-1'],
explicitMention: true,
},
},
},
})
await agentChat(task)
// Verify placeholder comment is NOT created
expect(mockActivities.createCommentActivity).not.toHaveBeenCalled()
expect(mockActivities.updateCommentActivity).not.toHaveBeenCalled()
// Verify prompt builder is populated and workflow runs agentChatActivity with context instruction
const expectedInstruction = new AgentChatPromptBuilder('a1')
.withPathContext('folder/subfolder/file.png')
.withAssetDetails('test-file.png', 'image/png', undefined)
.withCommentTimestamp(undefined)
.withExplicitMention(true)
.withAttachedFiles(['- Name: attachment.png (ID: file-attachment-1, Type: file, Media Type: image/png, Project ID: p1, Path: attachment.png)'])
.withReferencedAssets(['- Name: ref-folder (ID: referenced-asset-1, Type: folder, Media Type: unknown, Project ID: p1, Path: ref-folder)'])
.build()
expect(mockActivities.agentChatActivity).toHaveBeenCalledWith({
teamId: 't1',
agentId: 'b1',
message: 'chatbot prompt',
imageUrls: [],
projectId: 'p1',
folderId: '',
agentsInstruction: expectedInstruction,
sessionId: 'session-direct-123',
userId: undefined,
userCommentId: undefined,
explicitMention: true,
context: { agent: { id: 'b1' } },
})
})
})
@@ -122,11 +122,41 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
const mediaInfo = asset.media as any
const duration = mediaInfo?.duration
// Resolve Attached Files Details
const attachedFileDetailsList: string[] = []
if (payload.agent?.attachedFiles) {
for (const fileId of payload.agent.attachedFiles) {
const file = await executeActivity(agentWorkerQueue, getAssetActivity, fileId)
if (file) {
const path = await executeActivity(agentWorkerQueue, getAssetPathContextActivity, fileId)
attachedFileDetailsList.push(
`- Name: ${file.name} (ID: ${file.id}, Type: ${file.type}, Media Type: ${file.mediaType || 'unknown'}, Project ID: ${file.projectId || 'unknown'}, Path: ${path})`
)
}
}
}
// Resolve Referenced Workspace Assets Details
const referencedAssetDetailsList: string[] = []
if (payload.agent?.assetIds) {
for (const assetId of payload.agent.assetIds) {
const referencedAsset = await executeActivity(agentWorkerQueue, getAssetActivity, assetId)
if (referencedAsset) {
const path = await executeActivity(agentWorkerQueue, getAssetPathContextActivity, assetId)
referencedAssetDetailsList.push(
`- Name: ${referencedAsset.name} (ID: ${referencedAsset.id}, Type: ${referencedAsset.type}, Media Type: ${referencedAsset.mediaType || 'unknown'}, Project ID: ${referencedAsset.projectId || 'unknown'}, Path: ${path})`
)
}
}
}
const instruction = new AgentChatPromptBuilder(asset.id)
.withPathContext(pathContext)
.withAssetDetails(asset.name, asset.mediaType, duration)
.withCommentTimestamp(commentTimestamp)
.withExplicitMention(payload.agent?.explicitMention)
.withAttachedFiles(attachedFileDetailsList)
.withReferencedAssets(referencedAssetDetailsList)
.build()
// 6. Call AI Chat
+3 -6
View File
@@ -208,12 +208,9 @@ describe('ChatService', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const taskPayload = task?.payload as any
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?.prompt).toBe('process file')
expect(taskPayload?.agent?.attachedFiles).toContain(textFile.id)
expect(taskPayload?.agent?.assetIds).toContain(childFolder.id)
expect(taskPayload?.agent?.imageUrls).toContain('doc_s3_key')
})
+3 -32
View File
@@ -162,38 +162,7 @@ export class ChatService {
}
}
// 3. Context Prompt construction
let contextPrompt = ''
if (attachedFiles.length > 0 || assetIds.length > 0) {
contextPrompt += '[Context: Attached Files & Referenced Assets]\n'
if (attachedFiles.length > 0) {
contextPrompt += 'Attached Files:\n'
for (const fileId of attachedFiles) {
const file = await this.prismaClient.asset.findUnique({
where: { id: fileId },
})
if (file) {
const filePath = await this.getAssetPath(file.id)
contextPrompt += `- Name: ${file.name} (ID: ${file.id}, Type: ${file.type}, Media Type: ${file.mediaType || 'unknown'}, Project ID: ${file.projectId || 'unknown'}, Path: ${filePath})\n`
}
}
}
if (assetIds.length > 0) {
contextPrompt += 'Referenced Workspace Assets:\n'
for (const assetId of assetIds) {
const asset = await this.prismaClient.asset.findUnique({
where: { id: assetId },
})
if (asset) {
const assetPath = await this.getAssetPath(asset.id)
contextPrompt += `- Name: ${asset.name} (ID: ${asset.id}, Type: ${asset.type}, Media Type: ${asset.mediaType || 'unknown'}, Project ID: ${asset.projectId || 'unknown'}, Path: ${assetPath})\n`
}
}
}
contextPrompt += '\n---\n'
}
const finalPrompt = `${contextPrompt}${textPrompt || ''}`
const finalPrompt = textPrompt || ''
const resolvedImageUrls: string[] = []
for (const fileId of attachedFiles) {
@@ -288,6 +257,8 @@ export class ChatService {
agent: {
prompt: finalPrompt,
imageUrls: resolvedImageUrls,
attachedFiles,
assetIds,
explicitMention: true,
agentId,
sessionId: activeSessionId,
+2
View File
@@ -290,6 +290,8 @@ declare global {
explicitMention?: boolean
prompt?: string
imageUrls?: string[]
attachedFiles?: string[]
assetIds?: string[]
}
// ----------------------------------------------------------------------