mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 20:57:59 +00:00
refactor(agent): decouple agent orchestration and relocate workflows
Decoupled high-level agent orchestration (chat, chatWithAgent, autofill) from sandbox execution in `src/agent` to `src/services/agent/agent.ts`. Relocated all related workflows and activities to `src/workflow`.
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import { aiChatActivity } from './agent'
|
||||
import { agentService } from '@/services/agent/agent'
|
||||
|
||||
vi.mock('@/services/agent/agent', () => ({
|
||||
agentService: {
|
||||
chatWithAgent: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('Agent Activities', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should call aiChatActivity', async () => {
|
||||
vi.mocked(agentService.chatWithAgent).mockResolvedValue({
|
||||
text: 'AI response',
|
||||
usage: { inputTokens: 1, outputTokens: 1, model: 'gpt-4' },
|
||||
sessionId: 'mock-session-id',
|
||||
})
|
||||
|
||||
await aiChatActivity({
|
||||
teamId: 't1',
|
||||
agentId: 'b1',
|
||||
message: 'Hi',
|
||||
imageUrls: [],
|
||||
projectId: 'p1',
|
||||
folderId: 'f1',
|
||||
})
|
||||
|
||||
expect(agentService.chatWithAgent).toHaveBeenCalledWith(
|
||||
't1',
|
||||
'b1',
|
||||
'Hi',
|
||||
[],
|
||||
'',
|
||||
undefined,
|
||||
undefined,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
import { agentService } from '@/services/agent/agent'
|
||||
import type { AutofillField } from '@/agent'
|
||||
import { prisma } from '@/db'
|
||||
|
||||
export interface AutofillAiParams {
|
||||
teamId: string
|
||||
images: string[]
|
||||
fields: AutofillField[]
|
||||
}
|
||||
|
||||
export async function autofillAiActivity(params: AutofillAiParams) {
|
||||
const prompt = 'Analyze the provided images and extract metadata.'
|
||||
return agentService.autofill(params.teamId, prompt, params.images, params.fields)
|
||||
}
|
||||
|
||||
export interface AiChatParams {
|
||||
teamId: string
|
||||
agentId: string
|
||||
message: string
|
||||
imageUrls: string[]
|
||||
projectId: string
|
||||
folderId: string
|
||||
agentsInstruction?: string
|
||||
sessionId?: string
|
||||
userId?: string
|
||||
}
|
||||
|
||||
export async function aiChatActivity(params: AiChatParams) {
|
||||
const cleanMessage = params.message.replace(/<@[A-Z0-9]+>/g, '').trim()
|
||||
return agentService.chatWithAgent(
|
||||
params.teamId,
|
||||
params.agentId,
|
||||
cleanMessage,
|
||||
params.imageUrls,
|
||||
params.agentsInstruction || '',
|
||||
params.sessionId,
|
||||
params.userId,
|
||||
)
|
||||
}
|
||||
|
||||
export interface CreateCommentParams {
|
||||
assetId: string
|
||||
message: string
|
||||
isAi?: boolean
|
||||
agentId?: string | null
|
||||
replyToId?: string | null
|
||||
}
|
||||
|
||||
export async function createCommentActivity(params: CreateCommentParams) {
|
||||
return prisma.assetComment.create({
|
||||
data: {
|
||||
assetId: params.assetId,
|
||||
message: params.message,
|
||||
isAi: params.isAi ?? false,
|
||||
creatorId: params.agentId && params.agentId !== 'default' ? params.agentId : null,
|
||||
replyToId: params.replyToId,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export interface UpdateCommentParams {
|
||||
commentId: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export async function updateCommentActivity(params: UpdateCommentParams) {
|
||||
return prisma.assetComment.update({
|
||||
where: { id: params.commentId },
|
||||
data: { message: params.message },
|
||||
})
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as taskActivities from './task'
|
||||
import * as aiActivities from './ai'
|
||||
import * as transcodeActivities from '@/transcode/activities/transcode'
|
||||
import * as agentActivities from '@/agent/activities/agent'
|
||||
import * as agentActivities from './agent'
|
||||
|
||||
export const activities = {
|
||||
...taskActivities,
|
||||
|
||||
@@ -3,8 +3,8 @@ import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/
|
||||
import { Executor } from './executor'
|
||||
import { aiTranscriptionMedia } from './workflows/ai-transcription'
|
||||
import { aiEmbeddingMedia } from './workflows/ai-embedding'
|
||||
import { aiAutofillMedia } from '@/agent/workflows/ai-autofill'
|
||||
import { aiChat } from '@/agent/workflows/ai-chat'
|
||||
import { aiAutofillMedia } from './workflows/ai-autofill'
|
||||
import { aiChat } from './workflows/ai-chat'
|
||||
import { transcodeMedia } from '@/transcode/workflows/transcode'
|
||||
import { activities } from './activities/index'
|
||||
import { logger } from '@/logger'
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { aiAutofillMedia } from './ai-autofill'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('AIAutofill Workflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
extractAiMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'extractAiMetadataActivity',
|
||||
}),
|
||||
getProjectAutofillFieldsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getProjectAutofillFieldsActivity',
|
||||
}),
|
||||
autofillAiActivity: Object.assign(vi.fn(), { _activityName: 'autofillAiActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
updateAssetMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateAssetMetadataActivity',
|
||||
}),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), { _activityName: 'cleanupTmpDirActivity' }),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_worker_queue')
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({
|
||||
filePath: '/tmp/test.mp4',
|
||||
tmpDir: '/tmp',
|
||||
})
|
||||
})
|
||||
|
||||
it('should process AI autofill successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-1-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
key: 'test.mp4',
|
||||
mediaType: 'video/mp4',
|
||||
project: { id: 'proj-1', teamId: 'team-1' },
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue(['frame1.webp'])
|
||||
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
|
||||
{ id: 'field-1', config: { type: 'text', name: 'Field 1' } },
|
||||
])
|
||||
mockActivities.autofillAiActivity.mockResolvedValue({
|
||||
text: JSON.stringify({ 'field-1': 'Extracted Value' }),
|
||||
usage: { inputTokens: 10, outputTokens: 5, model: 'gpt-4v' },
|
||||
})
|
||||
|
||||
await aiAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__AUTOFILL__',
|
||||
isAi: true,
|
||||
agentId: 'default',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateAssetMetadataActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
metadata: [{ key: 'field-1', value: 'Extracted Value' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('should use agentId from payload if provided', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: { agentId: 'real-agent-id' },
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-1-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
key: 'test.mp4',
|
||||
mediaType: 'video/mp4',
|
||||
project: { id: 'proj-1', teamId: 'team-1' },
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue(['frame1.webp'])
|
||||
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([
|
||||
{ id: 'field-1', config: { type: 'text', name: 'Field 1' } },
|
||||
])
|
||||
mockActivities.autofillAiActivity.mockResolvedValue({
|
||||
text: JSON.stringify({ 'field-1': 'Extracted Value' }),
|
||||
usage: { inputTokens: 10, outputTokens: 5, model: 'gpt-4v' },
|
||||
})
|
||||
|
||||
await aiAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__AUTOFILL__',
|
||||
isAi: true,
|
||||
agentId: 'real-agent-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures and update task status with error', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-fail',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_metadata_autofill,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-fail-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-err' })
|
||||
mockActivities.getAssetActivity.mockRejectedValue(new Error('Asset missing'))
|
||||
|
||||
await expect(aiAutofillMedia(task)).rejects.toThrow('Asset missing')
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-err',
|
||||
message: expect.stringContaining('failed'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-fail',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'Asset missing' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,192 @@
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import {
|
||||
getActivities,
|
||||
executeActivity,
|
||||
TaskQueueDb,
|
||||
TaskQueueAgent,
|
||||
TaskQueueTranscode,
|
||||
} from '@/workflow/workflow-utils'
|
||||
|
||||
export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
extractAiMetadataActivity,
|
||||
getProjectAutofillFieldsActivity,
|
||||
autofillAiActivity,
|
||||
updateTaskUsageActivity,
|
||||
updateAssetMetadataActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
getTranscodeWorkerQueueActivity,
|
||||
getAgentWorkerQueueActivity,
|
||||
downloadMediaToTmpActivity,
|
||||
cleanupTmpDirActivity,
|
||||
} = getActivities()
|
||||
|
||||
let placeholderCommentId: string | undefined
|
||||
let tmpDir: string | undefined
|
||||
let transcodeWorkerQueue: string | undefined
|
||||
|
||||
try {
|
||||
// Update status to processing
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// 0. Create Placeholder Comment
|
||||
const payload = task.payload as Record<string, unknown>
|
||||
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
|
||||
assetId: task.assetId,
|
||||
message: '__AUTOFILL__',
|
||||
isAi: true,
|
||||
agentId: (payload?.agentId as string) || 'default',
|
||||
})
|
||||
placeholderCommentId = placeholder.id
|
||||
|
||||
// 1. Get Asset
|
||||
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
|
||||
if (!asset || !asset.project) {
|
||||
throw new Error('Asset or project not found')
|
||||
}
|
||||
const teamId = asset.project.teamId
|
||||
const projectId = asset.project.id
|
||||
|
||||
// 2. Prepare Data (Images)
|
||||
const isImage = asset.mediaType?.startsWith('image/') || false
|
||||
|
||||
// Extraction requires FFmpeg, run on Transcode worker
|
||||
transcodeWorkerQueue = await executeActivity(
|
||||
TaskQueueTranscode,
|
||||
getTranscodeWorkerQueueActivity,
|
||||
)
|
||||
|
||||
const download = await executeActivity(transcodeWorkerQueue, downloadMediaToTmpActivity, {
|
||||
assetKey: asset.key || '',
|
||||
})
|
||||
const { filePath } = download
|
||||
tmpDir = download.tmpDir
|
||||
|
||||
const generatedFiles = await executeActivity(transcodeWorkerQueue, extractAiMetadataActivity, {
|
||||
assetKey: asset.key || '',
|
||||
filePath,
|
||||
type: 'autofill',
|
||||
isImage,
|
||||
})
|
||||
|
||||
if (generatedFiles.length === 0) {
|
||||
// If no images could be extracted, we can't do much
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Autofill completed: No images could be extracted for analysis.',
|
||||
})
|
||||
}
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 3. Get Project Autofill Fields
|
||||
const fields = await executeActivity(TaskQueueDb, getProjectAutofillFieldsActivity, projectId)
|
||||
if (fields.length === 0) {
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Autofill completed: No autofill fields defined in project.',
|
||||
})
|
||||
}
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 4. Call AI Service
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
|
||||
teamId,
|
||||
images: generatedFiles,
|
||||
fields: fields.map((f) => ({
|
||||
id: f.id,
|
||||
config: f.config as unknown as PrismaJson.FieldConfig,
|
||||
description: f.description,
|
||||
})),
|
||||
})
|
||||
|
||||
if (aiResult.usage) {
|
||||
// Update Usage
|
||||
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
|
||||
taskId: task.id,
|
||||
inputTokens: aiResult.usage.inputTokens,
|
||||
outputTokens: aiResult.usage.outputTokens,
|
||||
model: aiResult.usage.model,
|
||||
})
|
||||
}
|
||||
|
||||
// 6. Update Asset Metadata
|
||||
const result = JSON.parse(aiResult.text)
|
||||
const metadataUpdates = Object.entries(result).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}))
|
||||
|
||||
if (metadataUpdates.length > 0) {
|
||||
await executeActivity(TaskQueueDb, updateAssetMetadataActivity, {
|
||||
assetId: asset.id,
|
||||
metadata: metadataUpdates,
|
||||
})
|
||||
}
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Autofill completed successfully.',
|
||||
})
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiAutofillMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: `Autofill failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
})
|
||||
} catch (commentErr) {
|
||||
console.error('Failed to update error comment:', commentErr)
|
||||
}
|
||||
}
|
||||
|
||||
// Update status to failed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
throw err
|
||||
} finally {
|
||||
if (tmpDir && transcodeWorkerQueue) {
|
||||
try {
|
||||
await executeActivity(transcodeWorkerQueue, cleanupTmpDirActivity, { tmpDir })
|
||||
} catch (cleanupErr) {
|
||||
console.error('Failed to cleanup tmp dir:', cleanupErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const aiAutofillWorkflow = aiAutofillMedia
|
||||
@@ -0,0 +1,222 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { aiChat } from './ai-chat'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async (importOriginal) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const actual = (await importOriginal()) as any
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
sleep: vi.fn().mockResolvedValue(undefined),
|
||||
}
|
||||
})
|
||||
|
||||
describe('AIChat Workflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getCommentActivity: Object.assign(vi.fn(), { _activityName: 'getCommentActivity' }),
|
||||
extractAiMetadataActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'extractAiMetadataActivity',
|
||||
}),
|
||||
aiChatActivity: Object.assign(vi.fn(), { _activityName: 'aiChatActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.getActivities as any).mockReturnValue(mockActivities)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(workflowUtils.executeActivity as any).mockImplementation(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(_queue: string, fn: any, ...args: any[]) => {
|
||||
if (typeof fn !== 'function') {
|
||||
throw new Error(`fn is not a function in executeActivity. Queue: ${_queue}`)
|
||||
}
|
||||
return fn(...args)
|
||||
},
|
||||
)
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_worker_queue')
|
||||
})
|
||||
|
||||
it('should process AI chat successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
projectId: 'proj-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
key: 'test.png',
|
||||
mediaType: 'image/png',
|
||||
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: 10, outputTokens: 20, model: 'gpt-4' },
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.processing,
|
||||
})
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__CHAT__',
|
||||
isAi: true,
|
||||
agentId: 'bot-1',
|
||||
replyToId: 'comment-1',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-1',
|
||||
message: 'Hello Human',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
inputTokens: 10,
|
||||
outputTokens: 20,
|
||||
model: 'gpt-4',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
output: { sessionId: undefined },
|
||||
})
|
||||
})
|
||||
|
||||
it('should attach AI response to thread root if triggering comment is a reply', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-nested',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'reply-1',
|
||||
agentId: 'bot-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-nested',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
project: { teamId: 'team-1', id: 'proj-1' },
|
||||
})
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'reply-1',
|
||||
replyToId: 'root-comment-id',
|
||||
message: 'Nested reply message',
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-nested' })
|
||||
|
||||
mockActivities.aiChatActivity.mockResolvedValue({
|
||||
text: 'AI response to root',
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__CHAT__',
|
||||
isAi: true,
|
||||
agentId: 'bot-1',
|
||||
replyToId: 'root-comment-id', // MUST be root, not reply-1
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures and update placeholder with error', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-fail',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({
|
||||
id: 'placeholder-err',
|
||||
})
|
||||
|
||||
mockActivities.getAssetActivity.mockRejectedValue(new Error('DB Down'))
|
||||
|
||||
await expect(aiChat(task)).rejects.toThrow('DB Down')
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-err',
|
||||
message: expect.stringContaining('error'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-fail',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'DB Down' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import {
|
||||
getActivities,
|
||||
executeActivity,
|
||||
TaskQueueDb,
|
||||
TaskQueueAgent,
|
||||
} from '@/workflow/workflow-utils'
|
||||
|
||||
export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
getCommentActivity,
|
||||
aiChatActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
updateTaskUsageActivity,
|
||||
getAgentWorkerQueueActivity,
|
||||
} = getActivities()
|
||||
|
||||
let placeholderCommentId: string | undefined
|
||||
|
||||
try {
|
||||
// Update status to processing
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const payload = task.payload as any
|
||||
|
||||
// 1. Get User Comment
|
||||
const userCommentId = payload?.userCommentId
|
||||
if (!userCommentId) throw new Error('userCommentId missing in payload')
|
||||
const userComment = await executeActivity(TaskQueueDb, getCommentActivity, userCommentId)
|
||||
if (!userComment) throw new Error('User comment not found')
|
||||
|
||||
// 2. Create Placeholder Comment
|
||||
const placeholder = await executeActivity(TaskQueueDb, createCommentActivity, {
|
||||
assetId: task.assetId,
|
||||
message: '__CHAT__',
|
||||
isAi: true,
|
||||
agentId: payload?.agentId,
|
||||
replyToId: userComment.replyToId ?? userComment.id,
|
||||
})
|
||||
placeholderCommentId = placeholder.id
|
||||
|
||||
// 3. Get Asset
|
||||
const asset = await executeActivity(TaskQueueDb, getAssetActivity, task.assetId)
|
||||
if (!asset || !asset.project) {
|
||||
throw new Error('Asset or project not found')
|
||||
}
|
||||
const teamId = asset.project.teamId
|
||||
|
||||
// 4. Prepare Images (Attachments only)
|
||||
const attachmentImageUrls: string[] = []
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const userCommentWithAttachments = userComment as any
|
||||
if (userCommentWithAttachments?.attachments) {
|
||||
for (const att of userCommentWithAttachments.attachments) {
|
||||
if (att.asset?.mediaType?.startsWith('image/') && att.asset?.key) {
|
||||
attachmentImageUrls.push(att.asset.key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let instruction = `The user is discussing an asset with ID: ${asset.id}.`
|
||||
|
||||
if (asset.media) {
|
||||
instruction += `\n\nAsset Media Info:\n${JSON.stringify(asset.media, null, 2)}`
|
||||
}
|
||||
|
||||
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).`
|
||||
|
||||
// 5. Call AI Chat
|
||||
let folderId = ''
|
||||
if (asset.type === 'folder') {
|
||||
folderId = asset.id
|
||||
} else if (asset.parentId) {
|
||||
folderId = asset.parentId
|
||||
}
|
||||
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
const aiResult = await executeActivity(agentWorkerQueue, aiChatActivity, {
|
||||
teamId,
|
||||
agentId: payload.agentId,
|
||||
message: userComment.message || '',
|
||||
imageUrls: attachmentImageUrls,
|
||||
projectId: payload.projectId,
|
||||
folderId,
|
||||
agentsInstruction: instruction,
|
||||
sessionId: payload.session_id,
|
||||
userId: payload.userId,
|
||||
})
|
||||
|
||||
// 6. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: aiResult.text,
|
||||
})
|
||||
|
||||
// Also store sessionId in comment's metadata if we had such a field,
|
||||
// but for now we just return it in task status.
|
||||
}
|
||||
|
||||
// 7. Update Usage
|
||||
if (aiResult.usage) {
|
||||
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
|
||||
taskId: task.id,
|
||||
inputTokens: aiResult.usage.inputTokens,
|
||||
outputTokens: aiResult.usage.outputTokens,
|
||||
model: aiResult.usage.model,
|
||||
})
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: { sessionId: aiResult.sessionId },
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiChat failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
const errorMessage =
|
||||
err instanceof Error && err.message.startsWith('AI error:')
|
||||
? `AI error: ${err.message.substring(9)}`
|
||||
: 'Sorry, I encountered an error while processing your request.'
|
||||
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: errorMessage,
|
||||
})
|
||||
} catch (commentErr) {
|
||||
console.error('Failed to update error comment:', commentErr)
|
||||
}
|
||||
}
|
||||
|
||||
// Update status to failed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export const aiChatWorkflow = aiChat
|
||||
@@ -1,5 +1,5 @@
|
||||
export * from './ai-transcription'
|
||||
export * from './ai-embedding'
|
||||
export * from '@/agent/workflows/ai-autofill'
|
||||
export * from '@/agent/workflows/ai-chat'
|
||||
export * from './ai-autofill'
|
||||
export * from './ai-chat'
|
||||
export * from '@/transcode/workflows/transcode'
|
||||
|
||||
Reference in New Issue
Block a user