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([]) const [selectedTypes, setSelectedTypes] = useState([]) const [taskToStop, setTaskToStop] = useState(null) const [detailsTask, setDetailsTask] = useState(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 | 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 | 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 ( completed ) case 'processing': return ( processing ) case 'pending': return ( pending ) case 'failed': return ( failed ) default: return ( {status || '-'} ) } } const getTypeBadge = (type?: string | null) => { if (!type) return - if (type.startsWith('transcode')) { return ( {type} ) } if (type.startsWith('ai_') || type === 'chat') { return ( {type} ) } if (type === 'archive_asset' || type === 'restore_asset') { return ( {type} ) } return ( {type} ) } return (
{m.workflow_tasks()} {m.workflow_tasks_description()}
{totalCount > 0 && ( {totalCount} {m.workflow_tasks()} )}
{/* Filter Bar */}
{/* Status Filter */}
{m.select_status()}
{ALL_WORKFLOW_TASK_STATUSES.map((status) => ( ))}
{selectedStatuses.length > 0 && ( )}
{/* Type Filter */}
{m.select_type()}
{ALL_WORKFLOW_TASK_TYPES.map((type) => ( ))}
{selectedTypes.length > 0 && ( )}
{/* Clear All Filters */} {(selectedStatuses.length > 0 || selectedTypes.length > 0) && ( )}
{isLoading ? (
) : isError ? (
{m.failed_to_load_workflow_tasks()}
) : allTasks.length === 0 ? (
{m.no_workflow_tasks()}
) : ( {m.task_type()} {m.task_status()} {m.file_name()} {m.size()} {m.project_name()} {m.created_at()} {m.actions()} {allTasks.map((task) => { const canStop = task.status === 'pending' || task.status === 'processing' return ( {getTypeBadge(task.type)} {getStatusBadge(task.status)} {task.fileName || task.assetId || '-'} {task.fileSize !== null && task.fileSize !== undefined ? formatSize(task.fileSize) : '-'} {task.projectName || task.projectId || '-'} {formatTimeAgo(task.createdAt)}
{canStop && ( )}
) })}
)} {/* Infinite Scroll Sentinel */}
{isFetchingNextPage && ( )}
{/* Stop Task Confirmation Dialog */} { if (!open) setTaskToStop(null) }} >
{m.stop_task_confirm_title()}
{m.stop_task_confirm_description()} {taskToStop && (
{m.task_id()}: {taskToStop.id}
{taskToStop.fileName && (
{m.file_name()}:{' '} {taskToStop.fileName}
)}
{m.task_type()}: {taskToStop.type || 'unknown'}
{m.task_status()}: {taskToStop.status}
)}
{m.cancel()} { if (taskToStop) { stopTaskMutation.mutate(taskToStop.id) } }} > {stopTaskMutation.isPending ? ( <> {m.stopping()} ) : ( m.stop_task() )}
{/* Task Details Dialog */} { if (!open) setDetailsTask(null) }} />
) }