feat(dashboard): add workflow tasks monitoring and stopping to team dashboard (#489)

* feat(dashboard): add workflow tasks monitoring and stopping to team dashboard

* fix(asset): retain workflow tasks on asset purge and mark active tasks as failed

* style(webui): add edge padding to audit logs and workflow tasks tables

* fix(workflow): atomically update asset status to failed when task is stopped

* fix(workflow): propagate cancellation errors, guard concurrent task stop, and localize UI

* docs(changelog): keep only added log for workflow tasks dashboard

* test(provider): mock upstream catalog api calls using saved fixtures

* feat(dashboard): show file name, size, and project name in workflow tasks list
This commit is contained in:
Yiling-J
2026-10-23 16:44:52 +08:00
committed by GitHub
parent 7a0ffca629
commit d87fe43b0f
22 changed files with 2450 additions and 26 deletions
+6 -3
View File
@@ -3240,7 +3240,7 @@ describe('AssetService — natural sort by name', () => {
await expect(assetService.emptyTrash(project.id)).resolves.not.toThrow()
})
it('should purge trashed assets whose status was processed, cancel their in-flight tasks, and delete WorkflowTasks', async () => {
it('should purge trashed assets whose status was processed, cancel their in-flight tasks, and retain WorkflowTasks as failed', async () => {
const cancelSpy = vi.spyOn(workflowService, 'cancel').mockResolvedValue(undefined)
const team = await prisma.team.create({ data: { name: 'Purge Task Team' } })
@@ -3292,9 +3292,12 @@ describe('AssetService — natural sort by name', () => {
// Task should be cancelled
expect(cancelSpy).toHaveBeenCalledWith(task.id)
// WorkflowTask should be deleted from DB
// WorkflowTask should be retained in DB and marked as failed
const taskInDb = await prisma.workflowTask.findUnique({ where: { id: task.id } })
expect(taskInDb).toBeNull()
expect(taskInDb).not.toBeNull()
expect(taskInDb?.status).toBe(WorkflowTaskStatus.failed)
const output = taskInDb?.output as { error?: string }
expect(output?.error).toBe('Asset was purged')
cancelSpy.mockRestore()
})
+20 -2
View File
@@ -1419,6 +1419,17 @@ export class AssetService {
logger.warn({ taskId: task.id, err }, 'Failed to cancel workflow task during purge')
}
}
await this.prismaClient.workflowTask.updateMany({
where: {
assetId: { in: affectedIds },
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
data: {
status: WorkflowTaskStatus.failed,
output: { error: 'Asset was purged' },
},
})
}
}
@@ -1518,8 +1529,15 @@ export class AssetService {
}
}
await this.prismaClient.workflowTask.deleteMany({
where: { assetId: { in: pendingAssetIds } },
await this.prismaClient.workflowTask.updateMany({
where: {
assetId: { in: pendingAssetIds },
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
data: {
status: WorkflowTaskStatus.failed,
output: { error: 'Asset was purged' },
},
})
}
@@ -0,0 +1,54 @@
{
"anthropic": {
"models": {
"claude-3-5-sonnet-20241022": {
"id": "claude-3-5-sonnet-20241022",
"name": "Claude 3.5 Sonnet",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 200000,
"output": 8192
},
"cost": {
"input": 3,
"output": 15,
"cache_read": 0.3,
"cache_write": 3.75
}
}
}
},
"openai": {
"models": {
"gpt-4o": {
"id": "gpt-4o",
"name": "GPT-4o",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 128000,
"output": 4096
},
"cost": {
"input": 2.5,
"output": 10
}
},
"gpt-4o-extra-new": {
"id": "gpt-4o-extra-new",
"name": "GPT-4o Extra New",
"tool_call": true,
"reasoning": false,
"limit": {
"context": 128000,
"output": 4096
},
"cost": {
"input": 2.5,
"output": 10
}
}
}
}
}
@@ -0,0 +1,7 @@
{
"data": [
{
"id": "meta/llama-3.1-70b-instruct"
}
]
}
@@ -0,0 +1,17 @@
{
"data": [
{
"id": "meta-llama/llama-3.1-8b-instruct",
"name": "Meta: Llama 3.1 8B Instruct",
"context_length": 131072,
"pricing": {
"prompt": "0.00000005",
"completion": "0.00000008"
},
"top_provider": {
"max_completion_tokens": 8192
},
"supported_parameters": ["tools"]
}
]
}
+44 -6
View File
@@ -8,6 +8,42 @@ import * as generateModelsModule from './generator/generate-models'
import { ProviderConfigSerializable, providerModelSchema } from '@shumai/dtos'
import { getBuiltinProvidersMap } from '@shumai/core/src/provider/builtin'
import { z } from 'zod'
import modelsDevFixture from './fixtures/models-dev.json'
import openRouterFixture from './fixtures/openrouter.json'
import nvidiaFixture from './fixtures/nvidia.json'
const originalFetch = globalThis.fetch
function setupCatalogFetchMock() {
return vi.spyOn(globalThis, 'fetch').mockImplementation(async (input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url
if (url.includes('models.dev')) {
return new Response(JSON.stringify(modelsDevFixture), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
if (url.includes('openrouter.ai')) {
return new Response(JSON.stringify(openRouterFixture), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
if (url.includes('nvidia')) {
return new Response(JSON.stringify(nvidiaFixture), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
if (url.includes('ai-gateway')) {
return new Response(JSON.stringify({ data: [] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
}
return originalFetch(input)
})
}
type ProviderModel = z.infer<typeof providerModelSchema>
@@ -349,10 +385,9 @@ describe('ProviderService', () => {
expect((modelsAfterUpdate[1].config as { api: string }).api).toBe('anthropic-messages')
})
it(
'should check for updates and correctly segregate new vs existing providers',
{ timeout: 30000 },
async () => {
it('should check for updates and correctly segregate new vs existing providers', async () => {
const fetchSpy = setupCatalogFetchMock()
try {
// 1. Check updates with empty team: all discovered providers are new
const emptyTeam = await prisma.team.create({
data: { name: 'Empty Provider Team' },
@@ -368,6 +403,7 @@ describe('ProviderService', () => {
// 3. Check updates after init: existing providers should have isNewProvider: false
const afterInitCheck = await providerService.checkUpdates(teamWithBuiltins.id)
const existing = afterInitCheck.providers.find((p) => !p.isNewProvider)
expect(existing).toBeDefined()
if (existing) {
expect(existing.isNewProvider).toBe(false)
const dbModels = await providerService.listModelsByProvider(
@@ -381,8 +417,10 @@ describe('ProviderService', () => {
expect(dbModelIds.has(m.modelId)).toBe(false)
}
}
},
)
} finally {
fetchSpy.mockRestore()
}
})
it('should throw an error when upstream catalog fetch fails in checkUpdates', async () => {
const team = await teamService.ensureDefaultTeam()
@@ -0,0 +1,550 @@
import { describe, it, expect } from 'vitest'
import {
prisma,
WorkflowTaskStatus,
WorkflowTaskType,
AssetStatus,
registerWorkflowCancel,
} from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { HTTPException } from 'hono/http-exception'
import { workflowTaskService } from './workflowTask'
describe('WorkflowTaskService', () => {
setupTestDbHooks()
it('lists workflow tasks for a team with pagination and filters', async () => {
const team1 = await prisma.team.create({
data: { name: 'Workflow Team 1' },
})
const team2 = await prisma.team.create({
data: { name: 'Workflow Team 2' },
})
const project1 = await prisma.project.create({
data: { name: 'Project 1', teamId: team1.id },
})
const asset1 = await prisma.asset.create({
data: {
name: 'video1.mp4',
type: 'file',
sizeByte: 2048,
status: 'uploaded',
projectId: project1.id,
},
})
// Task 1: Team 1 direct
const task1 = await prisma.workflowTask.create({
data: {
assetId: asset1.id,
teamId: team1.id,
projectId: project1.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.completed,
},
})
// Task 2: Team 1 via project (teamId is null)
const task2 = await prisma.workflowTask.create({
data: {
assetId: asset1.id,
projectId: project1.id,
type: WorkflowTaskType.chat,
status: WorkflowTaskStatus.pending,
},
})
// Task 3: Team 2
await prisma.workflowTask.create({
data: {
assetId: 'other-asset',
teamId: team2.id,
type: WorkflowTaskType.transcode_image,
status: WorkflowTaskStatus.processing,
},
})
// 1. List all for Team 1
const listAll = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
})
expect(listAll.total).toBe(2)
expect(listAll.nodes).toHaveLength(2)
expect(listAll.nodes.map((n) => n.id)).toEqual([task2.id, task1.id]) // ordered by id desc
expect(listAll.nodes[0].fileName).toBe('video1.mp4')
expect(listAll.nodes[0].fileSize).toBe(2048)
expect(listAll.nodes[0].projectName).toBe('Project 1')
expect(listAll.nodes[0].projectId).toBe(project1.id)
expect(listAll.nodes[1].fileName).toBe('video1.mp4')
expect(listAll.nodes[1].fileSize).toBe(2048)
expect(listAll.nodes[1].projectName).toBe('Project 1')
// 2. Filter by status
const listPending = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
status: [WorkflowTaskStatus.pending],
})
expect(listPending.total).toBe(1)
expect(listPending.nodes[0].id).toBe(task2.id)
// 3. Filter by type
const listChat = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
types: [WorkflowTaskType.chat],
})
expect(listChat.total).toBe(1)
expect(listChat.nodes[0].id).toBe(task2.id)
// 4. Pagination
const page1 = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
first: 1,
})
expect(page1.nodes).toHaveLength(1)
expect(page1.nodes[0].id).toBe(task2.id)
expect(page1.pageInfo.hasNextPage).toBe(true)
const page2 = await workflowTaskService.listWorkflowTasks({
teamId: team1.id,
first: 1,
after: page1.pageInfo.endCursor!,
})
expect(page2.nodes).toHaveLength(1)
expect(page2.nodes[0].id).toBe(task1.id)
})
it('gets batch status for specific task IDs with team security', async () => {
const team1 = await prisma.team.create({
data: { name: 'Batch Team 1' },
})
const team2 = await prisma.team.create({
data: { name: 'Batch Team 2' },
})
const task1 = await prisma.workflowTask.create({
data: {
assetId: 'a1',
teamId: team1.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
const task2 = await prisma.workflowTask.create({
data: {
assetId: 'a2',
teamId: team2.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
// Query empty
const empty = await workflowTaskService.getBatchWorkflowTaskStatus({
teamId: team1.id,
taskIds: [],
})
expect(empty.tasks).toEqual([])
// Query both task1 and task2 under team1
const res = await workflowTaskService.getBatchWorkflowTaskStatus({
teamId: team1.id,
taskIds: [task1.id, task2.id],
})
// task2 should be excluded because it belongs to team2
expect(res.tasks).toHaveLength(1)
expect(res.tasks[0].id).toBe(task1.id)
expect(res.tasks[0].status).toBe(WorkflowTaskStatus.processing)
})
it('stops a pending or processing task successfully', async () => {
const team = await prisma.team.create({
data: { name: 'Stop Team' },
})
const pendingTask = await prisma.workflowTask.create({
data: {
assetId: 'asset-pending',
teamId: team.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.pending,
payload: { projectId: 'p1' },
},
})
const processingTask = await prisma.workflowTask.create({
data: {
assetId: 'asset-processing',
teamId: team.id,
type: WorkflowTaskType.ai_metadata_autofill,
status: WorkflowTaskStatus.processing,
},
})
// Stop pending task
const stopPendingRes = await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: pendingTask.id,
})
expect(stopPendingRes.success).toBe(true)
expect(stopPendingRes.task.status).toBe(WorkflowTaskStatus.failed)
const pendingOutput = stopPendingRes.task.output as { error: string }
expect(pendingOutput.error).toBe('Task was stopped by user')
// Stop processing task
const stopProcessingRes = await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: processingTask.id,
})
expect(stopProcessingRes.success).toBe(true)
expect(stopProcessingRes.task.status).toBe(WorkflowTaskStatus.failed)
})
it('updates associated asset status to failed atomically when task is stopped', async () => {
const team = await prisma.team.create({
data: { name: 'Asset Stop Team' },
})
const project = await prisma.project.create({
data: { name: 'Asset Stop Project', teamId: team.id },
})
// Asset 1: currently uploaded (e.g. pending transcode)
const asset1 = await prisma.asset.create({
data: {
name: 'pending-video.mp4',
type: 'file',
status: AssetStatus.uploaded,
projectId: project.id,
media: {
duration: 120,
filesize: 1000,
frames: 3000,
imageTranscodes: [],
videoTranscodes: [],
finishedAt: '',
metadata: null,
original: null,
},
},
})
const task1 = await prisma.workflowTask.create({
data: {
assetId: asset1.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.pending,
},
})
// Asset 2: already processed (media finished)
const asset2 = await prisma.asset.create({
data: {
name: 'completed-video.mp4',
type: 'file',
status: AssetStatus.processed,
projectId: project.id,
media: {
duration: 60,
filesize: 500,
frames: 1500,
imageTranscodes: [],
videoTranscodes: [],
finishedAt: '2026-01-01',
metadata: null,
original: null,
},
},
})
const task2 = await prisma.workflowTask.create({
data: {
assetId: asset2.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.ai_metadata_autofill,
status: WorkflowTaskStatus.processing,
},
})
// Stop task 1 (pending transcode)
await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: task1.id,
})
const updatedAsset1 = await prisma.asset.findUniqueOrThrow({
where: { id: asset1.id },
})
expect(updatedAsset1.status).toBe(AssetStatus.failed)
const media1 = updatedAsset1.media as PrismaJson.MediaInfo
expect(media1.duration).toBe(120) // preserved other json properties
expect(media1.filesize).toBe(1000)
expect(media1.error).toBe('Task was stopped by user')
// Stop task 2 (asset already processed)
await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: task2.id,
})
const updatedAsset2 = await prisma.asset.findUniqueOrThrow({
where: { id: asset2.id },
})
// Must NOT be overwritten to failed
expect(updatedAsset2.status).toBe(AssetStatus.processed)
const media2 = updatedAsset2.media as PrismaJson.MediaInfo
expect(media2.duration).toBe(60)
expect(media2.error).toBeUndefined()
})
it('throws 400 when attempting to stop completed or failed task', async () => {
const team = await prisma.team.create({
data: { name: 'Stop Error Team' },
})
const completedTask = await prisma.workflowTask.create({
data: {
assetId: 'asset-completed',
teamId: team.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.completed,
},
})
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: completedTask.id,
}),
).rejects.toThrow(HTTPException)
})
it('throws 404 when stopping non-existent task and 403 when task belongs to other team', async () => {
const team1 = await prisma.team.create({
data: { name: 'Team 1' },
})
const team2 = await prisma.team.create({
data: { name: 'Team 2' },
})
const task2 = await prisma.workflowTask.create({
data: {
assetId: 'asset-team2',
teamId: team2.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.pending,
},
})
// Non-existent task
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team1.id,
taskId: 'non-existent-task-id',
}),
).rejects.toThrow(HTTPException)
// Task belongs to team 2
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team1.id,
taskId: task2.id,
}),
).rejects.toThrow(HTTPException)
})
it('throws 502 and does not modify task or asset when workflow cancellation fails', async () => {
const team = await prisma.team.create({
data: { name: 'Cancel Fail Team' },
})
const project = await prisma.project.create({
data: { name: 'Cancel Fail Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'fail-cancel.mp4',
type: 'file',
status: AssetStatus.processing,
projectId: project.id,
},
})
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
registerWorkflowCancel(async () => {
throw new Error('DBOS connection failure')
})
try {
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: task.id,
}),
).rejects.toMatchObject({ status: 502 })
// Verify task status was NOT changed to failed
const currentTask = await prisma.workflowTask.findUniqueOrThrow({
where: { id: task.id },
})
expect(currentTask.status).toBe(WorkflowTaskStatus.processing)
// Verify asset status was NOT changed to failed
const currentAsset = await prisma.asset.findUniqueOrThrow({
where: { id: asset.id },
})
expect(currentAsset.status).toBe(AssetStatus.processing)
} finally {
registerWorkflowCancel(async () => {})
}
})
it('throws 409 and does not overwrite status when task completes during cancellation', async () => {
const team = await prisma.team.create({
data: { name: 'Race Team' },
})
const project = await prisma.project.create({
data: { name: 'Race Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'race.mp4',
type: 'file',
status: AssetStatus.processing,
projectId: project.id,
},
})
const task = await prisma.workflowTask.create({
data: {
assetId: asset.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.processing,
},
})
// Simulate task completing in the background while cancelWorkflowTask is awaiting
registerWorkflowCancel(async () => {
await prisma.workflowTask.update({
where: { id: task.id },
data: { status: WorkflowTaskStatus.completed },
})
await prisma.asset.update({
where: { id: asset.id },
data: { status: AssetStatus.processed },
})
})
try {
await expect(
workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: task.id,
}),
).rejects.toMatchObject({ status: 409 })
// Verify task remains completed, not overwritten to failed
const currentTask = await prisma.workflowTask.findUniqueOrThrow({
where: { id: task.id },
})
expect(currentTask.status).toBe(WorkflowTaskStatus.completed)
// Verify asset remains processed, not overwritten to failed
const currentAsset = await prisma.asset.findUniqueOrThrow({
where: { id: asset.id },
})
expect(currentAsset.status).toBe(AssetStatus.processed)
} finally {
registerWorkflowCancel(async () => {})
}
})
it('enriches tasks with fileName, fileSize, and projectName, and handles purged assets gracefully', async () => {
const team = await prisma.team.create({
data: { name: 'Enrich Team' },
})
const project = await prisma.project.create({
data: { name: 'Enrich Project', teamId: team.id },
})
const asset = await prisma.asset.create({
data: {
name: 'sample_audio.mp3',
type: 'file',
sizeByte: 5242880,
status: 'uploaded',
projectId: project.id,
},
})
const taskWithAsset = await prisma.workflowTask.create({
data: {
assetId: asset.id,
teamId: team.id,
projectId: project.id,
type: WorkflowTaskType.transcode_video,
status: WorkflowTaskStatus.pending,
},
})
const taskWithPurgedAsset = await prisma.workflowTask.create({
data: {
assetId: 'purged-asset-id',
teamId: team.id,
type: WorkflowTaskType.transcode_image,
status: WorkflowTaskStatus.completed,
},
})
const listRes = await workflowTaskService.listWorkflowTasks({ teamId: team.id })
expect(listRes.total).toBe(2)
const foundActive = listRes.nodes.find((n) => n.id === taskWithAsset.id)
expect(foundActive).toBeDefined()
expect(foundActive?.fileName).toBe('sample_audio.mp3')
expect(foundActive?.fileSize).toBe(5242880)
expect(foundActive?.projectName).toBe('Enrich Project')
expect(foundActive?.projectId).toBe(project.id)
const foundPurged = listRes.nodes.find((n) => n.id === taskWithPurgedAsset.id)
expect(foundPurged).toBeDefined()
expect(foundPurged?.fileName).toBeNull()
expect(foundPurged?.fileSize).toBeNull()
expect(foundPurged?.projectName).toBeNull()
// Test batch status enrichment
const batchRes = await workflowTaskService.getBatchWorkflowTaskStatus({
teamId: team.id,
taskIds: [taskWithAsset.id, taskWithPurgedAsset.id],
})
expect(batchRes.tasks).toHaveLength(2)
const batchActive = batchRes.tasks.find((t) => t.id === taskWithAsset.id)
expect(batchActive?.fileName).toBe('sample_audio.mp3')
expect(batchActive?.fileSize).toBe(5242880)
expect(batchActive?.projectName).toBe('Enrich Project')
// Test stopWorkflowTask enrichment
const stopRes = await workflowTaskService.stopWorkflowTask({
teamId: team.id,
taskId: taskWithAsset.id,
})
expect(stopRes.success).toBe(true)
expect(stopRes.task.fileName).toBe('sample_audio.mp3')
expect(stopRes.task.fileSize).toBe(5242880)
expect(stopRes.task.projectName).toBe('Enrich Project')
})
})
@@ -0,0 +1,330 @@
import {
prisma,
cancelWorkflowTask,
WorkflowTaskStatus,
type WorkflowTaskType,
type Prisma,
} from '@shumai/db'
import type { WorkflowTaskItem, ListWorkflowTasksResponse } from '@shumai/dtos'
import { paginateQuery } from '@shumai/core/src/pagination'
import { logger } from '@shumai/core/src/logger'
import { HTTPException } from 'hono/http-exception'
export interface ListWorkflowTasksParams {
teamId: string
status?: WorkflowTaskStatus[]
types?: WorkflowTaskType[]
first?: number
after?: string
}
export interface StopWorkflowTaskParams {
teamId: string
taskId: string
}
export interface GetBatchWorkflowTaskStatusParams {
teamId: string
taskIds: string[]
}
interface EnrichedMetadata {
fileName?: string | null
fileSize?: number | null
projectId?: string | null
projectName?: string | null
}
function mapToWorkflowTaskItem(
task: {
id: string
uid: string
teamId: string | null
projectId: string | null
assetId: string
type: WorkflowTaskType | null
status: WorkflowTaskStatus | null
payload: unknown
output: unknown
heartbeat: Date | null
inputTokens: number
outputTokens: number
model: string | null
sessionId: string | null
createdAt: Date
updatedAt: Date
},
extra?: EnrichedMetadata,
): WorkflowTaskItem {
return {
id: task.id,
uid: task.uid,
teamId: task.teamId,
projectId: extra?.projectId !== undefined ? extra.projectId : task.projectId,
projectName: extra?.projectName ?? null,
assetId: task.assetId,
fileName: extra?.fileName ?? null,
fileSize: extra?.fileSize ?? null,
type: task.type,
status: task.status,
payload: task.payload,
output: task.output,
heartbeat: task.heartbeat ? task.heartbeat.toISOString() : null,
inputTokens: task.inputTokens,
outputTokens: task.outputTokens,
model: task.model,
sessionId: task.sessionId,
createdAt: task.createdAt.toISOString(),
updatedAt: task.updatedAt.toISOString(),
}
}
export class WorkflowTaskService {
private async enrichWorkflowTasks<
T extends {
id: string
uid: string
teamId: string | null
projectId: string | null
assetId: string
type: WorkflowTaskType | null
status: WorkflowTaskStatus | null
payload: unknown
output: unknown
heartbeat: Date | null
inputTokens: number
outputTokens: number
model: string | null
sessionId: string | null
createdAt: Date
updatedAt: Date
},
>(tasks: T[]): Promise<WorkflowTaskItem[]> {
if (tasks.length === 0) {
return []
}
const assetIds = [...new Set(tasks.map((t) => t.assetId).filter(Boolean))]
const assets =
assetIds.length > 0
? await prisma.asset.findMany({
where: { id: { in: assetIds } },
select: { id: true, name: true, sizeByte: true, projectId: true },
})
: []
const assetMap = new Map(assets.map((a) => [a.id, a]))
const allProjectIds = [
...new Set(
[...tasks.map((t) => t.projectId), ...assets.map((a) => a.projectId)].filter(
(id): id is string => Boolean(id),
),
),
]
const projects =
allProjectIds.length > 0
? await prisma.project.findMany({
where: { id: { in: allProjectIds } },
select: { id: true, name: true },
})
: []
const projectMap = new Map(projects.map((p) => [p.id, p.name]))
return tasks.map((task) => {
const asset = assetMap.get(task.assetId)
const effectiveProjectId = task.projectId || asset?.projectId || null
const projectName = effectiveProjectId ? (projectMap.get(effectiveProjectId) ?? null) : null
const fileName = asset?.name ?? null
const fileSize = asset ? Number(asset.sizeByte) : null
return mapToWorkflowTaskItem(task, {
fileName,
fileSize,
projectId: effectiveProjectId,
projectName,
})
})
}
async listWorkflowTasks(params: ListWorkflowTasksParams): Promise<ListWorkflowTasksResponse> {
const teamProjects = await prisma.project.findMany({
where: { teamId: params.teamId },
select: { id: true },
})
const projectIds = teamProjects.map((p) => p.id)
const where: Prisma.WorkflowTaskWhereInput = {
OR: [
{ teamId: params.teamId },
...(projectIds.length > 0 ? [{ projectId: { in: projectIds } }] : []),
],
}
if (params.status && params.status.length > 0) {
where.status = { in: params.status }
}
if (params.types && params.types.length > 0) {
where.type = { in: params.types }
}
const result = await paginateQuery(
(skip, take) =>
prisma.workflowTask.findMany({
where,
orderBy: { id: 'desc' },
skip,
take,
}),
() => prisma.workflowTask.count({ where }),
{ first: params.first, after: params.after },
)
const nodes = await this.enrichWorkflowTasks(result.data)
return {
nodes,
pageInfo: {
hasNextPage: !!result.pageInfo.cursor,
endCursor: result.pageInfo.cursor || null,
},
total: result.pageInfo.total ?? 0,
}
}
async getBatchWorkflowTaskStatus(
params: GetBatchWorkflowTaskStatusParams,
): Promise<{ tasks: WorkflowTaskItem[] }> {
if (!params.taskIds || params.taskIds.length === 0) {
return { tasks: [] }
}
const teamProjects = await prisma.project.findMany({
where: { teamId: params.teamId },
select: { id: true },
})
const projectIds = teamProjects.map((p) => p.id)
const tasks = await prisma.workflowTask.findMany({
where: {
id: { in: params.taskIds },
OR: [
{ teamId: params.teamId },
...(projectIds.length > 0 ? [{ projectId: { in: projectIds } }] : []),
],
},
orderBy: { id: 'desc' },
})
const enriched = await this.enrichWorkflowTasks(tasks)
return { tasks: enriched }
}
async stopWorkflowTask(
params: StopWorkflowTaskParams,
): Promise<{ success: boolean; task: WorkflowTaskItem }> {
const task = await prisma.workflowTask.findUnique({
where: { id: params.taskId },
})
if (!task) {
throw new HTTPException(404, { message: 'Workflow task not found' })
}
// Verify task belongs to this team (either directly or via project)
let belongsToTeam = task.teamId === params.teamId
if (!belongsToTeam && task.projectId) {
const project = await prisma.project.findUnique({
where: { id: task.projectId },
select: { teamId: true },
})
if (project?.teamId === params.teamId) {
belongsToTeam = true
}
}
if (!belongsToTeam) {
throw new HTTPException(403, { message: 'Permission denied: Task does not belong to team' })
}
if (
task.status !== WorkflowTaskStatus.pending &&
task.status !== WorkflowTaskStatus.processing
) {
throw new HTTPException(400, {
message: `Only pending or processing tasks can be stopped. Current status: ${task.status}`,
})
}
// Notify workflow engine (DBOS) to cancel workflow execution
try {
await cancelWorkflowTask(task.id)
} catch (err) {
logger.error({ taskId: task.id, err }, 'Failed to cancel workflow task in workflow engine')
throw new HTTPException(502, {
message: `Failed to cancel workflow task in engine: ${err instanceof Error ? err.message : String(err)}`,
})
}
const errorMsg = 'Task was stopped by user'
const prevOutput =
typeof task.output === 'object' && task.output !== null
? (task.output as Record<string, unknown>)
: {}
const updated = await prisma.$transaction(async (tx) => {
const updateResult = await tx.workflowTask.updateMany({
where: {
id: task.id,
status: { in: [WorkflowTaskStatus.pending, WorkflowTaskStatus.processing] },
},
data: {
status: WorkflowTaskStatus.failed,
output: {
...prevOutput,
error: errorMsg,
},
},
})
if (updateResult.count === 0) {
const latestTask = await tx.workflowTask.findUniqueOrThrow({
where: { id: task.id },
})
throw new HTTPException(409, {
message: `Task is no longer active. Current status: ${latestTask.status}`,
})
}
if (task.assetId) {
await tx.$executeRaw`
UPDATE "assets"
SET
"status" = 'failed'::"AssetStatus",
"media" = COALESCE("media", '{}'::jsonb) || jsonb_build_object('error', ${errorMsg}::text)
WHERE "id" = ${task.assetId}
AND "is_deleted" = false
AND "status" != 'processed'::"AssetStatus"
`
}
return await tx.workflowTask.findUniqueOrThrow({
where: { id: task.id },
})
})
logger.info({ taskId: task.id, teamId: params.teamId }, 'Workflow task stopped by user')
const [enriched] = await this.enrichWorkflowTasks([updated])
return {
success: true,
task: enriched,
}
}
}
export const workflowTaskService = new WorkflowTaskService()