mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-19 14:16:29 +00:00
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:
+1
-3
@@ -8,9 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Added
|
||||
|
||||
### Fixed
|
||||
|
||||
### Changed
|
||||
* **dashboard**: Add Workflow Tasks section to the Team Dashboard allowing team owners to monitor background workflow jobs, inspect execution payloads and outputs, and stop in-flight tasks
|
||||
|
||||
## [0.6.0] - 2026-10-20
|
||||
|
||||
|
||||
@@ -68,6 +68,14 @@ vi.mock('@shumai/core/src/gotenberg/gotenberg', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/workflowTask/workflowTask', () => ({
|
||||
workflowTaskService: {
|
||||
listWorkflowTasks: vi.fn(),
|
||||
getBatchWorkflowTaskStatus: vi.fn(),
|
||||
stopWorkflowTask: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('team api', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
|
||||
let mockCreateTeam: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
@@ -655,6 +663,129 @@ describe('team api', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/workflow-tasks returns list of workflow tasks for team owner', async () => {
|
||||
const { workflowTaskService } = await import('@shumai/core/src/workflowTask/workflowTask')
|
||||
vi.mocked(workflowTaskService.listWorkflowTasks).mockResolvedValue({
|
||||
nodes: [
|
||||
{
|
||||
id: 'task1',
|
||||
uid: 'uid1',
|
||||
teamId: 't1',
|
||||
projectId: 'p1',
|
||||
assetId: 'a1',
|
||||
type: 'transcode_video' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
status: 'processing' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
payload: {},
|
||||
output: null,
|
||||
heartbeat: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
model: null,
|
||||
sessionId: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
pageInfo: {
|
||||
hasNextPage: false,
|
||||
endCursor: null,
|
||||
},
|
||||
total: 1,
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/workflow-tasks')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.nodes).toHaveLength(1)
|
||||
expect(data.nodes[0].id).toBe('task1')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/workflow-tasks/batch-status returns batch task statuses', async () => {
|
||||
const { workflowTaskService } = await import('@shumai/core/src/workflowTask/workflowTask')
|
||||
vi.mocked(workflowTaskService.getBatchWorkflowTaskStatus).mockResolvedValue({
|
||||
tasks: [
|
||||
{
|
||||
id: 'task1',
|
||||
uid: 'uid1',
|
||||
teamId: 't1',
|
||||
projectId: 'p1',
|
||||
assetId: 'a1',
|
||||
type: 'transcode_video' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
status: 'completed' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
payload: {},
|
||||
output: null,
|
||||
heartbeat: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
model: null,
|
||||
sessionId: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/workflow-tasks/batch-status', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ taskIds: ['task1'] }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.tasks).toHaveLength(1)
|
||||
expect(data.tasks[0].status).toBe('completed')
|
||||
})
|
||||
|
||||
it('POST /teams/:teamId/workflow-tasks/:taskId/stop stops task for team owner', async () => {
|
||||
const { workflowTaskService } = await import('@shumai/core/src/workflowTask/workflowTask')
|
||||
vi.mocked(workflowTaskService.stopWorkflowTask).mockResolvedValue({
|
||||
success: true,
|
||||
task: {
|
||||
id: 'task1',
|
||||
uid: 'uid1',
|
||||
teamId: 't1',
|
||||
projectId: 'p1',
|
||||
assetId: 'a1',
|
||||
type: 'transcode_video' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
status: 'failed' as any, // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
payload: {},
|
||||
output: { error: 'Task was stopped by user' },
|
||||
heartbeat: null,
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
model: null,
|
||||
sessionId: null,
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/workflow-tasks/task1/stop', {
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.success).toBe(true)
|
||||
expect(data.task.status).toBe('failed')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/turntable-settings returns turntable settings', async () => {
|
||||
const { turntableService } = await import('@shumai/core/src/turntable/turntable')
|
||||
vi.mocked(turntableService.getSettings).mockResolvedValue({
|
||||
|
||||
@@ -16,6 +16,8 @@ import {
|
||||
updateTeamMemberRoleRequestSchema,
|
||||
createApiTokenRequestSchema,
|
||||
listAuditLogsQuerySchema,
|
||||
listWorkflowTasksQuerySchema,
|
||||
batchWorkflowTaskStatusSchema,
|
||||
} from '@shumai/dtos'
|
||||
import {
|
||||
updateUserMetadataRequestSchema,
|
||||
@@ -25,6 +27,7 @@ import {
|
||||
import { apiTokenService } from '@shumai/core/src/user/api-token'
|
||||
import { aiUsageService } from '@shumai/core/src/ai-usage/ai-usage'
|
||||
import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import { workflowTaskService } from '@shumai/core/src/workflowTask/workflowTask'
|
||||
import { turntableService } from '@shumai/core/src/turntable/turntable'
|
||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||
import { NotificationType } from '@shumai/db'
|
||||
@@ -517,5 +520,73 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
|
||||
return c.json(logs)
|
||||
})
|
||||
.get(
|
||||
'/teams/:teamId/workflow-tasks',
|
||||
zValidator('query', listWorkflowTasksQuerySchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const query = c.req.valid('query')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const tasks = await workflowTaskService.listWorkflowTasks({
|
||||
teamId,
|
||||
status: query.status,
|
||||
types: query.types,
|
||||
first: query.first,
|
||||
after: query.after,
|
||||
})
|
||||
|
||||
return c.json(tasks)
|
||||
},
|
||||
)
|
||||
.post(
|
||||
'/teams/:teamId/workflow-tasks/batch-status',
|
||||
zValidator('json', batchWorkflowTaskStatusSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const result = await workflowTaskService.getBatchWorkflowTaskStatus({
|
||||
teamId,
|
||||
taskIds: req.taskIds,
|
||||
})
|
||||
|
||||
return c.json(result)
|
||||
},
|
||||
)
|
||||
.post('/teams/:teamId/workflow-tasks/:taskId/stop', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const taskId = c.req.param('taskId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const result = await workflowTaskService.stopWorkflowTask({
|
||||
teamId,
|
||||
taskId,
|
||||
})
|
||||
|
||||
return c.json(result)
|
||||
})
|
||||
|
||||
export default route
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
|
||||
@@ -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"]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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()
|
||||
@@ -28,3 +28,4 @@ export * from './kanban'
|
||||
export * from './recents'
|
||||
export * from './context'
|
||||
export * from './media-generation'
|
||||
export * from './workflowTask'
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { z } from 'zod'
|
||||
import { WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db/enums'
|
||||
|
||||
export { WorkflowTaskType, WorkflowTaskStatus }
|
||||
|
||||
export const workflowTaskTypeSchema = z.nativeEnum(WorkflowTaskType)
|
||||
export type WorkflowTaskTypeEnum = z.infer<typeof workflowTaskTypeSchema>
|
||||
|
||||
export const workflowTaskStatusSchema = z.nativeEnum(WorkflowTaskStatus)
|
||||
export type WorkflowTaskStatusEnum = z.infer<typeof workflowTaskStatusSchema>
|
||||
|
||||
export const workflowTaskItemSchema = z.object({
|
||||
id: z.string(),
|
||||
uid: z.string(),
|
||||
teamId: z.string().nullable().optional(),
|
||||
projectId: z.string().nullable().optional(),
|
||||
projectName: z.string().nullable().optional(),
|
||||
assetId: z.string(),
|
||||
fileName: z.string().nullable().optional(),
|
||||
fileSize: z.number().nullable().optional(),
|
||||
type: z.nativeEnum(WorkflowTaskType).nullable().optional(),
|
||||
status: z.nativeEnum(WorkflowTaskStatus).nullable().optional(),
|
||||
payload: z.unknown().optional(),
|
||||
output: z.unknown().optional(),
|
||||
heartbeat: z.string().nullable().optional(),
|
||||
inputTokens: z.number(),
|
||||
outputTokens: z.number(),
|
||||
model: z.string().nullable().optional(),
|
||||
sessionId: z.string().nullable().optional(),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
})
|
||||
|
||||
export type WorkflowTaskItem = z.infer<typeof workflowTaskItemSchema>
|
||||
|
||||
export const listWorkflowTasksQuerySchema = z.object({
|
||||
first: z.coerce.number().optional(),
|
||||
after: z.string().optional(),
|
||||
status: z
|
||||
.union([z.nativeEnum(WorkflowTaskStatus), z.array(z.nativeEnum(WorkflowTaskStatus))])
|
||||
.transform((val) => (Array.isArray(val) ? val : [val]))
|
||||
.optional(),
|
||||
types: z
|
||||
.union([z.nativeEnum(WorkflowTaskType), z.array(z.nativeEnum(WorkflowTaskType))])
|
||||
.transform((val) => (Array.isArray(val) ? val : [val]))
|
||||
.optional(),
|
||||
})
|
||||
|
||||
export type ListWorkflowTasksQuery = z.infer<typeof listWorkflowTasksQuerySchema>
|
||||
|
||||
export const listWorkflowTasksResponseSchema = z.object({
|
||||
nodes: z.array(workflowTaskItemSchema),
|
||||
pageInfo: z.object({
|
||||
hasNextPage: z.boolean(),
|
||||
endCursor: z.string().nullable(),
|
||||
}),
|
||||
total: z.number(),
|
||||
})
|
||||
|
||||
export type ListWorkflowTasksResponse = z.infer<typeof listWorkflowTasksResponseSchema>
|
||||
|
||||
export const batchWorkflowTaskStatusSchema = z.object({
|
||||
taskIds: z.array(z.string()).max(100),
|
||||
})
|
||||
|
||||
export type BatchWorkflowTaskStatus = z.infer<typeof batchWorkflowTaskStatusSchema>
|
||||
|
||||
export const batchWorkflowTaskStatusResponseSchema = z.object({
|
||||
tasks: z.array(workflowTaskItemSchema),
|
||||
})
|
||||
|
||||
export type BatchWorkflowTaskStatusResponse = z.infer<typeof batchWorkflowTaskStatusResponseSchema>
|
||||
|
||||
export const stopWorkflowTaskResponseSchema = z.object({
|
||||
success: z.boolean(),
|
||||
task: workflowTaskItemSchema,
|
||||
})
|
||||
|
||||
export type StopWorkflowTaskResponse = z.infer<typeof stopWorkflowTaskResponseSchema>
|
||||
@@ -325,11 +325,13 @@ export function AuditLogsDashboard({ teamId }: AuditLogsDashboardProps) {
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent border-b border-border/50">
|
||||
<TableHead className="w-[180px] text-xs font-semibold">{m.action()}</TableHead>
|
||||
<TableHead className="w-[200px] text-xs font-semibold">{m.user()}</TableHead>
|
||||
<TableHead className="text-xs font-semibold">{m.item_id()}</TableHead>
|
||||
<TableHead className="text-xs font-semibold">{m.project_id()}</TableHead>
|
||||
<TableHead className="w-[160px] text-right text-xs font-semibold">
|
||||
<TableHead className="w-[180px] pl-6 text-xs font-semibold">
|
||||
{m.action()}
|
||||
</TableHead>
|
||||
<TableHead className="w-[200px] px-4 text-xs font-semibold">{m.user()}</TableHead>
|
||||
<TableHead className="px-4 text-xs font-semibold">{m.item_id()}</TableHead>
|
||||
<TableHead className="px-4 text-xs font-semibold">{m.project_id()}</TableHead>
|
||||
<TableHead className="w-[160px] pr-6 text-right text-xs font-semibold">
|
||||
{m.timestamp()}
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
@@ -342,10 +344,10 @@ export function AuditLogsDashboard({ teamId }: AuditLogsDashboardProps) {
|
||||
|
||||
return (
|
||||
<TableRow key={log.id} className="hover:bg-muted/40 transition-colors">
|
||||
<TableCell className="py-3 font-medium">
|
||||
<TableCell className="py-3 pl-6 font-medium">
|
||||
{getActionBadge(log.action)}
|
||||
</TableCell>
|
||||
<TableCell className="py-3">
|
||||
<TableCell className="py-3 px-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Avatar className="h-6 w-6">
|
||||
<AvatarImage src={userImage || undefined} />
|
||||
@@ -366,13 +368,13 @@ export function AuditLogsDashboard({ teamId }: AuditLogsDashboardProps) {
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell className="py-3 text-xs font-mono text-muted-foreground">
|
||||
<TableCell className="py-3 px-4 text-xs font-mono text-muted-foreground">
|
||||
{log.itemId || '-'}
|
||||
</TableCell>
|
||||
<TableCell className="py-3 text-xs font-mono text-muted-foreground">
|
||||
<TableCell className="py-3 px-4 text-xs font-mono text-muted-foreground">
|
||||
{log.projectId || '-'}
|
||||
</TableCell>
|
||||
<TableCell className="py-3 text-right text-xs text-muted-foreground">
|
||||
<TableCell className="py-3 pr-6 text-right text-xs text-muted-foreground">
|
||||
{formatTimeAgo(log.createdAt)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
import { useState } from 'react'
|
||||
import type { WorkflowTaskItem } from '@shumai/dtos'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Copy, Check, Clock, Cpu, FileText } from 'lucide-react'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { formatTimeAgo } from '@/ui/lib/time'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
|
||||
interface WorkflowTaskDetailsDialogProps {
|
||||
task: WorkflowTaskItem | null
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
}
|
||||
|
||||
export function WorkflowTaskDetailsDialog({
|
||||
task,
|
||||
open,
|
||||
onOpenChange,
|
||||
}: WorkflowTaskDetailsDialogProps) {
|
||||
const [copiedKey, setCopiedKey] = useState<string | null>(null)
|
||||
|
||||
if (!task) return null
|
||||
|
||||
const copyToClipboard = (text: string, key: string) => {
|
||||
navigator.clipboard.writeText(text)
|
||||
setCopiedKey(key)
|
||||
setTimeout(() => {
|
||||
setCopiedKey(null)
|
||||
}, 2000)
|
||||
}
|
||||
|
||||
const getStatusBadge = (status?: string | null) => {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20 text-xs font-mono"
|
||||
>
|
||||
completed
|
||||
</Badge>
|
||||
)
|
||||
case 'processing':
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20 text-xs font-mono"
|
||||
>
|
||||
processing
|
||||
</Badge>
|
||||
)
|
||||
case 'pending':
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-yellow-500/10 text-yellow-600 dark:text-yellow-400 border-yellow-500/20 text-xs font-mono"
|
||||
>
|
||||
pending
|
||||
</Badge>
|
||||
)
|
||||
case 'failed':
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-destructive/10 text-destructive border-destructive/20 text-xs font-mono"
|
||||
>
|
||||
failed
|
||||
</Badge>
|
||||
)
|
||||
default:
|
||||
return (
|
||||
<Badge variant="outline" className="text-xs font-mono">
|
||||
{status || 'unknown'}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] flex flex-col p-6">
|
||||
<DialogHeader className="pb-2 border-b border-border/50">
|
||||
<div className="flex items-center justify-between gap-2 pr-6">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="h-5 w-5 text-primary" />
|
||||
<DialogTitle className="text-lg font-bold">{m.task_details()}</DialogTitle>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{getStatusBadge(task.status)}
|
||||
{task.type && (
|
||||
<Badge variant="secondary" className="font-mono text-xs">
|
||||
{task.type}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<DialogDescription className="text-xs text-muted-foreground mt-1 flex items-center gap-2">
|
||||
<span>
|
||||
{m.task_id()}: <span className="font-mono text-foreground">{task.id}</span>
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-5 w-5 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => copyToClipboard(task.id, 'task_id')}
|
||||
>
|
||||
{copiedKey === 'task_id' ? (
|
||||
<Check className="h-3 w-3 text-emerald-500" />
|
||||
) : (
|
||||
<Copy className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{/* Metadata Grid */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 py-3 text-xs border-b border-border/40">
|
||||
<div>
|
||||
<div className="text-muted-foreground">{m.file_name()}</div>
|
||||
<div
|
||||
className="truncate font-medium text-foreground mt-0.5"
|
||||
title={task.fileName || '-'}
|
||||
>
|
||||
{task.fileName || '-'}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-muted-foreground">{m.size()}</div>
|
||||
<div className="font-mono truncate font-medium text-foreground mt-0.5">
|
||||
{task.fileSize !== null && task.fileSize !== undefined
|
||||
? formatSize(task.fileSize)
|
||||
: '-'}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-muted-foreground">{m.project_name()}</div>
|
||||
<div
|
||||
className="truncate font-medium text-foreground mt-0.5"
|
||||
title={task.projectName || '-'}
|
||||
>
|
||||
{task.projectName || '-'}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-muted-foreground">{m.asset_id()}</div>
|
||||
<div className="font-mono truncate font-medium text-foreground mt-0.5">
|
||||
{task.assetId || '-'}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-muted-foreground">{m.project_id()}</div>
|
||||
<div className="font-mono truncate font-medium text-foreground mt-0.5">
|
||||
{task.projectId || '-'}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-muted-foreground">{m.created_at()}</div>
|
||||
<div className="font-medium text-foreground mt-0.5 flex items-center gap-1">
|
||||
<Clock className="h-3 w-3 text-muted-foreground" />
|
||||
{formatTimeAgo(task.createdAt)}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-muted-foreground">{m.updated_at()}</div>
|
||||
<div className="font-medium text-foreground mt-0.5">
|
||||
{formatTimeAgo(task.updatedAt)}
|
||||
</div>
|
||||
</div>
|
||||
{task.heartbeat && (
|
||||
<div>
|
||||
<div className="text-muted-foreground">{m.heartbeat()}</div>
|
||||
<div className="font-medium text-foreground mt-0.5">
|
||||
{formatTimeAgo(task.heartbeat)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{task.model && (
|
||||
<div>
|
||||
<div className="text-muted-foreground">{m.model()}</div>
|
||||
<div className="font-mono truncate font-medium text-foreground mt-0.5">
|
||||
{task.model}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{(task.inputTokens > 0 || task.outputTokens > 0) && (
|
||||
<div>
|
||||
<div className="text-muted-foreground flex items-center gap-1">
|
||||
<Cpu className="h-3 w-3" /> {m.tokens_label()}
|
||||
</div>
|
||||
<div className="font-medium text-foreground mt-0.5 font-mono">
|
||||
{task.inputTokens.toLocaleString()} in / {task.outputTokens.toLocaleString()} out
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{task.sessionId && (
|
||||
<div className="col-span-2">
|
||||
<div className="text-muted-foreground">{m.session_id()}</div>
|
||||
<div className="font-mono truncate font-medium text-foreground mt-0.5">
|
||||
{task.sessionId}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tabs for Payload and Output */}
|
||||
<div className="flex-1 min-h-0 pt-3">
|
||||
<Tabs defaultValue="payload" className="w-full h-full flex flex-col">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="payload">{m.payload()}</TabsTrigger>
|
||||
<TabsTrigger value="output">{m.output()}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="payload" className="flex-1 mt-2 min-h-0">
|
||||
<ScrollArea className="h-64 w-full rounded-md border border-border/50 bg-muted/30 p-3 font-mono text-xs">
|
||||
<pre className="whitespace-pre-wrap break-all text-foreground/90">
|
||||
{task.payload ? JSON.stringify(task.payload, null, 2) : 'null'}
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
<TabsContent value="output" className="flex-1 mt-2 min-h-0">
|
||||
<ScrollArea className="h-64 w-full rounded-md border border-border/50 bg-muted/30 p-3 font-mono text-xs">
|
||||
<pre className="whitespace-pre-wrap break-all text-foreground/90">
|
||||
{task.output ? JSON.stringify(task.output, null, 2) : 'null'}
|
||||
</pre>
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { WorkflowTasksDashboard } from './WorkflowTasksDashboard'
|
||||
import type { ListWorkflowTasksResponse } from '@shumai/dtos'
|
||||
|
||||
const mockGetWorkflowTasks = vi.fn()
|
||||
const mockBatchStatus = vi.fn()
|
||||
const mockStopTask = vi.fn()
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
teams: {
|
||||
':teamId': {
|
||||
'workflow-tasks': {
|
||||
$get: () => mockGetWorkflowTasks(),
|
||||
'batch-status': {
|
||||
$post: () => mockBatchStatus(),
|
||||
},
|
||||
':taskId': {
|
||||
stop: {
|
||||
$post: () => mockStopTask(),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('react-intersection-observer', () => ({
|
||||
useInView: () => ({ ref: vi.fn(), inView: false }),
|
||||
}))
|
||||
|
||||
const mockTasksData: ListWorkflowTasksResponse = {
|
||||
nodes: [
|
||||
{
|
||||
id: 'task_01M5KTTEST1',
|
||||
uid: 'uid-1',
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
projectName: 'Project Alpha',
|
||||
assetId: 'asset-1',
|
||||
fileName: 'nature_video.mp4',
|
||||
fileSize: 10485760, // 10.49 MB
|
||||
type: 'transcode_video',
|
||||
status: 'processing',
|
||||
createdAt: '2026-10-23T10:00:00.000Z',
|
||||
updatedAt: '2026-10-23T10:01:00.000Z',
|
||||
inputTokens: 0,
|
||||
outputTokens: 0,
|
||||
},
|
||||
{
|
||||
id: 'task_01M5KTTEST2',
|
||||
uid: 'uid-2',
|
||||
teamId: 'team-1',
|
||||
projectId: null,
|
||||
projectName: null,
|
||||
assetId: 'asset-2',
|
||||
fileName: null,
|
||||
fileSize: null,
|
||||
type: 'chat',
|
||||
status: 'completed',
|
||||
createdAt: '2026-10-23T09:00:00.000Z',
|
||||
updatedAt: '2026-10-23T09:05:00.000Z',
|
||||
inputTokens: 100,
|
||||
outputTokens: 50,
|
||||
},
|
||||
],
|
||||
pageInfo: {
|
||||
hasNextPage: false,
|
||||
endCursor: null,
|
||||
},
|
||||
total: 2,
|
||||
}
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('WorkflowTasksDashboard', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockGetWorkflowTasks.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => mockTasksData,
|
||||
})
|
||||
mockBatchStatus.mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ tasks: [] }),
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
it('renders table columns with File Name, Size, and Project Name, without Task ID column', async () => {
|
||||
render(<WorkflowTasksDashboard teamId="team-1" />, { wrapper: createWrapper() })
|
||||
|
||||
// Wait for tasks to load
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('nature_video.mp4')).toBeTruthy()
|
||||
})
|
||||
|
||||
// Check table headers
|
||||
expect(screen.getByText('File Name')).toBeTruthy()
|
||||
expect(screen.getByText('Size')).toBeTruthy()
|
||||
expect(screen.getByText('Project Name')).toBeTruthy()
|
||||
expect(screen.queryByText('Task ID')).toBeNull() // Not in table headers
|
||||
|
||||
// Check row data
|
||||
expect(screen.getByText('nature_video.mp4')).toBeTruthy()
|
||||
expect(screen.getByText('10.49 MB')).toBeTruthy()
|
||||
expect(screen.getByText('Project Alpha')).toBeTruthy()
|
||||
|
||||
// Fallback row data
|
||||
expect(screen.getByText('asset-2')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('opens details dialog and displays file name, size, project name, and task ID', async () => {
|
||||
render(<WorkflowTasksDashboard teamId="team-1" />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('nature_video.mp4')).toBeTruthy()
|
||||
})
|
||||
|
||||
const viewButtons = screen.getAllByTitle('View Details')
|
||||
fireEvent.click(viewButtons[0])
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Task Details')).toBeTruthy()
|
||||
})
|
||||
|
||||
// Details dialog should show Task ID
|
||||
expect(screen.getByText('task_01M5KTTEST1')).toBeTruthy()
|
||||
// Details dialog should show File Name, Size, Project Name
|
||||
expect(screen.getAllByText('nature_video.mp4').length).toBeGreaterThanOrEqual(1)
|
||||
expect(screen.getAllByText('10.49 MB').length).toBeGreaterThanOrEqual(1)
|
||||
expect(screen.getAllByText('Project Alpha').length).toBeGreaterThanOrEqual(1)
|
||||
})
|
||||
|
||||
it('shows file name in stop task confirmation dialog', async () => {
|
||||
render(<WorkflowTasksDashboard teamId="team-1" />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('nature_video.mp4')).toBeTruthy()
|
||||
})
|
||||
|
||||
const stopButton = screen.getByText('Stop Task')
|
||||
fireEvent.click(stopButton)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Stop Workflow Task')).toBeTruthy()
|
||||
})
|
||||
|
||||
expect(screen.getByText(/task_01M5KTTEST1/)).toBeTruthy()
|
||||
expect(screen.getAllByText('nature_video.mp4').length).toBeGreaterThanOrEqual(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,602 @@
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import {
|
||||
useInfiniteQuery,
|
||||
useMutation,
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
type InfiniteData,
|
||||
} from '@tanstack/react-query'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import {
|
||||
WorkflowTaskType,
|
||||
WorkflowTaskStatus,
|
||||
type WorkflowTaskItem,
|
||||
type ListWorkflowTasksResponse,
|
||||
} from '@shumai/dtos'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/ui/components/ui/table'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/ui/components/ui/popover'
|
||||
import { Checkbox } from '@/ui/components/ui/checkbox'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
import { Loader2, Filter, Workflow, Square, Eye, RotateCw, AlertTriangle } from 'lucide-react'
|
||||
import { formatTimeAgo } from '@/ui/lib/time'
|
||||
import { formatSize } from '@/ui/lib/format'
|
||||
import { toast } from 'sonner'
|
||||
import { WorkflowTaskDetailsDialog } from './WorkflowTaskDetailsDialog'
|
||||
|
||||
const ALL_WORKFLOW_TASK_TYPES = Object.values(WorkflowTaskType)
|
||||
const ALL_WORKFLOW_TASK_STATUSES = Object.values(WorkflowTaskStatus)
|
||||
|
||||
interface WorkflowTasksDashboardProps {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
export function WorkflowTasksDashboard({ teamId }: WorkflowTasksDashboardProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const [selectedStatuses, setSelectedStatuses] = useState<WorkflowTaskStatus[]>([])
|
||||
const [selectedTypes, setSelectedTypes] = useState<WorkflowTaskType[]>([])
|
||||
const [taskToStop, setTaskToStop] = useState<WorkflowTaskItem | null>(null)
|
||||
const [detailsTask, setDetailsTask] = useState<WorkflowTaskItem | null>(null)
|
||||
|
||||
const { ref: loadMoreRef, inView } = useInView()
|
||||
|
||||
const queryKey = useMemo(
|
||||
() => ['teams', teamId, 'workflow-tasks', selectedStatuses, selectedTypes],
|
||||
[teamId, selectedStatuses, selectedTypes],
|
||||
)
|
||||
|
||||
// Infinite query for listing workflow tasks
|
||||
const {
|
||||
data,
|
||||
isLoading,
|
||||
isError,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
refetch,
|
||||
isRefetching,
|
||||
} = useInfiniteQuery({
|
||||
queryKey,
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const res = await client.api.teams[':teamId']['workflow-tasks'].$get({
|
||||
param: { teamId },
|
||||
query: {
|
||||
first: '20',
|
||||
after: pageParam ? String(pageParam) : undefined,
|
||||
status: selectedStatuses.length > 0 ? selectedStatuses : undefined,
|
||||
types: selectedTypes.length > 0 ? selectedTypes : undefined,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch workflow tasks')
|
||||
return (await res.json()) as ListWorkflowTasksResponse
|
||||
},
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => lastPage.pageInfo.endCursor || undefined,
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
// Trigger next page when scrolling into view
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
|
||||
|
||||
const allTasks = useMemo(() => data?.pages.flatMap((page) => page.nodes) || [], [data])
|
||||
const totalCount = data?.pages[0]?.total ?? 0
|
||||
|
||||
// Targeted Active Task Poller: Extract active (pending/processing) task IDs
|
||||
const activeTaskIds = useMemo(() => {
|
||||
return allTasks
|
||||
.filter((t) => t.status === 'pending' || t.status === 'processing')
|
||||
.map((t) => t.id)
|
||||
}, [allTasks])
|
||||
|
||||
// Polling query: Only active when there are pending or processing tasks
|
||||
useQuery({
|
||||
queryKey: ['teams', teamId, 'workflow-tasks', 'batch-status', activeTaskIds],
|
||||
queryFn: async () => {
|
||||
if (activeTaskIds.length === 0) return null
|
||||
const res = await client.api.teams[':teamId']['workflow-tasks']['batch-status'].$post({
|
||||
param: { teamId },
|
||||
json: { taskIds: activeTaskIds },
|
||||
})
|
||||
if (!res.ok) return null
|
||||
const result = await res.json()
|
||||
|
||||
// Update active tasks in-place in the infinite query cache
|
||||
if (result.tasks && result.tasks.length > 0) {
|
||||
queryClient.setQueryData(
|
||||
queryKey,
|
||||
(old: InfiniteData<ListWorkflowTasksResponse> | undefined) => {
|
||||
if (!old) return old
|
||||
const updatedMap = new Map(
|
||||
result.tasks.map((task: WorkflowTaskItem) => [task.id, task]),
|
||||
)
|
||||
return {
|
||||
...old,
|
||||
pages: old.pages.map((page) => ({
|
||||
...page,
|
||||
nodes: page.nodes.map((node) => updatedMap.get(node.id) || node),
|
||||
})),
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
return result
|
||||
},
|
||||
enabled: activeTaskIds.length > 0,
|
||||
refetchInterval: 6000,
|
||||
})
|
||||
|
||||
// Stop task mutation
|
||||
const stopTaskMutation = useMutation({
|
||||
mutationFn: async (taskId: string) => {
|
||||
const res = await client.api.teams[':teamId']['workflow-tasks'][':taskId'].stop.$post({
|
||||
param: { teamId, taskId },
|
||||
})
|
||||
if (!res.ok) {
|
||||
const errorData = await res.json().catch(() => ({ message: 'Failed to stop task' }))
|
||||
throw new Error((errorData as { message?: string }).message || 'Failed to stop task')
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
toast.success(m.task_stopped_successfully())
|
||||
// In-place update in infinite query cache
|
||||
queryClient.setQueryData(
|
||||
queryKey,
|
||||
(old: InfiniteData<ListWorkflowTasksResponse> | undefined) => {
|
||||
if (!old) return old
|
||||
return {
|
||||
...old,
|
||||
pages: old.pages.map((page) => ({
|
||||
...page,
|
||||
nodes: page.nodes.map((node) => (node.id === data.task.id ? data.task : node)),
|
||||
})),
|
||||
}
|
||||
},
|
||||
)
|
||||
setTaskToStop(null)
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error(err.message || 'Failed to stop task')
|
||||
},
|
||||
})
|
||||
|
||||
const toggleStatus = (status: WorkflowTaskStatus) => {
|
||||
setSelectedStatuses((prev) =>
|
||||
prev.includes(status) ? prev.filter((s) => s !== status) : [...prev, status],
|
||||
)
|
||||
}
|
||||
|
||||
const toggleType = (type: WorkflowTaskType) => {
|
||||
setSelectedTypes((prev) =>
|
||||
prev.includes(type) ? prev.filter((t) => t !== type) : [...prev, type],
|
||||
)
|
||||
}
|
||||
|
||||
const getStatusBadge = (status?: string | null) => {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20 font-mono text-xs"
|
||||
>
|
||||
completed
|
||||
</Badge>
|
||||
)
|
||||
case 'processing':
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-blue-500/10 text-blue-600 dark:text-blue-400 border-blue-500/20 font-mono text-xs gap-1.5"
|
||||
>
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
processing
|
||||
</Badge>
|
||||
)
|
||||
case 'pending':
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-yellow-500/10 text-yellow-600 dark:text-yellow-400 border-yellow-500/20 font-mono text-xs"
|
||||
>
|
||||
pending
|
||||
</Badge>
|
||||
)
|
||||
case 'failed':
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-destructive/10 text-destructive border-destructive/20 font-mono text-xs"
|
||||
>
|
||||
failed
|
||||
</Badge>
|
||||
)
|
||||
default:
|
||||
return (
|
||||
<Badge variant="outline" className="font-mono text-xs">
|
||||
{status || '-'}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const getTypeBadge = (type?: string | null) => {
|
||||
if (!type) return <Badge variant="outline">-</Badge>
|
||||
if (type.startsWith('transcode')) {
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-purple-500/10 text-purple-600 dark:text-purple-400 border-purple-500/20 font-mono text-xs"
|
||||
>
|
||||
{type}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
if (type.startsWith('ai_') || type === 'chat') {
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="bg-indigo-500/10 text-indigo-600 dark:text-indigo-400 border-indigo-500/20 font-mono text-xs"
|
||||
>
|
||||
{type}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<Badge variant="secondary" className="font-mono text-xs">
|
||||
{type}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card className="border border-border/50 shadow-xs">
|
||||
<CardHeader className="pb-4">
|
||||
<div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
|
||||
<div>
|
||||
<CardTitle className="text-xl font-bold flex items-center gap-2">
|
||||
<Workflow className="h-5 w-5 text-primary" />
|
||||
{m.workflow_tasks()}
|
||||
</CardTitle>
|
||||
<CardDescription className="mt-1">{m.workflow_tasks_description()}</CardDescription>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
{totalCount > 0 && (
|
||||
<Badge variant="secondary" className="w-fit text-xs font-normal">
|
||||
{totalCount} {m.workflow_tasks()}
|
||||
</Badge>
|
||||
)}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-9 gap-1.5 text-xs"
|
||||
onClick={() => refetch()}
|
||||
disabled={isRefetching}
|
||||
>
|
||||
<RotateCw className={`h-3.5 w-3.5 ${isRefetching ? 'animate-spin' : ''}`} />
|
||||
{m.refresh_tasks()}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filter Bar */}
|
||||
<div className="mt-4 flex flex-wrap items-center gap-3 pt-4 border-t border-border/40">
|
||||
{/* Status Filter */}
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="h-9 gap-2 text-xs border-dashed">
|
||||
<Filter className="h-3.5 w-3.5" />
|
||||
{m.filter_by_status()}
|
||||
{selectedStatuses.length > 0 && (
|
||||
<Badge variant="secondary" className="ml-1 px-1.5 py-0 text-[10px]">
|
||||
{selectedStatuses.length}
|
||||
</Badge>
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-56 p-2" align="start">
|
||||
<div className="text-xs font-semibold text-muted-foreground px-2 py-1 mb-1">
|
||||
{m.select_status()}
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{ALL_WORKFLOW_TASK_STATUSES.map((status) => (
|
||||
<label
|
||||
key={status}
|
||||
className="flex items-center gap-2 px-2 py-1.5 hover:bg-accent rounded-md cursor-pointer text-xs"
|
||||
>
|
||||
<Checkbox
|
||||
checked={selectedStatuses.includes(status)}
|
||||
onCheckedChange={() => toggleStatus(status)}
|
||||
/>
|
||||
<span className="font-mono">{status}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{selectedStatuses.length > 0 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full mt-2 h-7 text-xs text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setSelectedStatuses([])}
|
||||
>
|
||||
{m.clear_status()}
|
||||
</Button>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{/* Type Filter */}
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="h-9 gap-2 text-xs border-dashed">
|
||||
<Filter className="h-3.5 w-3.5" />
|
||||
{m.filter_by_type()}
|
||||
{selectedTypes.length > 0 && (
|
||||
<Badge variant="secondary" className="ml-1 px-1.5 py-0 text-[10px]">
|
||||
{selectedTypes.length}
|
||||
</Badge>
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-64 p-2" align="start">
|
||||
<div className="text-xs font-semibold text-muted-foreground px-2 py-1 mb-1">
|
||||
{m.select_type()}
|
||||
</div>
|
||||
<div className="max-h-60 overflow-y-auto space-y-1 pr-1">
|
||||
{ALL_WORKFLOW_TASK_TYPES.map((type) => (
|
||||
<label
|
||||
key={type}
|
||||
className="flex items-center gap-2 px-2 py-1.5 hover:bg-accent rounded-md cursor-pointer text-xs"
|
||||
>
|
||||
<Checkbox
|
||||
checked={selectedTypes.includes(type)}
|
||||
onCheckedChange={() => toggleType(type)}
|
||||
/>
|
||||
<span className="font-mono truncate">{type}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
{selectedTypes.length > 0 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="w-full mt-2 h-7 text-xs text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setSelectedTypes([])}
|
||||
>
|
||||
{m.clear_types()}
|
||||
</Button>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
|
||||
{/* Clear All Filters */}
|
||||
{(selectedStatuses.length > 0 || selectedTypes.length > 0) && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-9 px-2 text-xs text-muted-foreground hover:text-foreground"
|
||||
onClick={() => {
|
||||
setSelectedStatuses([])
|
||||
setSelectedTypes([])
|
||||
}}
|
||||
>
|
||||
{m.clear_all()}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="p-0">
|
||||
{isLoading ? (
|
||||
<div className="flex h-64 items-center justify-center">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : isError ? (
|
||||
<div className="p-8 text-center text-sm text-destructive">
|
||||
{m.failed_to_load_workflow_tasks()}
|
||||
</div>
|
||||
) : allTasks.length === 0 ? (
|
||||
<div className="p-12 text-center text-sm text-muted-foreground">
|
||||
{m.no_workflow_tasks()}
|
||||
</div>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className="hover:bg-transparent border-b border-border/50">
|
||||
<TableHead className="w-[170px] pl-6 text-xs font-semibold">
|
||||
{m.task_type()}
|
||||
</TableHead>
|
||||
<TableHead className="w-[130px] px-4 text-xs font-semibold">
|
||||
{m.task_status()}
|
||||
</TableHead>
|
||||
<TableHead className="min-w-[180px] px-4 text-xs font-semibold">
|
||||
{m.file_name()}
|
||||
</TableHead>
|
||||
<TableHead className="w-[110px] px-4 text-xs font-semibold">{m.size()}</TableHead>
|
||||
<TableHead className="w-[160px] px-4 text-xs font-semibold">
|
||||
{m.project_name()}
|
||||
</TableHead>
|
||||
<TableHead className="w-[130px] px-4 text-right text-xs font-semibold">
|
||||
{m.created_at()}
|
||||
</TableHead>
|
||||
<TableHead className="w-[120px] pr-6 text-right text-xs font-semibold">
|
||||
{m.actions()}
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{allTasks.map((task) => {
|
||||
const canStop = task.status === 'pending' || task.status === 'processing'
|
||||
|
||||
return (
|
||||
<TableRow key={task.id} className="hover:bg-muted/40 transition-colors">
|
||||
<TableCell className="py-3 pl-6 font-medium">
|
||||
{getTypeBadge(task.type)}
|
||||
</TableCell>
|
||||
<TableCell className="py-3 px-4 font-medium">
|
||||
{getStatusBadge(task.status)}
|
||||
</TableCell>
|
||||
<TableCell className="py-3 px-4 text-xs font-medium">
|
||||
<span
|
||||
className="truncate block max-w-[220px]"
|
||||
title={task.fileName || task.assetId || '-'}
|
||||
>
|
||||
{task.fileName || task.assetId || '-'}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className="py-3 px-4 text-xs font-mono text-muted-foreground">
|
||||
{task.fileSize !== null && task.fileSize !== undefined
|
||||
? formatSize(task.fileSize)
|
||||
: '-'}
|
||||
</TableCell>
|
||||
<TableCell className="py-3 px-4 text-xs text-muted-foreground">
|
||||
<span
|
||||
className="truncate block max-w-[160px]"
|
||||
title={task.projectName || task.projectId || '-'}
|
||||
>
|
||||
{task.projectName || task.projectId || '-'}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className="py-3 px-4 text-right text-xs text-muted-foreground whitespace-nowrap">
|
||||
{formatTimeAgo(task.createdAt)}
|
||||
</TableCell>
|
||||
<TableCell className="py-3 pr-6 text-right">
|
||||
<div className="flex items-center justify-end gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
|
||||
onClick={() => setDetailsTask(task)}
|
||||
title={m.view_details()}
|
||||
>
|
||||
<Eye className="h-4 w-4" />
|
||||
</Button>
|
||||
|
||||
{canStop && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8 px-2 text-xs border-destructive/30 text-destructive hover:bg-destructive/10"
|
||||
onClick={() => setTaskToStop(task)}
|
||||
disabled={stopTaskMutation.isPending}
|
||||
>
|
||||
<Square className="h-3 w-3 mr-1 fill-current" />
|
||||
{m.stop_task()}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
|
||||
{/* Infinite Scroll Sentinel */}
|
||||
<div ref={loadMoreRef} className="py-4 flex justify-center">
|
||||
{isFetchingNextPage && (
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Stop Task Confirmation Dialog */}
|
||||
<AlertDialog
|
||||
open={!!taskToStop}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setTaskToStop(null)
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-destructive" />
|
||||
<AlertDialogTitle>{m.stop_task_confirm_title()}</AlertDialogTitle>
|
||||
</div>
|
||||
<AlertDialogDescription className="pt-2 text-sm text-muted-foreground">
|
||||
{m.stop_task_confirm_description()}
|
||||
</AlertDialogDescription>
|
||||
{taskToStop && (
|
||||
<div className="mt-3 p-2.5 rounded-md bg-muted/50 border border-border/40 font-mono text-xs space-y-1">
|
||||
<div>
|
||||
{m.task_id()}: {taskToStop.id}
|
||||
</div>
|
||||
{taskToStop.fileName && (
|
||||
<div className="font-sans">
|
||||
{m.file_name()}:{' '}
|
||||
<span className="font-medium text-foreground">{taskToStop.fileName}</span>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
{m.task_type()}: {taskToStop.type || 'unknown'}
|
||||
</div>
|
||||
<div>
|
||||
{m.task_status()}: {taskToStop.status}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={stopTaskMutation.isPending}>
|
||||
{m.cancel()}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive hover:bg-destructive/90 text-destructive-foreground"
|
||||
disabled={stopTaskMutation.isPending}
|
||||
onClick={() => {
|
||||
if (taskToStop) {
|
||||
stopTaskMutation.mutate(taskToStop.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{stopTaskMutation.isPending ? (
|
||||
<>
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin mr-1.5" />
|
||||
{m.stopping()}
|
||||
</>
|
||||
) : (
|
||||
m.stop_task()
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Task Details Dialog */}
|
||||
<WorkflowTaskDetailsDialog
|
||||
task={detailsTask}
|
||||
open={!!detailsTask}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDetailsTask(null)
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1184,6 +1184,38 @@
|
||||
"search_item_id": "Search Item ID...",
|
||||
"select_actions": "Select Actions",
|
||||
"select_users": "Select Users",
|
||||
"workflow_tasks": "Workflow Tasks",
|
||||
"workflow_tasks_description": "View, monitor, and manage background workflow execution tasks.",
|
||||
"no_workflow_tasks": "No workflow tasks found",
|
||||
"filter_by_status": "Filter by Status",
|
||||
"filter_by_type": "Filter by Type",
|
||||
"select_status": "Select Status",
|
||||
"select_type": "Select Type",
|
||||
"clear_status": "Clear Status",
|
||||
"clear_types": "Clear Types",
|
||||
"clear_all": "Clear all",
|
||||
"failed_to_load_workflow_tasks": "Failed to load workflow tasks.",
|
||||
"stop_task": "Stop Task",
|
||||
"stopping": "Stopping...",
|
||||
"stop_task_confirm_title": "Stop Workflow Task",
|
||||
"stop_task_confirm_description": "Are you sure you want to stop this task? Any ongoing processing will be cancelled.",
|
||||
"task_stopped_successfully": "Workflow task has been stopped.",
|
||||
"task_details": "Task Details",
|
||||
"task_id": "Task ID",
|
||||
"task_status": "Status",
|
||||
"task_type": "Type",
|
||||
"asset_id": "Asset ID",
|
||||
"file_name": "File Name",
|
||||
"payload": "Payload",
|
||||
"output": "Output",
|
||||
"input_tokens": "Input Tokens",
|
||||
"output_tokens": "Output Tokens",
|
||||
"tokens_label": "Tokens",
|
||||
"session_id": "Session ID",
|
||||
"heartbeat": "Heartbeat",
|
||||
"updated_at": "Updated At",
|
||||
"view_details": "View Details",
|
||||
"refresh_tasks": "Refresh Tasks",
|
||||
"watermark": "Watermark",
|
||||
"watermark_enabled": "Enable Watermark",
|
||||
"watermark_transcoding_processing": "Transcoding watermark media...",
|
||||
|
||||
@@ -1184,6 +1184,38 @@
|
||||
"search_item_id": "搜索条目 ID...",
|
||||
"select_actions": "选择操作",
|
||||
"select_users": "选择用户",
|
||||
"workflow_tasks": "工作流任务",
|
||||
"workflow_tasks_description": "查看、监控和管理后台工作流执行任务。",
|
||||
"no_workflow_tasks": "未找到工作流任务",
|
||||
"filter_by_status": "按状态筛选",
|
||||
"filter_by_type": "按类型筛选",
|
||||
"select_status": "选择状态",
|
||||
"select_type": "选择类型",
|
||||
"clear_status": "清除状态",
|
||||
"clear_types": "清除类型",
|
||||
"clear_all": "清除全部",
|
||||
"failed_to_load_workflow_tasks": "加载工作流任务失败。",
|
||||
"stop_task": "停止任务",
|
||||
"stopping": "正在停止...",
|
||||
"stop_task_confirm_title": "停止工作流任务",
|
||||
"stop_task_confirm_description": "确定要停止此任务吗?任何正在进行的处理都将被取消。",
|
||||
"task_stopped_successfully": "工作流任务已停止。",
|
||||
"task_details": "任务详情",
|
||||
"task_id": "任务 ID",
|
||||
"task_status": "状态",
|
||||
"task_type": "类型",
|
||||
"asset_id": "素材 ID",
|
||||
"file_name": "文件名",
|
||||
"payload": "负载数据",
|
||||
"output": "输出结果",
|
||||
"input_tokens": "输入 Token",
|
||||
"output_tokens": "输出 Token",
|
||||
"tokens_label": "Token",
|
||||
"session_id": "会话 ID",
|
||||
"heartbeat": "心跳时间",
|
||||
"updated_at": "更新时间",
|
||||
"view_details": "查看详情",
|
||||
"refresh_tasks": "刷新任务",
|
||||
"watermark": "水印",
|
||||
"watermark_enabled": "启用水印",
|
||||
"watermark_transcoding_processing": "水印媒体转码处理中...",
|
||||
|
||||
@@ -8,9 +8,18 @@ import { AiUsageDashboard } from '@/ui/components/dashboard/AiUsageDashboard'
|
||||
import { AgentSessionsDashboard } from '@/ui/components/dashboard/AgentSessionsDashboard'
|
||||
import { QuotaUsageDashboard } from '@/ui/components/dashboard/QuotaUsageDashboard'
|
||||
import { AuditLogsDashboard } from '@/ui/components/dashboard/AuditLogsDashboard'
|
||||
import { Activity, BarChart2, Gauge, Loader2, MessagesSquare, ShieldAlert } from 'lucide-react'
|
||||
import { WorkflowTasksDashboard } from '@/ui/components/dashboard/WorkflowTasksDashboard'
|
||||
import {
|
||||
Activity,
|
||||
BarChart2,
|
||||
Gauge,
|
||||
Loader2,
|
||||
MessagesSquare,
|
||||
ShieldAlert,
|
||||
Workflow,
|
||||
} from 'lucide-react'
|
||||
|
||||
type DashboardTab = 'audit-logs' | 'ai-usage' | 'ai-sessions' | 'quotas'
|
||||
type DashboardTab = 'audit-logs' | 'workflow-tasks' | 'ai-usage' | 'ai-sessions' | 'quotas'
|
||||
|
||||
function TeamDashboardPage() {
|
||||
const { teamId } = Route.useParams()
|
||||
@@ -77,6 +86,22 @@ function TeamDashboardPage() {
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('workflow-tasks')}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-3 px-4 py-3 text-sm font-medium rounded-lg transition-all',
|
||||
activeTab === 'workflow-tasks'
|
||||
? 'bg-sidebar-accent text-sidebar-accent-foreground ring-1 ring-sidebar-border'
|
||||
: 'text-sidebar-foreground/75 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
|
||||
)}
|
||||
>
|
||||
<Workflow className="w-5 h-5" />
|
||||
{m.workflow_tasks()}
|
||||
{activeTab === 'workflow-tasks' && (
|
||||
<div className="ml-auto w-1.5 h-1.5 rounded-full bg-sidebar-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setActiveTab('quotas')}
|
||||
className={cn(
|
||||
@@ -136,6 +161,7 @@ function TeamDashboardPage() {
|
||||
<div className="flex-1 overflow-y-auto p-4 md:p-8">
|
||||
<div className="max-w-6xl mx-auto space-y-8">
|
||||
{activeTab === 'audit-logs' && <AuditLogsDashboard teamId={teamId} />}
|
||||
{activeTab === 'workflow-tasks' && <WorkflowTasksDashboard teamId={teamId} />}
|
||||
{activeTab === 'ai-usage' && <AiUsageDashboard teamId={teamId} />}
|
||||
{activeTab === 'ai-sessions' && <AgentSessionsDashboard teamId={teamId} />}
|
||||
{activeTab === 'quotas' && <QuotaUsageDashboard teamId={teamId} />}
|
||||
|
||||
@@ -310,6 +310,17 @@ describe('DbosExecutor Tests', () => {
|
||||
|
||||
expect(heartbeats.has(taskId)).toBe(false)
|
||||
})
|
||||
|
||||
it('should propagate error if client.cancelWorkflow fails', async () => {
|
||||
const taskId = 'test-failing-cancel'
|
||||
const mockClient = {
|
||||
cancelWorkflow: vi.fn().mockRejectedValue(new Error('DBOS connection failure')),
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(executor, 'getClient').mockResolvedValue(mockClient as any)
|
||||
|
||||
await expect(executor.cancel(taskId)).rejects.toThrow('DBOS connection failure')
|
||||
})
|
||||
})
|
||||
|
||||
describe('Submit', () => {
|
||||
|
||||
@@ -387,6 +387,7 @@ export class DbosExecutor extends EventEmitter {
|
||||
logger.info({ taskId }, '[DbosExecutor] Cancelled workflow task')
|
||||
} catch (err) {
|
||||
logger.warn({ taskId, err }, '[DbosExecutor] Failed to cancel workflow task in DBOS')
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user