mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 13:29:48 +00:00
refactor(workflow): split database and agent activities for strict database isolation
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentAutofillMedia } from './agent-autofill'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async () => {
|
||||
const actual = await vi.importActual('@/workflow/workflow-utils')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent Autofill Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should run agent autofill workflow successfully', async () => {
|
||||
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',
|
||||
}),
|
||||
getAgentAutofillContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentAutofillContextActivity',
|
||||
}),
|
||||
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' }),
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getAssetActivity.mockResolvedValue({ id: 'a1', storageKey: { key: 'asset-key' }, project: { id: 'p1', teamId: 't1' }, mediaType: 'image/png' })
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue')
|
||||
mockActivities.downloadMediaToTmpActivity.mockResolvedValue({ filePath: '/tmp/test.png', tmpDir: '/tmp' })
|
||||
mockActivities.extractAiMetadataActivity.mockResolvedValue(['/tmp/1.webp'])
|
||||
mockActivities.getProjectAutofillFieldsActivity.mockResolvedValue([{ id: 'f1', config: { name: 'F1', type: 'text' } }])
|
||||
mockActivities.getAgentAutofillContextActivity.mockResolvedValue({ agent: { id: 'b1' } })
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.autofillAiActivity.mockResolvedValue({
|
||||
text: '{"f1":"val"}',
|
||||
sessionId: 'session-123',
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_metadata_autofill',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
},
|
||||
})
|
||||
|
||||
await agentAutofillMedia(task)
|
||||
|
||||
expect(mockActivities.getAgentAutofillContextActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.autofillAiActivity).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -7,12 +7,13 @@ import {
|
||||
TaskQueueTranscode,
|
||||
} from '@/workflow/workflow-utils'
|
||||
|
||||
export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
extractAiMetadataActivity,
|
||||
getProjectAutofillFieldsActivity,
|
||||
getAgentAutofillContextActivity,
|
||||
autofillAiActivity,
|
||||
updateTaskUsageActivity,
|
||||
updateAssetMetadataActivity,
|
||||
@@ -107,6 +108,11 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
return
|
||||
}
|
||||
|
||||
// 3b. Fetch Agent Context (Database Activity on db_queue)
|
||||
const context = await executeActivity(TaskQueueDb, getAgentAutofillContextActivity, {
|
||||
teamId,
|
||||
})
|
||||
|
||||
// 4. Call AI Service
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
@@ -118,6 +124,7 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
config: f.config as unknown as PrismaJson.FieldConfig,
|
||||
description: f.description,
|
||||
})),
|
||||
context,
|
||||
})
|
||||
|
||||
if (aiResult.usage) {
|
||||
@@ -159,7 +166,7 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
status: 'completed',
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiAutofillMedia failed for task ${task.id}:`, err)
|
||||
console.error(`AgentAutofillMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
@@ -191,4 +198,4 @@ export async function aiAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export const aiAutofillWorkflow = aiAutofillMedia
|
||||
export const agentAutofillWorkflow = agentAutofillMedia
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentChat } from './agent-chat'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async () => {
|
||||
const actual = await vi.importActual('@/workflow/workflow-utils')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent Chat Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should run agent chat workflow successfully', async () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getCommentActivity: Object.assign(vi.fn(), { _activityName: 'getCommentActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
initializeAgentSessionActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'initializeAgentSessionActivity',
|
||||
}),
|
||||
getAgentChatContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentChatContextActivity',
|
||||
}),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
agentChatActivity: Object.assign(vi.fn(), { _activityName: 'agentChatActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }),
|
||||
}
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({ id: 'c1', message: 'hello', replyToId: null })
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getAssetActivity.mockResolvedValue({ id: 'a1', project: { teamId: 't1' } })
|
||||
mockActivities.initializeAgentSessionActivity.mockResolvedValue('session-123')
|
||||
mockActivities.getAgentChatContextActivity.mockResolvedValue({ agent: { id: 'b1' } })
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.agentChatActivity.mockResolvedValue({
|
||||
text: 'arr matey!',
|
||||
sessionId: 'session-123',
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'chat',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
payload: { userCommentId: 'c1', agentId: 'b1' },
|
||||
},
|
||||
})
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
expect(mockActivities.getAgentChatContextActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.agentChatActivity).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -6,12 +6,13 @@ import {
|
||||
TaskQueueDb,
|
||||
} from '@/workflow/workflow-utils'
|
||||
|
||||
export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
getCommentActivity,
|
||||
aiChatActivity,
|
||||
getAgentChatContextActivity,
|
||||
agentChatActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
updateTaskUsageActivity,
|
||||
@@ -67,6 +68,12 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
})
|
||||
}
|
||||
|
||||
// 4b. Fetch Agent Context (Database Activity on db_queue)
|
||||
const context = await executeActivity(TaskQueueDb, getAgentChatContextActivity, {
|
||||
teamId,
|
||||
agentId: payload.agentId,
|
||||
})
|
||||
|
||||
// 5. Prepare Images (Attachments only)
|
||||
const attachmentImageUrls: string[] = []
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -103,7 +110,7 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
const aiResult = await executeActivity(agentWorkerQueue, aiChatActivity, {
|
||||
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
|
||||
teamId,
|
||||
agentId: payload.agentId,
|
||||
message: userComment.message || '',
|
||||
@@ -114,6 +121,7 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
sessionId,
|
||||
userId: payload.userId,
|
||||
explicitMention: payload?.explicitMention,
|
||||
context,
|
||||
})
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
@@ -146,7 +154,7 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
output: { sessionId: aiResult.sessionId },
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiChat failed for task ${task.id}:`, err)
|
||||
console.error(`AgentChat failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
@@ -175,4 +183,4 @@ export async function aiChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export const aiChatWorkflow = aiChat
|
||||
export const agentChatWorkflow = agentChat
|
||||
@@ -0,0 +1,75 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentEmbeddingMedia } from './agent-embedding'
|
||||
import { prisma } from '@/db'
|
||||
import { setupTestDbHooks } from '@/db-test-hooks'
|
||||
import * as workflowUtils from '@/workflow/workflow-utils'
|
||||
|
||||
vi.mock('@/workflow/workflow-utils', async () => {
|
||||
const actual = await vi.importActual('@/workflow/workflow-utils')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
describe('Agent Embedding Workflow', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should run agent embedding workflow successfully', async () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getEmbeddingContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getEmbeddingContextActivity',
|
||||
}),
|
||||
generateEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateEmbeddingActivity',
|
||||
}),
|
||||
saveAssetEmbeddingsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'saveAssetEmbeddingsActivity',
|
||||
}),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getEmbeddingContextActivity.mockResolvedValue({ agent: { id: 'b1' }, asset: { id: 'a1' }, dbProvider: { name: 'google' } })
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.generateEmbeddingActivity.mockResolvedValue({
|
||||
embeddings: [{ embedding: [0.1, 0.2] }],
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt' },
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mockActivities contains vi.fn mock functions which are cast to expected activity proxy types
|
||||
vi.mocked(workflowUtils.getActivities).mockReturnValue(mockActivities as any)
|
||||
vi.mocked(workflowUtils.executeActivity).mockImplementation(async (_queue, act, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- act is one of the mocked activities
|
||||
return (act as any)(...args)
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.create({
|
||||
data: {
|
||||
type: 'ai_embedding',
|
||||
status: 'pending',
|
||||
assetId: 'a1',
|
||||
teamId: 't1',
|
||||
},
|
||||
})
|
||||
|
||||
await agentEmbeddingMedia(task)
|
||||
|
||||
expect(mockActivities.getEmbeddingContextActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.generateEmbeddingActivity).toHaveBeenCalled()
|
||||
expect(mockActivities.saveAssetEmbeddingsActivity).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,12 @@
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import { getActivities, executeActivity, TaskQueueDb, TaskQueueAgent } from '../workflow-utils'
|
||||
|
||||
export async function aiEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getEmbeddingContextActivity,
|
||||
generateEmbeddingActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
updateTaskUsageActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
@@ -32,21 +34,36 @@ export async function aiEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
if (!task.teamId) throw new Error('Task has no teamId')
|
||||
|
||||
// 1. Fetch Agent Context (Database Activity on db_queue)
|
||||
const context = await executeActivity(TaskQueueDb, getEmbeddingContextActivity, {
|
||||
teamId: task.teamId,
|
||||
assetId: task.assetId,
|
||||
})
|
||||
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
// Call the activity to generate embeddings
|
||||
const result = await executeActivity(agentWorkerQueue, generateEmbeddingActivity, {
|
||||
teamId: task.teamId,
|
||||
assetId: task.assetId,
|
||||
context,
|
||||
})
|
||||
|
||||
// Save computed embeddings
|
||||
if (result.embeddings.length > 0) {
|
||||
await executeActivity(TaskQueueDb, saveAssetEmbeddingsActivity, {
|
||||
assetId: task.assetId,
|
||||
embeddings: result.embeddings,
|
||||
})
|
||||
}
|
||||
|
||||
// Update Usage
|
||||
if (result) {
|
||||
if (result.usage) {
|
||||
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
|
||||
taskId: task.id,
|
||||
inputTokens: result.inputTokens,
|
||||
outputTokens: result.outputTokens,
|
||||
model: result.model,
|
||||
inputTokens: result.usage.inputTokens,
|
||||
outputTokens: result.usage.outputTokens,
|
||||
model: result.usage.model,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -64,7 +81,7 @@ export async function aiEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
status: 'completed',
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiEmbeddingMedia failed for task ${task.id}:`, err)
|
||||
console.error(`AgentEmbeddingMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
@@ -88,4 +105,4 @@ export async function aiEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export const aiEmbeddingWorkflow = aiEmbeddingMedia
|
||||
export const agentEmbeddingWorkflow = agentEmbeddingMedia
|
||||
@@ -1,203 +0,0 @@
|
||||
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',
|
||||
storageKey: { 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__',
|
||||
sessionId: 'task-1',
|
||||
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',
|
||||
storageKey: { 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__',
|
||||
sessionId: 'task-1',
|
||||
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' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,327 +0,0 @@
|
||||
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',
|
||||
}),
|
||||
deleteCommentActivity: Object.assign(vi.fn(), { _activityName: 'deleteCommentActivity' }),
|
||||
initializeAgentSessionActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'initializeAgentSessionActivity',
|
||||
}),
|
||||
}
|
||||
|
||||
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')
|
||||
mockActivities.initializeAgentSessionActivity.mockResolvedValue('mock-session-id')
|
||||
})
|
||||
|
||||
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__',
|
||||
sessionId: 'pending',
|
||||
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__',
|
||||
sessionId: 'pending',
|
||||
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' },
|
||||
})
|
||||
})
|
||||
|
||||
it('should pass explicitMention payload parameter and format instruction when true', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-explicit',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
explicitMention: true,
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-explicit',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
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: 5, outputTokens: 5, model: 'gpt-4' },
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.aiChatActivity).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
explicitMention: true,
|
||||
agentsInstruction: expect.stringContaining('MUST reply to this message'),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('should delete placeholder comment when AI response is __NO_REPLY__', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-no-reply',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.chat,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {
|
||||
userCommentId: 'comment-1',
|
||||
agentId: 'bot-1',
|
||||
explicitMention: false,
|
||||
},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid-no-reply',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
id: 'asset-1',
|
||||
project: { teamId: 'team-1', id: 'proj-1' },
|
||||
})
|
||||
|
||||
mockActivities.getCommentActivity.mockResolvedValue({
|
||||
id: 'comment-1',
|
||||
message: 'Hello AI',
|
||||
})
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({
|
||||
id: 'placeholder-delete-me',
|
||||
})
|
||||
|
||||
mockActivities.aiChatActivity.mockResolvedValue({
|
||||
text: ' __NO_REPLY__ ',
|
||||
usage: { inputTokens: 5, outputTokens: 5, model: 'gpt-4' },
|
||||
})
|
||||
|
||||
await aiChat(task)
|
||||
|
||||
expect(mockActivities.deleteCommentActivity).toHaveBeenCalledWith('placeholder-delete-me')
|
||||
expect(mockActivities.updateCommentActivity).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,179 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { aiEmbeddingMedia } from './ai-embedding'
|
||||
import { WorkflowTask, WorkflowTaskStatus, WorkflowTaskType } from '@/generated/prisma/client'
|
||||
import * as workflowUtils from '../workflow-utils'
|
||||
|
||||
vi.mock('../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('AIEmbedding Workflow', () => {
|
||||
const mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
generateEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateEmbeddingActivity',
|
||||
}),
|
||||
updateTaskUsageActivity: Object.assign(vi.fn(), { _activityName: 'updateTaskUsageActivity' }),
|
||||
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
|
||||
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
|
||||
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 generate embeddings successfully', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
teamId: 'team-1',
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.generateEmbeddingActivity.mockResolvedValue({
|
||||
inputTokens: 5,
|
||||
outputTokens: 5,
|
||||
model: 'clip',
|
||||
})
|
||||
|
||||
await aiEmbeddingMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__EMBEDDING__',
|
||||
sessionId: 'task-1',
|
||||
agentId: 'default',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.processing,
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskUsageActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
inputTokens: 5,
|
||||
outputTokens: 5,
|
||||
model: 'clip',
|
||||
})
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-1',
|
||||
message: expect.stringContaining('successfully'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-1',
|
||||
status: WorkflowTaskStatus.completed,
|
||||
})
|
||||
})
|
||||
|
||||
it('should use agentId from payload if provided', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-1',
|
||||
assetId: 'asset-1',
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId: 'team-1',
|
||||
output: null,
|
||||
payload: { agentId: 'real-agent-id' },
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-1' })
|
||||
mockActivities.generateEmbeddingActivity.mockResolvedValue({
|
||||
inputTokens: 5,
|
||||
outputTokens: 5,
|
||||
model: 'clip',
|
||||
})
|
||||
|
||||
await aiEmbeddingMedia(task)
|
||||
|
||||
expect(mockActivities.createCommentActivity).toHaveBeenCalledWith({
|
||||
assetId: 'asset-1',
|
||||
message: '__EMBEDDING__',
|
||||
sessionId: 'task-1',
|
||||
agentId: 'real-agent-id',
|
||||
})
|
||||
})
|
||||
|
||||
it('should handle failures and update task status with error', async () => {
|
||||
const task: WorkflowTask = {
|
||||
id: 'task-fail',
|
||||
assetId: 'asset-1',
|
||||
teamId: 'team-1',
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
output: null,
|
||||
payload: {},
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
heartbeat: null,
|
||||
projectId: 'proj-1',
|
||||
uid: 'task-uid',
|
||||
model: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
}
|
||||
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'placeholder-err' })
|
||||
mockActivities.generateEmbeddingActivity.mockRejectedValue(new Error('Embedding error'))
|
||||
|
||||
await expect(aiEmbeddingMedia(task)).rejects.toThrow('Embedding error')
|
||||
|
||||
expect(mockActivities.updateCommentActivity).toHaveBeenCalledWith({
|
||||
commentId: 'placeholder-err',
|
||||
message: expect.stringContaining('failed'),
|
||||
})
|
||||
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: 'task-fail',
|
||||
status: WorkflowTaskStatus.failed,
|
||||
output: { error: 'Embedding error' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
export * from './ai-transcription'
|
||||
export * from './ai-embedding'
|
||||
export * from './ai-autofill'
|
||||
export * from './ai-chat'
|
||||
export * from './agent-embedding'
|
||||
export * from './agent-autofill'
|
||||
export * from './agent-chat'
|
||||
export * from '@/transcode/workflows/transcode'
|
||||
|
||||
Reference in New Issue
Block a user