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.
This commit is contained in:
yiling
2026-10-17 15:50:17 +08:00
parent f7ed3bafdf
commit 97af81d157
65 changed files with 4397 additions and 5933 deletions
+30 -46
View File
@@ -23,8 +23,7 @@ import {
import * as piAgent from '../index'
import { type AgentHarness, type Session } from '@earendil-works/pi-agent-core'
import { DatabaseSessionStorage, type DatabaseSessionMetadata } from '../database-session-storage'
import { triggerLocalCancel } from '@shumai/workflow-core'
import { Context } from '@temporalio/activity'
import { triggerLocalCancel, runInLocalTaskContext } from '@shumai/workflow-core'
import { logger } from '@shumai/core/src/logger'
import {
@@ -50,9 +49,6 @@ vi.mock('../index', async () => {
describe('Agent Activities', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.spyOn(Context, 'current').mockImplementation(() => {
throw new Error('Not in Temporal')
})
})
it('should call agentChatActivity and prompt the harness', async () => {
@@ -240,13 +236,7 @@ describe('Agent Activities', () => {
await executionPromise
})
it('should listen to Temporal cancellation signal and call harness.abort when cancelled in Temporal mode', async () => {
const mockTemporalContext = {
cancellationSignal: new EventTarget(),
heartbeat: vi.fn(),
} as unknown as Context
vi.spyOn(Context, 'current').mockReturnValue(mockTemporalContext)
it('should listen to abort signal and call harness.abort when cancelled', async () => {
let resolvePrompt!: (value: {
content: Array<{ type: string; text: string } | { type: string }>
usage: { input: number; output: number }
@@ -280,42 +270,36 @@ describe('Agent Activities', () => {
allowedDomains: [],
} as unknown as AgentExecutionContext
const addEventListenerSpy = vi.spyOn(mockTemporalContext.cancellationSignal, 'addEventListener')
const removeEventListenerSpy = vi.spyOn(
mockTemporalContext.cancellationSignal,
'removeEventListener',
)
const taskId = 'test-abort-task'
const abortController = new AbortController()
const executionPromise = agentChatActivity({
teamId: 't1',
agentId: 'b1',
message: 'Hi',
imageUrls: [],
projectId: 'p1',
folderId: 'f1',
sessionId: 'mock-session-id',
context,
await runInLocalTaskContext({ taskId, abortController }, async () => {
const executionPromise = agentChatActivity({
taskId,
teamId: 't1',
agentId: 'b1',
message: 'Hi',
imageUrls: [],
projectId: 'p1',
folderId: 'f1',
sessionId: 'mock-session-id',
context,
})
// Yield to let the asynchronous setup add the abort event listener
await new Promise((resolve) => setTimeout(resolve, 50))
abortController.abort()
expect(mockHarness.abort).toHaveBeenCalled()
// Resolve the prompt promise to allow the activity to finish clean
resolvePrompt({
content: [{ type: 'text', text: 'AI response' }],
usage: { input: 10, output: 20 },
})
await executionPromise
})
// Yield to let the asynchronous setup add the abort event listener
await new Promise((resolve) => setTimeout(resolve, 50))
expect(addEventListenerSpy).toHaveBeenCalledWith('abort', expect.any(Function), { once: true })
// Simulate Temporal cancellation event
mockTemporalContext.cancellationSignal.dispatchEvent(new Event('abort'))
expect(mockHarness.abort).toHaveBeenCalled()
// Resolve the prompt promise to allow the activity to finish clean
resolvePrompt({
content: [{ type: 'text', text: 'AI response' }],
usage: { input: 10, output: 20 },
})
await executionPromise
expect(removeEventListenerSpy).toHaveBeenCalledWith('abort', expect.any(Function))
addEventListenerSpy.mockRestore()
removeEventListenerSpy.mockRestore()
})
it('should include error message in text when stopReason is error', async () => {
+15 -26
View File
@@ -8,8 +8,12 @@ import { metadataService } from '@shumai/core/src/metadata/metadata'
import { s3Service } from '@shumai/core/src/s3/s3'
import { getAgentRequiredLevel, getRoleLevel } from '@shumai/core/src/agent/permissions'
import { AssetType, prisma, Prisma, type Skill } from '@shumai/db'
import { registerLocalCancelHandler, unregisterLocalCancelHandler } from '@shumai/workflow-core'
import { ApplicationFailure, Context } from '@temporalio/activity'
import {
ApplicationFailure,
getLocalTaskAbortSignal,
registerLocalCancelHandler,
unregisterLocalCancelHandler,
} from '@shumai/workflow-core'
import { DatabaseSessionStorage } from '../database-session-storage'
import {
createAgentSession,
@@ -248,29 +252,17 @@ User messages may contain a <context> block detailing the user, active asset loc
}
}
let heartbeatInterval: ReturnType<typeof setInterval> | null = null
const onAbort = () => {
harness.abort()
}
let temporalSignal: EventTarget | undefined
try {
temporalSignal = Context.current().cancellationSignal
} catch {
// Ignore
}
if (temporalSignal) {
temporalSignal.addEventListener('abort', onAbort, { once: true })
heartbeatInterval = setInterval(() => {
try {
Context.current().heartbeat()
} catch (err) {
logger.debug({ err }, 'Failed to send activity heartbeat')
}
}, 2000)
const abortSignal = getLocalTaskAbortSignal(params.taskId)
if (abortSignal) {
if (abortSignal.aborted) {
harness.abort()
} else {
abortSignal.addEventListener('abort', onAbort, { once: true })
}
} else if (params.taskId) {
registerLocalCancelHandler(params.taskId, () => {
harness.abort()
@@ -457,11 +449,8 @@ User messages may contain a <context> block detailing the user, active asset loc
}
return { text, usage, sessionId }
} finally {
if (heartbeatInterval) {
clearInterval(heartbeatInterval)
}
if (temporalSignal) {
temporalSignal.removeEventListener('abort', onAbort)
if (abortSignal) {
abortSignal.removeEventListener('abort', onAbort)
}
if (params.taskId) {
unregisterLocalCancelHandler(params.taskId)
+1 -1
View File
@@ -3,7 +3,7 @@ import { s3Service } from '@shumai/core/src/s3/s3'
import { transcodeService } from '@shumai/core'
import * as fs from 'fs'
import * as path from 'path'
import { ApplicationFailure } from '@temporalio/activity'
import { ApplicationFailure } from '@shumai/workflow-core'
import { prisma } from '@shumai/db'
import sharp from 'sharp'
@@ -43,12 +43,8 @@ describe('Agent Autofill Workflow', () => {
}),
createCommentActivity: Object.assign(vi.fn(), { _activityName: 'createCommentActivity' }),
updateCommentActivity: Object.assign(vi.fn(), { _activityName: 'updateCommentActivity' }),
getAgentWorkerQueueActivity: Object.assign(vi.fn(), {
_activityName: 'getAgentWorkerQueueActivity',
}),
}
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
mockActivities.getAssetActivity.mockResolvedValue({
@@ -93,9 +89,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,6 +1,10 @@
import type { WorkflowTask } from '@shumai/db'
import { executeActivity, getActivities, TaskQueueAgent } from '@shumai/workflow-core'
import { ApplicationFailure } from '@temporalio/workflow'
import {
ApplicationFailure,
executeActivity,
getActivities,
TaskQueueAgent,
} from '@shumai/workflow-core'
import { getProxyType } from '@shumai/core/src/utils/mime'
export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
@@ -14,16 +18,12 @@ export async function agentAutofillMedia(task: WorkflowTask): Promise<void> {
updateAssetMetadataActivity,
createCommentActivity,
updateCommentActivity,
getAgentWorkerQueueActivity,
} = getActivities()
let placeholderCommentId: string | undefined
let agentWorkerQueue = ''
const agentWorkerQueue = TaskQueueAgent
try {
// 0. Discover queues
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
// Update status to processing
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
taskId: task.id,
@@ -35,9 +35,6 @@ describe('Agent Chat Workflow', () => {
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' }),
@@ -56,7 +53,6 @@ describe('Agent Chat Workflow', () => {
}),
}
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
mockActivities.generateSessionNameActivity.mockResolvedValue(undefined)
@@ -116,9 +112,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,
+7 -7
View File
@@ -1,6 +1,10 @@
import { ApplicationFailure } from '@temporalio/workflow'
import type { WorkflowTask } from '@shumai/db'
import { executeActivity, getActivities, TaskQueueAgent } from '@shumai/workflow-core'
import {
ApplicationFailure,
executeActivity,
getActivities,
TaskQueueAgent,
} from '@shumai/workflow-core'
import type {
ShumaiMessageContext,
ShumaiAssetContext,
@@ -20,7 +24,6 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
createCommentActivity,
updateCommentActivity,
updateTaskUsageActivity,
getAgentWorkerQueueActivity,
initializeAgentSessionActivity,
getAssetPathHierarchyActivity,
getAssetPathContextActivity,
@@ -29,12 +32,9 @@ export async function agentChat(task: WorkflowTask): Promise<void> {
} = getActivities()
let placeholderCommentId: string | undefined
let agentWorkerQueue = ''
const agentWorkerQueue = TaskQueueAgent
try {
// 0. Discover queue
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
// Update status to processing
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
taskId: task.id,
@@ -44,12 +44,6 @@ describe('Agent Embedding Workflow', () => {
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',
}),
@@ -64,8 +58,6 @@ describe('Agent Embedding Workflow', () => {
}),
}
mockActivities.getAgentWorkerQueueActivity.mockResolvedValue('agent_queue')
mockActivities.getTranscodeWorkerQueueActivity.mockResolvedValue('transcode_queue')
mockActivities.updateTaskStatusActivity.mockResolvedValue({})
mockActivities.createCommentActivity.mockResolvedValue({ id: 'comment-placeholder-id' })
mockActivities.getEmbeddingContextActivity.mockResolvedValue({
@@ -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,6 +1,6 @@
import { ApplicationFailure } from '@temporalio/workflow'
import type { WorkflowTask } from '@shumai/db'
import {
ApplicationFailure,
getActivities,
executeActivity,
TaskQueueAgent,
@@ -32,24 +32,15 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
updateTaskUsageActivity,
createCommentActivity,
updateCommentActivity,
getAgentWorkerQueueActivity,
getTranscodeWorkerQueueActivity,
transcodeVideoChunkActivity,
deleteS3ObjectActivity,
} = getActivities()
let placeholderCommentId: string | undefined
let agentWorkerQueue = ''
let transcodeWorkerQueue: string
const agentWorkerQueue = TaskQueueAgent
const transcodeWorkerQueue = TaskQueueTranscode
try {
// 0. Discover queues
agentWorkerQueue = await executeActivity(TaskQueueAgent, getAgentWorkerQueueActivity)
transcodeWorkerQueue = await executeActivity(
TaskQueueTranscode,
getTranscodeWorkerQueueActivity,
)
// Update status to processing
await executeActivity(agentWorkerQueue, updateTaskStatusActivity, {
taskId: task.id,