mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-25 21:49:05 +00:00
initial commit
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
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__',
|
||||
isAi: true,
|
||||
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__',
|
||||
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',
|
||||
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' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,91 @@
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import { getActivities, executeActivity, TaskQueueDb, TaskQueueAgent } from '../workflow-utils'
|
||||
|
||||
export async function aiEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
generateEmbeddingActivity,
|
||||
updateTaskUsageActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
getAgentWorkerQueueActivity,
|
||||
} = getActivities()
|
||||
|
||||
let placeholderCommentId: 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: '__EMBEDDING__',
|
||||
isAi: true,
|
||||
agentId: (payload?.agentId as string) || 'default',
|
||||
})
|
||||
placeholderCommentId = placeholder.id
|
||||
|
||||
if (!task.teamId) throw new Error('Task has no teamId')
|
||||
|
||||
const agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
// Call the activity to generate embeddings
|
||||
const result = await executeActivity(agentWorkerQueue, generateEmbeddingActivity, {
|
||||
teamId: task.teamId,
|
||||
assetId: task.assetId,
|
||||
})
|
||||
|
||||
// Update Usage
|
||||
if (result) {
|
||||
await executeActivity(TaskQueueDb, updateTaskUsageActivity, {
|
||||
taskId: task.id,
|
||||
inputTokens: result.inputTokens,
|
||||
outputTokens: result.outputTokens,
|
||||
model: result.model,
|
||||
})
|
||||
}
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Embedding completed successfully.',
|
||||
})
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiEmbeddingMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: `Embedding 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
|
||||
}
|
||||
}
|
||||
|
||||
export const aiEmbeddingWorkflow = aiEmbeddingMedia
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { WorkflowTask } from '@/generated/prisma/client'
|
||||
import { getActivities, executeActivity, TaskQueueDb, TaskQueueTranscode, sleep } from '../workflow-utils'
|
||||
|
||||
export async function aiTranscriptionMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
extractAiMetadataActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
getTranscodeWorkerQueueActivity,
|
||||
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: '__TRANSCRIPTION__',
|
||||
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.key) {
|
||||
throw new Error('Asset not found')
|
||||
}
|
||||
|
||||
// 2. Extract Audio (Requires FFmpeg)
|
||||
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: 'transcription',
|
||||
isImage: false,
|
||||
})
|
||||
|
||||
if (generatedFiles.length === 0) {
|
||||
throw new Error('Failed to extract audio for transcription')
|
||||
}
|
||||
|
||||
// Simulate work
|
||||
await sleep(2000)
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Transcription completed successfully.',
|
||||
})
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(TaskQueueDb, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
} catch (err) {
|
||||
console.error(`AiTranscriptionMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
await executeActivity(TaskQueueDb, updateCommentActivity, {
|
||||
commentId: placeholderCommentId,
|
||||
message: `Transcription 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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// For Temporal, we often export as a named workflow
|
||||
export const aiTranscriptionWorkflow = aiTranscriptionMedia
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from './ai-transcription'
|
||||
export * from './ai-embedding'
|
||||
export * from '@/agent/workflows/ai-autofill'
|
||||
export * from '@/agent/workflows/ai-chat'
|
||||
export * from '@/transcode/workflows/transcode'
|
||||
Reference in New Issue
Block a user