"use client"; import { useState } from "react"; import Link from "next/link"; import { useQuery, useQueryClient } from "@tanstack/react-query"; import { useSession } from "next-auth/react"; import { RefreshCw, RotateCcw, XCircle, CheckCircle2, Server, Package, ChevronLeft, ChevronRight } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Progress } from "@/components/ui/progress"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { useToast } from "@/components/ui/use-toast"; import { cn } from "@/lib/utils"; import { EXPORT_STATUS_STYLES, FAILED_STATUSES, ACTIVE_STATUSES, statusLabel, formatEta, } from "./status-colors"; interface QueueExport { id: string; shotCode: string; episode: string | null; projectName: string; projectCode: string; versionString: string; status: string; statusChangedAt: string; createdAt: string; outputDir: string; job: { id: string; attempt: number; status: string; progress: number; currentFrame: number | null; totalFrames: number | null; etaSeconds: number | null; priority: number; machineName: string | null; errorMessage: string | null; } | null; } interface Props { projects: { id: string; name: string; code: string }[]; /** Status to open filtered to, from `?status=` (see page.tsx). */ initialStatus?: string; } const PAGE_SIZE = 25; const BLENDER_ACTIVE = ["QUEUED", "CLAIMED", "RUNNING"]; export function PipelineQueueClient({ projects, initialStatus = "all" }: Props) { const { data: session } = useSession(); const { toast } = useToast(); const queryClient = useQueryClient(); const [projectId, setProjectId] = useState("all"); const [statusFilter, setStatusFilter] = useState(initialStatus); const [page, setPage] = useState(1); const isAdmin = ["ADMIN", "PRODUCER", "SUPERVISOR"].includes(session?.user?.role ?? ""); const { data, isLoading, refetch, isFetching } = useQuery({ queryKey: ["pipeline-queue", projectId, statusFilter, page], queryFn: async () => { const params = new URLSearchParams({ limit: String(PAGE_SIZE), page: String(page) }); if (projectId !== "all") params.set("projectId", projectId); if (statusFilter !== "all") params.set("status", statusFilter); const res = await fetch(`/api/render/queue?${params}`); if (!res.ok) throw new Error("Failed to load queue"); return res.json() as Promise<{ exports: QueueExport[]; pagination: { page: number; total: number; pages: number }; statusCounts: Record; }>; }, refetchInterval: 5000, // Keep the current page on screen while the next one loads, instead of // flashing "Loading…" on every page turn. placeholderData: (previous) => previous, }); // Fetched here rather than in the tab so the tab label can say how many are // running: a Blender render must not become invisible by sitting in a tab. const { data: blenderData } = useQuery({ queryKey: ["blender-jobs", projectId], queryFn: async () => { const qs = projectId !== "all" ? `?projectId=${encodeURIComponent(projectId)}` : ""; const res = await fetch(`/api/render/blender${qs}`); if (!res.ok) throw new Error("Failed to load Blender jobs"); return res.json() as Promise<{ jobs: BlenderJobRow[] }>; }, refetchInterval: 5000, }); const exports = data?.exports ?? []; const pagination = data?.pagination; const statusCounts = data?.statusCounts ?? {}; const countOf = (statuses: string[]) => statuses.reduce((n, s) => n + (statusCounts[s] ?? 0), 0); const totalExports = Object.values(statusCounts).reduce((n, c) => n + c, 0); const blenderJobs = blenderData?.jobs ?? []; const blenderActive = blenderJobs.filter((j) => BLENDER_ACTIVE.includes(j.status)).length; const blenderFailed = blenderJobs.filter((j) => ["FAILED", "EXPIRED"].includes(j.status)).length; async function action(exportId: string, verb: "retry" | "cancel" | "mark-done") { const res = await fetch(`/api/render/exports/${exportId}/${verb}`, { method: "POST" }); const body = await res.json().catch(() => ({})); if (!res.ok) { toast({ title: `${verb} failed`, description: body.error ?? res.statusText, variant: "destructive" }); } else { toast({ title: `Export ${verb === "mark-done" ? "marked done" : verb === "retry" ? "requeued" : "cancelled"}` }); } queryClient.invalidateQueries({ queryKey: ["pipeline-queue"] }); } const cards: { label: string; value: number; status?: string; className?: string }[] = [ { label: "Queued", value: countOf(["QUEUED"]), status: "QUEUED" }, { label: "Rendering", value: countOf(["RENDERING"]), status: "RENDERING", className: "text-blue-400" }, // Several statuses count as failed and the filter takes one, so this card // is a figure only. { label: "Failed", value: countOf(FAILED_STATUSES), className: "text-red-400" }, { label: "Ready for QC", value: countOf(["READY_FOR_QC"]), status: "READY_FOR_QC", className: "text-amber-400" }, { label: "Ready for Delivery", value: countOf(["READY_FOR_DELIVERY"]), status: "READY_FOR_DELIVERY", className: "text-green-400", }, ]; const changeProject = (id: string) => { setProjectId(id); setPage(1); }; const changeStatus = (status: string) => { setStatusFilter(status); setPage(1); }; const firstRow = pagination && pagination.total > 0 ? (pagination.page - 1) * PAGE_SIZE + 1 : 0; const lastRow = pagination ? Math.min(pagination.page * PAGE_SIZE, pagination.total) : 0; return (

Render Queue

After Effects exports and Blender renders — live status, retries and history

After Effects exports {totalExports} Blender renders {blenderActive > 0 ? ( {blenderActive} active ) : blenderFailed > 0 ? ( {blenderFailed} failed ) : ( {blenderJobs.length} )} {/* Summary cards — each one with a status filters the table to what it counts */}
{cards.map((c) => { const selected = c.status !== undefined && statusFilter === c.status; const body = ( <>
{c.value}
{c.label}
); return c.status ? ( ) : (
{body}
); })}
{isLoading ? ( ) : exports.length === 0 ? ( ) : ( exports.map((e) => ( )) )}
Shot Version Status Progress Machine Attempt Queued Actions
Loading…
{statusFilter === "all" ? "No exports yet — queue one from the After Effects panel" : `No exports are ${statusLabel(statusFilter).toLowerCase()}`}
{e.shotCode}
{e.projectCode} {e.episode ? ` · ep ${e.episode}` : ""}
{e.versionString} {statusLabel(e.status)} {e.status === "RENDERING" && e.job ? (
{e.job.currentFrame != null && e.job.totalFrames != null ? `frame ${e.job.currentFrame}/${e.job.totalFrames} · ` : ""} ETA {formatEta(e.job.etaSeconds)}
) : ( — )}
{e.job?.machineName ?? "—"} {e.job ? `${e.job.attempt}` : "—"} {new Date(e.createdAt).toLocaleString()}
{FAILED_STATUSES.includes(e.status) && ( )} {ACTIVE_STATUSES.includes(e.status) && ( )} {isAdmin && ["QUEUED", "RENDERING"].includes(e.status) && ( )}
{pagination && pagination.pages > 1 && (
{firstRow}–{lastRow} of {pagination.total}
Page {pagination.page} of {pagination.pages}
)}
); } interface BlenderJobRow { id: string; label: string | null; status: string; attempt: number; maxAttempts: number; progress: number; currentFrame: number | null; totalFrames: number | null; etaSeconds: number | null; errorMessage: string | null; machineName: string | null; submittedBy: string | null; projectCode: string | null; blendFile: string | null; frameStart: number | null; frameEnd: number | null; createdAt: string; } const BLENDER_STATUS_STYLES: Record = { QUEUED: "bg-zinc-500/15 text-zinc-300 border-zinc-500/30", CLAIMED: "bg-blue-500/15 text-blue-400 border-blue-500/30", RUNNING: "bg-blue-500/15 text-blue-400 border-blue-500/30", COMPLETED: "bg-emerald-500/15 text-emerald-400 border-emerald-500/30", FAILED: "bg-red-500/15 text-red-400 border-red-500/30", CANCELLED: "bg-zinc-500/10 text-zinc-500 border-zinc-600/30", EXPIRED: "bg-red-500/15 text-red-400 border-red-500/30", }; /** * Standalone Blender renders. They have no Export behind them, so they cannot * appear in the exports table — but they share the queue, and a render nobody * can see is a render nobody can retry. */ function BlenderQueue({ jobs, loaded }: { jobs: BlenderJobRow[]; loaded: boolean }) { const { toast } = useToast(); const queryClient = useQueryClient(); async function jobAction(id: string, verb: "cancel" | "retry") { const res = await fetch(`/api/render/blender/${id}?action=${verb}`, { method: "POST" }); if (!res.ok) { const body = await res.json().catch(() => ({})); toast({ title: `${verb} failed`, description: body.error ?? res.statusText, variant: "destructive" }); } queryClient.invalidateQueries({ queryKey: ["blender-jobs"] }); } if (jobs.length === 0) { return (
{loaded ? "No Blender renders yet — submit one from the Blender panel" : "Loading…"}
); } return (
{jobs.map((j) => (
{j.label ?? "(untitled)"} {j.status.toLowerCase()} {j.projectCode && {j.projectCode}} {j.frameStart != null && ( frames {j.frameStart}–{j.frameEnd} )} {j.status === "RUNNING" && ( {Math.round(j.progress * 100)}% {j.currentFrame != null ? ` · frame ${j.currentFrame}` : ""} {j.etaSeconds ? ` · ETA ${formatEta(j.etaSeconds)}` : ""} )} {j.machineName && {j.machineName}} {j.attempt > 1 && ( attempt {j.attempt}/{j.maxAttempts} )} {["QUEUED", "CLAIMED", "RUNNING"].includes(j.status) && ( )} {["FAILED", "CANCELLED", "EXPIRED"].includes(j.status) && ( )}
{j.blendFile &&
{j.blendFile}
} {j.errorMessage &&
{j.errorMessage}
}
))}
); }