mirror of
https://github.com/Significant-Gravitas/AutoGPT.git
synced 2026-04-08 03:00:28 -04:00
feat(frontend): New Run Agent Modal (2/2) (#10769)
## Changes 🏗️ <img width="400" height="821" alt="Screenshot 2025-08-28 at 23 57 41" src="https://github.com/user-attachments/assets/f5f7c0a6-0b87-4c1f-b644-3ee2ddd1db95" /> <img width="400" height="822" alt="Screenshot 2025-08-28 at 23 57 47" src="https://github.com/user-attachments/assets/120dbb60-d9e1-4a4a-a593-971badb4a97a" /> This is the final piece of work on the new **Run Agent Modal**... It is all behind a feature flag so I'm relatively comfortable is safe. The idea is to test with the team once it lands into dev to try different combinations of agent inputs / credentials and schedules... I have moved and tied a lot of the original logic around running agents. Mostly importantly, I have made all the dynamic inputs adhere to the design system. ### AI changes summary - Allow to run schedules in the main modal body - Integrate and tidy old logic around dynamic run agent inputs - Integrate and tidy old logic around credentials inputs - Refactor: `<TypeBasedInputs />` to use Design System components (`atoms/Input`, `atoms/Select`, `molecules/MultiToggle`, and native date/time picker via `<Input />` using the browser's date picker ) - Added support for `type="date"` and `type="datetime-local"` to `<Input />` ( _for the above_ ) - On the `<Select />` component: - added `size` prop (`small` | `medium`). - added rich items: `icon`, `disabled`, `separator`, `onSelect`, and `renderItem` prop. - stories updated/added for size variants, icons/separators, and custom rendering. - Added and documented to the design system: - `molecules/TimePicker` + story. - `atoms/FileInput`: added `accept` and `maxFileSize` props; story documents constraints. - `atoms/Progress` stories (Basic, CustomMax, Sizes, Live) with fixed-width container. - `atoms/Switch` stories (Basic, Disabled, WithLabel). - `molecules/Dialog` story: Modal-over-Modal example. ## Checklist 📋 ### For code changes: - [x] I have clearly listed my changes in the PR description - [x] I have made a test plan - [x] I have tested my changes according to the test plan: - [x] Open Storybook and verify new/updated stories render correctly. - [x] In app, validate modals open/close correctly using DS `Dialog`. - [x] Validate DS Select rich items (icon, separator, disabled, action) behave as expected. - [x] Run lints and ensure no errors. - [x] Manually test File upload constraints (type/size) and progress. ### For configuration changes: None
This commit is contained in:
@@ -9,7 +9,6 @@ import {
|
||||
import { OnboardingText } from "@/components/onboarding/OnboardingText";
|
||||
import StarRating from "@/components/onboarding/StarRating";
|
||||
import SchemaTooltip from "@/components/SchemaTooltip";
|
||||
import { TypeBasedInput } from "@/components/type-based-input";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { useToast } from "@/components/molecules/Toast/use-toast";
|
||||
import { GraphMeta, StoreAgentDetails } from "@/lib/autogpt-server-api";
|
||||
@@ -18,6 +17,7 @@ import { cn } from "@/lib/utils";
|
||||
import { Play } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { RunAgentInputs } from "@/app/(platform)/library/agents/[id]/components/AgentRunsView/components/RunAgentInputs/RunAgentInputs";
|
||||
|
||||
export default function Page() {
|
||||
const { state, updateState, setStep } = useOnboarding(
|
||||
@@ -233,7 +233,7 @@ export default function Page() {
|
||||
description={inputSubSchema.description}
|
||||
/>
|
||||
</label>
|
||||
<TypeBasedInput
|
||||
<RunAgentInputs
|
||||
schema={inputSubSchema}
|
||||
value={state?.agentInput?.[key]}
|
||||
placeholder={inputSubSchema.description}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { OAuthPopupResultMessage } from "@/components/integrations/credentials-input";
|
||||
import { OAuthPopupResultMessage } from "@/app/(platform)/library/agents/[id]/components/AgentRunsView/components/CredentialsInputs/CredentialsInputs";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
// This route is intended to be used as the callback for integration OAuth flows,
|
||||
|
||||
@@ -1,16 +1,6 @@
|
||||
import { FC } from "react";
|
||||
import { z } from "zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/atoms/Input/Input";
|
||||
import { Button } from "@/components/atoms/Button/Button";
|
||||
import { Dialog } from "@/components/molecules/Dialog/Dialog";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -20,73 +10,55 @@ import {
|
||||
FormLabel,
|
||||
FormMessage,
|
||||
} from "@/components/ui/form";
|
||||
import useCredentials from "@/hooks/useCredentials";
|
||||
import {
|
||||
BlockIOCredentialsSubSchema,
|
||||
CredentialsMetaInput,
|
||||
} from "@/lib/autogpt-server-api/types";
|
||||
import { useAPIKeyCredentialsModal } from "./useAPIKeyCredentialsModal";
|
||||
|
||||
export const APIKeyCredentialsModal: FC<{
|
||||
type Props = {
|
||||
schema: BlockIOCredentialsSubSchema;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onCredentialsCreate: (creds: CredentialsMetaInput) => void;
|
||||
siblingInputs?: Record<string, any>;
|
||||
}> = ({ schema, open, onClose, onCredentialsCreate, siblingInputs }) => {
|
||||
const credentials = useCredentials(schema, siblingInputs);
|
||||
};
|
||||
|
||||
const formSchema = z.object({
|
||||
apiKey: z.string().min(1, "API Key is required"),
|
||||
title: z.string().min(1, "Name is required"),
|
||||
expiresAt: z.string().optional(),
|
||||
});
|
||||
export function APIKeyCredentialsModal({
|
||||
schema,
|
||||
open,
|
||||
onClose,
|
||||
onCredentialsCreate,
|
||||
siblingInputs,
|
||||
}: Props) {
|
||||
const {
|
||||
form,
|
||||
isLoading,
|
||||
supportsApiKey,
|
||||
providerName,
|
||||
schemaDescription,
|
||||
onSubmit,
|
||||
} = useAPIKeyCredentialsModal({ schema, siblingInputs, onCredentialsCreate });
|
||||
|
||||
const form = useForm<z.infer<typeof formSchema>>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
apiKey: "",
|
||||
title: "",
|
||||
expiresAt: "",
|
||||
},
|
||||
});
|
||||
|
||||
if (!credentials || credentials.isLoading || !credentials.supportsApiKey) {
|
||||
if (isLoading || !supportsApiKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { provider, providerName, createAPIKeyCredentials } = credentials;
|
||||
|
||||
async function onSubmit(values: z.infer<typeof formSchema>) {
|
||||
const expiresAt = values.expiresAt
|
||||
? new Date(values.expiresAt).getTime() / 1000
|
||||
: undefined;
|
||||
const newCredentials = await createAPIKeyCredentials({
|
||||
api_key: values.apiKey,
|
||||
title: values.title,
|
||||
expires_at: expiresAt,
|
||||
});
|
||||
onCredentialsCreate({
|
||||
provider,
|
||||
id: newCredentials.id,
|
||||
type: "api_key",
|
||||
title: newCredentials.title,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onClose();
|
||||
title={`Add new API key for ${providerName ?? ""}`}
|
||||
controlled={{
|
||||
isOpen: open,
|
||||
set: (isOpen) => {
|
||||
if (!isOpen) onClose();
|
||||
},
|
||||
}}
|
||||
onClose={onClose}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add new API key for {providerName}</DialogTitle>
|
||||
{schema.description && (
|
||||
<DialogDescription>{schema.description}</DialogDescription>
|
||||
)}
|
||||
</DialogHeader>
|
||||
<Dialog.Content>
|
||||
{schemaDescription && (
|
||||
<p className="mb-4 text-sm text-zinc-600">{schemaDescription}</p>
|
||||
)}
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
@@ -109,6 +81,9 @@ export const APIKeyCredentialsModal: FC<{
|
||||
)}
|
||||
<FormControl>
|
||||
<Input
|
||||
id="apiKey"
|
||||
label="API Key"
|
||||
hideLabel
|
||||
type="password"
|
||||
placeholder="Enter API key..."
|
||||
{...field}
|
||||
@@ -126,6 +101,9 @@ export const APIKeyCredentialsModal: FC<{
|
||||
<FormLabel>Name</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
id="title"
|
||||
label="Name"
|
||||
hideLabel
|
||||
type="text"
|
||||
placeholder="Enter a name for this API key..."
|
||||
{...field}
|
||||
@@ -143,6 +121,9 @@ export const APIKeyCredentialsModal: FC<{
|
||||
<FormLabel>Expiration Date (Optional)</FormLabel>
|
||||
<FormControl>
|
||||
<Input
|
||||
id="expiresAt"
|
||||
label="Expiration Date"
|
||||
hideLabel
|
||||
type="datetime-local"
|
||||
placeholder="Select expiration date..."
|
||||
{...field}
|
||||
@@ -157,7 +138,7 @@ export const APIKeyCredentialsModal: FC<{
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog.Content>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { z } from "zod";
|
||||
import { useForm, type UseFormReturn } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import useCredentials from "@/hooks/useCredentials";
|
||||
import {
|
||||
BlockIOCredentialsSubSchema,
|
||||
CredentialsMetaInput,
|
||||
} from "@/lib/autogpt-server-api/types";
|
||||
|
||||
export type APIKeyFormValues = {
|
||||
apiKey: string;
|
||||
title: string;
|
||||
expiresAt?: string;
|
||||
};
|
||||
|
||||
type Args = {
|
||||
schema: BlockIOCredentialsSubSchema;
|
||||
siblingInputs?: Record<string, any>;
|
||||
onCredentialsCreate: (creds: CredentialsMetaInput) => void;
|
||||
};
|
||||
|
||||
export function useAPIKeyCredentialsModal({
|
||||
schema,
|
||||
siblingInputs,
|
||||
onCredentialsCreate,
|
||||
}: Args): {
|
||||
form: UseFormReturn<APIKeyFormValues>;
|
||||
isLoading: boolean;
|
||||
supportsApiKey: boolean;
|
||||
provider?: string;
|
||||
providerName?: string;
|
||||
schemaDescription?: string;
|
||||
onSubmit: (values: APIKeyFormValues) => Promise<void>;
|
||||
} {
|
||||
const credentials = useCredentials(schema, siblingInputs);
|
||||
|
||||
const formSchema = z.object({
|
||||
apiKey: z.string().min(1, "API Key is required"),
|
||||
title: z.string().min(1, "Name is required"),
|
||||
expiresAt: z.string().optional(),
|
||||
});
|
||||
|
||||
const form = useForm<APIKeyFormValues>({
|
||||
resolver: zodResolver(formSchema),
|
||||
defaultValues: {
|
||||
apiKey: "",
|
||||
title: "",
|
||||
expiresAt: "",
|
||||
},
|
||||
});
|
||||
|
||||
async function onSubmit(values: APIKeyFormValues) {
|
||||
if (!credentials || credentials.isLoading) return;
|
||||
const expiresAt = values.expiresAt
|
||||
? new Date(values.expiresAt).getTime() / 1000
|
||||
: undefined;
|
||||
const newCredentials = await credentials.createAPIKeyCredentials({
|
||||
api_key: values.apiKey,
|
||||
title: values.title,
|
||||
expires_at: expiresAt,
|
||||
});
|
||||
onCredentialsCreate({
|
||||
provider: credentials.provider,
|
||||
id: newCredentials.id,
|
||||
type: "api_key",
|
||||
title: newCredentials.title,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
form,
|
||||
isLoading: !credentials || credentials.isLoading,
|
||||
supportsApiKey: !!credentials?.supportsApiKey,
|
||||
provider: credentials?.provider,
|
||||
providerName:
|
||||
!credentials || credentials.isLoading
|
||||
? undefined
|
||||
: credentials.providerName,
|
||||
schemaDescription: schema.description,
|
||||
onSubmit,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import SchemaTooltip from "@/components/SchemaTooltip";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Button } from "@/components/atoms/Button/Button";
|
||||
import { IconKey, IconKeyPlus, IconUserPlus } from "@/components/ui/icons";
|
||||
import {
|
||||
Select,
|
||||
@@ -28,10 +28,10 @@ import {
|
||||
FaMedium,
|
||||
FaTwitter,
|
||||
} from "react-icons/fa";
|
||||
import { APIKeyCredentialsModal } from "./api-key-credentials-modal";
|
||||
import { HostScopedCredentialsModal } from "./host-scoped-credentials-modal";
|
||||
import { OAuth2FlowWaitingModal } from "./oauth2-flow-waiting-modal";
|
||||
import { UserPasswordCredentialsModal } from "./user-password-credentials-modal";
|
||||
import { APIKeyCredentialsModal } from "../APIKeyCredentialsModal/APIKeyCredentialsModal";
|
||||
import { HostScopedCredentialsModal } from "../HotScopedCredentialsModal/HotScopedCredentialsModal";
|
||||
import { OAuthFlowWaitingModal } from "../OAuthWaitingModal/OAuthWaitingModal";
|
||||
import { PasswordCredentialsModal } from "../PasswordCredentialsModal/PasswordCredentialsModal";
|
||||
|
||||
const fallbackIcon = FaKey;
|
||||
|
||||
@@ -290,14 +290,14 @@ export const CredentialsInput: FC<{
|
||||
/>
|
||||
)}
|
||||
{supportsOAuth2 && (
|
||||
<OAuth2FlowWaitingModal
|
||||
<OAuthFlowWaitingModal
|
||||
open={isOAuth2FlowInProgress}
|
||||
onClose={() => oAuthPopupController?.abort("canceled")}
|
||||
providerName={providerName}
|
||||
/>
|
||||
)}
|
||||
{supportsUserPassword && (
|
||||
<UserPasswordCredentialsModal
|
||||
<PasswordCredentialsModal
|
||||
schema={schema}
|
||||
open={isUserPasswordCredentialsModalOpen}
|
||||
onClose={() => setUserPasswordCredentialsModalOpen(false)}
|
||||
@@ -1,16 +1,10 @@
|
||||
import { FC, useEffect, useState } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { z } from "zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/atoms/Input/Input";
|
||||
import { Button } from "@/components/atoms/Button/Button";
|
||||
import { Dialog } from "@/components/molecules/Dialog/Dialog";
|
||||
import {
|
||||
Form,
|
||||
FormControl,
|
||||
@@ -27,13 +21,21 @@ import {
|
||||
} from "@/lib/autogpt-server-api/types";
|
||||
import { getHostFromUrl } from "@/lib/utils/url";
|
||||
|
||||
export const HostScopedCredentialsModal: FC<{
|
||||
type Props = {
|
||||
schema: BlockIOCredentialsSubSchema;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onCredentialsCreate: (creds: CredentialsMetaInput) => void;
|
||||
siblingInputs?: Record<string, any>;
|
||||
}> = ({ schema, open, onClose, onCredentialsCreate, siblingInputs }) => {
|
||||
};
|
||||
|
||||
export function HostScopedCredentialsModal({
|
||||
schema,
|
||||
open,
|
||||
onClose,
|
||||
onCredentialsCreate,
|
||||
siblingInputs,
|
||||
}: Props) {
|
||||
const credentials = useCredentials(schema, siblingInputs);
|
||||
|
||||
// Get current host from siblingInputs or discriminator_values
|
||||
@@ -129,18 +131,19 @@ export const HostScopedCredentialsModal: FC<{
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onClose();
|
||||
title={`Add sensitive headers for ${providerName}`}
|
||||
controlled={{
|
||||
isOpen: open,
|
||||
set: (isOpen) => {
|
||||
if (!isOpen) onClose();
|
||||
},
|
||||
}}
|
||||
onClose={onClose}
|
||||
>
|
||||
<DialogContent className="max-h-[90vh] max-w-2xl overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add sensitive headers for {providerName}</DialogTitle>
|
||||
{schema.description && (
|
||||
<DialogDescription>{schema.description}</DialogDescription>
|
||||
)}
|
||||
</DialogHeader>
|
||||
<Dialog.Content>
|
||||
{schema.description && (
|
||||
<p className="mb-4 text-sm text-zinc-600">{schema.description}</p>
|
||||
)}
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
@@ -157,6 +160,9 @@ export const HostScopedCredentialsModal: FC<{
|
||||
</FormDescription>
|
||||
<FormControl>
|
||||
<Input
|
||||
id="host"
|
||||
label="Host Pattern"
|
||||
hideLabel
|
||||
type="text"
|
||||
readOnly={!!currentHost}
|
||||
placeholder={
|
||||
@@ -184,6 +190,9 @@ export const HostScopedCredentialsModal: FC<{
|
||||
<div key={index} className="flex items-end gap-2">
|
||||
<div className="flex-1">
|
||||
<Input
|
||||
id={`header-${index}-key`}
|
||||
label="Header Name"
|
||||
hideLabel
|
||||
placeholder="Header name (e.g., Authorization)"
|
||||
value={pair.key}
|
||||
onChange={(e) =>
|
||||
@@ -193,6 +202,9 @@ export const HostScopedCredentialsModal: FC<{
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<Input
|
||||
id={`header-${index}-value`}
|
||||
label="Header Value"
|
||||
hideLabel
|
||||
type="password"
|
||||
placeholder="Header value (e.g., Bearer token123)"
|
||||
value={pair.value}
|
||||
@@ -204,7 +216,7 @@ export const HostScopedCredentialsModal: FC<{
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
size="small"
|
||||
onClick={() => removeHeaderPair(index)}
|
||||
disabled={headerPairs.length === 1}
|
||||
>
|
||||
@@ -216,7 +228,7 @@ export const HostScopedCredentialsModal: FC<{
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
size="small"
|
||||
onClick={addHeaderPair}
|
||||
className="w-full"
|
||||
>
|
||||
@@ -229,7 +241,7 @@ export const HostScopedCredentialsModal: FC<{
|
||||
</Button>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog.Content>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Dialog } from "@/components/molecules/Dialog/Dialog";
|
||||
|
||||
type Props = {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
providerName: string;
|
||||
};
|
||||
|
||||
export function OAuthFlowWaitingModal({ open, onClose, providerName }: Props) {
|
||||
return (
|
||||
<Dialog
|
||||
title={`Waiting on ${providerName} sign-in process...`}
|
||||
controlled={{
|
||||
isOpen: open,
|
||||
set: (isOpen) => {
|
||||
if (!isOpen) onClose();
|
||||
},
|
||||
}}
|
||||
onClose={onClose}
|
||||
>
|
||||
<Dialog.Content>
|
||||
<p className="text-sm text-zinc-600">
|
||||
Complete the sign-in process in the pop-up window.
|
||||
<br />
|
||||
Closing this dialog will cancel the sign-in process.
|
||||
</p>
|
||||
</Dialog.Content>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import { FC } from "react";
|
||||
import { z } from "zod";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
@@ -24,13 +23,21 @@ import {
|
||||
CredentialsMetaInput,
|
||||
} from "@/lib/autogpt-server-api/types";
|
||||
|
||||
export const UserPasswordCredentialsModal: FC<{
|
||||
type Props = {
|
||||
schema: BlockIOCredentialsSubSchema;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onCredentialsCreate: (creds: CredentialsMetaInput) => void;
|
||||
siblingInputs?: Record<string, any>;
|
||||
}> = ({ schema, open, onClose, onCredentialsCreate, siblingInputs }) => {
|
||||
};
|
||||
|
||||
export function PasswordCredentialsModal({
|
||||
schema,
|
||||
open,
|
||||
onClose,
|
||||
onCredentialsCreate,
|
||||
siblingInputs,
|
||||
}: Props) {
|
||||
const credentials = useCredentials(schema, siblingInputs);
|
||||
|
||||
const formSchema = z.object({
|
||||
@@ -146,4 +153,4 @@ export const UserPasswordCredentialsModal: FC<{
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import React from "react";
|
||||
import { format } from "date-fns";
|
||||
|
||||
import { Input as DSInput } from "@/components/atoms/Input/Input";
|
||||
import { Select as DSSelect } from "@/components/atoms/Select/Select";
|
||||
import { MultiToggle } from "@/components/molecules/MultiToggle/MultiToggle";
|
||||
// Removed shadcn Select usage in favor of DS Select for time picker
|
||||
import {
|
||||
BlockIOObjectSubSchema,
|
||||
BlockIOSubSchema,
|
||||
DataType,
|
||||
determineDataType,
|
||||
} from "@/lib/autogpt-server-api/types";
|
||||
import { TimePicker } from "@/components/molecules/TimePicker/TimePicker";
|
||||
import { FileInput } from "@/components/atoms/FileInput/FileInput";
|
||||
import { useRunAgentInputs } from "./useRunAgentInputs";
|
||||
import { Switch } from "@/components/atoms/Switch/Switch";
|
||||
|
||||
/**
|
||||
* A generic prop structure for the TypeBasedInput.
|
||||
*
|
||||
* onChange expects an event-like object with e.target.value so the parent
|
||||
* can do something like setInputValues(e.target.value).
|
||||
*/
|
||||
interface Props {
|
||||
schema: BlockIOSubSchema;
|
||||
value?: any;
|
||||
placeholder?: string;
|
||||
onChange: (value: any) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A generic, data-type-based input component that uses Shadcn UI.
|
||||
* It inspects the schema via `determineDataType` and renders
|
||||
* the correct UI component.
|
||||
*/
|
||||
export function RunAgentInputs({
|
||||
schema,
|
||||
value,
|
||||
placeholder,
|
||||
onChange,
|
||||
...props
|
||||
}: Props & React.HTMLAttributes<HTMLElement>) {
|
||||
const { handleUploadFile, uploadProgress } = useRunAgentInputs();
|
||||
|
||||
const dataType = determineDataType(schema);
|
||||
const baseId = String(schema.title ?? "input")
|
||||
.replace(/\s+/g, "-")
|
||||
.toLowerCase();
|
||||
|
||||
let innerInputElement: React.ReactNode = null;
|
||||
switch (dataType) {
|
||||
case DataType.NUMBER:
|
||||
innerInputElement = (
|
||||
<DSInput
|
||||
id={`${baseId}-number`}
|
||||
label={schema.title ?? placeholder ?? "Number"}
|
||||
hideLabel
|
||||
type="number"
|
||||
value={value ?? ""}
|
||||
placeholder={placeholder || "Enter number"}
|
||||
onChange={(e) =>
|
||||
onChange(Number((e.target as HTMLInputElement).value))
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.LONG_TEXT:
|
||||
innerInputElement = (
|
||||
<DSInput
|
||||
id={`${baseId}-textarea`}
|
||||
label={schema.title ?? placeholder ?? "Text"}
|
||||
hideLabel
|
||||
type="textarea"
|
||||
rows={3}
|
||||
value={value ?? ""}
|
||||
placeholder={placeholder || "Enter text"}
|
||||
onChange={(e) => onChange((e.target as HTMLInputElement).value)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.BOOLEAN:
|
||||
innerInputElement = (
|
||||
<>
|
||||
<span className="text-sm text-gray-500">
|
||||
{placeholder || (value ? "Enabled" : "Disabled")}
|
||||
</span>
|
||||
<Switch
|
||||
className="ml-auto"
|
||||
checked={!!value}
|
||||
onCheckedChange={(checked: boolean) => onChange(checked)}
|
||||
{...props}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.DATE:
|
||||
innerInputElement = (
|
||||
<DSInput
|
||||
id={`${baseId}-date`}
|
||||
label={schema.title ?? placeholder ?? "Date"}
|
||||
hideLabel
|
||||
type="date"
|
||||
value={value ? format(value as Date, "yyyy-MM-dd") : ""}
|
||||
onChange={(e) => {
|
||||
const v = (e.target as HTMLInputElement).value;
|
||||
if (!v) onChange(undefined);
|
||||
else {
|
||||
const [y, m, d] = v.split("-").map(Number);
|
||||
onChange(new Date(y, m - 1, d));
|
||||
}
|
||||
}}
|
||||
placeholder={placeholder || "Pick a date"}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.TIME:
|
||||
innerInputElement = (
|
||||
<TimePicker value={value?.toString()} onChange={onChange} />
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.DATE_TIME:
|
||||
innerInputElement = (
|
||||
<DSInput
|
||||
id={`${baseId}-datetime`}
|
||||
label={schema.title ?? placeholder ?? "Date time"}
|
||||
hideLabel
|
||||
type="datetime-local"
|
||||
value={value ?? ""}
|
||||
onChange={(e) => onChange((e.target as HTMLInputElement).value)}
|
||||
placeholder={placeholder || "Enter date and time"}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.FILE:
|
||||
innerInputElement = (
|
||||
<FileInput
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
onChange={onChange}
|
||||
onUploadFile={handleUploadFile}
|
||||
uploadProgress={uploadProgress}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.SELECT:
|
||||
if (
|
||||
"enum" in schema &&
|
||||
Array.isArray(schema.enum) &&
|
||||
schema.enum.length > 0
|
||||
) {
|
||||
innerInputElement = (
|
||||
<DSSelect
|
||||
id={`${baseId}-select`}
|
||||
label={schema.title ?? placeholder ?? "Select"}
|
||||
hideLabel
|
||||
value={value ?? ""}
|
||||
onValueChange={(val: string) => onChange(val)}
|
||||
placeholder={placeholder || "Select an option"}
|
||||
options={schema.enum
|
||||
.filter((opt) => opt)
|
||||
.map((opt) => ({ value: opt, label: String(opt) }))}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
case DataType.MULTI_SELECT: {
|
||||
const _schema = schema as BlockIOObjectSubSchema;
|
||||
const allKeys = Object.keys(_schema.properties);
|
||||
const selectedValues = Object.entries(value || {})
|
||||
.filter(([_, v]) => v)
|
||||
.map(([k]) => k);
|
||||
|
||||
innerInputElement = (
|
||||
<MultiToggle
|
||||
items={allKeys.map((key) => ({
|
||||
value: key,
|
||||
label: _schema.properties[key]?.title ?? key,
|
||||
}))}
|
||||
selectedValues={selectedValues}
|
||||
onChange={(values: string[]) =>
|
||||
onChange(
|
||||
Object.fromEntries(
|
||||
allKeys.map((opt) => [opt, values.includes(opt)]),
|
||||
),
|
||||
)
|
||||
}
|
||||
className="nodrag"
|
||||
aria-label={schema.title}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
case DataType.SHORT_TEXT:
|
||||
default:
|
||||
innerInputElement = (
|
||||
<DSInput
|
||||
id={`${baseId}-text`}
|
||||
label={schema.title ?? placeholder ?? "Text"}
|
||||
hideLabel
|
||||
type="text"
|
||||
value={value ?? ""}
|
||||
onChange={(e) => onChange((e.target as HTMLInputElement).value)}
|
||||
placeholder={placeholder || "Enter text"}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <div className="no-drag relative flex">{innerInputElement}</div>;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import BackendAPI from "@/lib/autogpt-server-api";
|
||||
import { useState } from "react";
|
||||
|
||||
export function useRunAgentInputs() {
|
||||
const api = new BackendAPI();
|
||||
const [uploadProgress, setUploadProgress] = useState(0);
|
||||
|
||||
async function handleUploadFile(file: File) {
|
||||
const result = await api.uploadFile(file, "gcs", 24, (progress) =>
|
||||
setUploadProgress(progress),
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
return {
|
||||
uploadProgress,
|
||||
handleUploadFile,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { Dialog } from "@/components/molecules/Dialog/Dialog";
|
||||
import { Button } from "@/components/atoms/Button/Button";
|
||||
import { useState } from "react";
|
||||
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
|
||||
import { useAgentRunModal } from "./useAgentRunModal";
|
||||
@@ -8,10 +9,13 @@ import { ModalHeader } from "./components/ModalHeader/ModalHeader";
|
||||
import { AgentCostSection } from "./components/AgentCostSection/AgentCostSection";
|
||||
import { AgentSectionHeader } from "./components/AgentSectionHeader/AgentSectionHeader";
|
||||
import { DefaultRunView } from "./components/DefaultRunView/DefaultRunView";
|
||||
import { RunAgentModalContextProvider } from "./context";
|
||||
import { ScheduleView } from "./components/ScheduleView/ScheduleView";
|
||||
import { AgentDetails } from "./components/AgentDetails/AgentDetails";
|
||||
import { RunActions } from "./components/RunActions/RunActions";
|
||||
import { ScheduleActions } from "./components/ScheduleActions/ScheduleActions";
|
||||
import { Text } from "@/components/atoms/Text/Text";
|
||||
import { AlarmIcon, TrashIcon } from "@phosphor-icons/react";
|
||||
|
||||
interface Props {
|
||||
triggerSlot: React.ReactNode;
|
||||
@@ -28,10 +32,18 @@ export function RunAgentModal({ triggerSlot, agent }: Props) {
|
||||
defaultRunType,
|
||||
inputValues,
|
||||
setInputValues,
|
||||
inputCredentials,
|
||||
setInputCredentials,
|
||||
presetName,
|
||||
presetDescription,
|
||||
setPresetName,
|
||||
setPresetDescription,
|
||||
scheduleName,
|
||||
cronExpression,
|
||||
allRequiredInputsAreSet,
|
||||
// agentInputFields, // Available if needed for future use
|
||||
agentInputFields,
|
||||
agentCredentialsInputFields,
|
||||
hasInputFields,
|
||||
isExecuting,
|
||||
isCreatingSchedule,
|
||||
@@ -53,104 +65,158 @@ export function RunAgentModal({ triggerSlot, agent }: Props) {
|
||||
}));
|
||||
}
|
||||
|
||||
function handleCredentialsChange(key: string, value: any | undefined) {
|
||||
setInputCredentials((prev) => {
|
||||
const next = { ...prev } as Record<string, any>;
|
||||
if (value === undefined) {
|
||||
delete next[key];
|
||||
return next;
|
||||
}
|
||||
next[key] = value;
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function handleSetOpen(open: boolean) {
|
||||
setIsOpen(open);
|
||||
// Always reset to Run view when opening/closing
|
||||
if (open || !open) handleGoBack();
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
controlled={{ isOpen, set: handleSetOpen }}
|
||||
styling={{ maxWidth: "600px", maxHeight: "90vh" }}
|
||||
>
|
||||
<Dialog.Trigger>{triggerSlot}</Dialog.Trigger>
|
||||
<Dialog.Content>
|
||||
<div className="flex h-full flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex-shrink-0">
|
||||
<ModalHeader agent={agent} />
|
||||
<AgentCostSection flowId={agent.graph_id} />
|
||||
</div>
|
||||
function handleRemoveSchedule() {
|
||||
handleGoBack();
|
||||
handleSetScheduleName("");
|
||||
handleSetCronExpression("");
|
||||
}
|
||||
|
||||
{/* Scrollable content */}
|
||||
<div
|
||||
className="flex-1 overflow-y-auto overflow-x-hidden pr-1"
|
||||
style={{ scrollbarGutter: "stable" }}
|
||||
>
|
||||
{/* Setup Section */}
|
||||
<div className="mt-10">
|
||||
{showScheduleView ? (
|
||||
<>
|
||||
<AgentSectionHeader title="Schedule Setup" />
|
||||
<div>
|
||||
return (
|
||||
<>
|
||||
<Dialog
|
||||
controlled={{ isOpen, set: handleSetOpen }}
|
||||
styling={{ maxWidth: "600px", maxHeight: "90vh" }}
|
||||
>
|
||||
<Dialog.Trigger>{triggerSlot}</Dialog.Trigger>
|
||||
<Dialog.Content>
|
||||
<div className="flex h-full flex-col">
|
||||
{/* Header */}
|
||||
<div className="flex-shrink-0">
|
||||
<ModalHeader agent={agent} />
|
||||
<AgentCostSection flowId={agent.graph_id} />
|
||||
</div>
|
||||
|
||||
{/* Scrollable content */}
|
||||
<div
|
||||
className="flex-1 overflow-y-auto overflow-x-hidden pr-1"
|
||||
style={{ scrollbarGutter: "stable" }}
|
||||
>
|
||||
{/* Setup Section */}
|
||||
<div className="mt-10">
|
||||
{hasInputFields ? (
|
||||
<RunAgentModalContextProvider
|
||||
value={{
|
||||
agent,
|
||||
defaultRunType,
|
||||
presetName,
|
||||
setPresetName,
|
||||
presetDescription,
|
||||
setPresetDescription,
|
||||
inputValues,
|
||||
setInputValue: handleInputChange,
|
||||
agentInputFields,
|
||||
inputCredentials,
|
||||
setInputCredentialsValue: handleCredentialsChange,
|
||||
agentCredentialsInputFields,
|
||||
}}
|
||||
>
|
||||
<>
|
||||
<AgentSectionHeader
|
||||
title={
|
||||
defaultRunType === "automatic-trigger"
|
||||
? "Trigger Setup"
|
||||
: "Agent Setup"
|
||||
}
|
||||
/>
|
||||
<div>
|
||||
<DefaultRunView />
|
||||
</div>
|
||||
</>
|
||||
</RunAgentModalContextProvider>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{/* Schedule Section - always visible */}
|
||||
<div className="mt-8">
|
||||
<AgentSectionHeader title="Schedule Setup" />
|
||||
{showScheduleView ? (
|
||||
<>
|
||||
<div className="mb-3 flex justify-start">
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="small"
|
||||
onClick={handleRemoveSchedule}
|
||||
>
|
||||
<TrashIcon size={16} />
|
||||
Remove schedule
|
||||
</Button>
|
||||
</div>
|
||||
<ScheduleView
|
||||
agent={agent}
|
||||
scheduleName={scheduleName}
|
||||
cronExpression={cronExpression}
|
||||
inputValues={inputValues}
|
||||
onScheduleNameChange={handleSetScheduleName}
|
||||
onCronExpressionChange={handleSetCronExpression}
|
||||
onInputChange={handleInputChange}
|
||||
onValidityChange={setIsScheduleFormValid}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex flex-col items-start gap-2">
|
||||
<Text variant="body" className="mb-3 !text-zinc-500">
|
||||
No schedule configured. Create a schedule to run this
|
||||
agent automatically at a specific time.{" "}
|
||||
</Text>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="small"
|
||||
onClick={handleShowSchedule}
|
||||
>
|
||||
<AlarmIcon size={16} />
|
||||
Create schedule
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : hasInputFields ? (
|
||||
<>
|
||||
<AgentSectionHeader
|
||||
title={
|
||||
defaultRunType === "automatic-trigger"
|
||||
? "Trigger Setup"
|
||||
: "Agent Setup"
|
||||
}
|
||||
/>
|
||||
<div>
|
||||
<DefaultRunView
|
||||
agent={agent}
|
||||
defaultRunType={defaultRunType}
|
||||
inputValues={inputValues}
|
||||
onInputChange={handleInputChange}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Agent Details Section */}
|
||||
<div className="mt-8">
|
||||
<AgentSectionHeader title="Agent Details" />
|
||||
<AgentDetails agent={agent} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Agent Details Section */}
|
||||
<div className="mt-8">
|
||||
<AgentSectionHeader title="Agent Details" />
|
||||
<AgentDetails agent={agent} />
|
||||
</div>
|
||||
{/* Fixed Actions - sticky inside dialog scroll */}
|
||||
<Dialog.Footer className="sticky bottom-0 z-10 bg-white">
|
||||
{showScheduleView ? (
|
||||
<ScheduleActions
|
||||
onSchedule={handleSchedule}
|
||||
isCreatingSchedule={isCreatingSchedule}
|
||||
allRequiredInputsAreSet={
|
||||
allRequiredInputsAreSet &&
|
||||
!!scheduleName.trim() &&
|
||||
isScheduleFormValid
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<RunActions
|
||||
defaultRunType={defaultRunType}
|
||||
onRun={handleRun}
|
||||
isExecuting={isExecuting}
|
||||
isSettingUpTrigger={isSettingUpTrigger}
|
||||
allRequiredInputsAreSet={allRequiredInputsAreSet}
|
||||
/>
|
||||
)}
|
||||
</Dialog.Footer>
|
||||
</div>
|
||||
|
||||
{/* Fixed Actions - sticky inside dialog scroll */}
|
||||
<Dialog.Footer className="sticky bottom-0 z-10 bg-white">
|
||||
{!showScheduleView ? (
|
||||
<RunActions
|
||||
hasExternalTrigger={agent.has_external_trigger}
|
||||
defaultRunType={defaultRunType}
|
||||
onShowSchedule={handleShowSchedule}
|
||||
onRun={handleRun}
|
||||
isExecuting={isExecuting}
|
||||
isSettingUpTrigger={isSettingUpTrigger}
|
||||
allRequiredInputsAreSet={allRequiredInputsAreSet}
|
||||
/>
|
||||
) : (
|
||||
<ScheduleActions
|
||||
onGoBack={handleGoBack}
|
||||
onSchedule={handleSchedule}
|
||||
isCreatingSchedule={isCreatingSchedule}
|
||||
allRequiredInputsAreSet={
|
||||
allRequiredInputsAreSet &&
|
||||
!!scheduleName.trim() &&
|
||||
isScheduleFormValid
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</Dialog.Footer>
|
||||
</div>
|
||||
</Dialog.Content>
|
||||
</Dialog>
|
||||
</Dialog.Content>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
|
||||
import { Text } from "@/components/atoms/Text/Text";
|
||||
import { Badge } from "@/components/atoms/Badge/Badge";
|
||||
import { formatAgentStatus, getStatusColor } from "./helpers";
|
||||
import { formatDate } from "@/lib/utils/time";
|
||||
|
||||
interface Props {
|
||||
@@ -11,20 +10,6 @@ interface Props {
|
||||
export function AgentDetails({ agent }: Props) {
|
||||
return (
|
||||
<div className="mt-4 flex flex-col gap-5">
|
||||
<div>
|
||||
<Text variant="body-medium" className="mb-1 !text-black">
|
||||
Current Status
|
||||
</Text>
|
||||
<div className="flex items-center gap-2">
|
||||
<div
|
||||
className={`h-2 w-2 rounded-full ${getStatusColor(agent.status)}`}
|
||||
/>
|
||||
<Text variant="body" className="!text-zinc-700">
|
||||
{formatAgentStatus(agent.status)}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Text variant="body-medium" className="mb-1 !text-black">
|
||||
Version
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import { LibraryAgentStatus } from "@/app/api/__generated__/models/libraryAgentStatus";
|
||||
|
||||
export function formatAgentStatus(status: LibraryAgentStatus) {
|
||||
const statusMap: Record<string, string> = {
|
||||
COMPLETED: "Ready",
|
||||
HEALTHY: "Running",
|
||||
WAITING: "Run Queued",
|
||||
ERROR: "Failed Run",
|
||||
};
|
||||
|
||||
return statusMap[status];
|
||||
}
|
||||
|
||||
export function getStatusColor(status: LibraryAgentStatus): string {
|
||||
const colorMap: Record<LibraryAgentStatus, string> = {
|
||||
COMPLETED: "bg-blue-300",
|
||||
HEALTHY: "bg-green-300",
|
||||
WAITING: "bg-amber-300",
|
||||
ERROR: "bg-red-300",
|
||||
};
|
||||
|
||||
return colorMap[status] || "bg-gray-300";
|
||||
}
|
||||
@@ -1,30 +1,100 @@
|
||||
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
|
||||
import { RunVariant } from "../../useAgentRunModal";
|
||||
import { WebhookTriggerBanner } from "../WebhookTriggerBanner/WebhookTriggerBanner";
|
||||
import { AgentInputFields } from "../AgentInputFields/AgentInputFields";
|
||||
import { Input } from "@/components/atoms/Input/Input";
|
||||
import SchemaTooltip from "@/components/SchemaTooltip";
|
||||
import { CredentialsInput } from "@/app/(platform)/library/agents/[id]/components/AgentRunsView/components/CredentialsInputs/CredentialsInputs";
|
||||
import { useRunAgentModalContext } from "../../context";
|
||||
import { RunAgentInputs } from "../../../RunAgentInputs/RunAgentInputs";
|
||||
|
||||
interface Props {
|
||||
agent: LibraryAgent;
|
||||
defaultRunType: RunVariant;
|
||||
inputValues: Record<string, any>;
|
||||
onInputChange: (key: string, value: string) => void;
|
||||
}
|
||||
export function DefaultRunView() {
|
||||
const {
|
||||
agent,
|
||||
defaultRunType,
|
||||
presetName,
|
||||
setPresetName,
|
||||
presetDescription,
|
||||
setPresetDescription,
|
||||
inputValues,
|
||||
setInputValue,
|
||||
agentInputFields,
|
||||
inputCredentials,
|
||||
setInputCredentialsValue,
|
||||
agentCredentialsInputFields,
|
||||
} = useRunAgentModalContext();
|
||||
|
||||
export function DefaultRunView({
|
||||
agent,
|
||||
defaultRunType,
|
||||
inputValues,
|
||||
onInputChange,
|
||||
}: Props) {
|
||||
return (
|
||||
<div className="mt-6">
|
||||
<div className="mb-12 mt-6">
|
||||
{defaultRunType === "automatic-trigger" && <WebhookTriggerBanner />}
|
||||
|
||||
<AgentInputFields
|
||||
agent={agent}
|
||||
inputValues={inputValues}
|
||||
onInputChange={onInputChange}
|
||||
/>
|
||||
{/* Preset/Trigger fields */}
|
||||
{defaultRunType === "automatic-trigger" && (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col space-y-2">
|
||||
<label className="flex items-center gap-1 text-sm font-medium">
|
||||
Trigger Name
|
||||
<SchemaTooltip description="Name of the trigger you are setting up" />
|
||||
</label>
|
||||
<Input
|
||||
id="trigger_name"
|
||||
label="Trigger Name"
|
||||
hideLabel
|
||||
value={presetName}
|
||||
placeholder="Enter trigger name"
|
||||
onChange={(e) => setPresetName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col space-y-2">
|
||||
<label className="flex items-center gap-1 text-sm font-medium">
|
||||
Trigger Description
|
||||
<SchemaTooltip description="Description of the trigger you are setting up" />
|
||||
</label>
|
||||
<Input
|
||||
id="trigger_description"
|
||||
label="Trigger Description"
|
||||
hideLabel
|
||||
value={presetDescription}
|
||||
placeholder="Enter trigger description"
|
||||
onChange={(e) => setPresetDescription(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Credentials inputs */}
|
||||
{Object.entries(agentCredentialsInputFields || {}).map(
|
||||
([key, inputSubSchema]) => (
|
||||
<CredentialsInput
|
||||
key={key}
|
||||
schema={{ ...inputSubSchema, discriminator: undefined } as any}
|
||||
selectedCredentials={
|
||||
(inputCredentials && inputCredentials[key]) ??
|
||||
inputSubSchema.default
|
||||
}
|
||||
onSelectCredentials={(value) =>
|
||||
setInputCredentialsValue(key, value)
|
||||
}
|
||||
siblingInputs={inputValues}
|
||||
hideIfSingleCredentialAvailable={!agent.has_external_trigger}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
|
||||
{/* Regular inputs */}
|
||||
{Object.entries(agentInputFields || {}).map(([key, inputSubSchema]) => (
|
||||
<div key={key} className="flex flex-col gap-0 space-y-2">
|
||||
<label className="flex items-center gap-1 text-sm font-medium">
|
||||
{inputSubSchema.title || key}
|
||||
<SchemaTooltip description={inputSubSchema.description} />
|
||||
</label>
|
||||
|
||||
<RunAgentInputs
|
||||
schema={inputSubSchema}
|
||||
value={inputValues[key] ?? inputSubSchema.default}
|
||||
placeholder={inputSubSchema.description}
|
||||
onChange={(value) => setInputValue(key, value)}
|
||||
data-testid={`agent-input-${key}`}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ interface ModalHeaderProps {
|
||||
}
|
||||
|
||||
export function ModalHeader({ agent }: ModalHeaderProps) {
|
||||
const isUnknownCreator = agent.creator_name === "Unknown";
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-3">
|
||||
@@ -15,9 +16,9 @@ export function ModalHeader({ agent }: ModalHeaderProps) {
|
||||
</div>
|
||||
<div>
|
||||
<Text variant="h3">{agent.name}</Text>
|
||||
<Text variant="body-medium">
|
||||
by {agent.creator_name === "Unknown" ? "–" : agent.creator_name}
|
||||
</Text>
|
||||
{!isUnknownCreator ? (
|
||||
<Text variant="body-medium">by {agent.creator_name}</Text>
|
||||
) : null}
|
||||
<ShowMoreText
|
||||
previewLimit={80}
|
||||
variant="small"
|
||||
|
||||
@@ -2,9 +2,7 @@ import { Button } from "@/components/atoms/Button/Button";
|
||||
import { RunVariant } from "../../useAgentRunModal";
|
||||
|
||||
interface Props {
|
||||
hasExternalTrigger: boolean;
|
||||
defaultRunType: RunVariant;
|
||||
onShowSchedule: () => void;
|
||||
onRun: () => void;
|
||||
isExecuting?: boolean;
|
||||
isSettingUpTrigger?: boolean;
|
||||
@@ -12,9 +10,7 @@ interface Props {
|
||||
}
|
||||
|
||||
export function RunActions({
|
||||
hasExternalTrigger,
|
||||
defaultRunType,
|
||||
onShowSchedule,
|
||||
onRun,
|
||||
isExecuting = false,
|
||||
isSettingUpTrigger = false,
|
||||
@@ -22,11 +18,6 @@ export function RunActions({
|
||||
}: Props) {
|
||||
return (
|
||||
<div className="flex justify-end gap-3">
|
||||
{!hasExternalTrigger && (
|
||||
<Button variant="secondary" onClick={onShowSchedule}>
|
||||
Schedule Run
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={onRun}
|
||||
|
||||
@@ -1,30 +1,25 @@
|
||||
import { Button } from "@/components/atoms/Button/Button";
|
||||
|
||||
interface Props {
|
||||
onGoBack: () => void;
|
||||
onSchedule: () => void;
|
||||
isCreatingSchedule?: boolean;
|
||||
allRequiredInputsAreSet?: boolean;
|
||||
}
|
||||
|
||||
export function ScheduleActions({
|
||||
onGoBack,
|
||||
onSchedule,
|
||||
isCreatingSchedule = false,
|
||||
allRequiredInputsAreSet = true,
|
||||
}: Props) {
|
||||
return (
|
||||
<div className="flex justify-end gap-3">
|
||||
<Button variant="ghost" onClick={onGoBack}>
|
||||
Go Back
|
||||
</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
onClick={onSchedule}
|
||||
disabled={!allRequiredInputsAreSet || isCreatingSchedule}
|
||||
loading={isCreatingSchedule}
|
||||
>
|
||||
Create Schedule
|
||||
Schedule Agent
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { Input } from "@/components/atoms/Input/Input";
|
||||
import { MultiToggle } from "@/components/molecules/MultiToggle/MultiToggle";
|
||||
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
|
||||
import { AgentInputFields } from "../AgentInputFields/AgentInputFields";
|
||||
import { Text } from "@/components/atoms/Text/Text";
|
||||
import { Select } from "@/components/atoms/Select/Select";
|
||||
import { useScheduleView } from "./useScheduleView";
|
||||
@@ -9,24 +7,18 @@ import { useCallback, useState } from "react";
|
||||
import { validateSchedule } from "./helpers";
|
||||
|
||||
interface Props {
|
||||
agent: LibraryAgent;
|
||||
scheduleName: string;
|
||||
cronExpression: string;
|
||||
inputValues: Record<string, any>;
|
||||
onScheduleNameChange: (name: string) => void;
|
||||
onCronExpressionChange: (expression: string) => void;
|
||||
onInputChange: (key: string, value: string) => void;
|
||||
onValidityChange?: (valid: boolean) => void;
|
||||
}
|
||||
|
||||
export function ScheduleView({
|
||||
agent,
|
||||
scheduleName,
|
||||
cronExpression: _cronExpression,
|
||||
inputValues,
|
||||
onScheduleNameChange,
|
||||
onCronExpressionChange,
|
||||
onInputChange,
|
||||
onValidityChange,
|
||||
}: Props) {
|
||||
const {
|
||||
@@ -139,12 +131,7 @@ export function ScheduleView({
|
||||
error={errors.time}
|
||||
/>
|
||||
|
||||
<AgentInputFields
|
||||
agent={agent}
|
||||
inputValues={inputValues}
|
||||
onInputChange={onInputChange}
|
||||
variant="schedule"
|
||||
/>
|
||||
{/** Agent inputs are rendered in the main modal; none here. */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext } from "react";
|
||||
import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
|
||||
import { RunVariant } from "./useAgentRunModal";
|
||||
|
||||
export interface RunAgentModalContextValue {
|
||||
agent: LibraryAgent;
|
||||
defaultRunType: RunVariant;
|
||||
// Preset / Trigger
|
||||
presetName: string;
|
||||
setPresetName: (value: string) => void;
|
||||
presetDescription: string;
|
||||
setPresetDescription: (value: string) => void;
|
||||
// Inputs
|
||||
inputValues: Record<string, any>;
|
||||
setInputValue: (key: string, value: any) => void;
|
||||
agentInputFields: Record<string, any>;
|
||||
// Credentials
|
||||
inputCredentials: Record<string, any>;
|
||||
setInputCredentialsValue: (key: string, value: any | undefined) => void;
|
||||
agentCredentialsInputFields: Record<string, any>;
|
||||
}
|
||||
|
||||
const RunAgentModalContext = createContext<RunAgentModalContextValue | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
export function useRunAgentModalContext(): RunAgentModalContextValue {
|
||||
const ctx = useContext(RunAgentModalContext);
|
||||
if (!ctx) throw new Error("RunAgentModalContext missing provider");
|
||||
return ctx;
|
||||
}
|
||||
|
||||
interface ProviderProps {
|
||||
value: RunAgentModalContextValue;
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export function RunAgentModalContextProvider({
|
||||
value,
|
||||
children,
|
||||
}: ProviderProps) {
|
||||
return (
|
||||
<RunAgentModalContext.Provider value={value}>
|
||||
{children}
|
||||
</RunAgentModalContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -29,6 +29,11 @@ export function useAgentRunModal(
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [showScheduleView, setShowScheduleView] = useState(false);
|
||||
const [inputValues, setInputValues] = useState<Record<string, any>>({});
|
||||
const [inputCredentials, setInputCredentials] = useState<Record<string, any>>(
|
||||
{},
|
||||
);
|
||||
const [presetName, setPresetName] = useState<string>("");
|
||||
const [presetDescription, setPresetDescription] = useState<string>("");
|
||||
const defaultScheduleName = useMemo(() => `Run ${agent.name}`, [agent.name]);
|
||||
const [scheduleName, setScheduleName] = useState(defaultScheduleName);
|
||||
const [cronExpression, setCronExpression] = useState("0 9 * * 1");
|
||||
@@ -44,8 +49,7 @@ export function useAgentRunModal(
|
||||
onSuccess: (response) => {
|
||||
if (response.status === 200) {
|
||||
toast({
|
||||
title: "✅ Agent execution started",
|
||||
description: "Your agent is now running.",
|
||||
title: "Agent execution started",
|
||||
});
|
||||
callbacks?.onRun?.(response.data);
|
||||
setIsOpen(false);
|
||||
@@ -66,8 +70,7 @@ export function useAgentRunModal(
|
||||
onSuccess: (response) => {
|
||||
if (response.status === 200) {
|
||||
toast({
|
||||
title: "✅ Schedule created",
|
||||
description: `Agent scheduled to run: ${scheduleName}`,
|
||||
title: "Schedule created",
|
||||
});
|
||||
callbacks?.onCreateSchedule?.(response.data);
|
||||
setIsOpen(false);
|
||||
@@ -88,8 +91,7 @@ export function useAgentRunModal(
|
||||
onSuccess: (response: any) => {
|
||||
if (response.status === 200) {
|
||||
toast({
|
||||
title: "✅ Trigger setup complete",
|
||||
description: "Your webhook trigger is now active.",
|
||||
title: "Trigger setup complete",
|
||||
});
|
||||
callbacks?.onSetupTrigger?.(response.data);
|
||||
setIsOpen(false);
|
||||
@@ -128,8 +130,20 @@ export function useAgentRunModal(
|
||||
);
|
||||
}, [agentInputSchema]);
|
||||
|
||||
const agentCredentialsInputFields = useMemo(() => {
|
||||
if (
|
||||
!agent.credentials_input_schema ||
|
||||
typeof agent.credentials_input_schema !== "object" ||
|
||||
!("properties" in agent.credentials_input_schema) ||
|
||||
!agent.credentials_input_schema.properties
|
||||
) {
|
||||
return {} as Record<string, any>;
|
||||
}
|
||||
return agent.credentials_input_schema.properties as Record<string, any>;
|
||||
}, [agent.credentials_input_schema]);
|
||||
|
||||
// Validation logic
|
||||
const [allRequiredInputsAreSet, missingInputs] = useMemo(() => {
|
||||
const [allRequiredInputsAreSetRaw, missingInputs] = useMemo(() => {
|
||||
const nonEmptyInputs = new Set(
|
||||
Object.keys(inputValues).filter((k) => !isEmpty(inputValues[k])),
|
||||
);
|
||||
@@ -142,11 +156,41 @@ export function useAgentRunModal(
|
||||
return [missing.length === 0, missing];
|
||||
}, [agentInputSchema.required, inputValues]);
|
||||
|
||||
const notifyMissingInputs = useCallback(
|
||||
const [allCredentialsAreSet, missingCredentials] = useMemo(() => {
|
||||
const availableCredentials = new Set(Object.keys(inputCredentials));
|
||||
const allCredentials = new Set(
|
||||
Object.keys(agentCredentialsInputFields || {}) ?? [],
|
||||
);
|
||||
const missing = [...allCredentials].filter(
|
||||
(key) => !availableCredentials.has(key),
|
||||
);
|
||||
return [missing.length === 0, missing];
|
||||
}, [agentCredentialsInputFields, inputCredentials]);
|
||||
|
||||
const credentialsRequired = useMemo(
|
||||
() => Object.keys(agentCredentialsInputFields || {}).length > 0,
|
||||
[agentCredentialsInputFields],
|
||||
);
|
||||
|
||||
// Final readiness flag combining inputs + credentials when credentials are shown
|
||||
const allRequiredInputsAreSet = useMemo(
|
||||
() =>
|
||||
allRequiredInputsAreSetRaw &&
|
||||
(!credentialsRequired || allCredentialsAreSet),
|
||||
[allRequiredInputsAreSetRaw, credentialsRequired, allCredentialsAreSet],
|
||||
);
|
||||
|
||||
const notifyMissingRequirements = useCallback(
|
||||
(needScheduleName: boolean = false) => {
|
||||
const allMissingFields = (
|
||||
needScheduleName && !scheduleName ? ["schedule_name"] : []
|
||||
).concat(missingInputs);
|
||||
)
|
||||
.concat(missingInputs)
|
||||
.concat(
|
||||
credentialsRequired && !allCredentialsAreSet
|
||||
? missingCredentials.map((k) => `credentials:${k}`)
|
||||
: [],
|
||||
);
|
||||
|
||||
toast({
|
||||
title: "⚠️ Missing required inputs",
|
||||
@@ -154,13 +198,20 @@ export function useAgentRunModal(
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
[missingInputs, scheduleName, toast],
|
||||
[
|
||||
missingInputs,
|
||||
scheduleName,
|
||||
toast,
|
||||
credentialsRequired,
|
||||
allCredentialsAreSet,
|
||||
missingCredentials,
|
||||
],
|
||||
);
|
||||
|
||||
// Action handlers
|
||||
const handleRun = useCallback(() => {
|
||||
if (!allRequiredInputsAreSet) {
|
||||
notifyMissingInputs();
|
||||
notifyMissingRequirements();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -177,12 +228,12 @@ export function useAgentRunModal(
|
||||
|
||||
setupTriggerMutation.mutate({
|
||||
data: {
|
||||
name: scheduleName,
|
||||
description: `Trigger for ${agent.name}`,
|
||||
name: presetName || scheduleName,
|
||||
description: presetDescription || `Trigger for ${agent.name}`,
|
||||
graph_id: agent.graph_id,
|
||||
graph_version: agent.graph_version,
|
||||
trigger_config: inputValues,
|
||||
agent_credentials: {}, // TODO: Add credentials handling if needed
|
||||
agent_credentials: inputCredentials,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
@@ -192,7 +243,7 @@ export function useAgentRunModal(
|
||||
graphVersion: agent.graph_version,
|
||||
data: {
|
||||
inputs: inputValues,
|
||||
credentials_inputs: {}, // TODO: Add credentials handling if needed
|
||||
credentials_inputs: inputCredentials,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -201,8 +252,11 @@ export function useAgentRunModal(
|
||||
defaultRunType,
|
||||
scheduleName,
|
||||
inputValues,
|
||||
inputCredentials,
|
||||
agent,
|
||||
notifyMissingInputs,
|
||||
presetName,
|
||||
presetDescription,
|
||||
notifyMissingRequirements,
|
||||
setupTriggerMutation,
|
||||
executeGraphMutation,
|
||||
toast,
|
||||
@@ -210,7 +264,7 @@ export function useAgentRunModal(
|
||||
|
||||
const handleSchedule = useCallback(() => {
|
||||
if (!allRequiredInputsAreSet) {
|
||||
notifyMissingInputs(true);
|
||||
notifyMissingRequirements(true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -226,11 +280,11 @@ export function useAgentRunModal(
|
||||
createScheduleMutation.mutate({
|
||||
graphId: agent.graph_id,
|
||||
data: {
|
||||
name: scheduleName,
|
||||
name: presetName || scheduleName,
|
||||
cron: cronExpression,
|
||||
inputs: inputValues,
|
||||
graph_version: agent.graph_version,
|
||||
credentials: {}, // TODO: Add credentials handling if needed
|
||||
credentials: inputCredentials,
|
||||
},
|
||||
});
|
||||
}, [
|
||||
@@ -238,8 +292,9 @@ export function useAgentRunModal(
|
||||
scheduleName,
|
||||
cronExpression,
|
||||
inputValues,
|
||||
inputCredentials,
|
||||
agent,
|
||||
notifyMissingInputs,
|
||||
notifyMissingRequirements,
|
||||
createScheduleMutation,
|
||||
toast,
|
||||
]);
|
||||
@@ -277,11 +332,22 @@ export function useAgentRunModal(
|
||||
defaultRunType,
|
||||
inputValues,
|
||||
setInputValues,
|
||||
inputCredentials,
|
||||
setInputCredentials,
|
||||
presetName,
|
||||
presetDescription,
|
||||
setPresetName,
|
||||
setPresetDescription,
|
||||
scheduleName,
|
||||
cronExpression,
|
||||
allRequiredInputsAreSet,
|
||||
missingInputs,
|
||||
// Expose credential readiness for any UI hints if needed
|
||||
// but enforcement is already applied in allRequiredInputsAreSet
|
||||
// allCredentialsAreSet,
|
||||
// missingCredentials,
|
||||
agentInputFields,
|
||||
agentCredentialsInputFields,
|
||||
hasInputFields,
|
||||
isExecuting: executeGraphMutation.isPending,
|
||||
isCreatingSchedule: createScheduleMutation.isPending,
|
||||
|
||||
@@ -41,7 +41,7 @@ import LoadingBox, { LoadingSpinner } from "@/components/ui/loading";
|
||||
import { useToast } from "@/components/molecules/Toast/use-toast";
|
||||
import { AgentRunDetailsView } from "./components/agent-run-details-view";
|
||||
import { AgentRunDraftView } from "./components/agent-run-draft-view";
|
||||
import { useAgentRunsInfinite } from "../use-agent-runs";
|
||||
import { useAgentRunsInfinite } from "./use-agent-runs";
|
||||
import { AgentRunsSelectorList } from "./components/agent-runs-selector-list";
|
||||
import { AgentScheduleDetailsView } from "./components/agent-schedule-details-view";
|
||||
|
||||
|
||||
@@ -19,8 +19,8 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { IconCross, IconPlay, IconSave } from "@/components/ui/icons";
|
||||
import { CalendarClockIcon, Trash2Icon } from "lucide-react";
|
||||
import { CronSchedulerDialog } from "@/components/cron-scheduler-dialog";
|
||||
import { CredentialsInput } from "@/components/integrations/credentials-input";
|
||||
import { TypeBasedInput } from "@/components/type-based-input";
|
||||
import { CredentialsInput } from "@/app/(platform)/library/agents/[id]/components/AgentRunsView/components/CredentialsInputs/CredentialsInputs";
|
||||
import { RunAgentInputs } from "@/app/(platform)/library/agents/[id]/components/AgentRunsView/components/RunAgentInputs/RunAgentInputs";
|
||||
import { useOnboarding } from "@/components/onboarding/onboarding-provider";
|
||||
import { cn, isEmpty } from "@/lib/utils";
|
||||
import SchemaTooltip from "@/components/SchemaTooltip";
|
||||
@@ -596,7 +596,7 @@ export function AgentRunDraftView({
|
||||
<SchemaTooltip description={inputSubSchema.description} />
|
||||
</label>
|
||||
|
||||
<TypeBasedInput
|
||||
<RunAgentInputs
|
||||
schema={inputSubSchema}
|
||||
value={inputValues[key] ?? inputSubSchema.default}
|
||||
placeholder={inputSubSchema.description}
|
||||
|
||||
@@ -21,8 +21,12 @@ import { Separator } from "@/components/ui/separator";
|
||||
|
||||
import { agentRunStatusMap } from "@/components/agents/agent-run-status-chip";
|
||||
import AgentRunSummaryCard from "@/components/agents/agent-run-summary-card";
|
||||
import { AgentRunsQuery } from "../../use-agent-runs";
|
||||
import { AgentRunsQuery } from "../use-agent-runs";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
|
||||
import { RunAgentModal } from "../../AgentRunsView/components/RunAgentModal/RunAgentModal";
|
||||
import { PlusIcon } from "@phosphor-icons/react";
|
||||
import { LibraryAgent as GeneratedLibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
|
||||
|
||||
interface AgentRunsSelectorListProps {
|
||||
agent: LibraryAgent;
|
||||
@@ -67,6 +71,8 @@ export function AgentRunsSelectorList({
|
||||
"runs",
|
||||
);
|
||||
|
||||
const isNewAgentRunsEnabled = useGetFlag(Flag.NEW_AGENT_RUNS);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedView.type === "schedule") {
|
||||
setActiveListTab("scheduled");
|
||||
@@ -79,7 +85,17 @@ export function AgentRunsSelectorList({
|
||||
|
||||
return (
|
||||
<aside className={cn("flex flex-col gap-4", className)}>
|
||||
{allowDraftNewRun && (
|
||||
{isNewAgentRunsEnabled ? (
|
||||
<RunAgentModal
|
||||
triggerSlot={
|
||||
<Button variant="primary" size="large" className="w-full">
|
||||
<PlusIcon size={20} /> New Run
|
||||
</Button>
|
||||
}
|
||||
agent={agent as unknown as GeneratedLibraryAgent}
|
||||
agentId={agent.id.toString()}
|
||||
/>
|
||||
) : allowDraftNewRun ? (
|
||||
<Button
|
||||
className={"mb-4 hidden lg:flex"}
|
||||
onClick={onSelectDraftNewRun}
|
||||
@@ -87,7 +103,7 @@ export function AgentRunsSelectorList({
|
||||
>
|
||||
New {agent.has_external_trigger ? "trigger" : "run"}
|
||||
</Button>
|
||||
)}
|
||||
) : null}
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Badge
|
||||
|
||||
@@ -1,16 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
|
||||
|
||||
import { OldAgentLibraryView } from "./components/OldAgentLibraryView/OldAgentLibraryView";
|
||||
import { AgentRunsView } from "./components/AgentRunsView/AgentRunsView";
|
||||
|
||||
export default function AgentLibraryPage() {
|
||||
const isNewAgentRunsEnabled = useGetFlag(Flag.NEW_AGENT_RUNS);
|
||||
|
||||
if (isNewAgentRunsEnabled) {
|
||||
return <AgentRunsView />;
|
||||
}
|
||||
|
||||
return <OldAgentLibraryView />;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { useToast } from "@/components/molecules/Toast/use-toast";
|
||||
import { IconKey, IconUser } from "@/components/ui/icons";
|
||||
import { Trash2Icon } from "lucide-react";
|
||||
import { KeyIcon } from "@phosphor-icons/react/dist/ssr";
|
||||
import { providerIcons } from "@/components/integrations/credentials-input";
|
||||
import { providerIcons } from "@/app/(platform)/library/agents/[id]/components/AgentRunsView/components/CredentialsInputs/CredentialsInputs";
|
||||
import { CredentialsProvidersContext } from "@/components/integrations/credentials-provider";
|
||||
import {
|
||||
Table,
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { Form, FormControl, FormField, FormItem } from "@/components/ui/form";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Text } from "@/components/atoms/Text/Text";
|
||||
import { Button } from "@/components/atoms/Button/Button";
|
||||
import { NotificationPreference } from "@/app/api/__generated__/models/notificationPreference";
|
||||
import { User } from "@supabase/supabase-js";
|
||||
import { useNotificationForm } from "./useNotificationForm";
|
||||
import { Switch } from "@/components/atoms/Switch/Switch";
|
||||
|
||||
type NotificationFormProps = {
|
||||
preferences: NotificationPreference;
|
||||
|
||||
@@ -32,7 +32,6 @@ import {
|
||||
setNestedProperty,
|
||||
} from "@/lib/utils";
|
||||
import { Button } from "@/components/atoms/Button/Button";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { TextRenderer } from "@/components/ui/render";
|
||||
import { history } from "./history";
|
||||
import NodeHandle from "./NodeHandle";
|
||||
@@ -60,6 +59,7 @@ import useCredits from "@/hooks/useCredits";
|
||||
import { getV1GetAyrshareSsoUrl } from "@/app/api/__generated__/endpoints/integrations/integrations";
|
||||
import { toast } from "@/components/molecules/Toast/use-toast";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "./atoms/Switch/Switch";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { Meta, StoryObj } from "@storybook/nextjs";
|
||||
import { useState } from "react";
|
||||
import { FileInput } from "./FileInput";
|
||||
|
||||
const meta: Meta<typeof FileInput> = {
|
||||
title: "Atoms/FileInput",
|
||||
component: FileInput,
|
||||
tags: ["autodocs"],
|
||||
parameters: {
|
||||
layout: "centered",
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"File upload input with progress and removable preview.\n\nProps:\n- accept: optional MIME/extensions filter (e.g. ['image/*', '.pdf']).\n- maxFileSize: optional maximum size in bytes; larger files are rejected with an inline error.",
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
onUploadFile: { action: "upload" },
|
||||
accept: {
|
||||
control: "object",
|
||||
description:
|
||||
"Optional accept filter. Supports MIME types (image/*) and extensions (.pdf).",
|
||||
},
|
||||
maxFileSize: {
|
||||
control: "number",
|
||||
description: "Optional maximum file size in bytes.",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
function mockUpload(file: File): Promise<{
|
||||
file_name: string;
|
||||
size: number;
|
||||
content_type: string;
|
||||
file_uri: string;
|
||||
}> {
|
||||
return new Promise((resolve) =>
|
||||
setTimeout(
|
||||
() =>
|
||||
resolve({
|
||||
file_name: file.name,
|
||||
size: file.size,
|
||||
content_type: file.type || "application/octet-stream",
|
||||
file_uri: URL.createObjectURL(file),
|
||||
}),
|
||||
400,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const Basic: Story = {
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
"This example accepts images or PDFs only and limits size to 5MB. Oversized or disallowed file types show an inline error and do not upload.",
|
||||
},
|
||||
},
|
||||
},
|
||||
render: function BasicStory() {
|
||||
const [value, setValue] = useState<string>("");
|
||||
const [progress, setProgress] = useState<number>(0);
|
||||
|
||||
async function onUploadFile(file: File) {
|
||||
setProgress(0);
|
||||
const interval = setInterval(() => {
|
||||
setProgress((p) => (p >= 100 ? 100 : p + 20));
|
||||
}, 80);
|
||||
const result = await mockUpload(file);
|
||||
clearInterval(interval);
|
||||
setProgress(100);
|
||||
return result;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-[560px]">
|
||||
<FileInput
|
||||
value={value}
|
||||
onChange={setValue}
|
||||
onUploadFile={onUploadFile}
|
||||
uploadProgress={progress}
|
||||
accept={["image/*", ".pdf"]}
|
||||
maxFileSize={5 * 1024 * 1024}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,213 @@
|
||||
import { FileTextIcon, TrashIcon, UploadIcon } from "@phosphor-icons/react";
|
||||
import { useRef, useState } from "react";
|
||||
import { Button } from "../Button/Button";
|
||||
import { formatFileSize, getFileLabel } from "./helpers";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Progress } from "../Progress/Progress";
|
||||
|
||||
type UploadFileResult = {
|
||||
file_name: string;
|
||||
size: number;
|
||||
content_type: string;
|
||||
file_uri: string;
|
||||
};
|
||||
|
||||
interface Props {
|
||||
onUploadFile: (file: File) => Promise<UploadFileResult>;
|
||||
uploadProgress: number;
|
||||
value?: string; // file URI or empty
|
||||
placeholder?: string; // e.g. "Resume", "Document", etc.
|
||||
onChange: (value: string) => void;
|
||||
className?: string;
|
||||
maxFileSize?: number; // bytes (optional)
|
||||
accept?: string | string[]; // input accept filter (optional)
|
||||
}
|
||||
|
||||
export function FileInput({
|
||||
onUploadFile,
|
||||
uploadProgress,
|
||||
value,
|
||||
onChange,
|
||||
className,
|
||||
maxFileSize,
|
||||
accept,
|
||||
}: Props) {
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||
const [fileInfo, setFileInfo] = useState<{
|
||||
name: string;
|
||||
size: number;
|
||||
content_type: string;
|
||||
} | null>(null);
|
||||
|
||||
const uploadFile = async (file: File) => {
|
||||
setIsUploading(true);
|
||||
setUploadError(null);
|
||||
|
||||
try {
|
||||
const result = await onUploadFile(file);
|
||||
|
||||
setFileInfo({
|
||||
name: result.file_name,
|
||||
size: result.size,
|
||||
content_type: result.content_type,
|
||||
});
|
||||
|
||||
// Set the file URI as the value
|
||||
onChange(result.file_uri);
|
||||
} catch (error) {
|
||||
console.error("Upload failed:", error);
|
||||
setUploadError(error instanceof Error ? error.message : "Upload failed");
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
// Validate max size
|
||||
if (typeof maxFileSize === "number" && file.size > maxFileSize) {
|
||||
setUploadError(
|
||||
`File exceeds maximum size of ${formatFileSize(maxFileSize)} (selected ${formatFileSize(file.size)})`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Validate accept types
|
||||
if (!isAcceptedType(file, accept)) {
|
||||
setUploadError("Selected file type is not allowed");
|
||||
return;
|
||||
}
|
||||
uploadFile(file);
|
||||
};
|
||||
|
||||
const handleFileDrop = (event: React.DragEvent<HTMLDivElement>) => {
|
||||
event.preventDefault();
|
||||
const file = event.dataTransfer.files[0];
|
||||
if (file) uploadFile(file);
|
||||
};
|
||||
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const storageNote =
|
||||
"Files are stored securely and will be automatically deleted at most 24 hours after upload.";
|
||||
|
||||
function acceptToString(a?: string | string[]) {
|
||||
if (!a) return "*/*";
|
||||
return Array.isArray(a) ? a.join(",") : a;
|
||||
}
|
||||
|
||||
function isAcceptedType(file: File, a?: string | string[]) {
|
||||
if (!a) return true;
|
||||
const list = Array.isArray(a) ? a : a.split(",").map((s) => s.trim());
|
||||
const fileType = file.type; // e.g. image/png
|
||||
const fileExt = file.name.includes(".")
|
||||
? `.${file.name.split(".").pop()}`.toLowerCase()
|
||||
: "";
|
||||
|
||||
for (const entry of list) {
|
||||
if (!entry) continue;
|
||||
const e = entry.toLowerCase();
|
||||
if (e.includes("/")) {
|
||||
// MIME type, support wildcards like image/*
|
||||
const [main, sub] = e.split("/");
|
||||
const [fMain, fSub] = fileType.toLowerCase().split("/");
|
||||
if (!fMain || !fSub) continue;
|
||||
if (sub === "*") {
|
||||
if (main === fMain) return true;
|
||||
} else {
|
||||
if (e === fileType.toLowerCase()) return true;
|
||||
}
|
||||
} else if (e.startsWith(".")) {
|
||||
// Extension match
|
||||
if (fileExt === e) return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("w-full", className)}>
|
||||
{isUploading ? (
|
||||
<div className="space-y-2">
|
||||
<div className="flex min-h-14 items-center gap-4">
|
||||
<div className="agpt-border-input flex min-h-14 w-full flex-col justify-center rounded-xl bg-zinc-50 p-4 text-sm">
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<UploadIcon className="h-5 w-5 text-blue-600" />
|
||||
<span className="text-gray-700">Uploading...</span>
|
||||
<span className="text-gray-500">
|
||||
{Math.round(uploadProgress)}%
|
||||
</span>
|
||||
</div>
|
||||
<Progress value={uploadProgress} className="w-full" />
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">{storageNote}</p>
|
||||
</div>
|
||||
) : value ? (
|
||||
<div className="space-y-2">
|
||||
<div className="flex min-h-14 items-center gap-4">
|
||||
<div className="agpt-border-input flex min-h-14 w-full items-center justify-between rounded-xl bg-zinc-50 p-4 text-sm text-gray-500">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileTextIcon className="h-7 w-7 text-black" />
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="font-normal text-black">
|
||||
{fileInfo
|
||||
? getFileLabel(fileInfo.name, fileInfo.content_type)
|
||||
: "File"}
|
||||
</span>
|
||||
<span>{fileInfo ? formatFileSize(fileInfo.size) : ""}</span>
|
||||
</div>
|
||||
</div>
|
||||
<TrashIcon
|
||||
className="h-5 w-5 cursor-pointer text-black"
|
||||
onClick={() => {
|
||||
if (inputRef.current) {
|
||||
inputRef.current.value = "";
|
||||
}
|
||||
onChange("");
|
||||
setFileInfo(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">{storageNote}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div className="flex min-h-14 items-center gap-4">
|
||||
<div
|
||||
onDrop={handleFileDrop}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
className="agpt-border-input flex min-h-14 w-full items-center justify-center rounded-xl border-dashed bg-zinc-50 text-sm text-gray-500"
|
||||
>
|
||||
Choose a file or drag and drop it here
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={() => inputRef.current?.click()}
|
||||
className="min-w-40"
|
||||
>
|
||||
Browse File
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{uploadError && (
|
||||
<div className="text-sm text-red-600">Error: {uploadError}</div>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-gray-500">{storageNote}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept={acceptToString(accept)}
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
disabled={isUploading}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
export function getFileLabel(filename: string, contentType?: string) {
|
||||
if (contentType) {
|
||||
const mimeParts = contentType.split("/");
|
||||
if (mimeParts.length > 1) {
|
||||
return `${mimeParts[1].toUpperCase()} file`;
|
||||
}
|
||||
return `${contentType} file`;
|
||||
}
|
||||
|
||||
const pathParts = filename.split(".");
|
||||
if (pathParts.length > 1) {
|
||||
const ext = pathParts.pop();
|
||||
if (ext) return `${ext.toUpperCase()} file`;
|
||||
}
|
||||
return "File";
|
||||
}
|
||||
|
||||
export function formatFileSize(bytes: number): string {
|
||||
if (bytes >= 1024 * 1024) {
|
||||
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
||||
} else if (bytes >= 1024) {
|
||||
return `${(bytes / 1024).toFixed(2)} KB`;
|
||||
} else {
|
||||
return `${bytes} B`;
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,8 @@ const meta: Meta<typeof Input> = {
|
||||
"tel",
|
||||
"url",
|
||||
"textarea",
|
||||
"date",
|
||||
"datetime-local",
|
||||
],
|
||||
description: "Input type",
|
||||
},
|
||||
@@ -110,6 +112,38 @@ export const WithError: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
export const DateInput: Story = {
|
||||
args: {
|
||||
label: "Date",
|
||||
type: "date",
|
||||
placeholder: "Select a date",
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
"Native HTML date input integrated in the design system Input. Value format is yyyy-MM-dd.",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const DateTimeLocalInput: Story = {
|
||||
args: {
|
||||
label: "Date & Time",
|
||||
type: "datetime-local",
|
||||
placeholder: "Select date and time",
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
"Native datetime-local input. Value is a local time string (e.g. 2025-08-28T14:30).",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const TextareaInput: Story = {
|
||||
args: {
|
||||
label: "Description",
|
||||
@@ -212,6 +246,21 @@ function renderInputTypes() {
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4">
|
||||
<p className="font-mono text-sm">Native date input.</p>
|
||||
<Input label="Date" type="date" placeholder="Select a date" id="date" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-4">
|
||||
<p className="font-mono text-sm">
|
||||
Native datetime-local input (local time, no timezone).
|
||||
</p>
|
||||
<Input
|
||||
label="Date & Time"
|
||||
type="datetime-local"
|
||||
placeholder="Select date and time"
|
||||
id="datetime"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,7 +22,9 @@ export interface TextFieldProps extends Omit<InputProps, "size"> {
|
||||
| "amount"
|
||||
| "tel"
|
||||
| "url"
|
||||
| "textarea";
|
||||
| "textarea"
|
||||
| "date"
|
||||
| "datetime-local";
|
||||
// Textarea-specific props
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
@@ -17,7 +17,9 @@ interface ExtendedInputProps extends InputProps {
|
||||
| "amount"
|
||||
| "tel"
|
||||
| "url"
|
||||
| "textarea";
|
||||
| "textarea"
|
||||
| "date"
|
||||
| "datetime-local";
|
||||
}
|
||||
|
||||
export function useInput(args: ExtendedInputProps) {
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { Meta, StoryObj } from "@storybook/nextjs";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Progress } from "./Progress";
|
||||
|
||||
const meta: Meta<typeof Progress> = {
|
||||
title: "Atoms/Progress",
|
||||
component: Progress,
|
||||
tags: ["autodocs"],
|
||||
parameters: {
|
||||
layout: "centered",
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"Simple progress bar with value and optional max (default 100).",
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
value: {
|
||||
control: { type: "number", min: 0, max: 100 },
|
||||
description: "Current value.",
|
||||
},
|
||||
max: {
|
||||
control: { type: "number", min: 1 },
|
||||
description: "Maximum value (default 100).",
|
||||
},
|
||||
className: {
|
||||
control: "text",
|
||||
description: "Optional className for container (e.g. height).",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Basic: Story = {
|
||||
args: { value: 50 },
|
||||
render: function BasicStory(args) {
|
||||
return (
|
||||
<div className="w-80">
|
||||
<Progress {...args} />
|
||||
</div>
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
export const CustomMax: Story = {
|
||||
args: { value: 30, max: 60 },
|
||||
render: function CustomMaxStory(args) {
|
||||
return (
|
||||
<div className="w-80">
|
||||
<Progress {...args} />
|
||||
</div>
|
||||
);
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: { story: "With max=60, value=30 renders as 50%." },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const Sizes: Story = {
|
||||
render: function SizesStory() {
|
||||
return (
|
||||
<div className="w-80 space-y-4">
|
||||
<Progress value={40} className="h-1" />
|
||||
<Progress value={60} className="h-2" />
|
||||
<Progress value={80} className="h-3" />
|
||||
</div>
|
||||
);
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story: "Adjust height via className (e.g., h-1, h-2, h-3).",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const Live: Story = {
|
||||
render: function LiveStory() {
|
||||
const [value, setValue] = useState<number>(0);
|
||||
useEffect(() => {
|
||||
const id = setInterval(
|
||||
() => setValue((v) => (v >= 100 ? 0 : v + 10)),
|
||||
400,
|
||||
);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
return <Progress value={value} className="w-80" />;
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: { story: "Animated example updating value on an interval." },
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -20,7 +20,7 @@ const Progress = React.forwardRef<HTMLDivElement, ProgressProps>(
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
className="h-full bg-blue-600 transition-all duration-300 ease-in-out"
|
||||
className="h-full bg-zinc-800 transition-all duration-300 ease-in-out"
|
||||
style={{ width: `${percentage}%` }}
|
||||
/>
|
||||
</div>
|
||||
@@ -10,7 +10,7 @@ const meta: Meta<typeof Select> = {
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"Select component based on our design system. Built on top of shadcn/ui select with custom styling matching Figma designs and consistent with the Input component.",
|
||||
"Select component based on our design system. Built on shadcn/ui with styling that matches our Input. Supports size variants (small | medium) and optional hidden label.",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -44,6 +44,12 @@ const meta: Meta<typeof Select> = {
|
||||
control: "object",
|
||||
description: "Array of options with value and label properties",
|
||||
},
|
||||
size: {
|
||||
control: { type: "radio" },
|
||||
options: ["small", "medium"],
|
||||
description:
|
||||
"Visual size variant. small = compact trigger (22px line-height), medium = default (46px height).",
|
||||
},
|
||||
},
|
||||
args: {
|
||||
placeholder: "Select an option...",
|
||||
@@ -91,6 +97,119 @@ export const WithValue: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
export const Small: Story = {
|
||||
args: {
|
||||
id: "select-small",
|
||||
label: "Compact",
|
||||
hideLabel: true,
|
||||
size: "small",
|
||||
placeholder: "Choose option",
|
||||
options: [
|
||||
{ value: "opt1", label: "Option 1" },
|
||||
{ value: "opt2", label: "Option 2" },
|
||||
{ value: "opt3", label: "Option 3" },
|
||||
],
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
"Small size is ideal for dense UIs (e.g., inline controls like TimePicker).",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const Medium: Story = {
|
||||
args: {
|
||||
id: "select-medium",
|
||||
label: "Medium",
|
||||
size: "medium",
|
||||
placeholder: "Choose option",
|
||||
options: [
|
||||
{ value: "opt1", label: "Option 1" },
|
||||
{ value: "opt2", label: "Option 2" },
|
||||
{ value: "opt3", label: "Option 3" },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
export const WithIconsAndSeparators: Story = {
|
||||
render: function IconsStory() {
|
||||
const opts = [
|
||||
{ value: "oauth", label: "Your Google account", icon: <span>✅</span> },
|
||||
{ separator: true, value: "sep1", label: "" } as any,
|
||||
{
|
||||
value: "signin",
|
||||
label: "Sign in with Google",
|
||||
icon: <span>🔐</span>,
|
||||
onSelect: () => alert("Sign in"),
|
||||
},
|
||||
{
|
||||
value: "add-key",
|
||||
label: "Add API key",
|
||||
onSelect: () => alert("Add key"),
|
||||
},
|
||||
];
|
||||
return (
|
||||
<div className="w-[320px]">
|
||||
<Select
|
||||
id="rich"
|
||||
label="Rich"
|
||||
hideLabel
|
||||
options={opts as any}
|
||||
placeholder="Choose"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
"Demonstrates icons, separators, and actionable rows via onSelect. onSelect prevents value change and triggers the action.",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const WithRenderItem: Story = {
|
||||
render: function RenderItemStory() {
|
||||
const opts = [
|
||||
{ value: "opt1", label: "Option 1" },
|
||||
{ value: "opt2", label: "Option 2", disabled: true },
|
||||
{ value: "opt3", label: "Option 3" },
|
||||
];
|
||||
return (
|
||||
<div className="w-[320px]">
|
||||
<Select
|
||||
id="render"
|
||||
label="Custom"
|
||||
hideLabel
|
||||
options={opts}
|
||||
placeholder="Pick one"
|
||||
renderItem={(o) => (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium">{o.label}</span>
|
||||
{o.disabled && (
|
||||
<span className="text-xs text-zinc-400">(disabled)</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
parameters: {
|
||||
docs: {
|
||||
description: {
|
||||
story:
|
||||
"Custom rendering for options via renderItem prop; disabled items are styled and non-selectable.",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export const WithoutLabel: Story = {
|
||||
args: {
|
||||
label: "Country",
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectSeparator,
|
||||
} from "@/components/ui/select";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ReactNode } from "react";
|
||||
@@ -15,6 +16,10 @@ import { Text } from "../Text/Text";
|
||||
export interface SelectOption {
|
||||
value: string;
|
||||
label: string;
|
||||
icon?: ReactNode;
|
||||
disabled?: boolean;
|
||||
separator?: boolean;
|
||||
onSelect?: () => void; // optional action handler
|
||||
}
|
||||
|
||||
export interface SelectFieldProps {
|
||||
@@ -29,6 +34,8 @@ export interface SelectFieldProps {
|
||||
value?: string;
|
||||
onValueChange?: (value: string) => void;
|
||||
options: SelectOption[];
|
||||
size?: "small" | "medium";
|
||||
renderItem?: (option: SelectOption) => React.ReactNode;
|
||||
}
|
||||
|
||||
export function Select({
|
||||
@@ -43,14 +50,24 @@ export function Select({
|
||||
value,
|
||||
onValueChange,
|
||||
options,
|
||||
size = "medium",
|
||||
renderItem,
|
||||
}: SelectFieldProps) {
|
||||
const triggerStyles = cn(
|
||||
// Override the default select styles with Figma design matching Input
|
||||
"h-[2.875rem] rounded-3xl border border-zinc-200 bg-white px-4 py-2.5 shadow-none",
|
||||
"font-normal text-black text-sm w-full",
|
||||
// Base styles matching Input
|
||||
"rounded-3xl border border-zinc-200 bg-white px-4 shadow-none",
|
||||
"font-normal text-black w-full",
|
||||
"placeholder:font-normal !placeholder:text-zinc-400",
|
||||
// Focus and hover states
|
||||
"focus:border-zinc-400 focus:shadow-none focus:outline-none focus:ring-1 focus:ring-zinc-400 focus:ring-offset-0",
|
||||
// Size variants
|
||||
size === "small" && [
|
||||
"h-[2.25rem]",
|
||||
"py-2",
|
||||
"text-sm leading-[22px]",
|
||||
"placeholder:text-sm placeholder:leading-[22px]",
|
||||
],
|
||||
size === "medium" && ["h-[2.875rem]", "py-2.5", "text-sm"],
|
||||
// Error state
|
||||
error &&
|
||||
"border-1.5 border-red-500 focus:border-red-500 focus:ring-red-500",
|
||||
@@ -69,11 +86,32 @@ export function Select({
|
||||
<SelectValue placeholder={placeholder || label} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{options.map((option) => (
|
||||
<SelectItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
{options.map((option, idx) => {
|
||||
if (option.separator) return <SelectSeparator key={`sep-${idx}`} />;
|
||||
const content = renderItem ? (
|
||||
renderItem(option)
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
{option.icon}
|
||||
<span>{option.label}</span>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<SelectItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
disabled={option.disabled}
|
||||
onMouseDown={(e) => {
|
||||
if (option.onSelect) {
|
||||
e.preventDefault();
|
||||
option.onSelect();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</SelectItem>
|
||||
);
|
||||
})}
|
||||
</SelectContent>
|
||||
</BaseSelect>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { Meta, StoryObj } from "@storybook/nextjs";
|
||||
import { useState } from "react";
|
||||
import { Switch } from "./Switch";
|
||||
|
||||
const meta: Meta<typeof Switch> = {
|
||||
title: "Atoms/Switch",
|
||||
component: Switch,
|
||||
tags: ["autodocs"],
|
||||
parameters: {
|
||||
layout: "centered",
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"Shadcn-based toggle switch. Controlled via checked and onCheckedChange.",
|
||||
},
|
||||
},
|
||||
},
|
||||
argTypes: {
|
||||
checked: { control: "boolean", description: "Checked state (controlled)." },
|
||||
disabled: { control: "boolean", description: "Disable the switch." },
|
||||
onCheckedChange: { action: "change", description: "Change handler." },
|
||||
className: { control: "text", description: "Optional className." },
|
||||
},
|
||||
};
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Basic: Story = {
|
||||
render: function BasicStory(args) {
|
||||
const [on, setOn] = useState<boolean>(true);
|
||||
return (
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch
|
||||
aria-label="Toggle"
|
||||
checked={on}
|
||||
onCheckedChange={(v) => {
|
||||
setOn(v);
|
||||
if (args.onCheckedChange) args.onCheckedChange(v);
|
||||
}}
|
||||
/>
|
||||
<span className="text-sm">{on ? "On" : "Off"}</span>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
export const Disabled: Story = {
|
||||
args: { disabled: true },
|
||||
render: function DisabledStory(args) {
|
||||
return <Switch aria-label="Disabled switch" disabled {...args} />;
|
||||
},
|
||||
};
|
||||
|
||||
export const WithLabel: Story = {
|
||||
render: function WithLabelStory() {
|
||||
const [on, setOn] = useState<boolean>(false);
|
||||
const id = "ds-switch-label";
|
||||
return (
|
||||
<label htmlFor={id} className="flex items-center gap-3">
|
||||
<Switch id={id} checked={on} onCheckedChange={setOn} />
|
||||
<span className="text-sm">Enable notifications</span>
|
||||
</label>
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -1,36 +0,0 @@
|
||||
import { FC } from "react";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
|
||||
export const OAuth2FlowWaitingModal: FC<{
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
providerName: string;
|
||||
}> = ({ open, onClose, providerName }) => {
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onClose();
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
Waiting on {providerName} sign-in process...
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Complete the sign-in process in the pop-up window.
|
||||
<br />
|
||||
Closing this dialog will cancel the sign-in process.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -69,6 +69,10 @@ export const CustomStyling: Story = {
|
||||
render: renderCustomStyledDialog,
|
||||
};
|
||||
|
||||
export const ModalOverModal: Story = {
|
||||
render: renderModalOverModal,
|
||||
};
|
||||
|
||||
function renderBasicDialog() {
|
||||
return (
|
||||
<Dialog title="Basic Dialog">
|
||||
@@ -195,3 +199,33 @@ function renderCustomStyledDialog() {
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function renderModalOverModal() {
|
||||
return (
|
||||
<Dialog title="Parent Dialog">
|
||||
<Dialog.Trigger>
|
||||
<Button variant="primary">Open Parent</Button>
|
||||
</Dialog.Trigger>
|
||||
<Dialog.Content>
|
||||
<div className="space-y-4">
|
||||
<p>
|
||||
This is the parent dialog. You can open another modal on top of it
|
||||
using a nested Dialog.
|
||||
</p>
|
||||
|
||||
<Dialog title="Child Dialog">
|
||||
<Dialog.Trigger>
|
||||
<Button size="small">Open Child Modal</Button>
|
||||
</Dialog.Trigger>
|
||||
<Dialog.Content>
|
||||
<p>
|
||||
This child dialog is rendered above the parent. Close it first
|
||||
to interact with the parent again.
|
||||
</p>
|
||||
</Dialog.Content>
|
||||
</Dialog>
|
||||
</div>
|
||||
</Dialog.Content>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { Meta, StoryObj } from "@storybook/nextjs";
|
||||
import { useState } from "react";
|
||||
import { TimePicker } from "./TimePicker";
|
||||
|
||||
const meta: Meta<typeof TimePicker> = {
|
||||
title: "Molecules/TimePicker",
|
||||
component: TimePicker,
|
||||
tags: ["autodocs"],
|
||||
parameters: {
|
||||
layout: "centered",
|
||||
docs: {
|
||||
description: {
|
||||
component:
|
||||
"Compact time selector using three small Selects (hour, minute, AM/PM).",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof meta>;
|
||||
|
||||
export const Basic: Story = {
|
||||
render: function BasicStory() {
|
||||
const [value, setValue] = useState<string>("12:00");
|
||||
return <TimePicker value={value} onChange={setValue} />;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Select } from "@/components/atoms/Select/Select";
|
||||
|
||||
interface Props {
|
||||
value?: string;
|
||||
onChange: (time: string) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function TimePicker({ value, onChange }: Props) {
|
||||
const pad = (n: number) => n.toString().padStart(2, "0");
|
||||
const [hourNum, minuteNum] = value ? value.split(":").map(Number) : [0, 0];
|
||||
|
||||
const meridiem = hourNum >= 12 ? "PM" : "AM";
|
||||
const hour = pad(hourNum % 12 || 12);
|
||||
const minute = pad(minuteNum);
|
||||
|
||||
const changeTime = (hour: string, minute: string, meridiem: string) => {
|
||||
const hour24 = (Number(hour) % 12) + (meridiem === "PM" ? 12 : 0);
|
||||
onChange(`${pad(hour24)}:${minute}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<Select
|
||||
id={`time-hour`}
|
||||
label="Hour"
|
||||
hideLabel
|
||||
size="small"
|
||||
value={hour}
|
||||
onValueChange={(val: string) => changeTime(val, minute, meridiem)}
|
||||
options={Array.from({ length: 12 }, (_, i) => pad(i + 1)).map(
|
||||
(h) => ({
|
||||
value: h,
|
||||
label: h,
|
||||
}),
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mb-6 flex flex-col items-center">
|
||||
<span className="m-auto text-xl font-bold">:</span>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center">
|
||||
<Select
|
||||
id={`time-minute`}
|
||||
label="Minute"
|
||||
hideLabel
|
||||
size="small"
|
||||
value={minute}
|
||||
onValueChange={(val: string) => changeTime(hour, val, meridiem)}
|
||||
options={Array.from({ length: 60 }, (_, i) => pad(i)).map((m) => ({
|
||||
value: m.toString(),
|
||||
label: m,
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center">
|
||||
<Select
|
||||
id={`time-meridiem`}
|
||||
label="AM/PM"
|
||||
hideLabel
|
||||
size="small"
|
||||
value={meridiem}
|
||||
onValueChange={(val: string) => changeTime(hour, minute, val)}
|
||||
options={[
|
||||
{ value: "AM", label: "AM" },
|
||||
{ value: "PM", label: "PM" },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -34,7 +34,6 @@ import React, {
|
||||
useRef,
|
||||
} from "react";
|
||||
import { Button } from "./ui/button";
|
||||
import { Switch } from "./ui/switch";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
@@ -52,7 +51,8 @@ import {
|
||||
} from "./ui/multiselect";
|
||||
import { LocalValuedInput } from "./ui/input";
|
||||
import NodeHandle from "./NodeHandle";
|
||||
import { CredentialsInput } from "@/components/integrations/credentials-input";
|
||||
import { CredentialsInput } from "@/app/(platform)/library/agents/[id]/components/AgentRunsView/components/CredentialsInputs/CredentialsInputs";
|
||||
import { Switch } from "./atoms/Switch/Switch";
|
||||
|
||||
type NodeObjectInputTreeProps = {
|
||||
nodeId: string;
|
||||
|
||||
@@ -1,547 +0,0 @@
|
||||
import React, { FC, useState } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { format } from "date-fns";
|
||||
import { CalendarIcon, UploadIcon } from "lucide-react";
|
||||
import { Cross2Icon, FileTextIcon } from "@radix-ui/react-icons";
|
||||
|
||||
import { Input as BaseInput } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import {
|
||||
Popover,
|
||||
PopoverTrigger,
|
||||
PopoverContent,
|
||||
} from "@/components/ui/popover";
|
||||
import { Calendar } from "@/components/ui/calendar";
|
||||
import {
|
||||
Select,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
MultiSelector,
|
||||
MultiSelectorContent,
|
||||
MultiSelectorInput,
|
||||
MultiSelectorItem,
|
||||
MultiSelectorList,
|
||||
MultiSelectorTrigger,
|
||||
} from "@/components/ui/multiselect";
|
||||
import {
|
||||
BlockIOObjectSubSchema,
|
||||
BlockIOSubSchema,
|
||||
DataType,
|
||||
determineDataType,
|
||||
} from "@/lib/autogpt-server-api/types";
|
||||
import BackendAPI from "@/lib/autogpt-server-api/client";
|
||||
|
||||
/**
|
||||
* A generic prop structure for the TypeBasedInput.
|
||||
*
|
||||
* onChange expects an event-like object with e.target.value so the parent
|
||||
* can do something like setInputValues(e.target.value).
|
||||
*/
|
||||
export interface TypeBasedInputProps {
|
||||
schema: BlockIOSubSchema;
|
||||
value?: any;
|
||||
placeholder?: string;
|
||||
onChange: (value: any) => void;
|
||||
}
|
||||
|
||||
const inputClasses = "min-h-11 rounded-[1.375rem] border px-4 py-2.5 bg-text";
|
||||
|
||||
function Input({
|
||||
className,
|
||||
...props
|
||||
}: React.InputHTMLAttributes<HTMLInputElement>) {
|
||||
return <BaseInput {...props} className={cn(inputClasses, className)} />;
|
||||
}
|
||||
|
||||
/**
|
||||
* A generic, data-type-based input component that uses Shadcn UI.
|
||||
* It inspects the schema via `determineDataType` and renders
|
||||
* the correct UI component.
|
||||
*/
|
||||
export const TypeBasedInput: FC<
|
||||
TypeBasedInputProps & React.HTMLAttributes<HTMLElement>
|
||||
> = ({ schema, value, placeholder, onChange, ...props }) => {
|
||||
const dataType = determineDataType(schema);
|
||||
|
||||
let innerInputElement: React.ReactNode = null;
|
||||
switch (dataType) {
|
||||
case DataType.NUMBER:
|
||||
innerInputElement = (
|
||||
<Input
|
||||
type="number"
|
||||
value={value ?? ""}
|
||||
placeholder={placeholder || "Enter number"}
|
||||
onChange={(e) => onChange(Number(e.target.value))}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.LONG_TEXT:
|
||||
innerInputElement = (
|
||||
<Textarea
|
||||
className="rounded-xl px-3 py-2"
|
||||
value={value ?? ""}
|
||||
placeholder={placeholder || "Enter text"}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.BOOLEAN:
|
||||
innerInputElement = (
|
||||
<>
|
||||
<span className="text-sm text-gray-500">
|
||||
{placeholder || (value ? "Enabled" : "Disabled")}
|
||||
</span>
|
||||
<Switch
|
||||
className="ml-auto"
|
||||
checked={!!value}
|
||||
onCheckedChange={(checked: boolean) => onChange(checked)}
|
||||
{...props}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.DATE:
|
||||
innerInputElement = (
|
||||
<DatePicker
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
onChange={onChange}
|
||||
className={cn(inputClasses)}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.TIME:
|
||||
innerInputElement = (
|
||||
<TimePicker value={value?.toString()} onChange={onChange} />
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.DATE_TIME:
|
||||
innerInputElement = (
|
||||
<Input
|
||||
type="datetime-local"
|
||||
value={value ?? ""}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder || "Enter date and time"}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.FILE:
|
||||
innerInputElement = (
|
||||
<FileInput
|
||||
value={value}
|
||||
placeholder={placeholder}
|
||||
onChange={onChange}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.SELECT:
|
||||
if (
|
||||
"enum" in schema &&
|
||||
Array.isArray(schema.enum) &&
|
||||
schema.enum.length > 0
|
||||
) {
|
||||
innerInputElement = (
|
||||
<Select
|
||||
value={value ?? ""}
|
||||
onValueChange={(val: string) => onChange(val)}
|
||||
>
|
||||
<SelectTrigger
|
||||
className={cn(
|
||||
inputClasses,
|
||||
"agpt-border-input text-sm text-gray-500",
|
||||
)}
|
||||
>
|
||||
<SelectValue placeholder={placeholder || "Select an option"} />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="rounded-xl">
|
||||
{schema.enum
|
||||
.filter((opt) => opt)
|
||||
.map((opt) => (
|
||||
<SelectItem key={opt} value={opt}>
|
||||
{String(opt)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
case DataType.MULTI_SELECT:
|
||||
const _schema = schema as BlockIOObjectSubSchema;
|
||||
|
||||
innerInputElement = (
|
||||
<MultiSelector
|
||||
className="nodrag"
|
||||
values={Object.entries(value || {})
|
||||
.filter(([_, v]) => v)
|
||||
.map(([k, _]) => k)}
|
||||
onValuesChange={(values: string[]) => {
|
||||
const allKeys = Object.keys(_schema.properties);
|
||||
onChange(
|
||||
Object.fromEntries(
|
||||
allKeys.map((opt) => [opt, values.includes(opt)]),
|
||||
),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MultiSelectorTrigger className={inputClasses}>
|
||||
<MultiSelectorInput
|
||||
placeholder={schema.placeholder ?? `Select ${schema.title}...`}
|
||||
/>
|
||||
</MultiSelectorTrigger>
|
||||
<MultiSelectorContent className="nowheel">
|
||||
<MultiSelectorList
|
||||
className={cn(inputClasses, "agpt-border-input bg-white")}
|
||||
>
|
||||
{Object.keys(_schema.properties)
|
||||
.map((key) => ({ ..._schema.properties[key], key }))
|
||||
.map(({ key, title, description }) => (
|
||||
<MultiSelectorItem key={key} value={key} title={description}>
|
||||
{title ?? key}
|
||||
</MultiSelectorItem>
|
||||
))}
|
||||
</MultiSelectorList>
|
||||
</MultiSelectorContent>
|
||||
</MultiSelector>
|
||||
);
|
||||
break;
|
||||
|
||||
case DataType.SHORT_TEXT:
|
||||
default:
|
||||
innerInputElement = (
|
||||
<Input
|
||||
type="text"
|
||||
value={value ?? ""}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder={placeholder || "Enter text"}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return <div className="no-drag relative flex">{innerInputElement}</div>;
|
||||
};
|
||||
|
||||
interface DatePickerProps {
|
||||
value?: Date;
|
||||
placeholder?: string;
|
||||
onChange: (date: Date | undefined) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function DatePicker({
|
||||
value,
|
||||
placeholder,
|
||||
onChange,
|
||||
className,
|
||||
}: DatePickerProps) {
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className={cn(
|
||||
"agpt-border-input w-full justify-start font-normal",
|
||||
!value && "text-muted-foreground",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<CalendarIcon className="mr-2 h-5 w-5" />
|
||||
{value ? (
|
||||
format(value, "PPP")
|
||||
) : (
|
||||
<span>{placeholder || "Pick a date"}</span>
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
|
||||
<PopoverContent className="flex min-h-[340px] w-auto p-0">
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={value}
|
||||
onSelect={(selected) => onChange(selected)}
|
||||
autoFocus
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
|
||||
interface TimePickerProps {
|
||||
value?: string;
|
||||
onChange: (time: string) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function TimePicker({ value, onChange }: TimePickerProps) {
|
||||
const pad = (n: number) => n.toString().padStart(2, "0");
|
||||
const [hourNum, minuteNum] = value ? value.split(":").map(Number) : [0, 0];
|
||||
|
||||
const meridiem = hourNum >= 12 ? "PM" : "AM";
|
||||
const hour = pad(hourNum % 12 || 12);
|
||||
const minute = pad(minuteNum);
|
||||
|
||||
const changeTime = (hour: string, minute: string, meridiem: string) => {
|
||||
const hour24 = (Number(hour) % 12) + (meridiem === "PM" ? 12 : 0);
|
||||
onChange(`${pad(hour24)}:${minute}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="flex flex-col items-center">
|
||||
<Select
|
||||
value={hour}
|
||||
onValueChange={(val: string) => changeTime(val, minute, meridiem)}
|
||||
>
|
||||
<SelectTrigger
|
||||
className={cn("agpt-border-input ml-1 text-center", inputClasses)}
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Array.from({ length: 12 }, (_, i) => pad(i + 1)).map((h) => (
|
||||
<SelectItem key={h} value={h}>
|
||||
{h}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center">
|
||||
<span className="m-auto text-xl font-bold">:</span>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center">
|
||||
<Select
|
||||
value={minute}
|
||||
onValueChange={(val: string) => changeTime(hour, val, meridiem)}
|
||||
>
|
||||
<SelectTrigger
|
||||
className={cn("agpt-border-input text-center", inputClasses)}
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Array.from({ length: 60 }, (_, i) => pad(i)).map((m) => (
|
||||
<SelectItem key={m} value={m.toString()}>
|
||||
{m}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col items-center">
|
||||
<Select
|
||||
value={meridiem}
|
||||
onValueChange={(val: string) => changeTime(hour, minute, val)}
|
||||
>
|
||||
<SelectTrigger
|
||||
className={cn("agpt-border-input text-center", inputClasses)}
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="AM">AM</SelectItem>
|
||||
<SelectItem value="PM">PM</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function getFileLabel(filename: string, contentType?: string) {
|
||||
if (contentType) {
|
||||
const mimeParts = contentType.split("/");
|
||||
if (mimeParts.length > 1) {
|
||||
return `${mimeParts[1].toUpperCase()} file`;
|
||||
}
|
||||
return `${contentType} file`;
|
||||
}
|
||||
|
||||
const pathParts = filename.split(".");
|
||||
if (pathParts.length > 1) {
|
||||
const ext = pathParts.pop();
|
||||
if (ext) return `${ext.toUpperCase()} file`;
|
||||
}
|
||||
return "File";
|
||||
}
|
||||
|
||||
function formatFileSize(bytes: number): string {
|
||||
if (bytes >= 1024 * 1024) {
|
||||
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
||||
} else if (bytes >= 1024) {
|
||||
return `${(bytes / 1024).toFixed(2)} KB`;
|
||||
} else {
|
||||
return `${bytes} B`;
|
||||
}
|
||||
}
|
||||
|
||||
interface FileInputProps {
|
||||
value?: string; // file URI or empty
|
||||
placeholder?: string; // e.g. "Resume", "Document", etc.
|
||||
onChange: (value: string) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const FileInput: FC<FileInputProps> = ({ value, onChange, className }) => {
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [uploadProgress, setUploadProgress] = useState(0);
|
||||
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||
const [fileInfo, setFileInfo] = useState<{
|
||||
name: string;
|
||||
size: number;
|
||||
content_type: string;
|
||||
} | null>(null);
|
||||
|
||||
const api = new BackendAPI();
|
||||
|
||||
const uploadFile = async (file: File) => {
|
||||
setIsUploading(true);
|
||||
setUploadProgress(0);
|
||||
setUploadError(null);
|
||||
|
||||
try {
|
||||
const result = await api.uploadFile(
|
||||
file,
|
||||
"gcs",
|
||||
24, // 24 hours expiration
|
||||
(progress) => setUploadProgress(progress),
|
||||
);
|
||||
|
||||
setFileInfo({
|
||||
name: result.file_name,
|
||||
size: result.size,
|
||||
content_type: result.content_type,
|
||||
});
|
||||
|
||||
// Set the file URI as the value
|
||||
onChange(result.file_uri);
|
||||
} catch (error) {
|
||||
console.error("Upload failed:", error);
|
||||
setUploadError(error instanceof Error ? error.message : "Upload failed");
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
setUploadProgress(0);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (file) uploadFile(file);
|
||||
};
|
||||
|
||||
const handleFileDrop = (event: React.DragEvent<HTMLDivElement>) => {
|
||||
event.preventDefault();
|
||||
const file = event.dataTransfer.files[0];
|
||||
if (file) uploadFile(file);
|
||||
};
|
||||
|
||||
const inputRef = React.useRef<HTMLInputElement>(null);
|
||||
|
||||
const storageNote =
|
||||
"Files are stored securely and will be automatically deleted at most 24 hours after upload.";
|
||||
|
||||
return (
|
||||
<div className={cn("w-full", className)}>
|
||||
{isUploading ? (
|
||||
<div className="space-y-2">
|
||||
<div className="flex min-h-14 items-center gap-4">
|
||||
<div className="agpt-border-input flex min-h-14 w-full flex-col justify-center rounded-xl bg-zinc-50 p-4 text-sm">
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
<UploadIcon className="h-5 w-5 text-blue-600" />
|
||||
<span className="text-gray-700">Uploading...</span>
|
||||
<span className="text-gray-500">
|
||||
{Math.round(uploadProgress)}%
|
||||
</span>
|
||||
</div>
|
||||
<Progress value={uploadProgress} className="w-full" />
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">{storageNote}</p>
|
||||
</div>
|
||||
) : value ? (
|
||||
<div className="space-y-2">
|
||||
<div className="flex min-h-14 items-center gap-4">
|
||||
<div className="agpt-border-input flex min-h-14 w-full items-center justify-between rounded-xl bg-zinc-50 p-4 text-sm text-gray-500">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileTextIcon className="h-7 w-7 text-black" />
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="font-normal text-black">
|
||||
{fileInfo
|
||||
? getFileLabel(fileInfo.name, fileInfo.content_type)
|
||||
: "File"}
|
||||
</span>
|
||||
<span>{fileInfo ? formatFileSize(fileInfo.size) : ""}</span>
|
||||
</div>
|
||||
</div>
|
||||
<Cross2Icon
|
||||
className="h-5 w-5 cursor-pointer text-black"
|
||||
onClick={() => {
|
||||
if (inputRef.current) {
|
||||
inputRef.current.value = "";
|
||||
}
|
||||
onChange("");
|
||||
setFileInfo(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">{storageNote}</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div className="flex min-h-14 items-center gap-4">
|
||||
<div
|
||||
onDrop={handleFileDrop}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
className="agpt-border-input flex min-h-14 w-full items-center justify-center rounded-xl border-dashed bg-zinc-50 text-sm text-gray-500"
|
||||
>
|
||||
Choose a file or drag and drop it here
|
||||
</div>
|
||||
|
||||
<Button variant="default" onClick={() => inputRef.current?.click()}>
|
||||
Browse File
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{uploadError && (
|
||||
<div className="text-sm text-red-600">Error: {uploadError}</div>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-gray-500">{storageNote}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept="*/*"
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
disabled={isUploading}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -3,7 +3,7 @@
|
||||
This guide will walk you through the process of creating and testing a new block for the AutoGPT Agent Server, using the WikipediaSummaryBlock as an example.
|
||||
|
||||
!!! tip "New SDK-Based Approach"
|
||||
For a more comprehensive guide using the new SDK pattern with ProviderBuilder and advanced features like OAuth and webhooks, see the [Block SDK Guide](block-sdk-guide.md).
|
||||
For a more comprehensive guide using the new SDK pattern with ProviderBuilder and advanced features like OAuth and webhooks, see the [Block SDK Guide](block-sdk-guide.md).
|
||||
|
||||
## Understanding Blocks and Testing
|
||||
|
||||
@@ -17,74 +17,74 @@ Follow these steps to create and test a new block:
|
||||
|
||||
2. **Import necessary modules and create a class that inherits from `Block`**. Make sure to include all necessary imports for your block.
|
||||
|
||||
Every block should contain the following:
|
||||
Every block should contain the following:
|
||||
|
||||
```python
|
||||
from backend.data.block import Block, BlockSchema, BlockOutput
|
||||
```
|
||||
```python
|
||||
from backend.data.block import Block, BlockSchema, BlockOutput
|
||||
```
|
||||
|
||||
Example for the Wikipedia summary block:
|
||||
Example for the Wikipedia summary block:
|
||||
|
||||
```python
|
||||
from backend.data.block import Block, BlockSchema, BlockOutput
|
||||
from backend.utils.get_request import GetRequest
|
||||
import requests
|
||||
```python
|
||||
from backend.data.block import Block, BlockSchema, BlockOutput
|
||||
from backend.utils.get_request import GetRequest
|
||||
import requests
|
||||
|
||||
class WikipediaSummaryBlock(Block, GetRequest):
|
||||
# Block implementation will go here
|
||||
```
|
||||
class WikipediaSummaryBlock(Block, GetRequest):
|
||||
# Block implementation will go here
|
||||
```
|
||||
|
||||
3. **Define the input and output schemas** using `BlockSchema`. These schemas specify the data structure that the block expects to receive (input) and produce (output).
|
||||
|
||||
- The input schema defines the structure of the data the block will process. Each field in the schema represents a required piece of input data.
|
||||
- The output schema defines the structure of the data the block will return after processing. Each field in the schema represents a piece of output data.
|
||||
|
||||
Example:
|
||||
Example:
|
||||
|
||||
```python
|
||||
class Input(BlockSchema):
|
||||
topic: str # The topic to get the Wikipedia summary for
|
||||
```python
|
||||
class Input(BlockSchema):
|
||||
topic: str # The topic to get the Wikipedia summary for
|
||||
|
||||
class Output(BlockSchema):
|
||||
summary: str # The summary of the topic from Wikipedia
|
||||
error: str # Any error message if the request fails, error field needs to be named `error`.
|
||||
```
|
||||
class Output(BlockSchema):
|
||||
summary: str # The summary of the topic from Wikipedia
|
||||
error: str # Any error message if the request fails, error field needs to be named `error`.
|
||||
```
|
||||
|
||||
4. **Implement the `__init__` method, including test data and mocks:**
|
||||
|
||||
!!! important
|
||||
Use UUID generator (e.g. https://www.uuidgenerator.net/) for every new block `id` and *do not* make up your own. Alternatively, you can run this python code to generate an uuid: `print(__import__('uuid').uuid4())`
|
||||
!!! important
|
||||
Use UUID generator (e.g. https://www.uuidgenerator.net/) for every new block `id` and _do not_ make up your own. Alternatively, you can run this python code to generate an uuid: `print(__import__('uuid').uuid4())`
|
||||
|
||||
```python
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
# Unique ID for the block, used across users for templates
|
||||
# If you are an AI leave it as is or change to "generate-proper-uuid"
|
||||
id="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
|
||||
input_schema=WikipediaSummaryBlock.Input, # Assign input schema
|
||||
output_schema=WikipediaSummaryBlock.Output, # Assign output schema
|
||||
```python
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
# Unique ID for the block, used across users for templates
|
||||
# If you are an AI leave it as is or change to "generate-proper-uuid"
|
||||
id="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
|
||||
input_schema=WikipediaSummaryBlock.Input, # Assign input schema
|
||||
output_schema=WikipediaSummaryBlock.Output, # Assign output schema
|
||||
|
||||
# Provide sample input, output and test mock for testing the block
|
||||
# Provide sample input, output and test mock for testing the block
|
||||
|
||||
test_input={"topic": "Artificial Intelligence"},
|
||||
test_output=("summary", "summary content"),
|
||||
test_mock={"get_request": lambda url, json: {"extract": "summary content"}},
|
||||
)
|
||||
```
|
||||
test_input={"topic": "Artificial Intelligence"},
|
||||
test_output=("summary", "summary content"),
|
||||
test_mock={"get_request": lambda url, json: {"extract": "summary content"}},
|
||||
)
|
||||
```
|
||||
|
||||
- `id`: A unique identifier for the block.
|
||||
- `id`: A unique identifier for the block.
|
||||
|
||||
- `input_schema` and `output_schema`: Define the structure of the input and output data.
|
||||
- `input_schema` and `output_schema`: Define the structure of the input and output data.
|
||||
|
||||
Let's break down the testing components:
|
||||
Let's break down the testing components:
|
||||
|
||||
- `test_input`: This is a sample input that will be used to test the block. It should be a valid input according to your Input schema.
|
||||
- `test_input`: This is a sample input that will be used to test the block. It should be a valid input according to your Input schema.
|
||||
|
||||
- `test_output`: This is the expected output when running the block with the `test_input`. It should match your Output schema. For non-deterministic outputs or when you only want to assert the type, you can use Python types instead of specific values. In this example, `("summary", str)` asserts that the output key is "summary" and its value is a string.
|
||||
- `test_output`: This is the expected output when running the block with the `test_input`. It should match your Output schema. For non-deterministic outputs or when you only want to assert the type, you can use Python types instead of specific values. In this example, `("summary", str)` asserts that the output key is "summary" and its value is a string.
|
||||
|
||||
- `test_mock`: This is crucial for blocks that make network calls. It provides a mock function that replaces the actual network call during testing.
|
||||
- `test_mock`: This is crucial for blocks that make network calls. It provides a mock function that replaces the actual network call during testing.
|
||||
|
||||
In this case, we're mocking the `get_request` method to always return a dictionary with an 'extract' key, simulating a successful API response. This allows us to test the block's logic without making actual network requests, which could be slow, unreliable, or rate-limited.
|
||||
In this case, we're mocking the `get_request` method to always return a dictionary with an 'extract' key, simulating a successful API response. This allows us to test the block's logic without making actual network requests, which could be slow, unreliable, or rate-limited.
|
||||
|
||||
5. **Implement the `run` method with error handling.** This should contain the main logic of the block:
|
||||
|
||||
@@ -106,19 +106,21 @@ Follow these steps to create and test a new block:
|
||||
- **Error handling**: Handle various exceptions that might occur during the API request and data processing. We don't need to catch all exceptions, only the ones we expect and can handle. The uncaught exceptions will be automatically yielded as `error` in the output. Any block that raises an exception (or yields an `error` output) will be marked as failed. Prefer raising exceptions over yielding `error`, as it will stop the execution immediately.
|
||||
- **Yield**: Use `yield` to output the results. Prefer to output one result object at a time. If you are calling a function that returns a list, you can yield each item in the list separately. You can also yield the whole list as well, but do both rather than yielding the list. For example: If you were writing a block that outputs emails, you'd yield each email as a separate result object, but you could also yield the whole list as an additional single result object. Yielding output named `error` will break the execution right away and mark the block execution as failed.
|
||||
- **kwargs**: The `kwargs` parameter is used to pass additional arguments to the block. It is not used in the example above, but it is available to the block. You can also have args as inline signatures in the run method ala `def run(self, input_data: Input, *, user_id: str, **kwargs) -> BlockOutput:`.
|
||||
Available kwargs are:
|
||||
- `user_id`: The ID of the user running the block.
|
||||
- `graph_id`: The ID of the agent that is executing the block. This is the same for every version of the agent
|
||||
- `graph_exec_id`: The ID of the execution of the agent. This changes every time the agent has a new "run"
|
||||
- `node_exec_id`: The ID of the execution of the node. This changes every time the node is executed
|
||||
- `node_id`: The ID of the node that is being executed. It changes every version of the graph, but not every time the node is executed.
|
||||
Available kwargs are:
|
||||
- `user_id`: The ID of the user running the block.
|
||||
- `graph_id`: The ID of the agent that is executing the block. This is the same for every version of the agent
|
||||
- `graph_exec_id`: The ID of the execution of the agent. This changes every time the agent has a new "run"
|
||||
- `node_exec_id`: The ID of the execution of the node. This changes every time the node is executed
|
||||
- `node_id`: The ID of the node that is being executed. It changes every version of the graph, but not every time the node is executed.
|
||||
|
||||
### Field Types
|
||||
|
||||
#### oneOf fields
|
||||
|
||||
`oneOf` allows you to specify that a field must be exactly one of several possible options. This is useful when you want your block to accept different types of inputs that are mutually exclusive.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
attachment: Union[Media, DeepLink, Poll, Place, Quote] = SchemaField(
|
||||
discriminator='discriminator',
|
||||
@@ -129,6 +131,7 @@ attachment: Union[Media, DeepLink, Poll, Place, Quote] = SchemaField(
|
||||
The `discriminator` parameter tells AutoGPT which field to look at in the input to determine which type it is.
|
||||
|
||||
In each model, you need to define the discriminator value:
|
||||
|
||||
```python
|
||||
class Media(BaseModel):
|
||||
discriminator: Literal['media']
|
||||
@@ -140,9 +143,11 @@ class DeepLink(BaseModel):
|
||||
```
|
||||
|
||||
#### OptionalOneOf fields
|
||||
|
||||
`OptionalOneOf` is similar to `oneOf` but allows the field to be optional (None). This means the field can be either one of the specified types or None.
|
||||
|
||||
Example:
|
||||
|
||||
```python
|
||||
attachment: Union[Media, DeepLink, Poll, Place, Quote] | None = SchemaField(
|
||||
discriminator='discriminator',
|
||||
@@ -279,16 +284,20 @@ response = requests.post(
|
||||
|
||||
The `ProviderName` enum is the single source of truth for which providers exist in our system.
|
||||
Naturally, to add an authenticated block for a new provider, you'll have to add it here too.
|
||||
|
||||
<details>
|
||||
<summary><code>ProviderName</code> definition</summary>
|
||||
|
||||
```python title="backend/integrations/providers.py"
|
||||
--8<-- "autogpt_platform/backend/backend/integrations/providers.py:ProviderName"
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
#### Multiple credentials inputs
|
||||
|
||||
Multiple credentials inputs are supported, under the following conditions:
|
||||
|
||||
- The name of each of the credentials input fields must end with `_credentials`.
|
||||
- The names of the credentials input fields must match the names of the corresponding
|
||||
parameters on the `run(..)` method of the block.
|
||||
@@ -296,7 +305,6 @@ Multiple credentials inputs are supported, under the following conditions:
|
||||
is a `dict[str, Credentials]`, with for each required credentials input the
|
||||
parameter name as the key and suitable test credentials as the value.
|
||||
|
||||
|
||||
#### Adding an OAuth2 service integration
|
||||
|
||||
To add support for a new OAuth2-authenticated service, you'll need to add an `OAuthHandler`.
|
||||
@@ -334,22 +342,25 @@ Aside from implementing the `OAuthHandler` itself, adding a handler into the sys
|
||||
|
||||
#### Adding to the frontend
|
||||
|
||||
You will need to add the provider (api or oauth) to the `CredentialsInput` component in [`frontend/src/components/integrations/credentials-input.tsx`](https://github.com/Significant-Gravitas/AutoGPT/blob/master/autogpt_platform/frontend/src/components/integrations/credentials-input.tsx).
|
||||
You will need to add the provider (api or oauth) to the `CredentialsInput` component in [`/frontend/src/app/(platform)/library/agents/[id]/components/AgentRunsView/components/CredentialsInputs/CredentialsInputs.tsx`](<https://github.com/Significant-Gravitas/AutoGPT/blob/dev/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/AgentRunsView/components/CredentialsInputs/CredentialsInputs.tsx>).
|
||||
|
||||
```ts title="frontend/src/components/integrations/credentials-input.tsx"
|
||||
--8<-- "autogpt_platform/frontend/src/components/integrations/credentials-input.tsx:ProviderIconsEmbed"
|
||||
--8 <
|
||||
--"autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/AgentRunsView/components/CredentialsInputs/CredentialsInputs.tsx:ProviderIconsEmbed";
|
||||
```
|
||||
|
||||
You will also need to add the provider to the credentials provider list in [`frontend/src/components/integrations/helper.ts`](https://github.com/Significant-Gravitas/AutoGPT/blob/master/autogpt_platform/frontend/src/components/integrations/helper.ts).
|
||||
|
||||
```ts title="frontend/src/components/integrations/helper.ts"
|
||||
--8<-- "autogpt_platform/frontend/src/components/integrations/helper.ts:CredentialsProviderNames"
|
||||
--8 <
|
||||
--"autogpt_platform/frontend/src/components/integrations/helper.ts:CredentialsProviderNames";
|
||||
```
|
||||
|
||||
Finally you will need to add the provider to the `CredentialsType` enum in [`frontend/src/lib/autogpt-server-api/types.ts`](https://github.com/Significant-Gravitas/AutoGPT/blob/master/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts).
|
||||
|
||||
```ts title="frontend/src/lib/autogpt-server-api/types.ts"
|
||||
--8<-- "autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts:BlockIOCredentialsSubSchema"
|
||||
--8 <
|
||||
--"autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts:BlockIOCredentialsSubSchema";
|
||||
```
|
||||
|
||||
#### Example: GitHub integration
|
||||
@@ -391,12 +402,12 @@ rather than being executed manually.
|
||||
Creating and running a webhook-triggered block involves three main components:
|
||||
|
||||
- The block itself, which specifies:
|
||||
- Inputs for the user to select a resource and events to subscribe to
|
||||
- A `credentials` input with the scopes needed to manage webhooks
|
||||
- Logic to turn the webhook payload into outputs for the webhook block
|
||||
- Inputs for the user to select a resource and events to subscribe to
|
||||
- A `credentials` input with the scopes needed to manage webhooks
|
||||
- Logic to turn the webhook payload into outputs for the webhook block
|
||||
- The `WebhooksManager` for the corresponding webhook service provider, which handles:
|
||||
- (De)registering webhooks with the provider
|
||||
- Parsing and validating incoming webhook payloads
|
||||
- (De)registering webhooks with the provider
|
||||
- Parsing and validating incoming webhook payloads
|
||||
- The credentials system for the corresponding service provider, which may include an `OAuthHandler`
|
||||
|
||||
There is more going on under the hood, e.g. to store and retrieve webhooks and their
|
||||
@@ -409,67 +420,72 @@ To create a webhook-triggered block, follow these additional steps on top of the
|
||||
|
||||
1. **Define `webhook_config`** in your block's `__init__` method.
|
||||
|
||||
<details>
|
||||
<summary>Example: <code>GitHubPullRequestTriggerBlock</code></summary>
|
||||
<details>
|
||||
<summary>Example: <code>GitHubPullRequestTriggerBlock</code></summary>
|
||||
|
||||
```python title="backend/blocks/github/triggers.py"
|
||||
--8<-- "autogpt_platform/backend/backend/blocks/github/triggers.py:example-webhook_config"
|
||||
```
|
||||
</details>
|
||||
```python title="backend/blocks/github/triggers.py"
|
||||
--8<-- "autogpt_platform/backend/backend/blocks/github/triggers.py:example-webhook_config"
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><code>BlockWebhookConfig</code> definition</summary>
|
||||
</details>
|
||||
|
||||
```python title="backend/data/block.py"
|
||||
--8<-- "autogpt_platform/backend/backend/data/block.py:BlockWebhookConfig"
|
||||
```
|
||||
</details>
|
||||
<details>
|
||||
<summary><code>BlockWebhookConfig</code> definition</summary>
|
||||
|
||||
```python title="backend/data/block.py"
|
||||
--8<-- "autogpt_platform/backend/backend/data/block.py:BlockWebhookConfig"
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
2. **Define event filter input** in your block's Input schema.
|
||||
This allows the user to select which specific types of events will trigger the block in their agent.
|
||||
This allows the user to select which specific types of events will trigger the block in their agent.
|
||||
|
||||
<details>
|
||||
<summary>Example: <code>GitHubPullRequestTriggerBlock</code></summary>
|
||||
<details>
|
||||
<summary>Example: <code>GitHubPullRequestTriggerBlock</code></summary>
|
||||
|
||||
```python title="backend/blocks/github/triggers.py"
|
||||
--8<-- "autogpt_platform/backend/backend/blocks/github/triggers.py:example-event-filter"
|
||||
```
|
||||
</details>
|
||||
```python title="backend/blocks/github/triggers.py"
|
||||
--8<-- "autogpt_platform/backend/backend/blocks/github/triggers.py:example-event-filter"
|
||||
```
|
||||
|
||||
- The name of the input field (`events` in this case) must match `webhook_config.event_filter_input`.
|
||||
- The event filter itself must be a Pydantic model with only boolean fields.
|
||||
</details>
|
||||
|
||||
4. **Include payload field** in your block's Input schema.
|
||||
- The name of the input field (`events` in this case) must match `webhook_config.event_filter_input`.
|
||||
- The event filter itself must be a Pydantic model with only boolean fields.
|
||||
|
||||
<details>
|
||||
<summary>Example: <code>GitHubTriggerBase</code></summary>
|
||||
3. **Include payload field** in your block's Input schema.
|
||||
|
||||
```python title="backend/blocks/github/triggers.py"
|
||||
--8<-- "autogpt_platform/backend/backend/blocks/github/triggers.py:example-payload-field"
|
||||
```
|
||||
</details>
|
||||
<details>
|
||||
<summary>Example: <code>GitHubTriggerBase</code></summary>
|
||||
|
||||
5. **Define `credentials` input** in your block's Input schema.
|
||||
- Its scopes must be sufficient to manage a user's webhooks through the provider's API
|
||||
- See [Blocks with authentication](#blocks-with-authentication) for further details
|
||||
```python title="backend/blocks/github/triggers.py"
|
||||
--8<-- "autogpt_platform/backend/backend/blocks/github/triggers.py:example-payload-field"
|
||||
```
|
||||
|
||||
6. **Process webhook payload** and output relevant parts of it in your block's `run` method.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Example: <code>GitHubPullRequestTriggerBlock</code></summary>
|
||||
4. **Define `credentials` input** in your block's Input schema.
|
||||
|
||||
```python
|
||||
def run(self, input_data: Input, **kwargs) -> BlockOutput:
|
||||
yield "payload", input_data.payload
|
||||
yield "sender", input_data.payload["sender"]
|
||||
yield "event", input_data.payload["action"]
|
||||
yield "number", input_data.payload["number"]
|
||||
yield "pull_request", input_data.payload["pull_request"]
|
||||
```
|
||||
- Its scopes must be sufficient to manage a user's webhooks through the provider's API
|
||||
- See [Blocks with authentication](#blocks-with-authentication) for further details
|
||||
|
||||
Note that the `credentials` parameter can be omitted if the credentials
|
||||
aren't used at block runtime, like in the example.
|
||||
</details>
|
||||
5. **Process webhook payload** and output relevant parts of it in your block's `run` method.
|
||||
|
||||
<details>
|
||||
<summary>Example: <code>GitHubPullRequestTriggerBlock</code></summary>
|
||||
|
||||
```python
|
||||
def run(self, input_data: Input, **kwargs) -> BlockOutput:
|
||||
yield "payload", input_data.payload
|
||||
yield "sender", input_data.payload["sender"]
|
||||
yield "event", input_data.payload["action"]
|
||||
yield "number", input_data.payload["number"]
|
||||
yield "pull_request", input_data.payload["pull_request"]
|
||||
```
|
||||
|
||||
Note that the `credentials` parameter can be omitted if the credentials
|
||||
aren't used at block runtime, like in the example.
|
||||
</details>
|
||||
|
||||
#### Adding a Webhooks Manager
|
||||
|
||||
@@ -500,6 +516,7 @@ GitHub Webhook triggers: <a href="https://github.com/Significant-Gravitas/AutoGP
|
||||
```python title="backend/blocks/github/triggers.py"
|
||||
--8<-- "autogpt_platform/backend/backend/blocks/github/triggers.py:GithubTriggerExample"
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
@@ -510,6 +527,7 @@ GitHub Webhooks Manager: <a href="https://github.com/Significant-Gravitas/AutoGP
|
||||
```python title="backend/integrations/webhooks/github.py"
|
||||
--8<-- "autogpt_platform/backend/backend/integrations/webhooks/github.py:GithubWebhooksManager"
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
## Key Points to Remember
|
||||
@@ -563,22 +581,24 @@ class MyNetworkBlock(Block):
|
||||
The `Requests` wrapper provides these security features:
|
||||
|
||||
1. **URL Validation**:
|
||||
- Blocks requests to private IP ranges (RFC 1918)
|
||||
- Validates URL format and protocol
|
||||
- Resolves DNS and checks IP addresses
|
||||
- Supports whitelisting trusted origins
|
||||
|
||||
- Blocks requests to private IP ranges (RFC 1918)
|
||||
- Validates URL format and protocol
|
||||
- Resolves DNS and checks IP addresses
|
||||
- Supports whitelisting trusted origins
|
||||
|
||||
2. **Secure Defaults**:
|
||||
- Disables redirects by default
|
||||
- Raises exceptions for non-200 status codes
|
||||
- Supports custom headers and validators
|
||||
|
||||
- Disables redirects by default
|
||||
- Raises exceptions for non-200 status codes
|
||||
- Supports custom headers and validators
|
||||
|
||||
3. **Protected IP Ranges**:
|
||||
The wrapper denies requests to these networks:
|
||||
|
||||
```python title="backend/util/request.py"
|
||||
--8<-- "autogpt_platform/backend/backend/util/request.py:BLOCKED_IP_NETWORKS"
|
||||
```
|
||||
```python title="backend/util/request.py"
|
||||
--8<-- "autogpt_platform/backend/backend/util/request.py:BLOCKED_IP_NETWORKS"
|
||||
```
|
||||
|
||||
### Custom Request Configuration
|
||||
|
||||
@@ -601,9 +621,9 @@ custom_requests = Requests(
|
||||
|
||||
2. **Define appropriate test_output**:
|
||||
|
||||
- For deterministic outputs, use specific expected values.
|
||||
- For non-deterministic outputs or when only the type matters, use Python types (e.g., `str`, `int`, `dict`).
|
||||
- You can mix specific values and types, e.g., `("key1", str), ("key2", 42)`.
|
||||
- For deterministic outputs, use specific expected values.
|
||||
- For non-deterministic outputs or when only the type matters, use Python types (e.g., `str`, `int`, `dict`).
|
||||
- You can mix specific values and types, e.g., `("key1", str), ("key2", 42)`.
|
||||
|
||||
3. **Use test_mock for network calls**: This prevents tests from failing due to network issues or API changes.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user