Update workflow run page (#1372)

This commit is contained in:
Shuchang Zheng
2024-12-11 09:23:07 -08:00
committed by GitHub
parent 9cf4743961
commit 7272dadf3d
11 changed files with 661 additions and 494 deletions

View File

@@ -17,6 +17,10 @@ import { WorkflowRunParameters } from "./routes/workflows/WorkflowRunParameters"
import { Workflows } from "./routes/workflows/Workflows";
import { WorkflowsPageLayout } from "./routes/workflows/WorkflowsPageLayout";
import { WorkflowEditor } from "./routes/workflows/editor/WorkflowEditor";
import { WorkflowRunBlocks } from "./routes/workflows/workflowRun/WorkflowRunBlocks";
import { WorkflowRunOutput } from "./routes/workflows/workflowRun/WorkflowRunOutput";
import { WorkflowPostRunParameters } from "./routes/workflows/workflowRun/WorkflowPostRunParameters";
import { WorkflowRunRecording } from "./routes/workflows/workflowRun/WorkflowRunRecording";
const router = createBrowserRouter([
{
@@ -108,6 +112,29 @@ const router = createBrowserRouter([
{
path: ":workflowRunId",
element: <WorkflowRun />,
children: [
{
index: true,
element: <Navigate to="blocks" />,
},
{
path: "blocks",
element: <WorkflowRunBlocks />,
},
{
path: "output",
element: <WorkflowRunOutput />,
},
{
path: "parameters",
element: <WorkflowPostRunParameters />,
},
{
path: "recording",
element: <WorkflowRunRecording />,
},
],
},
],
},

View File

@@ -257,7 +257,7 @@ function TaskDetails() {
workflow &&
workflowRun && (
<Link
to={`/workflows/${workflow.workflow_permanent_id}/${workflowRun.workflow_run_id}`}
to={`/workflows/${workflow.workflow_permanent_id}/${workflowRun.workflow_run_id}/blocks`}
>
{workflow.title}
</Link>

View File

@@ -135,7 +135,7 @@ function RunWorkflowForm({
<ToastAction altText="View">
<Button asChild>
<Link
to={`/workflows/${workflowPermanentId}/${response.data.workflow_run_id}`}
to={`/workflows/${workflowPermanentId}/${response.data.workflow_run_id}/blocks`}
>
View
</Link>

View File

@@ -132,14 +132,14 @@ function WorkflowPage() {
if (event.ctrlKey || event.metaKey) {
window.open(
window.location.origin +
`/workflows/${workflowPermanentId}/${workflowRun.workflow_run_id}`,
`/workflows/${workflowPermanentId}/${workflowRun.workflow_run_id}/blocks`,
"_blank",
"noopener,noreferrer",
);
return;
}
navigate(
`/workflows/${workflowPermanentId}/${workflowRun.workflow_run_id}`,
`/workflows/${workflowPermanentId}/${workflowRun.workflow_run_id}/blocks`,
);
}}
className="cursor-pointer"

View File

@@ -1,12 +1,5 @@
import { getClient } from "@/api/AxiosClient";
import {
Status,
TaskApiResponse,
WorkflowRunStatusApiResponse,
} from "@/api/types";
import { StatusBadge } from "@/components/StatusBadge";
import { ZoomableImage } from "@/components/ZoomableImage";
import { AspectRatio } from "@/components/ui/aspect-ratio";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -18,83 +11,29 @@ import {
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Pagination,
PaginationContent,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from "@/components/ui/pagination";
import { Skeleton } from "@/components/ui/skeleton";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { toast } from "@/components/ui/use-toast";
import { useApiCredential } from "@/hooks/useApiCredential";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { copyText } from "@/util/copyText";
import { apiBaseUrl, envCredential } from "@/util/env";
import {
localTimeFormatWithShortDate,
timeFormatWithShortDate,
} from "@/util/timeFormat";
import { cn } from "@/util/utils";
import { apiBaseUrl } from "@/util/env";
import {
CopyIcon,
FileIcon,
Pencil2Icon,
PlayIcon,
ReaderIcon,
ReloadIcon,
} from "@radix-ui/react-icons";
import {
keepPreviousData,
useMutation,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import fetchToCurl from "fetch-to-curl";
import { useEffect, useState } from "react";
import {
Link,
useNavigate,
useParams,
useSearchParams,
} from "react-router-dom";
import {
statusIsFinalized,
statusIsNotFinalized,
statusIsRunningOrQueued,
} from "../tasks/types";
import { WorkflowBlockCollapsibleContent } from "./WorkflowBlockCollapsibleContent";
import { CodeEditor } from "./components/CodeEditor";
import { Link, NavLink, Outlet, useParams } from "react-router-dom";
import { statusIsFinalized, statusIsRunningOrQueued } from "../tasks/types";
import { useWorkflowQuery } from "./hooks/useWorkflowQuery";
type StreamMessage = {
task_id: string;
status: string;
screenshot?: string;
};
let socket: WebSocket | null = null;
const wssBaseUrl = import.meta.env.VITE_WSS_BASE_URL;
import { useWorkflowRunQuery } from "./hooks/useWorkflowRunQuery";
import { cn } from "@/util/utils";
function WorkflowRun() {
const [searchParams, setSearchParams] = useSearchParams();
const page = searchParams.get("page") ? Number(searchParams.get("page")) : 1;
const { workflowRunId, workflowPermanentId } = useParams();
const credentialGetter = useCredentialGetter();
const [streamImgSrc, setStreamImgSrc] = useState<string>("");
const navigate = useNavigate();
const apiCredential = useApiCredential();
const queryClient = useQueryClient();
@@ -103,61 +42,7 @@ function WorkflowRun() {
});
const { data: workflowRun, isLoading: workflowRunIsLoading } =
useQuery<WorkflowRunStatusApiResponse>({
queryKey: ["workflowRun", workflowPermanentId, workflowRunId],
queryFn: async () => {
const client = await getClient(credentialGetter);
return client
.get(`/workflows/${workflowPermanentId}/runs/${workflowRunId}`)
.then((response) => response.data);
},
refetchInterval: (query) => {
if (!query.state.data) {
return false;
}
if (statusIsNotFinalized(query.state.data)) {
return 5000;
}
return false;
},
placeholderData: keepPreviousData,
refetchOnMount: (query) => {
if (!query.state.data) {
return false;
}
return statusIsRunningOrQueued(query.state.data) ? "always" : false;
},
refetchOnWindowFocus: (query) => {
if (!query.state.data) {
return false;
}
return statusIsRunningOrQueued(query.state.data);
},
});
const { data: workflowTasks, isLoading: workflowTasksIsLoading } = useQuery<
Array<TaskApiResponse>
>({
queryKey: ["workflowTasks", workflowRunId, page],
queryFn: async () => {
const client = await getClient(credentialGetter);
const params = new URLSearchParams();
params.append("page", String(page));
return client
.get(`/tasks?workflow_run_id=${workflowRunId}`, { params })
.then((response) => response.data);
},
refetchInterval: () => {
if (workflowRun?.status === Status.Running) {
return 5000;
}
return false;
},
placeholderData: keepPreviousData,
refetchOnMount: workflowRun?.status === Status.Running ? "always" : false,
refetchOnWindowFocus:
workflowRun?.status === Status.Running ? "always" : false,
});
useWorkflowRunQuery();
const cancelWorkflowMutation = useMutation({
mutationFn: async () => {
@@ -188,152 +73,11 @@ function WorkflowRun() {
},
});
const currentRunningTask = workflowTasks?.find(
(task) => task.status === Status.Running,
);
const workflowRunIsRunningOrQueued =
workflowRun && statusIsRunningOrQueued(workflowRun);
const workflowRunIsFinalized = workflowRun && statusIsFinalized(workflowRun);
const showStream = workflowRun && statusIsNotFinalized(workflowRun);
useEffect(() => {
if (!workflowRunIsRunningOrQueued) {
return;
}
async function run() {
// Create WebSocket connection.
let credential = null;
if (credentialGetter) {
const token = await credentialGetter();
credential = `?token=Bearer ${token}`;
} else {
credential = `?apikey=${envCredential}`;
}
if (socket) {
socket.close();
}
socket = new WebSocket(
`${wssBaseUrl}/stream/workflow_runs/${workflowRunId}${credential}`,
);
// Listen for messages
socket.addEventListener("message", (event) => {
try {
const message: StreamMessage = JSON.parse(event.data);
if (message.screenshot) {
setStreamImgSrc(message.screenshot);
}
if (
message.status === "completed" ||
message.status === "failed" ||
message.status === "terminated"
) {
socket?.close();
queryClient.invalidateQueries({
queryKey: ["workflowRuns"],
});
queryClient.invalidateQueries({
queryKey: ["workflowRun", workflowPermanentId, workflowRunId],
});
queryClient.invalidateQueries({
queryKey: ["workflowTasks", workflowRunId],
});
if (
message.status === "failed" ||
message.status === "terminated"
) {
toast({
title: "Run Failed",
description: "The workflow run has failed.",
variant: "destructive",
});
} else if (message.status === "completed") {
toast({
title: "Run Completed",
description: "The workflow run has been completed.",
variant: "success",
});
}
}
} catch (e) {
console.error("Failed to parse message", e);
}
});
socket.addEventListener("close", () => {
socket = null;
});
}
run();
return () => {
if (socket) {
socket.close();
socket = null;
}
};
}, [
credentialGetter,
workflowRunId,
workflowRunIsRunningOrQueued,
queryClient,
workflowPermanentId,
]);
function getStream() {
if (workflowRun?.status === Status.Created) {
return (
<div className="flex h-full w-full flex-col items-center justify-center gap-8 rounded-md bg-slate-900 py-8 text-lg">
<span>Workflow has been created.</span>
<span>Stream will start when the workflow is running.</span>
</div>
);
}
if (workflowRun?.status === Status.Queued) {
return (
<div className="flex h-full w-full flex-col items-center justify-center gap-8 rounded-md bg-slate-900 py-8 text-lg">
<span>Your workflow run is queued.</span>
<span>Stream will start when the workflow is running.</span>
</div>
);
}
if (workflowRun?.status === Status.Running && streamImgSrc.length === 0) {
return (
<div className="flex h-full w-full items-center justify-center rounded-md bg-slate-900 py-8 text-lg">
Starting the stream...
</div>
);
}
if (workflowRun?.status === Status.Running && streamImgSrc.length > 0) {
return (
<div className="h-full w-full">
<ZoomableImage
src={`data:image/png;base64,${streamImgSrc}`}
className="rounded-md"
/>
</div>
);
}
return null;
}
function handleNavigate(event: React.MouseEvent, id: string) {
if (event.ctrlKey || event.metaKey) {
window.open(
window.location.origin + `/tasks/${id}/actions`,
"_blank",
"noopener,noreferrer",
);
} else {
navigate(`/tasks/${id}/actions`);
}
}
const parameters = workflowRun?.parameters ?? {};
const title = workflowIsLoading ? (
@@ -354,31 +98,6 @@ function WorkflowRun() {
</div>
) : null;
const skeleton = (
<TableRow>
<TableCell className="w-10">
<Skeleton className="h-6 w-full" />
</TableCell>
<TableCell className="w-1/5">
<Skeleton className="h-6 w-full" />
</TableCell>
<TableCell className="w-1/6">
<Skeleton className="h-6 w-full" />
</TableCell>
<TableCell className="w-1/4">
<Skeleton className="h-6 w-full" />
</TableCell>
<TableCell className="w-1/8">
<Skeleton className="h-6 w-full" />
</TableCell>
<TableCell className="w-1/5">
<Skeleton className="h-6 w-full" />
</TableCell>
</TableRow>
);
const fileUrls = workflowRun?.downloaded_file_urls ?? [];
return (
<div className="space-y-8">
<header className="flex justify-between">
@@ -480,207 +199,65 @@ function WorkflowRun() {
</div>
</header>
{workflowFailureReason}
{showStream && (
<div className="flex gap-5">
<div className="w-3/4 shrink-0">
<AspectRatio ratio={16 / 9}>{getStream()}</AspectRatio>
</div>
<div className="flex w-full min-w-0 flex-col gap-4 rounded-md bg-slate-elevation1 p-4">
<header className="text-lg">Current Task</header>
{workflowRunIsLoading || !currentRunningTask ? (
<div>Waiting for a task to start...</div>
) : (
<div className="flex h-full flex-col gap-2">
<div className="flex gap-2 rounded-sm bg-slate-elevation3 p-2">
<Label className="text-sm text-slate-400">ID</Label>
<span className="text-sm">{currentRunningTask.task_id}</span>
</div>
<div className="flex gap-2 rounded-sm bg-slate-elevation3 p-2">
<Label className="text-sm text-slate-400">URL</Label>
<span
className="truncate text-sm"
title={currentRunningTask.request.url}
>
{currentRunningTask.request.url}
</span>
</div>
<div className="flex items-center gap-2 rounded-sm bg-slate-elevation3 p-2">
<Label className="text-sm text-slate-400">Status</Label>
<span className="text-sm">
<StatusBadge status={currentRunningTask.status} />
</span>
</div>
<div className="flex gap-2 rounded-sm bg-slate-elevation3 p-2">
<Label className="text-sm text-slate-400">Created</Label>
<span
className="truncate text-sm"
title={timeFormatWithShortDate(
currentRunningTask.created_at,
)}
>
{currentRunningTask &&
localTimeFormatWithShortDate(
currentRunningTask.created_at,
)}
</span>
</div>
<div className="mt-auto flex justify-end">
<Button asChild>
<Link to={`/tasks/${currentRunningTask.task_id}/actions`}>
<ReaderIcon className="mr-2 h-4 w-4" />
View Actions
</Link>
</Button>
</div>
</div>
)}
</div>
</div>
)}
<div className="space-y-5">
<header>
<h2 className="text-2xl">
{workflowRunIsRunningOrQueued ? "Previous Blocks" : "Blocks"}
</h2>
</header>
<div className="rounded-md border">
<Table>
<TableHeader className="rounded-t-md bg-slate-elevation2">
<TableRow>
<TableHead className="w-10 rounded-tl-md"></TableHead>
<TableHead className="w-1/5 text-slate-400">
Task Title
</TableHead>
<TableHead className="w-1/6 text-slate-400">ID</TableHead>
<TableHead className="w-1/4 text-slate-400">URL</TableHead>
<TableHead className="w-1/8 text-slate-400">Status</TableHead>
<TableHead className="w-1/5 rounded-tr-md text-slate-400">
Created At
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{workflowTasksIsLoading ? (
skeleton
) : workflowTasks?.length === 0 ? (
<TableRow>
<TableCell colSpan={6}>Could not find any tasks</TableCell>
</TableRow>
) : (
workflowTasks
?.filter(
(task) => task.task_id !== currentRunningTask?.task_id,
)
.map((task) => {
return (
<WorkflowBlockCollapsibleContent
key={task.task_id}
task={task}
onNavigate={handleNavigate}
/>
);
})
)}
</TableBody>
</Table>
<Pagination className="pt-2">
<PaginationContent>
<PaginationItem>
<PaginationPrevious
className={cn({ "cursor-not-allowed": page === 1 })}
onClick={() => {
if (page === 1) {
return;
}
const params = new URLSearchParams();
params.set("page", String(Math.max(1, page - 1)));
setSearchParams(params, { replace: true });
}}
/>
</PaginationItem>
<PaginationItem>
<PaginationLink>{page}</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationNext
onClick={() => {
const params = new URLSearchParams();
params.set("page", String(page + 1));
setSearchParams(params, { replace: true });
}}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
</div>
</div>
{workflowRunIsFinalized && (
<div className="space-y-4">
<header>
<h2 className="text-lg font-semibold">Block Outputs</h2>
</header>
<CodeEditor
language="json"
value={JSON.stringify(workflowRun.outputs, null, 2)}
readOnly
minHeight="96px"
maxHeight="500px"
/>
</div>
)}
{workflowRunIsFinalized && (
<div className="space-y-4">
<header>
<h2 className="text-lg font-semibold">Downloaded Files</h2>
</header>
<div className="space-y-2">
{fileUrls.length > 0 ? (
fileUrls.map((url, index) => {
return (
<div key={url} title={url} className="flex gap-2">
<FileIcon className="size-6" />
<a href={url} className="underline underline-offset-4">
<span>{`File ${index + 1}`}</span>
</a>
</div>
);
})
) : (
<div>No files downloaded</div>
)}
</div>
</div>
)}
{Object.entries(parameters).length > 0 && (
<div className="space-y-4">
<header>
<h2 className="text-lg font-semibold">Input Parameter Values</h2>
</header>
{Object.entries(parameters).length === 0 && (
<div>This workflow doesn't have any input parameters.</div>
)}
{Object.entries(parameters).map(([key, value]) => {
return (
<div key={key} className="flex flex-col gap-2">
<Label>{key}</Label>
{typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean" ? (
<Input value={String(value)} readOnly />
) : (
<CodeEditor
value={JSON.stringify(value, null, 2)}
readOnly
language="json"
minHeight="96px"
maxHeight="500px"
/>
)}
</div>
<div className="flex w-fit gap-2 rounded-sm border border-slate-700 p-2">
<NavLink
to="blocks"
replace
className={({ isActive }) => {
return cn(
"cursor-pointer rounded-sm px-3 py-2 hover:bg-slate-700",
{
"bg-slate-700": isActive,
},
);
})}
</div>
)}
}}
>
Blocks
</NavLink>
<NavLink
to="output"
replace
className={({ isActive }) => {
return cn(
"cursor-pointer rounded-sm px-3 py-2 hover:bg-slate-700",
{
"bg-slate-700": isActive,
},
);
}}
>
Output
</NavLink>
<NavLink
to="parameters"
replace
className={({ isActive }) => {
return cn(
"cursor-pointer rounded-sm px-3 py-2 hover:bg-slate-700",
{
"bg-slate-700": isActive,
},
);
}}
>
Parameters
</NavLink>
<NavLink
to="recording"
replace
className={({ isActive }) => {
return cn(
"cursor-pointer rounded-sm px-3 py-2 hover:bg-slate-700",
{
"bg-slate-700": isActive,
},
);
}}
>
Recording
</NavLink>
</div>
<Outlet />
</div>
);
}

View File

@@ -396,14 +396,14 @@ function Workflows() {
if (event.ctrlKey || event.metaKey) {
window.open(
window.location.origin +
`/workflows/${workflowRun.workflow_permanent_id}/${workflowRun.workflow_run_id}`,
`/workflows/${workflowRun.workflow_permanent_id}/${workflowRun.workflow_run_id}/blocks`,
"_blank",
"noopener,noreferrer",
);
return;
}
navigate(
`/workflows/${workflowRun.workflow_permanent_id}/${workflowRun.workflow_run_id}`,
`/workflows/${workflowRun.workflow_permanent_id}/${workflowRun.workflow_run_id}/blocks`,
);
}}
className="cursor-pointer"

View File

@@ -0,0 +1,48 @@
import { getClient } from "@/api/AxiosClient";
import { WorkflowRunStatusApiResponse } from "@/api/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import {
statusIsNotFinalized,
statusIsRunningOrQueued,
} from "@/routes/tasks/types";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { useParams } from "react-router-dom";
function useWorkflowRunQuery() {
const { workflowRunId, workflowPermanentId } = useParams();
const credentialGetter = useCredentialGetter();
return useQuery<WorkflowRunStatusApiResponse>({
queryKey: ["workflowRun", workflowPermanentId, workflowRunId],
queryFn: async () => {
const client = await getClient(credentialGetter);
return client
.get(`/workflows/${workflowPermanentId}/runs/${workflowRunId}`)
.then((response) => response.data);
},
refetchInterval: (query) => {
if (!query.state.data) {
return false;
}
if (statusIsNotFinalized(query.state.data)) {
return 5000;
}
return false;
},
placeholderData: keepPreviousData,
refetchOnMount: (query) => {
if (!query.state.data) {
return false;
}
return statusIsRunningOrQueued(query.state.data) ? "always" : false;
},
refetchOnWindowFocus: (query) => {
if (!query.state.data) {
return false;
}
return statusIsRunningOrQueued(query.state.data);
},
});
}
export { useWorkflowRunQuery };

View File

@@ -0,0 +1,43 @@
import { Label } from "@/components/ui/label";
import { useWorkflowRunQuery } from "../hooks/useWorkflowRunQuery";
import { CodeEditor } from "../components/CodeEditor";
import { AutoResizingTextarea } from "@/components/AutoResizingTextarea/AutoResizingTextarea";
function WorkflowPostRunParameters() {
const { data: workflowRun } = useWorkflowRunQuery();
const parameters = workflowRun?.parameters ?? {};
return Object.entries(parameters).length > 0 ? (
<div className="space-y-4 rounded-lg bg-slate-elevation3 px-6 py-5">
<header>
<h2 className="text-lg font-semibold">Input Parameter Values</h2>
</header>
{Object.entries(parameters).map(([key, value]) => {
return (
<div key={key} className="space-y-2">
<Label className="text-lg">{key}</Label>
{typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean" ? (
<AutoResizingTextarea value={String(value)} readOnly />
) : (
<CodeEditor
value={JSON.stringify(value, null, 2)}
readOnly
language="json"
minHeight="96px"
maxHeight="500px"
/>
)}
</div>
);
})}
</div>
) : (
Object.entries(parameters).length === 0 && (
<div>This workflow doesn't have any input parameters.</div>
)
);
}
export { WorkflowPostRunParameters };

View File

@@ -0,0 +1,411 @@
import { getClient } from "@/api/AxiosClient";
import { Status, TaskApiResponse } from "@/api/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import {
keepPreviousData,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import {
Link,
useNavigate,
useParams,
useSearchParams,
} from "react-router-dom";
import { useWorkflowRunQuery } from "../hooks/useWorkflowRunQuery";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Skeleton } from "@/components/ui/skeleton";
import { WorkflowBlockCollapsibleContent } from "../WorkflowBlockCollapsibleContent";
import {
Pagination,
PaginationContent,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from "@/components/ui/pagination";
import { cn } from "@/util/utils";
import {
statusIsNotFinalized,
statusIsRunningOrQueued,
} from "@/routes/tasks/types";
import { useEffect, useState } from "react";
import { envCredential } from "@/util/env";
import { toast } from "@/components/ui/use-toast";
import { ZoomableImage } from "@/components/ZoomableImage";
import { AspectRatio } from "@/components/ui/aspect-ratio";
import { Label } from "@/components/ui/label";
import { StatusBadge } from "@/components/StatusBadge";
import {
localTimeFormatWithShortDate,
timeFormatWithShortDate,
} from "@/util/timeFormat";
import { Button } from "@/components/ui/button";
import { ReaderIcon } from "@radix-ui/react-icons";
type StreamMessage = {
task_id: string;
status: string;
screenshot?: string;
};
let socket: WebSocket | null = null;
const wssBaseUrl = import.meta.env.VITE_WSS_BASE_URL;
function WorkflowRunBlocks() {
const navigate = useNavigate();
const [searchParams, setSearchParams] = useSearchParams();
const [streamImgSrc, setStreamImgSrc] = useState<string>("");
const { workflowRunId, workflowPermanentId } = useParams();
const page = searchParams.get("page") ? Number(searchParams.get("page")) : 1;
const credentialGetter = useCredentialGetter();
const queryClient = useQueryClient();
const { data: workflowRun, isLoading: workflowRunIsLoading } =
useWorkflowRunQuery();
const workflowRunIsRunningOrQueued =
workflowRun && statusIsRunningOrQueued(workflowRun);
const showStream = workflowRun && statusIsNotFinalized(workflowRun);
useEffect(() => {
if (!workflowRunIsRunningOrQueued) {
return;
}
async function run() {
// Create WebSocket connection.
let credential = null;
if (credentialGetter) {
const token = await credentialGetter();
credential = `?token=Bearer ${token}`;
} else {
credential = `?apikey=${envCredential}`;
}
if (socket) {
socket.close();
}
socket = new WebSocket(
`${wssBaseUrl}/stream/workflow_runs/${workflowRunId}${credential}`,
);
// Listen for messages
socket.addEventListener("message", (event) => {
try {
const message: StreamMessage = JSON.parse(event.data);
if (message.screenshot) {
setStreamImgSrc(message.screenshot);
}
if (
message.status === "completed" ||
message.status === "failed" ||
message.status === "terminated"
) {
socket?.close();
queryClient.invalidateQueries({
queryKey: ["workflowRuns"],
});
queryClient.invalidateQueries({
queryKey: ["workflowRun", workflowPermanentId, workflowRunId],
});
queryClient.invalidateQueries({
queryKey: ["workflowTasks", workflowRunId],
});
if (
message.status === "failed" ||
message.status === "terminated"
) {
toast({
title: "Run Failed",
description: "The workflow run has failed.",
variant: "destructive",
});
} else if (message.status === "completed") {
toast({
title: "Run Completed",
description: "The workflow run has been completed.",
variant: "success",
});
}
}
} catch (e) {
console.error("Failed to parse message", e);
}
});
socket.addEventListener("close", () => {
socket = null;
});
}
run();
return () => {
if (socket) {
socket.close();
socket = null;
}
};
}, [
credentialGetter,
workflowRunId,
workflowRunIsRunningOrQueued,
queryClient,
workflowPermanentId,
]);
function getStream() {
if (workflowRun?.status === Status.Created) {
return (
<div className="flex h-full w-full flex-col items-center justify-center gap-8 rounded-md bg-slate-900 py-8 text-lg">
<span>Workflow has been created.</span>
<span>Stream will start when the workflow is running.</span>
</div>
);
}
if (workflowRun?.status === Status.Queued) {
return (
<div className="flex h-full w-full flex-col items-center justify-center gap-8 rounded-md bg-slate-900 py-8 text-lg">
<span>Your workflow run is queued.</span>
<span>Stream will start when the workflow is running.</span>
</div>
);
}
if (workflowRun?.status === Status.Running && streamImgSrc.length === 0) {
return (
<div className="flex h-full w-full items-center justify-center rounded-md bg-slate-900 py-8 text-lg">
Starting the stream...
</div>
);
}
if (workflowRun?.status === Status.Running && streamImgSrc.length > 0) {
return (
<div className="h-full w-full">
<ZoomableImage
src={`data:image/png;base64,${streamImgSrc}`}
className="rounded-md"
/>
</div>
);
}
return null;
}
const { data: workflowTasks, isLoading: workflowTasksIsLoading } = useQuery<
Array<TaskApiResponse>
>({
queryKey: ["workflowTasks", workflowRunId, page],
queryFn: async () => {
const client = await getClient(credentialGetter);
const params = new URLSearchParams();
params.append("page", String(page));
params.append("page_size", "20");
return client
.get(`/tasks?workflow_run_id=${workflowRunId}`, { params })
.then((response) => response.data);
},
refetchInterval: () => {
if (workflowRun?.status === Status.Running) {
return 5000;
}
return false;
},
placeholderData: keepPreviousData,
refetchOnMount: workflowRun?.status === Status.Running ? "always" : false,
refetchOnWindowFocus:
workflowRun?.status === Status.Running ? "always" : false,
});
const skeleton = (
<TableRow>
<TableCell className="w-10">
<Skeleton className="h-6 w-full" />
</TableCell>
<TableCell className="w-1/5">
<Skeleton className="h-6 w-full" />
</TableCell>
<TableCell className="w-1/6">
<Skeleton className="h-6 w-full" />
</TableCell>
<TableCell className="w-1/4">
<Skeleton className="h-6 w-full" />
</TableCell>
<TableCell className="w-1/8">
<Skeleton className="h-6 w-full" />
</TableCell>
<TableCell className="w-1/5">
<Skeleton className="h-6 w-full" />
</TableCell>
</TableRow>
);
const currentRunningTask = workflowTasks?.find(
(task) => task.status === Status.Running,
);
function handleNavigate(event: React.MouseEvent, id: string) {
if (event.ctrlKey || event.metaKey) {
window.open(
window.location.origin + `/tasks/${id}/actions`,
"_blank",
"noopener,noreferrer",
);
} else {
navigate(`/tasks/${id}/actions`);
}
}
return (
<div className="space-y-8">
{showStream && (
<div className="space-y-4">
<header>
<h1 className="text-2xl">Live Stream</h1>
</header>
<div className="flex gap-5">
<div className="w-3/4 shrink-0">
<AspectRatio ratio={16 / 9}>{getStream()}</AspectRatio>
</div>
<div className="flex w-full min-w-0 flex-col gap-4 rounded-md bg-slate-elevation1 p-4">
<header className="text-lg">Current Task</header>
{workflowRunIsLoading || !currentRunningTask ? (
<div>Waiting for a task to start...</div>
) : (
<div className="flex h-full flex-col gap-2">
<div className="flex gap-2 rounded-sm bg-slate-elevation3 p-2">
<Label className="text-sm text-slate-400">ID</Label>
<span className="text-sm">
{currentRunningTask.task_id}
</span>
</div>
<div className="flex gap-2 rounded-sm bg-slate-elevation3 p-2">
<Label className="text-sm text-slate-400">URL</Label>
<span
className="truncate text-sm"
title={currentRunningTask.request.url}
>
{currentRunningTask.request.url}
</span>
</div>
<div className="flex items-center gap-2 rounded-sm bg-slate-elevation3 p-2">
<Label className="text-sm text-slate-400">Status</Label>
<span className="text-sm">
<StatusBadge status={currentRunningTask.status} />
</span>
</div>
<div className="flex gap-2 rounded-sm bg-slate-elevation3 p-2">
<Label className="text-sm text-slate-400">Created</Label>
<span
className="truncate text-sm"
title={timeFormatWithShortDate(
currentRunningTask.created_at,
)}
>
{currentRunningTask &&
localTimeFormatWithShortDate(
currentRunningTask.created_at,
)}
</span>
</div>
<div className="mt-auto flex justify-end">
<Button asChild>
<Link to={`/tasks/${currentRunningTask.task_id}/actions`}>
<ReaderIcon className="mr-2 h-4 w-4" />
View Actions
</Link>
</Button>
</div>
</div>
)}
</div>
</div>
</div>
)}
<div className="space-y-4">
<header>
<h1 className="text-2xl">Workflow Blocks</h1>
</header>
<div className="rounded-md border">
<Table>
<TableHeader className="rounded-t-md bg-slate-elevation2">
<TableRow>
<TableHead className="w-10 rounded-tl-md"></TableHead>
<TableHead className="w-1/5 text-slate-400">
Task Title
</TableHead>
<TableHead className="w-1/6 text-slate-400">ID</TableHead>
<TableHead className="w-1/4 text-slate-400">URL</TableHead>
<TableHead className="w-1/8 text-slate-400">Status</TableHead>
<TableHead className="w-1/5 rounded-tr-md text-slate-400">
Created At
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{workflowTasksIsLoading ? (
skeleton
) : workflowTasks?.length === 0 ? (
<TableRow>
<TableCell colSpan={6}>Could not find any tasks</TableCell>
</TableRow>
) : (
workflowTasks
?.filter(
(task) => task.task_id !== currentRunningTask?.task_id,
)
.map((task) => {
return (
<WorkflowBlockCollapsibleContent
key={task.task_id}
task={task}
onNavigate={handleNavigate}
/>
);
})
)}
</TableBody>
</Table>
<Pagination className="pt-2">
<PaginationContent>
<PaginationItem>
<PaginationPrevious
className={cn({ "cursor-not-allowed": page === 1 })}
onClick={() => {
if (page === 1) {
return;
}
const params = new URLSearchParams();
params.set("page", String(Math.max(1, page - 1)));
setSearchParams(params, { replace: true });
}}
/>
</PaginationItem>
<PaginationItem>
<PaginationLink>{page}</PaginationLink>
</PaginationItem>
<PaginationItem>
<PaginationNext
onClick={() => {
const params = new URLSearchParams();
params.set("page", String(page + 1));
setSearchParams(params, { replace: true });
}}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
</div>
</div>
</div>
);
}
export { WorkflowRunBlocks };

View File

@@ -0,0 +1,48 @@
import { FileIcon } from "@radix-ui/react-icons";
import { CodeEditor } from "../components/CodeEditor";
import { useWorkflowRunQuery } from "../hooks/useWorkflowRunQuery";
function WorkflowRunOutput() {
const { data: workflowRun } = useWorkflowRunQuery();
const outputs = workflowRun?.outputs;
const fileUrls = workflowRun?.downloaded_file_urls ?? [];
return (
<div className="space-y-4">
<header>
<h2 className="text-lg font-semibold">Workflow Run Output</h2>
</header>
<CodeEditor
language="json"
value={
outputs ? JSON.stringify(outputs, null, 2) : "Waiting for outputs.."
}
readOnly
minHeight="96px"
maxHeight="500px"
/>
<div className="space-y-4">
<header>
<h2 className="text-lg font-semibold">Downloaded Files</h2>
</header>
<div className="space-y-2">
{fileUrls.length > 0 ? (
fileUrls.map((url, index) => {
return (
<div key={url} title={url} className="flex gap-2">
<FileIcon className="size-6" />
<a href={url} className="underline underline-offset-4">
<span>{`File ${index + 1}`}</span>
</a>
</div>
);
})
) : (
<div>No files downloaded</div>
)}
</div>
</div>
</div>
);
}
export { WorkflowRunOutput };

View File

@@ -0,0 +1,13 @@
import { useWorkflowRunQuery } from "../hooks/useWorkflowRunQuery";
function WorkflowRunRecording() {
const { data: workflowRun } = useWorkflowRunQuery();
const recordingURL = workflowRun?.recording_url;
return recordingURL ? (
<video src={recordingURL} controls className="w-full rounded-md" />
) : (
<div>No recording available for this workflow</div>
);
}
export { WorkflowRunRecording };