Files
Dorod-Sky/skyvern-frontend/src/routes/tasks/create/CreateNewTaskForm.tsx

488 lines
16 KiB
TypeScript
Raw Normal View History

2024-04-01 21:34:52 +03:00
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { Button } from "@/components/ui/button";
import {
Form,
FormControl,
2024-06-19 19:15:11 +03:00
FormDescription,
2024-04-01 21:34:52 +03:00
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import {
dataExtractionGoalDescription,
extractedInformationSchemaDescription,
navigationGoalDescription,
navigationPayloadDescription,
urlDescription,
webhookCallbackUrlDescription,
} from "../data/descriptionHelperContent";
import { Textarea } from "@/components/ui/textarea";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
2024-05-07 11:31:05 -07:00
import { getClient } from "@/api/AxiosClient";
2024-04-01 21:34:52 +03:00
import { useToast } from "@/components/ui/use-toast";
import { InfoCircledIcon, ReloadIcon } from "@radix-ui/react-icons";
2024-04-01 21:34:52 +03:00
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { ToastAction } from "@radix-ui/react-toast";
import { Link } from "react-router-dom";
2024-04-17 00:15:04 +03:00
import fetchToCurl from "fetch-to-curl";
import { apiBaseUrl } from "@/util/env";
2024-05-07 11:31:05 -07:00
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { useApiCredential } from "@/hooks/useApiCredential";
2024-05-29 09:34:58 -07:00
import { AxiosError } from "axios";
2024-06-19 19:15:11 +03:00
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { OrganizationApiResponse } from "@/api/types";
import { Skeleton } from "@/components/ui/skeleton";
2024-04-01 21:34:52 +03:00
2024-05-20 13:50:21 -07:00
const createNewTaskFormSchema = z
.object({
url: z.string().url({
message: "Invalid URL",
}),
webhookCallbackUrl: z.string().or(z.null()).optional(), // url maybe, but shouldn't be validated as one
navigationGoal: z.string().or(z.null()).optional(),
dataExtractionGoal: z.string().or(z.null()).optional(),
navigationPayload: z.string().or(z.null()).optional(),
extractedInformationSchema: z.string().or(z.null()).optional(),
maxStepsOverride: z.number().optional(),
2024-05-20 13:50:21 -07:00
})
.superRefine(({ navigationGoal, dataExtractionGoal }, ctx) => {
if (!navigationGoal && !dataExtractionGoal) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"At least one of navigation goal or data extraction goal must be provided",
path: ["navigationGoal"],
});
ctx.addIssue({
code: z.ZodIssueCode.custom,
message:
"At least one of navigation goal or data extraction goal must be provided",
path: ["dataExtractionGoal"],
});
return z.NEVER;
}
});
2024-04-01 21:34:52 +03:00
export type CreateNewTaskFormValues = z.infer<typeof createNewTaskFormSchema>;
type Props = {
initialValues: CreateNewTaskFormValues;
};
2024-05-20 13:50:21 -07:00
function transform(value: unknown) {
return value === "" ? null : value;
}
2024-04-01 21:34:52 +03:00
function createTaskRequestObject(formValues: CreateNewTaskFormValues) {
return {
url: formValues.url,
2024-05-20 13:50:21 -07:00
webhook_callback_url: transform(formValues.webhookCallbackUrl),
navigation_goal: transform(formValues.navigationGoal),
data_extraction_goal: transform(formValues.dataExtractionGoal),
2024-06-03 22:15:48 +03:00
proxy_location: "RESIDENTIAL",
2024-04-17 00:15:04 +03:00
error_code_mapping: null,
2024-05-20 13:50:21 -07:00
navigation_payload: transform(formValues.navigationPayload),
extracted_information_schema: transform(
formValues.extractedInformationSchema,
),
2024-04-01 21:34:52 +03:00
};
}
const MAX_STEPS_DEFAULT = 10;
2024-04-01 21:34:52 +03:00
function CreateNewTaskForm({ initialValues }: Props) {
const queryClient = useQueryClient();
const { toast } = useToast();
2024-05-07 11:31:05 -07:00
const credentialGetter = useCredentialGetter();
const apiCredential = useApiCredential();
2024-04-01 21:34:52 +03:00
const { data: organizations, isPending } = useQuery<
Array<OrganizationApiResponse>
>({
queryKey: ["organizations"],
queryFn: async () => {
const client = await getClient(credentialGetter);
return await client
.get("/organizations")
.then((response) => response.data.organizations);
},
});
const organization = organizations?.[0];
2024-04-01 21:34:52 +03:00
const form = useForm<CreateNewTaskFormValues>({
resolver: zodResolver(createNewTaskFormSchema),
defaultValues: initialValues,
values: {
...initialValues,
maxStepsOverride: organization?.max_steps_per_run ?? MAX_STEPS_DEFAULT,
},
2024-04-01 21:34:52 +03:00
});
const mutation = useMutation({
2024-05-07 11:31:05 -07:00
mutationFn: async (formValues: CreateNewTaskFormValues) => {
2024-04-01 21:34:52 +03:00
const taskRequest = createTaskRequestObject(formValues);
2024-05-07 11:31:05 -07:00
const client = await getClient(credentialGetter);
const includeOverrideHeader =
formValues.maxStepsOverride !== organization?.max_steps_per_run &&
formValues.maxStepsOverride !== MAX_STEPS_DEFAULT;
2024-04-01 21:34:52 +03:00
return client.post<
ReturnType<typeof createTaskRequestObject>,
{ data: { task_id: string } }
>("/tasks", taskRequest, {
...(includeOverrideHeader && {
headers: {
"x-max-steps-override":
formValues.maxStepsOverride ?? MAX_STEPS_DEFAULT,
},
}),
});
2024-04-01 21:34:52 +03:00
},
2024-05-29 09:34:58 -07:00
onError: (error: AxiosError) => {
if (error.response?.status === 402) {
toast({
variant: "destructive",
title: "Failed to create task",
description:
"You don't have enough credits to run this task. Go to billing to see your credit balance.",
action: (
<ToastAction altText="Go to Billing">
<Button asChild>
<Link to="billing">Go to Billing</Link>
</Button>
</ToastAction>
),
});
return;
}
2024-04-01 21:34:52 +03:00
toast({
variant: "destructive",
title: "There was an error creating the task.",
2024-04-01 21:34:52 +03:00
description: error.message,
});
},
onSuccess: (response) => {
toast({
2024-05-29 09:34:58 -07:00
variant: "success",
2024-04-01 21:34:52 +03:00
title: "Task Created",
description: `${response.data.task_id} created successfully.`,
action: (
<ToastAction altText="View">
<Button asChild>
<Link to={`/tasks/${response.data.task_id}`}>View</Link>
</Button>
</ToastAction>
),
});
queryClient.invalidateQueries({
queryKey: ["tasks"],
});
},
});
function onSubmit(values: CreateNewTaskFormValues) {
mutation.mutate(values);
}
return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
<FormField
control={form.control}
name="url"
render={({ field }) => (
<FormItem>
<FormLabel>
<div className="flex gap-2">
URL *
2024-04-01 21:34:52 +03:00
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<InfoCircledIcon />
</TooltipTrigger>
<TooltipContent className="max-w-[250px]">
<p>{urlDescription}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
</FormLabel>
2024-06-19 19:15:11 +03:00
<FormDescription>The starting URL for the task</FormDescription>
2024-04-01 21:34:52 +03:00
<FormControl>
<Input placeholder="example.com" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="navigationGoal"
render={({ field }) => (
<FormItem>
<FormLabel>
<div className="flex gap-2">
Navigation Goal
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<InfoCircledIcon />
</TooltipTrigger>
<TooltipContent className="max-w-[250px]">
<p>{navigationGoalDescription}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
</FormLabel>
2024-06-19 19:15:11 +03:00
<FormDescription>
How do you want Skyvern to navigate?
</FormDescription>
2024-04-01 21:34:52 +03:00
<FormControl>
<Textarea
rows={5}
placeholder="Navigation Goal"
{...field}
value={field.value === null ? "" : field.value}
/>
2024-04-01 21:34:52 +03:00
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dataExtractionGoal"
render={({ field }) => (
<FormItem>
<FormLabel>
<div className="flex gap-2">
Data Extraction Goal
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<InfoCircledIcon />
</TooltipTrigger>
<TooltipContent className="max-w-[250px]">
<p>{dataExtractionGoalDescription}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
</FormLabel>
2024-06-19 19:15:11 +03:00
<FormDescription>
If you want Skyvern to extract data after it's finished
navigating
</FormDescription>
2024-04-01 21:34:52 +03:00
<FormControl>
<Textarea
rows={5}
placeholder="Data Extraction Goal"
{...field}
value={field.value === null ? "" : field.value}
2024-04-01 21:34:52 +03:00
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="navigationPayload"
render={({ field }) => (
<FormItem>
<FormLabel>
<div className="flex gap-2">
Navigation Payload
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<InfoCircledIcon />
</TooltipTrigger>
<TooltipContent className="max-w-[250px]">
<p>{navigationPayloadDescription}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
</FormLabel>
2024-06-19 19:15:11 +03:00
<FormDescription>
Any context Skyvern needs to complete its actions (ex. text that
may be required to fill out forms)
</FormDescription>
2024-04-01 21:34:52 +03:00
<FormControl>
<Textarea
rows={5}
placeholder="Navigation Payload"
{...field}
2024-05-20 13:50:21 -07:00
value={field.value === null ? "" : field.value}
2024-04-01 21:34:52 +03:00
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
2024-06-19 19:15:11 +03:00
<Accordion type="single" collapsible>
<AccordionItem value="advanced-settings">
<AccordionTrigger>Advanced Settings</AccordionTrigger>
<AccordionContent className="space-y-8 px-1 py-4">
<FormField
control={form.control}
name="extractedInformationSchema"
render={({ field }) => (
<FormItem>
<FormLabel>
<div className="flex gap-2">
Extracted Information Schema
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<InfoCircledIcon />
</TooltipTrigger>
<TooltipContent className="max-w-[250px]">
<p>{extractedInformationSchemaDescription}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
</FormLabel>
<FormDescription>
Jsonc schema to force the json format for extracted
information
</FormDescription>
<FormControl>
<Textarea
placeholder="Extracted Information Schema"
rows={5}
{...field}
value={field.value === null ? "" : field.value}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="webhookCallbackUrl"
render={({ field }) => (
<FormItem>
<FormLabel>
<div className="flex gap-2">
Webhook Callback URL
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<InfoCircledIcon />
</TooltipTrigger>
<TooltipContent className="max-w-[250px]">
<p>{webhookCallbackUrlDescription}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
</div>
</FormLabel>
<FormDescription>
The URL of a webhook endpoint to send the extracted
information
</FormDescription>
<FormControl>
<Input
placeholder="example.com"
{...field}
value={field.value === null ? "" : field.value}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="maxStepsOverride"
render={({ field }) => {
return (
<FormItem>
<FormLabel>Max Steps</FormLabel>
<FormDescription>
Max steps for this task. This will override your
organization wide setting.
</FormDescription>
<FormControl>
{isPending ? (
<Skeleton className="h-8" />
) : (
<Input
{...field}
type="number"
min={1}
max={
organization?.max_steps_per_run ??
MAX_STEPS_DEFAULT
}
value={field.value ?? MAX_STEPS_DEFAULT}
onChange={(event) => {
field.onChange(parseInt(event.target.value));
}}
/>
)}
</FormControl>
</FormItem>
);
}}
/>
2024-06-19 19:15:11 +03:00
</AccordionContent>
</AccordionItem>
</Accordion>
2024-04-01 21:34:52 +03:00
<div className="flex justify-end gap-3">
2024-04-17 00:15:04 +03:00
<Button
type="button"
variant="secondary"
2024-04-17 00:15:04 +03:00
onClick={async () => {
const curl = fetchToCurl({
method: "POST",
url: `${apiBaseUrl}/tasks`,
body: createTaskRequestObject(form.getValues()),
headers: {
"Content-Type": "application/json",
"x-api-key": apiCredential ?? "<your-api-key>",
2024-04-17 00:15:04 +03:00
},
});
await navigator.clipboard.writeText(curl);
toast({
title: "Copied cURL",
description: "cURL copied to clipboard",
});
}}
>
Copy cURL
</Button>
<Button type="submit" disabled={mutation.isPending}>
{mutation.isPending && (
<ReloadIcon className="mr-2 h-4 w-4 animate-spin" />
)}
Create
</Button>
2024-04-01 21:34:52 +03:00
</div>
</form>
</Form>
);
}
export { CreateNewTaskForm };