mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-28 20:04:26 +00:00
feat(workflow): migrate workflow engine from temporal to dbos (#481)
* feat(workflow): migrate workflow engine from temporal to dbos Replace Temporal and LocalExecutor with DBOS Transact (@dbos-inc/dbos-sdk) as the unified workflow engine. Background tasks, media transcoding, and AI agent workflows now execute with durable steps and task queues directly against PostgreSQL, eliminating the need for an external Temporal cluster and separate polling executors. * fix(workflow): submit tasks via DBOSClient to allow enqueueing from steps Enqueuing workflows using DBOS.enqueueWorkflowWithOptions threw a DBOSInvalidWorkflowTransitionError when triggered from within a running step or activity (e.g. creating embedding or autofill tasks during video transcoding). Use DBOSClient to submit and cancel workflow tasks directly against the system database, detaching execution from the ambient workflow/step context. * feat(web): support SHUMAI_WORKERS environment variable * fix(workflow): ensure CLI tasks are enqueued to DBOS and run DBOS migrations in global setup - Initialize workflows and wait for pending DBOS submissions in shumai regenerate-embeddings CLI - Remove no-op submit bypass and enqueue tasks via DBOSClient in producer and CLI contexts - Add DBOS migration runner in test global setup to avoid concurrent migration deadlocks across test forks - Update changelog and add regression tests * fix(workflow): ensure unique per-instance executor identity for worker replicas - Derive unique per-instance DBOS executor IDs across worker replicas - Support SHUMAI_WORKER_ID, DBOS__VMID, and POD_NAME (Kubernetes Downward API) - Disambiguate multi-replica bare metal/container deployments with host, PID, and instance suffix - Prevent startup recovery from re-enqueueing workflows actively executed by other live workers - Add multi-instance startup recovery tests and update deployment documentation * fix(workflow): only register listened queues and update concurrency on change - Only register queues that the executor instance actively listens to - Use always_update conflict resolution so environment variable changes take effect on restart - Prevent dedicated workers from overwriting unmanaged queue concurrency configurations - Add tests verifying concurrency updates and queue isolation across worker roles * refactor(workflow): simplify activities to use defineStep and direct calls (#482) * refactor(workflow): simplify activities to use defineStep and direct calls - Wrap activities using defineStep from @shumai/workflow-core - Remove obsolete getActivities, registerActivities, dynamic activity proxies, and workerQueue arguments - Remove executor.ts and registry.ts, consolidating workflow registration into workflow.ts - Call activities directly across transcode and agent workflows - Update all corresponding workflow tests and developer guide documentation * fix(workflow): properly detect DBOSWorkflowCancelledError in runOnCancel fallback - DBOSWorkflowCancelledError in DBOS SDK does not set name, inheriting 'Error' - Implement isDbosWorkflowCancelledError checking instanceof, constructor.name, and dbosErrorCode - Update unit tests to verify real DBOS SDK cancellation error instances * docs(workflow): update documentation and readme for dbos migration - Rename docs/configuration/temporal.mdx to docs/configuration/distributed.mdx - Document DBOS-based distributed worker architecture and task queues - Remove obsolete docker-compose/temporal/ - Update environment variables documentation in docs/configuration/env-variables.mdx - Update references in README.md, README_CN.md, docs/docs.json, and related guides * feat(deploy): implement KEDA ScaledJob and scale-to-zero On-Demand transcoding (#483) * feat(deploy): add shumai-transcode docker image and k8s autoscaling example with garage s3 * docs(k8s): document port-forwarding and in-cluster s3 domain mapping * feat(storage): support public s3 endpoint for browser uploads and update k8s example * fix(k8s): configure s3 bucket cors rules in garage initialization * fix(k8s): increase transcode worker memory limit to 4Gi for 4K video encoding * feat(deploy): add AWS EKS deployment with Graviton3 Spot nodegroups and autoscaling * docs(deploy): redesign EKS documentation, rename k8s to eks, and add scalable deployment feature * docs: rephrase DBOS feature bullet to Durable Workflows via DBOS * docs(eks): upgrade default instances to Graviton5 c9g.large and c9g.xlarge * feat(eks): use On-Demand for general nodegroup and add spot capacity diversification * docs(eks): fix Architecture diagram to locate all transcode worker pods in Transcode Compute Pool * feat(deploy): implement KEDA ScaledJob and scale-to-zero On-Demand transcoding * feat(transcode): support idle-timeout auto-drain for KEDA scaled jobs * fix(deploy): fix EKS deployment manifests and documentation based on cluster verification
This commit is contained in:
@@ -2,14 +2,29 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentAutofillMedia } from './agent-autofill'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import * as workflowCore from '@shumai/workflow-core'
|
||||
import * as agentActivities from '../activities/agent'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async () => {
|
||||
const actual = await vi.importActual('@shumai/workflow-core')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateTaskUsageActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/agent', async () => {
|
||||
const actual = await vi.importActual('../activities/agent')
|
||||
return {
|
||||
...actual,
|
||||
getAssetActivity: vi.fn(),
|
||||
getProjectAutofillFieldsActivity: vi.fn(),
|
||||
getAgentAutofillContextActivity: vi.fn(),
|
||||
autofillAiActivity: vi.fn(),
|
||||
updateAssetMetadataActivity: vi.fn(),
|
||||
createCommentActivity: vi.fn(),
|
||||
updateCommentActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -23,32 +38,17 @@ describe('Agent Autofill Workflow', () => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getAssetActivity: Object.assign(vi.fn(), { _activityName: 'getAssetActivity' }),
|
||||
getProjectAutofillFieldsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getProjectAutofillFieldsActivity',
|
||||
}),
|
||||
getAgentAutofillContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentAutofillContextActivity',
|
||||
}),
|
||||
getAssetAutofillContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAssetAutofillContextActivity',
|
||||
}),
|
||||
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' }),
|
||||
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAgentWorkerQueueActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(workflowCore.updateTaskStatusActivity),
|
||||
getAssetActivity: vi.mocked(agentActivities.getAssetActivity),
|
||||
getProjectAutofillFieldsActivity: vi.mocked(agentActivities.getProjectAutofillFieldsActivity),
|
||||
getAgentAutofillContextActivity: vi.mocked(agentActivities.getAgentAutofillContextActivity),
|
||||
autofillAiActivity: vi.mocked(agentActivities.autofillAiActivity),
|
||||
updateTaskUsageActivity: vi.mocked(workflowCore.updateTaskUsageActivity),
|
||||
updateAssetMetadataActivity: vi.mocked(agentActivities.updateAssetMetadataActivity),
|
||||
createCommentActivity: vi.mocked(agentActivities.createCommentActivity),
|
||||
updateCommentActivity: vi.mocked(agentActivities.updateCommentActivity),
|
||||
}
|
||||
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getAssetActivity.mockResolvedValue({
|
||||
@@ -69,13 +69,6 @@ describe('Agent Autofill Workflow', () => {
|
||||
sessionId: 'session-123',
|
||||
usage: { inputTokens: 10, outputTokens: 15, model: 'gemini-model' },
|
||||
})
|
||||
|
||||
// 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)
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent autofill workflow successfully', async () => {
|
||||
@@ -93,9 +86,6 @@ describe('Agent Autofill Workflow', () => {
|
||||
|
||||
await agentAutofillMedia(task)
|
||||
|
||||
// Verify queue discovery
|
||||
expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled()
|
||||
|
||||
// Verify task processing status
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
|
||||
@@ -1,38 +1,33 @@
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { executeActivity, getActivities, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import {
|
||||
ApplicationFailure,
|
||||
updateTaskStatusActivity,
|
||||
updateTaskUsageActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import { getProxyType } from '@shumai/core/src/utils/mime'
|
||||
import {
|
||||
autofillAiActivity,
|
||||
createCommentActivity,
|
||||
getAgentAutofillContextActivity,
|
||||
getAssetActivity,
|
||||
getProjectAutofillFieldsActivity,
|
||||
updateAssetMetadataActivity,
|
||||
updateCommentActivity,
|
||||
} from '../activities/agent'
|
||||
|
||||
export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
getProjectAutofillFieldsActivity,
|
||||
getAgentAutofillContextActivity,
|
||||
autofillAiActivity,
|
||||
updateTaskUsageActivity,
|
||||
updateAssetMetadataActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
getAgentWorkerQueueActivity,
|
||||
} = getActivities()
|
||||
|
||||
let placeholderCommentId: string | undefined
|
||||
let agentWorkerQueue = ''
|
||||
|
||||
try {
|
||||
// 0. Discover queues
|
||||
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
// Update status to processing
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// 0. Create Placeholder Comment
|
||||
const payload = task.payload
|
||||
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
|
||||
const placeholder = await createCommentActivity({
|
||||
assetId: task.assetId,
|
||||
message: '__AUTOFILL__',
|
||||
sessionId: payload?.agent?.sessionId || task.id,
|
||||
@@ -41,7 +36,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
placeholderCommentId = placeholder.id
|
||||
|
||||
// 1. Get Asset
|
||||
const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId)
|
||||
const asset = await getAssetActivity(task.assetId)
|
||||
if (!asset || !asset.project) {
|
||||
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
||||
}
|
||||
@@ -49,19 +44,15 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
const projectId = asset.project.id
|
||||
|
||||
// 2. Get Project Autofill Fields
|
||||
const fields = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getProjectAutofillFieldsActivity,
|
||||
projectId,
|
||||
)
|
||||
const fields = await getProjectAutofillFieldsActivity(projectId)
|
||||
if (fields.length === 0) {
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Autofill completed: No autofill fields defined in project.',
|
||||
})
|
||||
}
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
@@ -69,7 +60,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// 3. Fetch Agent Context
|
||||
const context = await executeActivity(agentWorkerQueue, getAgentAutofillContextActivity, {
|
||||
const context = await getAgentAutofillContextActivity({
|
||||
teamId,
|
||||
})
|
||||
|
||||
@@ -91,7 +82,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
: undefined
|
||||
: undefined
|
||||
|
||||
const aiResult = await executeActivity(agentWorkerQueue, autofillAiActivity, {
|
||||
const aiResult = await autofillAiActivity({
|
||||
teamId,
|
||||
assetId: asset.id,
|
||||
assetName: asset.name,
|
||||
@@ -99,19 +90,17 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
duration,
|
||||
pageCount,
|
||||
projectId: asset.projectId ?? undefined,
|
||||
fields: fields.map(
|
||||
(f: { key: string; config: Record<string, unknown>; description?: string | null }) => ({
|
||||
id: f.key,
|
||||
config: f.config as unknown as PrismaJson.FieldConfig,
|
||||
description: f.description,
|
||||
}),
|
||||
),
|
||||
fields: fields.map((f) => ({
|
||||
id: f.key,
|
||||
config: (f.config as unknown as PrismaJson.FieldConfig) ?? {},
|
||||
description: f.description,
|
||||
})),
|
||||
context,
|
||||
})
|
||||
|
||||
if (aiResult.usage) {
|
||||
// Update Usage
|
||||
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
|
||||
await updateTaskUsageActivity({
|
||||
taskId: task.id,
|
||||
inputTokens: aiResult.usage.inputTokens,
|
||||
outputTokens: aiResult.usage.outputTokens,
|
||||
@@ -129,7 +118,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}))
|
||||
|
||||
if (metadataUpdates.length > 0) {
|
||||
await executeActivity(agentWorkerQueue, updateAssetMetadataActivity, {
|
||||
await updateAssetMetadataActivity({
|
||||
assetId: asset.id,
|
||||
metadata: metadataUpdates,
|
||||
})
|
||||
@@ -137,7 +126,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Autofill completed successfully.',
|
||||
sessionId: aiResult.sessionId,
|
||||
@@ -145,7 +134,7 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
@@ -153,9 +142,9 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
console.error(`AgentAutofillMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId && agentWorkerQueue) {
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: `Autofill failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
})
|
||||
@@ -165,13 +154,11 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to failed
|
||||
if (agentWorkerQueue) {
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
}
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,14 +2,34 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentChat } from './agent-chat'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import * as workflowCore from '@shumai/workflow-core'
|
||||
import * as agentActivities from '../activities/agent'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async () => {
|
||||
const actual = await vi.importActual('@shumai/workflow-core')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateTaskUsageActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/agent', async () => {
|
||||
const actual = await vi.importActual('../activities/agent')
|
||||
return {
|
||||
...actual,
|
||||
getCommentActivity: vi.fn(),
|
||||
createCommentActivity: vi.fn(),
|
||||
getAssetActivity: vi.fn(),
|
||||
initializeAgentSessionActivity: vi.fn(),
|
||||
getAgentChatContextActivity: vi.fn(),
|
||||
agentChatActivity: vi.fn(),
|
||||
updateCommentActivity: vi.fn(),
|
||||
deleteCommentActivity: vi.fn(),
|
||||
getAssetPathHierarchyActivity: vi.fn(),
|
||||
getAssetPathContextActivity: vi.fn(),
|
||||
generateSessionNameActivity: vi.fn(),
|
||||
getUserTeamInfoActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -23,40 +43,22 @@ describe('Agent Chat Workflow', () => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
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' }),
|
||||
getAssetPathHierarchyActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAssetPathHierarchyActivity',
|
||||
}),
|
||||
getAssetPathContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getAssetPathContextActivity',
|
||||
}),
|
||||
generateSessionNameActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateSessionNameActivity',
|
||||
}),
|
||||
getUserTeamInfoActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getUserTeamInfoActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(workflowCore.updateTaskStatusActivity),
|
||||
getCommentActivity: vi.mocked(agentActivities.getCommentActivity),
|
||||
createCommentActivity: vi.mocked(agentActivities.createCommentActivity),
|
||||
getAssetActivity: vi.mocked(agentActivities.getAssetActivity),
|
||||
initializeAgentSessionActivity: vi.mocked(agentActivities.initializeAgentSessionActivity),
|
||||
getAgentChatContextActivity: vi.mocked(agentActivities.getAgentChatContextActivity),
|
||||
agentChatActivity: vi.mocked(agentActivities.agentChatActivity),
|
||||
updateCommentActivity: vi.mocked(agentActivities.updateCommentActivity),
|
||||
updateTaskUsageActivity: vi.mocked(workflowCore.updateTaskUsageActivity),
|
||||
deleteCommentActivity: vi.mocked(agentActivities.deleteCommentActivity),
|
||||
getAssetPathHierarchyActivity: vi.mocked(agentActivities.getAssetPathHierarchyActivity),
|
||||
getAssetPathContextActivity: vi.mocked(agentActivities.getAssetPathContextActivity),
|
||||
generateSessionNameActivity: vi.mocked(agentActivities.generateSessionNameActivity),
|
||||
getUserTeamInfoActivity: vi.mocked(agentActivities.getUserTeamInfoActivity),
|
||||
}
|
||||
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.generateSessionNameActivity.mockResolvedValue(undefined)
|
||||
@@ -92,13 +94,6 @@ describe('Agent Chat Workflow', () => {
|
||||
sessionId: 'session-123',
|
||||
usage: { inputTokens: 10, outputTokens: 20, model: 'gemini-model' },
|
||||
})
|
||||
|
||||
// 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)
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent chat workflow successfully with default configurations', async () => {
|
||||
@@ -116,9 +111,6 @@ describe('Agent Chat Workflow', () => {
|
||||
|
||||
await agentChat(task)
|
||||
|
||||
// Verify queue discovery
|
||||
expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled()
|
||||
|
||||
// Verify task status processing
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
|
||||
@@ -1,6 +1,22 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import { executeActivity, getActivities, TaskQueueAgent } from '@shumai/workflow-core'
|
||||
import {
|
||||
ApplicationFailure,
|
||||
updateTaskStatusActivity,
|
||||
updateTaskUsageActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import {
|
||||
agentChatActivity,
|
||||
createCommentActivity,
|
||||
generateSessionNameActivity,
|
||||
getAgentChatContextActivity,
|
||||
getAssetActivity,
|
||||
getAssetPathContextActivity,
|
||||
getAssetPathHierarchyActivity,
|
||||
getCommentActivity,
|
||||
getUserTeamInfoActivity,
|
||||
initializeAgentSessionActivity,
|
||||
updateCommentActivity,
|
||||
} from '../activities/agent'
|
||||
import type {
|
||||
ShumaiMessageContext,
|
||||
ShumaiAssetContext,
|
||||
@@ -11,32 +27,11 @@ import { getProxyType } from '@shumai/core/src/utils/mime'
|
||||
import { secondToDegree } from '@shumai/core/src/utils/model3d'
|
||||
|
||||
export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getAssetActivity,
|
||||
getCommentActivity,
|
||||
getAgentChatContextActivity,
|
||||
agentChatActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
updateTaskUsageActivity,
|
||||
getAgentWorkerQueueActivity,
|
||||
initializeAgentSessionActivity,
|
||||
getAssetPathHierarchyActivity,
|
||||
getAssetPathContextActivity,
|
||||
generateSessionNameActivity,
|
||||
getUserTeamInfoActivity,
|
||||
} = getActivities()
|
||||
|
||||
let placeholderCommentId: string | undefined
|
||||
let agentWorkerQueue = ''
|
||||
|
||||
try {
|
||||
// 0. Discover queue
|
||||
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
|
||||
// Update status to processing
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
@@ -65,7 +60,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
let commentAnnotations: unknown[] | undefined
|
||||
|
||||
if (userCommentId) {
|
||||
userComment = await executeActivity(agentWorkerQueue, getCommentActivity, userCommentId)
|
||||
userComment = await getCommentActivity(userCommentId)
|
||||
if (!userComment) {
|
||||
throw ApplicationFailure.create({ message: 'User comment not found', nonRetryable: true })
|
||||
}
|
||||
@@ -84,7 +79,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// 2. Create Placeholder Comment
|
||||
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
|
||||
const placeholder = await createCommentActivity({
|
||||
assetId: task.assetId,
|
||||
message: '__CHAT__',
|
||||
sessionId: sessionId || 'pending',
|
||||
@@ -119,7 +114,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// 3. Get Asset
|
||||
const asset = await executeActivity(agentWorkerQueue, getAssetActivity, task.assetId)
|
||||
const asset = await getAssetActivity(task.assetId)
|
||||
if (!asset || !asset.project) {
|
||||
throw ApplicationFailure.create({ message: 'Asset or project not found', nonRetryable: true })
|
||||
}
|
||||
@@ -134,7 +129,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
nonRetryable: true,
|
||||
})
|
||||
}
|
||||
sessionId = await executeActivity(agentWorkerQueue, initializeAgentSessionActivity, {
|
||||
sessionId = await initializeAgentSessionActivity({
|
||||
teamId,
|
||||
agentId: agentId,
|
||||
userCommentId,
|
||||
@@ -144,18 +139,14 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// 4b. Fetch Agent Context
|
||||
const context = await executeActivity(agentWorkerQueue, getAgentChatContextActivity, {
|
||||
const context = await getAgentChatContextActivity({
|
||||
teamId,
|
||||
agentId: agentId,
|
||||
userId: payload.agent?.userId,
|
||||
projectId: payload.projectId,
|
||||
})
|
||||
|
||||
const pathHierarchy = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetPathHierarchyActivity,
|
||||
task.assetId,
|
||||
)
|
||||
const pathHierarchy = await getAssetPathHierarchyActivity(task.assetId)
|
||||
const assetPath = pathHierarchy?.path || ''
|
||||
const ancestors = pathHierarchy?.ancestors || []
|
||||
|
||||
@@ -180,11 +171,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
if (userCommentId && userComment?.attachments) {
|
||||
for (const att of userComment.attachments) {
|
||||
if (att.asset) {
|
||||
const filePath = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetPathContextActivity,
|
||||
att.asset.id,
|
||||
)
|
||||
const filePath = await getAssetPathContextActivity(att.asset.id)
|
||||
const attProxyType =
|
||||
(att.asset.media as PrismaJson.MediaInfo | null)?.proxyType ||
|
||||
getProxyType(att.asset.mediaType, att.asset.name) ||
|
||||
@@ -203,13 +190,9 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
} else if (payload.agent?.attachedFiles) {
|
||||
for (const fileId of payload.agent.attachedFiles) {
|
||||
const file = await executeActivity(agentWorkerQueue, getAssetActivity, fileId)
|
||||
const file = await getAssetActivity(fileId)
|
||||
if (file) {
|
||||
const filePath = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetPathContextActivity,
|
||||
fileId,
|
||||
)
|
||||
const filePath = await getAssetPathContextActivity(fileId)
|
||||
const fileProxyType =
|
||||
(file.media as PrismaJson.MediaInfo | null)?.proxyType ||
|
||||
getProxyType(file.mediaType, file.name) ||
|
||||
@@ -232,13 +215,9 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const referencedAssets: ShumaiAttachedFileContext[] = []
|
||||
if (payload.agent?.assetIds) {
|
||||
for (const assetId of payload.agent.assetIds) {
|
||||
const referencedAsset = await executeActivity(agentWorkerQueue, getAssetActivity, assetId)
|
||||
const referencedAsset = await getAssetActivity(assetId)
|
||||
if (referencedAsset) {
|
||||
const filePath = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
getAssetPathContextActivity,
|
||||
assetId,
|
||||
)
|
||||
const filePath = await getAssetPathContextActivity(assetId)
|
||||
const refProxyType =
|
||||
(referencedAsset.media as PrismaJson.MediaInfo | null)?.proxyType ||
|
||||
getProxyType(referencedAsset.mediaType, referencedAsset.name) ||
|
||||
@@ -265,7 +244,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
const targetUserId = userCommentId ? commentCreatorId : payload.agent?.userId
|
||||
let userInfo: { name: string; role: string } | null = null
|
||||
if (targetUserId) {
|
||||
userInfo = await executeActivity(agentWorkerQueue, getUserTeamInfoActivity, {
|
||||
userInfo = await getUserTeamInfoActivity({
|
||||
userId: targetUserId,
|
||||
teamId,
|
||||
})
|
||||
@@ -325,7 +304,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
folderId = asset.parentId
|
||||
}
|
||||
|
||||
const aiResult = await executeActivity(agentWorkerQueue, agentChatActivity, {
|
||||
const aiResult = await agentChatActivity({
|
||||
taskId: task.id,
|
||||
teamId,
|
||||
agentId: agentId,
|
||||
@@ -344,7 +323,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: aiResult.text,
|
||||
sessionId: aiResult.sessionId,
|
||||
@@ -353,7 +332,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 8. Update Usage
|
||||
if (aiResult.usage) {
|
||||
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
|
||||
await updateTaskUsageActivity({
|
||||
taskId: task.id,
|
||||
inputTokens: aiResult.usage.inputTokens,
|
||||
outputTokens: aiResult.usage.outputTokens,
|
||||
@@ -363,7 +342,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 9. Generate Session Name for new chats
|
||||
if (isNewChat) {
|
||||
await executeActivity(agentWorkerQueue, generateSessionNameActivity, {
|
||||
await generateSessionNameActivity({
|
||||
teamId,
|
||||
agentId,
|
||||
prompt,
|
||||
@@ -375,7 +354,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
output: { sessionId: aiResult.sessionId },
|
||||
@@ -384,7 +363,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
console.error(`AgentChat failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId && agentWorkerQueue) {
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
let errorMessage = 'Sorry, I encountered an error while processing your request.'
|
||||
if (err instanceof Error) {
|
||||
@@ -406,7 +385,7 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
errorMessage = 'Agent execution stopped.'
|
||||
}
|
||||
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: errorMessage,
|
||||
})
|
||||
@@ -416,13 +395,11 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to failed
|
||||
if (agentWorkerQueue) {
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
}
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,14 +2,39 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { agentEmbeddingMedia } from './agent-embedding'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import * as workflowUtils from '@shumai/workflow-core'
|
||||
import * as workflowCore from '@shumai/workflow-core'
|
||||
import * as agentActivities from '../activities/agent'
|
||||
import * as aiActivities from '../activities/ai'
|
||||
|
||||
vi.mock('@shumai/workflow-core', async () => {
|
||||
const actual = await vi.importActual('@shumai/workflow-core')
|
||||
return {
|
||||
...actual,
|
||||
getActivities: vi.fn(),
|
||||
executeActivity: vi.fn(),
|
||||
updateTaskStatusActivity: vi.fn(),
|
||||
updateTaskUsageActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/agent', async () => {
|
||||
const actual = await vi.importActual('../activities/agent')
|
||||
return {
|
||||
...actual,
|
||||
createCommentActivity: vi.fn(),
|
||||
updateCommentActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('../activities/ai', async () => {
|
||||
const actual = await vi.importActual('../activities/ai')
|
||||
return {
|
||||
...actual,
|
||||
getEmbeddingContextActivity: vi.fn(),
|
||||
generateImageEmbeddingActivity: vi.fn(),
|
||||
generateVideoChunkEmbeddingActivity: vi.fn(),
|
||||
saveAssetEmbeddingsActivity: vi.fn(),
|
||||
deleteAssetEmbeddingsActivity: vi.fn(),
|
||||
transcodeVideoChunkActivity: vi.fn(),
|
||||
deleteS3ObjectActivity: vi.fn(),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -23,49 +48,23 @@ describe('Agent Embedding Workflow', () => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockActivities = {
|
||||
updateTaskStatusActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'updateTaskStatusActivity',
|
||||
}),
|
||||
getEmbeddingContextActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getEmbeddingContextActivity',
|
||||
}),
|
||||
generateImageEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateImageEmbeddingActivity',
|
||||
}),
|
||||
generateVideoChunkEmbeddingActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'generateVideoChunkEmbeddingActivity',
|
||||
}),
|
||||
saveAssetEmbeddingsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'saveAssetEmbeddingsActivity',
|
||||
}),
|
||||
deleteAssetEmbeddingsActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'deleteAssetEmbeddingsActivity',
|
||||
}),
|
||||
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',
|
||||
}),
|
||||
getTranscodeWorkerQueueActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'getTranscodeWorkerQueueActivity',
|
||||
}),
|
||||
downloadMediaToTmpActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'downloadMediaToTmpActivity',
|
||||
}),
|
||||
cleanupTmpDirActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'cleanupTmpDirActivity',
|
||||
}),
|
||||
transcodeVideoChunkActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'transcodeVideoChunkActivity',
|
||||
}),
|
||||
deleteS3ObjectActivity: Object.assign(vi.fn(), {
|
||||
_activityName: 'deleteS3ObjectActivity',
|
||||
}),
|
||||
updateTaskStatusActivity: vi.mocked(workflowCore.updateTaskStatusActivity),
|
||||
getEmbeddingContextActivity: vi.mocked(aiActivities.getEmbeddingContextActivity),
|
||||
generateImageEmbeddingActivity: vi.mocked(aiActivities.generateImageEmbeddingActivity),
|
||||
generateVideoChunkEmbeddingActivity: vi.mocked(
|
||||
aiActivities.generateVideoChunkEmbeddingActivity,
|
||||
),
|
||||
saveAssetEmbeddingsActivity: vi.mocked(aiActivities.saveAssetEmbeddingsActivity),
|
||||
deleteAssetEmbeddingsActivity: vi.mocked(aiActivities.deleteAssetEmbeddingsActivity),
|
||||
updateTaskUsageActivity: vi.mocked(workflowCore.updateTaskUsageActivity),
|
||||
createCommentActivity: vi.mocked(agentActivities.createCommentActivity),
|
||||
updateCommentActivity: vi.mocked(agentActivities.updateCommentActivity),
|
||||
downloadMediaToTmpActivity: vi.fn(),
|
||||
cleanupTmpDirActivity: vi.fn(),
|
||||
transcodeVideoChunkActivity: vi.mocked(aiActivities.transcodeVideoChunkActivity),
|
||||
deleteS3ObjectActivity: vi.mocked(aiActivities.deleteS3ObjectActivity),
|
||||
}
|
||||
|
||||
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
|
||||
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue')
|
||||
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
|
||||
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
|
||||
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
|
||||
@@ -99,13 +98,6 @@ describe('Agent Embedding Workflow', () => {
|
||||
)
|
||||
mockActivities.deleteS3ObjectActivity.mockResolvedValue(undefined)
|
||||
mockActivities.cleanupTmpDirActivity.mockResolvedValue(undefined)
|
||||
|
||||
// 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)
|
||||
})
|
||||
})
|
||||
|
||||
it('should run agent embedding workflow successfully for image', async () => {
|
||||
@@ -124,9 +116,6 @@ describe('Agent Embedding Workflow', () => {
|
||||
|
||||
await agentEmbeddingMedia(task)
|
||||
|
||||
// Verify queue discovery
|
||||
expect(mockActivities.getAgentWorkerQueueActivity).toHaveBeenCalled()
|
||||
|
||||
// Verify task processing status
|
||||
expect(mockActivities.updateTaskStatusActivity).toHaveBeenCalledWith({
|
||||
taskId: task.id,
|
||||
@@ -307,9 +296,6 @@ describe('Agent Embedding Workflow', () => {
|
||||
|
||||
await agentEmbeddingMedia(task)
|
||||
|
||||
// Verify video transcode queue discovery
|
||||
expect(mockActivities.getTranscodeWorkerQueueActivity).toHaveBeenCalled()
|
||||
|
||||
// Verify video chunk slicing activity called 3 times on transcode queue
|
||||
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenCalledTimes(3)
|
||||
expect(mockActivities.transcodeVideoChunkActivity).toHaveBeenNthCalledWith(1, {
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
import { ApplicationFailure } from '@temporalio/workflow'
|
||||
import type { WorkflowTask } from '@shumai/db'
|
||||
import {
|
||||
getActivities,
|
||||
executeActivity,
|
||||
TaskQueueAgent,
|
||||
TaskQueueTranscode,
|
||||
ApplicationFailure,
|
||||
updateTaskStatusActivity,
|
||||
updateTaskUsageActivity,
|
||||
} from '@shumai/workflow-core'
|
||||
import { createCommentActivity, updateCommentActivity } from '../activities/agent'
|
||||
import {
|
||||
deleteAssetEmbeddingsActivity,
|
||||
deleteS3ObjectActivity,
|
||||
generateImageEmbeddingActivity,
|
||||
generateVideoChunkEmbeddingActivity,
|
||||
getEmbeddingContextActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
transcodeVideoChunkActivity,
|
||||
type ExistingAssetEmbeddingInfo,
|
||||
} from '../activities/ai'
|
||||
|
||||
export interface GeneratedEmbedding {
|
||||
embedding: number[]
|
||||
@@ -13,52 +22,21 @@ export interface GeneratedEmbedding {
|
||||
endTime?: number
|
||||
}
|
||||
|
||||
export interface ExistingAssetEmbeddingInfo {
|
||||
id: string
|
||||
startTime: number | null
|
||||
endTime: number | null
|
||||
has1536: boolean
|
||||
has768: boolean
|
||||
}
|
||||
export type { ExistingAssetEmbeddingInfo }
|
||||
|
||||
export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
const {
|
||||
updateTaskStatusActivity,
|
||||
getEmbeddingContextActivity,
|
||||
generateImageEmbeddingActivity,
|
||||
generateVideoChunkEmbeddingActivity,
|
||||
saveAssetEmbeddingsActivity,
|
||||
deleteAssetEmbeddingsActivity,
|
||||
updateTaskUsageActivity,
|
||||
createCommentActivity,
|
||||
updateCommentActivity,
|
||||
getAgentWorkerQueueActivity,
|
||||
getTranscodeWorkerQueueActivity,
|
||||
transcodeVideoChunkActivity,
|
||||
deleteS3ObjectActivity,
|
||||
} = getActivities()
|
||||
|
||||
let placeholderCommentId: string | undefined
|
||||
let agentWorkerQueue = ''
|
||||
let transcodeWorkerQueue: string
|
||||
|
||||
try {
|
||||
// 0. Discover queues
|
||||
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
|
||||
transcodeWorkerQueue = await executeActivity(
|
||||
TaskQueueTranscode,
|
||||
getTranscodeWorkerQueueActivity,
|
||||
)
|
||||
|
||||
// Update status to processing
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'processing',
|
||||
})
|
||||
|
||||
// 0. Create Placeholder Comment
|
||||
const payload = task.payload
|
||||
const placeholder = await executeActivity(agentWorkerQueue, createCommentActivity, {
|
||||
const placeholder = await createCommentActivity({
|
||||
assetId: task.assetId,
|
||||
message: '__EMBEDDING__',
|
||||
sessionId: payload?.agent?.sessionId || task.id,
|
||||
@@ -71,7 +49,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// 1. Fetch Agent Context
|
||||
const context = (await executeActivity(agentWorkerQueue, getEmbeddingContextActivity, {
|
||||
const context = (await getEmbeddingContextActivity({
|
||||
teamId: task.teamId,
|
||||
assetId: task.assetId,
|
||||
})) as unknown as {
|
||||
@@ -98,7 +76,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
.map((e) => e.id)
|
||||
|
||||
if (incompatibleIds.length > 0) {
|
||||
await executeActivity(agentWorkerQueue, deleteAssetEmbeddingsActivity, {
|
||||
await deleteAssetEmbeddingsActivity({
|
||||
assetId: task.assetId,
|
||||
ids: incompatibleIds,
|
||||
})
|
||||
@@ -160,12 +138,12 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
(e) => e.startTime === null && e.endTime === null,
|
||||
)
|
||||
if (!alreadyEmbedded) {
|
||||
const result = await executeActivity(agentWorkerQueue, generateImageEmbeddingActivity, {
|
||||
const result = await generateImageEmbeddingActivity({
|
||||
teamId: task.teamId,
|
||||
assetKey: embeddingKey,
|
||||
mediaType: embeddingMediaType,
|
||||
mediaType: embeddingMediaType || 'image/jpeg',
|
||||
})
|
||||
await executeActivity(agentWorkerQueue, saveAssetEmbeddingsActivity, {
|
||||
await saveAssetEmbeddingsActivity({
|
||||
assetId: task.assetId,
|
||||
embeddings: [{ embedding: result.embedding }],
|
||||
})
|
||||
@@ -206,7 +184,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Step A: Slice chunk on transcode worker and upload to S3
|
||||
const chunkRes = await executeActivity(transcodeWorkerQueue, transcodeVideoChunkActivity, {
|
||||
const chunkRes = await transcodeVideoChunkActivity({
|
||||
assetId: asset.id,
|
||||
assetKey: embeddingKey,
|
||||
startTime: start,
|
||||
@@ -217,17 +195,13 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
try {
|
||||
// Step B: Generate embedding on agent worker
|
||||
const chunkResult = await executeActivity(
|
||||
agentWorkerQueue,
|
||||
generateVideoChunkEmbeddingActivity,
|
||||
{
|
||||
teamId: task.teamId,
|
||||
chunkKey,
|
||||
},
|
||||
)
|
||||
const chunkResult = await generateVideoChunkEmbeddingActivity({
|
||||
teamId: task.teamId,
|
||||
chunkKey,
|
||||
})
|
||||
|
||||
// Step C: Save chunk embedding to database immediately
|
||||
await executeActivity(agentWorkerQueue, saveAssetEmbeddingsActivity, {
|
||||
await saveAssetEmbeddingsActivity({
|
||||
assetId: task.assetId,
|
||||
embeddings: [
|
||||
{
|
||||
@@ -244,7 +218,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
} finally {
|
||||
// Step D: Delete temporary chunk from S3
|
||||
await executeActivity(transcodeWorkerQueue, deleteS3ObjectActivity, {
|
||||
await deleteS3ObjectActivity({
|
||||
key: chunkKey,
|
||||
})
|
||||
}
|
||||
@@ -257,7 +231,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update Usage
|
||||
await executeActivity(agentWorkerQueue, updateTaskUsageActivity, {
|
||||
await updateTaskUsageActivity({
|
||||
taskId: task.id,
|
||||
inputTokens: usage.inputTokens,
|
||||
outputTokens: usage.outputTokens,
|
||||
@@ -266,14 +240,14 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
|
||||
// 7. Update Placeholder Comment
|
||||
if (placeholderCommentId) {
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: 'Embedding completed successfully.',
|
||||
})
|
||||
}
|
||||
|
||||
// Update status to completed
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'completed',
|
||||
})
|
||||
@@ -281,9 +255,9 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
console.error(`AgentEmbeddingMedia failed for task ${task.id}:`, err)
|
||||
|
||||
// Update placeholder comment with error message
|
||||
if (placeholderCommentId && agentWorkerQueue) {
|
||||
if (placeholderCommentId) {
|
||||
try {
|
||||
await executeActivity(agentWorkerQueue, updateCommentActivity, {
|
||||
await updateCommentActivity({
|
||||
commentId: placeholderCommentId,
|
||||
message: `Embedding failed: ${err instanceof Error ? err.message : String(err)}`,
|
||||
})
|
||||
@@ -293,13 +267,11 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
||||
}
|
||||
|
||||
// Update status to failed
|
||||
if (agentWorkerQueue) {
|
||||
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
}
|
||||
await updateTaskStatusActivity({
|
||||
taskId: task.id,
|
||||
status: 'failed',
|
||||
output: { error: err instanceof Error ? err.message : String(err) },
|
||||
})
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user