Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(frontend): use the new set up on library data fetching client (#10266)

Abhimanyu Yadav6ef8119708ba
diff --git a/autogpt_platform/frontend/orval.config.ts b/autogpt_platform/frontend/orval.config.ts
index 296115d08e..136b437ff4 100644
--- a/autogpt_platform/frontend/orval.config.ts
+++ b/autogpt_platform/frontend/orval.config.ts
@@ -31,6 +31,14 @@ export default defineConfig({
useMutation: true,
// Will add more as their use cases arise
},
+ operations: {
+ "getV2List library agents": {
+ query: {
+ useInfinite: true,
+ useInfiniteQueryParam: "page",
+ },
+ },
+ },
},
},
hooks: {
diff --git a/autogpt_platform/frontend/src/components/library/library-action-header.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionHeader/LibraryActionHeader.tsx
similarity index 85%
rename from autogpt_platform/frontend/src/components/library/library-action-header.tsx
rename to autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionHeader/LibraryActionHeader.tsx
index b5d7f2c9c3..11011945fb 100644
--- a/autogpt_platform/frontend/src/components/library/library-action-header.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionHeader/LibraryActionHeader.tsx
@@ -1,6 +1,6 @@
// import LibraryNotificationDropdown from "./library-notification-dropdown";
-import LibraryUploadAgentDialog from "./library-upload-agent-dialog";
-import LibrarySearchBar from "./library-search-bar";
+import LibraryUploadAgentDialog from "../LibraryUploadAgentDialog/LibraryUploadAgentDialog";
+import LibrarySearchBar from "../LibrarySearchBar/LibrarySearchBar";
type LibraryActionHeaderProps = Record<string, never>;
diff --git a/autogpt_platform/frontend/src/components/library/library-action-sub-header.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionSubHeader/LibraryActionSubHeader.tsx
similarity index 61%
rename from autogpt_platform/frontend/src/components/library/library-action-sub-header.tsx
rename to autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionSubHeader/LibraryActionSubHeader.tsx
index 05fe6d48af..bb76233b6a 100644
--- a/autogpt_platform/frontend/src/components/library/library-action-sub-header.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryActionSubHeader/LibraryActionSubHeader.tsx
@@ -1,11 +1,14 @@
"use client";
-import { useLibraryPageContext } from "@/app/(platform)/library/state-provider";
-import LibrarySortMenu from "./library-sort-menu";
+import LibrarySortMenu from "../LibrarySortMenu/LibrarySortMenu";
-export default function LibraryActionSubHeader(): React.ReactNode {
- const { agents } = useLibraryPageContext();
+interface LibraryActionSubHeaderProps {
+ agentCount: number;
+}
+export default function LibraryActionSubHeader({
+ agentCount,
+}: LibraryActionSubHeaderProps) {
return (
<div className="flex items-center justify-between pb-[10px]">
<div className="flex items-center gap-[10px] p-2">
@@ -13,7 +16,7 @@ export default function LibraryActionSubHeader(): React.ReactNode {
My agents
</span>
<span className="w-[70px] font-sans text-[14px] font-normal leading-6">
- {agents.length} agents
+ {agentCount} agents
</span>
</div>
<LibrarySortMenu />
diff --git a/autogpt_platform/frontend/src/components/library/library-agent-card.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx
similarity index 95%
rename from autogpt_platform/frontend/src/components/library/library-agent-card.tsx
rename to autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx
index a2ee2ccc56..c9d21d5629 100644
--- a/autogpt_platform/frontend/src/components/library/library-agent-card.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx
@@ -1,7 +1,12 @@
import Link from "next/link";
import Image from "next/image";
-import { LibraryAgent } from "@/lib/autogpt-server-api";
+
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
+import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";
+
+interface LibraryAgentCardProps {
+ agent: LibraryAgent;
+}
export default function LibraryAgentCard({
agent: {
@@ -13,9 +18,7 @@ export default function LibraryAgentCard({
creator_image_url,
image_url,
},
-}: {
- agent: LibraryAgent;
-}): React.ReactNode {
+}: LibraryAgentCardProps) {
return (
<div className="inline-flex w-full max-w-[434px] flex-col items-start justify-start gap-2.5 rounded-[26px] bg-white transition-all duration-300 hover:shadow-lg dark:bg-transparent dark:hover:shadow-gray-700">
<Link
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx
new file mode 100644
index 0000000000..766c88169e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/LibraryAgentList.tsx
@@ -0,0 +1,44 @@
+"use client";
+import LibraryActionSubHeader from "../LibraryActionSubHeader/LibraryActionSubHeader";
+import LibraryAgentCard from "../LibraryAgentCard/LibraryAgentCard";
+import { useLibraryAgentList } from "./useLibraryAgentList";
+
+export default function LibraryAgentList() {
+ const {
+ agentLoading,
+ allAgents: agents,
+ isFetchingNextPage,
+ isSearching,
+ } = useLibraryAgentList();
+
+ const LoadingSpinner = () => (
+ <div className="h-8 w-8 animate-spin rounded-full border-b-2 border-t-2 border-neutral-800" />
+ );
+
+ return (
+ <>
+ {/* TODO: We need a new endpoint on backend that returns total number of agents */}
+ <LibraryActionSubHeader agentCount={agents.length} />
+ <div className="px-2">
+ {agentLoading ? (
+ <div className="flex h-[200px] items-center justify-center">
+ <LoadingSpinner />
+ </div>
+ ) : (
+ <>
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
+ {agents.map((agent) => (
+ <LibraryAgentCard key={agent.id} agent={agent} />
+ ))}
+ </div>
+ {(isFetchingNextPage || isSearching) && (
+ <div className="flex items-center justify-center py-4 pt-8">
+ <LoadingSpinner />
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ </>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/useLibraryAgentList.ts b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/useLibraryAgentList.ts
new file mode 100644
index 0000000000..d5d9e41933
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentList/useLibraryAgentList.ts
@@ -0,0 +1,66 @@
+import { useGetV2ListLibraryAgentsInfinite } from "@/app/api/__generated__/endpoints/library/library";
+import { LibraryAgentResponse } from "@/app/api/__generated__/models/libraryAgentResponse";
+import { useScrollThreshold } from "@/hooks/useScrollThreshold";
+import { useCallback } from "react";
+import { useLibraryPageContext } from "../state-provider";
+
+export const useLibraryAgentList = () => {
+ const { searchTerm, librarySort } = useLibraryPageContext();
+ const {
+ data: agents,
+ fetchNextPage,
+ hasNextPage,
+ isFetchingNextPage,
+ isLoading: agentLoading,
+ isFetching,
+ } = useGetV2ListLibraryAgentsInfinite(
+ {
+ page: 1,
+ page_size: 8,
+ search_term: searchTerm || undefined,
+ sort_by: librarySort,
+ },
+ {
+ query: {
+ getNextPageParam: (lastPage) => {
+ const pagination = (lastPage.data as LibraryAgentResponse).pagination;
+ const isMore =
+ pagination.current_page * pagination.page_size <
+ pagination.total_items;
+
+ return isMore ? pagination.current_page + 1 : undefined;
+ },
+ },
+ },
+ );
+
+ const handleInfiniteScroll = useCallback(
+ (scrollY: number) => {
+ if (!hasNextPage || isFetchingNextPage) return;
+
+ const { scrollHeight, clientHeight } = document.documentElement;
+ const SCROLL_THRESHOLD = 20;
+
+ if (scrollY + clientHeight >= scrollHeight - SCROLL_THRESHOLD) {
+ fetchNextPage();
+ }
+ },
+ [hasNextPage, isFetchingNextPage, fetchNextPage],
+ );
+
+ useScrollThreshold(handleInfiniteScroll, 50);
+
+ const allAgents =
+ agents?.pages.flatMap((page) => {
+ const data = page.data as LibraryAgentResponse;
+ return data.agents;
+ }) ?? [];
+
+ return {
+ allAgents,
+ agentLoading,
+ isFetchingNextPage,
+ hasNextPage,
+ isSearching: isFetching && !isFetchingNextPage,
+ };
+};
diff --git a/autogpt_platform/frontend/src/components/library/library-notification-card.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryNotificationCard/LibraryNotificationCard.tsx
similarity index 100%
rename from autogpt_platform/frontend/src/components/library/library-notification-card.tsx
rename to autogpt_platform/frontend/src/app/(platform)/library/components/LibraryNotificationCard/LibraryNotificationCard.tsx
diff --git a/autogpt_platform/frontend/src/components/library/library-notification-dropdown.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryNotificationDropdown/LibraryNotificationDropdown.tsx
similarity index 97%
rename from autogpt_platform/frontend/src/components/library/library-notification-dropdown.tsx
rename to autogpt_platform/frontend/src/app/(platform)/library/components/LibraryNotificationDropdown/LibraryNotificationDropdown.tsx
index 8bb131ceb4..f38ade2359 100644
--- a/autogpt_platform/frontend/src/components/library/library-notification-dropdown.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryNotificationDropdown/LibraryNotificationDropdown.tsx
@@ -11,9 +11,9 @@ import {
DropdownMenuLabel,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
-import LibraryNotificationCard, {
+import NotificationCard, {
NotificationCardData,
-} from "./library-notification-card";
+} from "../LibraryNotificationCard/LibraryNotificationCard";
export default function LibraryNotificationDropdown(): React.ReactNode {
const controls = useAnimationControls();
@@ -109,7 +109,7 @@ export default function LibraryNotificationDropdown(): React.ReactNode {
{notifications && notifications.length ? (
notifications.map((notification) => (
<DropdownMenuItem key={notification.id} className="p-0">
- <LibraryNotificationCard
+ <NotificationCard
notification={notification}
onClose={() =>
setNotifications((prev) => {
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySearchBar/LibrarySearchBar.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySearchBar/LibrarySearchBar.tsx
new file mode 100644
index 0000000000..099f036052
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySearchBar/LibrarySearchBar.tsx
@@ -0,0 +1,38 @@
+"use client";
+import { Input } from "@/components/ui/input";
+import { Search, X } from "lucide-react";
+import { useLibrarySearchbar } from "./useLibrarySearchbar";
+
+export default function LibrarySearchBar(): React.ReactNode {
+ const { handleSearchInput, handleClear, setIsFocused, isFocused, inputRef } =
+ useLibrarySearchbar();
+ return (
+ <div
+ onClick={() => inputRef.current?.focus()}
+ className="relative z-[21] mx-auto flex h-[50px] w-full max-w-[500px] flex-1 cursor-pointer items-center rounded-[45px] bg-[#EDEDED] px-[24px] py-[10px]"
+ >
+ <Search
+ className="mr-2 h-[29px] w-[29px] text-neutral-900"
+ strokeWidth={1.25}
+ />
+
+ <Input
+ ref={inputRef}
+ onFocus={() => setIsFocused(true)}
+ onBlur={() => !inputRef.current?.value && setIsFocused(false)}
+ onChange={handleSearchInput}
+ className="flex-1 border-none font-sans text-[16px] font-normal leading-7 shadow-none focus:shadow-none focus:ring-0"
+ type="text"
+ placeholder="Search agents"
+ />
+
+ {isFocused && inputRef.current?.value && (
+ <X
+ className="ml-2 h-[29px] w-[29px] cursor-pointer text-neutral-900"
+ strokeWidth={1.25}
+ onClick={handleClear}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySearchBar/useLibrarySearchbar.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySearchBar/useLibrarySearchbar.tsx
new file mode 100644
index 0000000000..f6428c6c4e
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySearchBar/useLibrarySearchbar.tsx
@@ -0,0 +1,36 @@
+import { useRef, useState } from "react";
+import { useLibraryPageContext } from "../state-provider";
+import { debounce } from "lodash";
+
+export const useLibrarySearchbar = () => {
+ const inputRef = useRef<HTMLInputElement>(null);
+ const [isFocused, setIsFocused] = useState(false);
+ const { setSearchTerm } = useLibraryPageContext();
+
+ const debouncedSearch = debounce((value: string) => {
+ setSearchTerm(value);
+ }, 300);
+
+ const handleSearchInput = (e: React.ChangeEvent<HTMLInputElement>) => {
+ const searchTerm = e.target.value;
+ debouncedSearch(searchTerm);
+ };
+
+ const handleClear = (e: React.MouseEvent) => {
+ if (inputRef.current) {
+ inputRef.current.value = "";
+ inputRef.current.blur();
+ setSearchTerm("");
+ e.preventDefault();
+ }
+ setIsFocused(false);
+ };
+
+ return {
+ handleClear,
+ handleSearchInput,
+ isFocused,
+ inputRef,
+ setIsFocused,
+ };
+};
diff --git a/autogpt_platform/frontend/src/components/library/library-sort-menu.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySortMenu/LibrarySortMenu.tsx
similarity index 52%
rename from autogpt_platform/frontend/src/components/library/library-sort-menu.tsx
rename to autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySortMenu/LibrarySortMenu.tsx
index c5ac2e819c..d1d973d295 100644
--- a/autogpt_platform/frontend/src/components/library/library-sort-menu.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySortMenu/LibrarySortMenu.tsx
@@ -1,6 +1,4 @@
-import { useBackendAPI } from "@/lib/autogpt-server-api/context";
-import { LibraryAgentSortEnum } from "@/lib/autogpt-server-api/types";
-import { useLibraryPageContext } from "@/app/(platform)/library/state-provider";
+"use client";
import { ArrowDownNarrowWideIcon } from "lucide-react";
import {
Select,
@@ -10,24 +8,11 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
+import { LibraryAgentSort } from "@/app/api/__generated__/models/libraryAgentSort";
+import { useLibrarySortMenu } from "./useLibrarySortMenu";
export default function LibrarySortMenu(): React.ReactNode {
- const api = useBackendAPI();
- const { setAgentLoading, setAgents, setLibrarySort, searchTerm } =
- useLibraryPageContext();
- const handleSortChange = async (value: LibraryAgentSortEnum) => {
- setLibrarySort(value);
- setAgentLoading(true);
- await new Promise((resolve) => setTimeout(resolve, 1000));
- const response = await api.listLibraryAgents({
- search_term: searchTerm,
- sort_by: value,
- page: 1,
- });
- setAgents(response.agents);
- setAgentLoading(false);
- };
-
+ const { handleSortChange } = useLibrarySortMenu();
return (
<div className="flex items-center">
<span className="hidden whitespace-nowrap sm:inline">sort by</span>
@@ -38,10 +23,10 @@ export default function LibrarySortMenu(): React.ReactNode {
</SelectTrigger>
<SelectContent>
<SelectGroup>
- <SelectItem value={LibraryAgentSortEnum.CREATED_AT}>
+ <SelectItem value={LibraryAgentSort.createdAt}>
Creation Date
</SelectItem>
- <SelectItem value={LibraryAgentSortEnum.UPDATED_AT}>
+ <SelectItem value={LibraryAgentSort.updatedAt}>
Last Modified
</SelectItem>
</SelectGroup>
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySortMenu/useLibrarySortMenu.ts b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySortMenu/useLibrarySortMenu.ts
new file mode 100644
index 0000000000..d2575c8936
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibrarySortMenu/useLibrarySortMenu.ts
@@ -0,0 +1,27 @@
+import { LibraryAgentSort } from "@/app/api/__generated__/models/libraryAgentSort";
+import { useLibraryPageContext } from "../state-provider";
+
+export const useLibrarySortMenu = () => {
+ const { setLibrarySort } = useLibraryPageContext();
+
+ const handleSortChange = (value: LibraryAgentSort) => {
+ // Simply updating the sort state - React Query will handle the rest
+ setLibrarySort(value);
+ };
+
+ const getSortLabel = (sort: LibraryAgentSort) => {
+ switch (sort) {
+ case LibraryAgentSort.createdAt:
+ return "Creation Date";
+ case LibraryAgentSort.updatedAt:
+ return "Last Modified";
+ default:
+ return "Last Modified";
+ }
+ };
+
+ return {
+ handleSortChange,
+ getSortLabel,
+ };
+};
diff --git a/autogpt_platform/frontend/src/components/library/library-upload-agent-dialog.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryUploadAgentDialog/LibraryUploadAgentDialog.tsx
similarity index 68%
rename from autogpt_platform/frontend/src/components/library/library-upload-agent-dialog.tsx
rename to autogpt_platform/frontend/src/app/(platform)/library/components/LibraryUploadAgentDialog/LibraryUploadAgentDialog.tsx
index a032f23361..e095da4f5f 100644
--- a/autogpt_platform/frontend/src/components/library/library-upload-agent-dialog.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryUploadAgentDialog/LibraryUploadAgentDialog.tsx
@@ -1,5 +1,4 @@
"use client";
-import { useState } from "react";
import { Upload, X } from "lucide-react";
import { Button } from "@/components/agptui/Button";
import {
@@ -10,8 +9,6 @@ import {
DialogTrigger,
} from "@/components/ui/dialog";
import { z } from "zod";
-import { useForm } from "react-hook-form";
-import { zodResolver } from "@hookform/resolvers/zod";
import { FileUploader } from "react-drag-drop-files";
import {
Form,
@@ -23,13 +20,7 @@ import {
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
-import {
- Graph,
- GraphCreatable,
- sanitizeImportedGraph,
-} from "@/lib/autogpt-server-api";
-import { useBackendAPI } from "@/lib/autogpt-server-api/context";
-import { useToast } from "@/components/ui/use-toast";
+import { useLibraryUploadAgentDialog } from "./useLibraryUploadAgentDialog";
const fileTypes = ["JSON"];
@@ -37,98 +28,24 @@ const fileSchema = z.custom<File>((val) => val instanceof File, {
message: "Must be a File object",
});
-const formSchema = z.object({
+export const uploadAgentFormSchema = z.object({
agentFile: fileSchema,
agentName: z.string().min(1, "Agent name is required"),
agentDescription: z.string(),
});
export default function LibraryUploadAgentDialog(): React.ReactNode {
- const [isDroped, setisDroped] = useState(false);
- const [isLoading, setIsLoading] = useState(false);
- const [isOpen, setIsOpen] = useState(false);
- const api = useBackendAPI();
- const { toast } = useToast();
- const [agentObject, setAgentObject] = useState<GraphCreatable | null>(null);
-
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
- defaultValues: {
- agentName: "",
- agentDescription: "",
- },
- });
-
- const onSubmit = async (values: z.infer<typeof formSchema>) => {
- if (!agentObject) {
- form.setError("root", { message: "No Agent object to save" });
- return;
- }
-
- setIsLoading(true);
-
- const payload: GraphCreatable = {
- ...agentObject,
- name: values.agentName,
- description: values.agentDescription,
- is_active: true,
- };
-
- try {
- const response = await api.createGraph(payload);
- setIsOpen(false);
- toast({
- title: "Success",
- description: "Agent uploaded successfully",
- variant: "default",
- });
- const qID = "flowID";
- window.location.href = `/build?${qID}=${response.id}`;
- } catch (error) {
- form.setError("root", {
- message: `Could not create agent: ${error}`,
- });
- } finally {
- setIsLoading(false);
- }
- };
-
- const handleChange = (file: File) => {
- setTimeout(() => {
- setisDroped(false);
- }, 2000);
-
- form.setValue("agentFile", file);
- const reader = new FileReader();
- reader.onload = (event) => {
- try {
- const obj = JSON.parse(event.target?.result as string);
- if (
- !["name", "description", "nodes", "links"].every(
- (key) => key in obj && obj[key] != null,
- )
- ) {
- throw new Error(
- "Invalid agent object in file: " + JSON.stringify(obj, null, 2),
- );
- }
- const agent = obj as Graph;
- sanitizeImportedGraph(agent);
- setAgentObject(agent);
- if (!form.getValues("agentName")) {
- form.setValue("agentName", agent.name);
- }
- if (!form.getValues("agentDescription")) {
- form.setValue("agentDescription", agent.description);
- }
- } catch (error) {
- console.error("Error loading agent file:", error);
- }
- };
- reader.readAsText(file);
- setisDroped(false);
- };
-
+ const {
+ onSubmit,
+ isUploading,
+ isOpen,
+ setIsOpen,
+ isDroped,
+ handleChange,
+ form,
+ setisDroped,
+ agentObject,
+ } = useLibraryUploadAgentDialog();
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogTrigger asChild>
@@ -249,9 +166,9 @@ export default function LibraryUploadAgentDialog(): React.ReactNode {
type="submit"
variant="primary"
className="mt-2 self-end"
- disabled={!agentObject || isLoading}
+ disabled={!agentObject || isUploading}
>
- {isLoading ? (
+ {isUploading ? (
<div className="flex items-center gap-2">
<div className="h-4 w-4 animate-spin rounded-full border-b-2 border-t-2 border-white"></div>
<span>Uploading...</span>
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryUploadAgentDialog/useLibraryUploadAgentDialog.ts b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryUploadAgentDialog/useLibraryUploadAgentDialog.ts
new file mode 100644
index 0000000000..e0a0b90716
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryUploadAgentDialog/useLibraryUploadAgentDialog.ts
@@ -0,0 +1,116 @@
+import { zodResolver } from "@hookform/resolvers/zod";
+import { useForm } from "react-hook-form";
+import { z } from "zod";
+import { uploadAgentFormSchema } from "./LibraryUploadAgentDialog";
+import { usePostV1CreateNewGraph } from "@/app/api/__generated__/endpoints/graphs/graphs";
+import { GraphModel } from "@/app/api/__generated__/models/graphModel";
+import { useToast } from "@/components/ui/use-toast";
+import { useState } from "react";
+import { Graph } from "@/app/api/__generated__/models/graph";
+import { sanitizeImportedGraph } from "@/lib/autogpt-server-api";
+
+export const useLibraryUploadAgentDialog = () => {
+ const [isDroped, setisDroped] = useState(false);
+ const [isOpen, setIsOpen] = useState(false);
+ const { toast } = useToast();
+ const [agentObject, setAgentObject] = useState<Graph | null>(null);
+
+ const { mutateAsync: createGraph, isPending: isUploading } =
+ usePostV1CreateNewGraph({
+ mutation: {
+ onSuccess: ({ data }) => {
+ setIsOpen(false);
+ toast({
+ title: "Success",
+ description: "Agent uploaded successfully",
+ variant: "default",
+ });
+ const qID = "flowID";
+ window.location.href = `/build?${qID}=${(data as GraphModel).id}`;
+ },
+ onError: () => {
+ toast({
+ title: "Error",
+ description: "Error Uploading agent",
+ variant: "destructive",
+ });
+ },
+ },
+ });
+
+ const form = useForm<z.infer<typeof uploadAgentFormSchema>>({
+ resolver: zodResolver(uploadAgentFormSchema),
+ defaultValues: {
+ agentName: "",
+ agentDescription: "",
+ },
+ });
+
+ const onSubmit = async (values: z.infer<typeof uploadAgentFormSchema>) => {
+ if (!agentObject) {
+ form.setError("root", { message: "No Agent object to save" });
+ return;
+ }
+
+ const payload: Graph = {
+ ...agentObject,
+ name: values.agentName,
+ description: values.agentDescription,
+ is_active: true,
+ };
+
+ await createGraph({
+ data: {
+ graph: payload,
+ },
+ });
+ };
+
+ const handleChange = (file: File) => {
+ setTimeout(() => {
+ setisDroped(false);
+ }, 2000);
+
+ form.setValue("agentFile", file);
+ const reader = new FileReader();
+ reader.onload = (event) => {
+ try {
+ const obj = JSON.parse(event.target?.result as string);
+ if (
+ !["name", "description", "nodes", "links"].every(
+ (key) => key in obj && obj[key] != null,
+ )
+ ) {
+ throw new Error(
+ "Invalid agent object in file: " + JSON.stringify(obj, null, 2),
+ );
+ }
+ const agent = obj as Graph;
+ sanitizeImportedGraph(agent);
+ setAgentObject(agent);
+ if (!form.getValues("agentName")) {
+ form.setValue("agentName", agent.name);
+ }
+ if (!form.getValues("agentDescription")) {
+ form.setValue("agentDescription", agent.description);
+ }
+ } catch (error) {
+ console.error("Error loading agent file:", error);
+ }
+ };
+ reader.readAsText(file);
+ setisDroped(false);
+ };
+
+ return {
+ onSubmit,
+ isUploading,
+ isOpen,
+ setIsOpen,
+ form,
+ agentObject,
+ isDroped,
+ handleChange,
+ setisDroped,
+ };
+};
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/state-provider.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/state-provider.tsx
similarity index 58%
rename from autogpt_platform/frontend/src/app/(platform)/library/state-provider.tsx
rename to autogpt_platform/frontend/src/app/(platform)/library/components/state-provider.tsx
index 70ac649a3f..20afbc9cd5 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/state-provider.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/state-provider.tsx
@@ -1,5 +1,6 @@
"use client";
+import { LibraryAgentSort } from "@/app/api/__generated__/models/libraryAgentSort";
import {
createContext,
useState,
@@ -8,19 +9,14 @@ import {
Dispatch,
SetStateAction,
} from "react";
-import { LibraryAgent, LibraryAgentSortEnum } from "@/lib/autogpt-server-api";
interface LibraryPageContextType {
- agents: LibraryAgent[];
- setAgents: Dispatch<SetStateAction<LibraryAgent[]>>;
- agentLoading: boolean;
- setAgentLoading: Dispatch<SetStateAction<boolean>>;
- searchTerm: string | undefined;
- setSearchTerm: Dispatch<SetStateAction<string | undefined>>;
+ searchTerm: string;
+ setSearchTerm: Dispatch<SetStateAction<string>>;
uploadedFile: File | null;
setUploadedFile: Dispatch<SetStateAction<File | null>>;
- librarySort: LibraryAgentSortEnum;
- setLibrarySort: Dispatch<SetStateAction<LibraryAgentSortEnum>>;
+ librarySort: LibraryAgentSort;
+ setLibrarySort: Dispatch<SetStateAction<LibraryAgentSort>>;
}
export const LibraryPageContext = createContext<LibraryPageContextType>(
@@ -32,21 +28,15 @@ export function LibraryPageStateProvider({
}: {
children: ReactNode;
}) {
- const [agents, setAgents] = useState<LibraryAgent[]>([]);
- const [agentLoading, setAgentLoading] = useState<boolean>(true);
- const [searchTerm, setSearchTerm] = useState<string | undefined>("");
+ const [searchTerm, setSearchTerm] = useState<string>("");
const [uploadedFile, setUploadedFile] = useState<File | null>(null);
- const [librarySort, setLibrarySort] = useState<LibraryAgentSortEnum>(
- LibraryAgentSortEnum.UPDATED_AT,
+ const [librarySort, setLibrarySort] = useState<LibraryAgentSort>(
+ LibraryAgentSort.updatedAt,
);
return (
<LibraryPageContext.Provider
value={{
- agents,
- setAgents,
- agentLoading,
- setAgentLoading,
searchTerm,
setSearchTerm,
uploadedFile,
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/page.tsx b/autogpt_platform/frontend/src/app/(platform)/library/page.tsx
index 5fa9804b12..ab7ea40f12 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/page.tsx
@@ -1,5 +1,5 @@
+"use client";
import Link from "next/link";
-import { Metadata } from "next/types";
import {
ArrowBottomRightIcon,
@@ -7,15 +7,9 @@ import {
} from "@radix-ui/react-icons";
import { Alert, AlertDescription } from "@/components/ui/alert";
-import { LibraryPageStateProvider } from "./state-provider";
-import LibraryActionSubHeader from "@/components/library/library-action-sub-header";
-import LibraryActionHeader from "@/components/library/library-action-header";
-import LibraryAgentList from "@/components/library/library-agent-list";
-
-export const metadata: Metadata = {
- title: "Library - AutoGPT Platform",
- description: "Your collection of Agents on the AutoGPT Platform",
-};
+import { LibraryPageStateProvider } from "./components/state-provider";
+import LibraryActionHeader from "./components/LibraryActionHeader/LibraryActionHeader";
+import LibraryAgentList from "./components/LibraryAgentList/LibraryAgentList";
/**
* LibraryPage Component
@@ -25,13 +19,7 @@ export default function LibraryPage() {
return (
<main className="container min-h-screen space-y-4 pb-20 sm:px-8 md:px-12">
<LibraryPageStateProvider>
- {/* Header section containing notifications, search functionality and upload mechanism */}
<LibraryActionHeader />
-
- {/* Subheader section containing agent counts and filtering options */}
- <LibraryActionSubHeader />
-
- {/* Content section displaying agent list with counter and filtering options */}
<LibraryAgentList />
</LibraryPageStateProvider>
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 00616f6fe9..b562384214 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -1541,11 +1541,24 @@
}
}
},
- "/api/schedules": {
+ "/api/graphs/{graph_id}/schedules": {
"post": {
"tags": ["v1", "schedules"],
"summary": "Create execution schedule",
"operationId": "postV1Create execution schedule",
+ "parameters": [
+ {
+ "name": "graph_id",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "description": "ID of the graph to schedule",
+ "title": "Graph Id"
+ },
+ "description": "ID of the graph to schedule"
+ }
+ ],
"requestBody": {
"required": true,
"content": {
@@ -1579,17 +1592,14 @@
},
"get": {
"tags": ["v1", "schedules"],
- "summary": "List execution schedules",
- "operationId": "getV1List execution schedules",
+ "summary": "List execution schedules for a graph",
+ "operationId": "getV1List execution schedules for a graph",
"parameters": [
{
"name": "graph_id",
- "in": "query",
- "required": false,
- "schema": {
- "anyOf": [{ "type": "string" }, { "type": "null" }],
- "title": "Graph Id"
- }
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Graph Id" }
}
],
"responses": {
@@ -1602,7 +1612,7 @@
"items": {
"$ref": "#/components/schemas/GraphExecutionJobInfo"
},
- "title": "Response Getv1List Execution Schedules"
+ "title": "Response Getv1List Execution Schedules For A Graph"
}
}
}
@@ -1618,6 +1628,29 @@
}
}
},
+ "/api/schedules": {
+ "get": {
+ "tags": ["v1", "schedules"],
+ "summary": "List execution schedules for a user",
+ "operationId": "getV1List execution schedules for a user",
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "items": {
+ "$ref": "#/components/schemas/GraphExecutionJobInfo"
+ },
+ "type": "array",
+ "title": "Response Getv1List Execution Schedules For A User"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/schedules/{schedule_id}": {
"delete": {
"tags": ["v1", "schedules"],
@@ -1628,7 +1661,12 @@
"name": "schedule_id",
"in": "path",
"required": true,
- "schema": { "type": "string", "title": "Schedule Id" }
+ "schema": {
+ "type": "string",
+ "description": "ID of the schedule to delete",
+ "title": "Schedule Id"
+ },
+ "description": "ID of the schedule to delete"
}
],
"responses": {
@@ -3199,48 +3237,6 @@
}
}
},
- "/api/library/agents/by-graph/{graph_id}": {
- "get": {
- "tags": ["v2", "library", "private"],
- "summary": "Get Library Agent By Graph Id",
- "operationId": "getV2GetLibraryAgentByGraphId",
- "parameters": [
- {
- "name": "graph_id",
- "in": "path",
- "required": true,
- "schema": { "type": "string", "title": "Graph Id" }
- },
- {
- "name": "version",
- "in": "query",
- "required": false,
- "schema": {
- "anyOf": [{ "type": "integer" }, { "type": "null" }],
- "title": "Version"
- }
- }
- ],
- "responses": {
- "200": {
- "description": "Successful Response",
- "content": {
- "application/json": {
- "schema": { "$ref": "#/components/schemas/LibraryAgent" }
- }
- }
- },
- "422": {
- "description": "Validation Error",
- "content": {
- "application/json": {
- "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
- }
- }
- }
- }
- }
- },
"/api/library/agents/marketplace/{store_listing_version_id}": {
"get": {
"tags": ["v2", "library", "private", "store, library"],
@@ -4187,26 +4183,33 @@
},
"GraphExecutionJobInfo": {
"properties": {
+ "user_id": { "type": "string", "title": "User Id" },
"graph_id": { "type": "string", "title": "Graph Id" },
+ "graph_version": { "type": "integer", "title": "Graph Version" },
+ "cron": { "type": "string", "title": "Cron" },
"input_data": {
"additionalProperties": true,
"type": "object",
"title": "Input Data"
},
- "user_id": { "type": "string", "title": "User Id" },
- "graph_version": { "type": "integer", "title": "Graph Version" },
- "cron": { "type": "string", "title": "Cron" },
+ "input_credentials": {
+ "additionalProperties": {
+ "$ref": "#/components/schemas/CredentialsMetaInput"
+ },
+ "type": "object",
+ "title": "Input Credentials"
+ },
"id": { "type": "string", "title": "Id" },
"name": { "type": "string", "title": "Name" },
"next_run_time": { "type": "string", "title": "Next Run Time" }
},
"type": "object",
"required": [
- "graph_id",
- "input_data",
"user_id",
+ "graph_id",
"graph_version",
"cron",
+ "input_data",
"id",
"name",
"next_run_time"
@@ -5636,17 +5639,27 @@
},
"ScheduleCreationRequest": {
"properties": {
+ "graph_version": {
+ "anyOf": [{ "type": "integer" }, { "type": "null" }],
+ "title": "Graph Version"
+ },
+ "name": { "type": "string", "title": "Name" },
"cron": { "type": "string", "title": "Cron" },
- "input_data": {
+ "inputs": {
"additionalProperties": true,
"type": "object",
- "title": "Input Data"
+ "title": "Inputs"
},
- "graph_id": { "type": "string", "title": "Graph Id" },
- "graph_version": { "type": "integer", "title": "Graph Version" }
+ "credentials": {
+ "additionalProperties": {
+ "$ref": "#/components/schemas/CredentialsMetaInput"
+ },
+ "type": "object",
+ "title": "Credentials"
+ }
},
"type": "object",
- "required": ["cron", "input_data", "graph_id", "graph_version"],
+ "required": ["name", "cron", "inputs"],
"title": "ScheduleCreationRequest"
},
"SetGraphActiveVersion": {
diff --git a/autogpt_platform/frontend/src/components/library/library-agent-list.tsx b/autogpt_platform/frontend/src/components/library/library-agent-list.tsx
deleted file mode 100644
index d98b4077f8..0000000000
--- a/autogpt_platform/frontend/src/components/library/library-agent-list.tsx
+++ /dev/null
@@ -1,95 +0,0 @@
-"use client";
-import { useEffect, useState, useCallback } from "react";
-
-import { useBackendAPI } from "@/lib/autogpt-server-api/context";
-
-import { useLibraryPageContext } from "@/app/(platform)/library/state-provider";
-import { useScrollThreshold } from "@/hooks/useScrollThreshold";
-import LibraryAgentCard from "./library-agent-card";
-
-/**
- * Displays a grid of library agents with infinite scroll functionality.
- */
-export default function LibraryAgentList(): React.ReactNode {
- const [currentPage, setCurrentPage] = useState<number>(1);
- const [loadingMore, setLoadingMore] = useState(false);
- const [hasMore, setHasMore] = useState(true);
-
- const api = useBackendAPI();
- const { agents, setAgents, setAgentLoading, agentLoading } =
- useLibraryPageContext();
-
- const fetchAgents = useCallback(
- async (page: number) => {
- try {
- const response = await api.listLibraryAgents(
- page === 1 ? {} : { page: page },
- );
- if (page > 1) {
- setAgents((prevAgent) => [...prevAgent, ...response.agents]);
- } else {
- setAgents(response.agents);
- }
- setHasMore(
- response.pagination.current_page * response.pagination.page_size <
- response.pagination.total_items,
- );
- } finally {
- setAgentLoading(false);
- setLoadingMore(false);
- }
- },
- [api, setAgents, setAgentLoading],
- );
-
- useEffect(() => {
- fetchAgents(1);
- }, [fetchAgents]);
-
- const handleInfiniteScroll = useCallback(
- (scrollY: number) => {
- if (!hasMore || loadingMore) return;
-
- const { scrollHeight, clientHeight } = document.documentElement;
- const SCROLL_THRESHOLD = 20;
- const FETCH_DELAY = 1000;
-
- if (scrollY + clientHeight >= scrollHeight - SCROLL_THRESHOLD) {
- setLoadingMore(true);
- const nextPage = currentPage + 1;
- setCurrentPage(nextPage);
- setTimeout(() => fetchAgents(nextPage), FETCH_DELAY);
- }
- },
- [currentPage, hasMore, loadingMore, fetchAgents],
- );
-
- useScrollThreshold(handleInfiniteScroll, 50);
-
- const LoadingSpinner = () => (
- <div className="h-8 w-8 animate-spin rounded-full border-b-2 border-t-2 border-neutral-800" />
- );
-
- return (
- <div className="px-2">
- {agentLoading ? (
- <div className="flex h-[200px] items-center justify-center">
- <LoadingSpinner />
- </div>
- ) : (
- <>
- <div className="grid grid-cols-1 gap-3 sm:grid-cols-2 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
- {agents.map((agent) => (
- <LibraryAgentCard key={agent.id} agent={agent} />
- ))}
- </div>
- {loadingMore && hasMore && (
- <div className="flex items-center justify-center py-4 pt-8">
- <LoadingSpinner />
- </div>
- )}
- </>
- )}
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/components/library/library-search-bar.tsx b/autogpt_platform/frontend/src/components/library/library-search-bar.tsx
deleted file mode 100644
index a33bd63c9f..0000000000
--- a/autogpt_platform/frontend/src/components/library/library-search-bar.tsx
+++ /dev/null
@@ -1,74 +0,0 @@
-"use client";
-import { useRef, useState } from "react";
-import debounce from "lodash/debounce";
-import { Input } from "@/components/ui/input";
-import { Search, X } from "lucide-react";
-import { useBackendAPI } from "@/lib/autogpt-server-api/context";
-import { useLibraryPageContext } from "@/app/(platform)/library/state-provider";
-
-export default function LibrarySearchBar(): React.ReactNode {
- const inputRef = useRef<HTMLInputElement>(null);
- const [isFocused, setIsFocused] = useState(false);
- const api = useBackendAPI();
- const { setAgentLoading, setAgents, librarySort, setSearchTerm } =
- useLibraryPageContext();
-
- const debouncedSearch = debounce(async (value: string) => {
- try {
- setAgentLoading(true);
- setSearchTerm(value);
- await new Promise((resolve) => setTimeout(resolve, 1000));
- const response = await api.listLibraryAgents({
- search_term: value,
- sort_by: librarySort,
- page: 1,
- });
- setAgents(response.agents);
- setAgentLoading(false);
- } catch (error) {
- console.error("Search failed:", error);
- }
- }, 300);
- const handleSearchInput = (e: React.ChangeEvent<HTMLInputElement>) => {
- const searchTerm = e.target.value;
- debouncedSearch(searchTerm);
- };
-
- return (
- <div
- onClick={() => inputRef.current?.focus()}
- className="relative z-[21] mx-auto flex h-[50px] w-full max-w-[500px] flex-1 cursor-pointer items-center rounded-[45px] bg-[#EDEDED] px-[24px] py-[10px]"
- >
- <Search
- className="mr-2 h-[29px] w-[29px] text-neutral-900"
- strokeWidth={1.25}
- />
-
- <Input
- ref={inputRef}
- onFocus={() => setIsFocused(true)}
- onBlur={() => !inputRef.current?.value && setIsFocused(false)}
- onChange={handleSearchInput}
- className="flex-1 border-none font-sans text-[16px] font-normal leading-7 shadow-none focus:shadow-none focus:ring-0"
- type="text"
- placeholder="Search agents"
- />
-
- {isFocused && inputRef.current?.value && (
- <X
- className="ml-2 h-[29px] w-[29px] cursor-pointer text-neutral-900"
- strokeWidth={1.25}
- onClick={(e: React.MouseEvent) => {
- if (inputRef.current) {
- debouncedSearch("");
- inputRef.current.value = "";
- inputRef.current.blur();
- e.preventDefault();
- }
- setIsFocused(false);
- }}
- />
- )}
- </div>
- );
-}
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/utils.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/utils.ts
index a0d2262c28..4c7e9b9bca 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/utils.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/utils.ts
@@ -1,14 +1,15 @@
import { Connection } from "@xyflow/react";
-import { Graph, Block, BlockUIType, Link } from "./types";
+import { Block, BlockUIType, Link } from "./types";
+import { Graph } from "@/app/api/__generated__/models/graph";
export function removeAgentInputBlockValues(graph: Graph, blocks: Block[]) {
- const inputBlocks = graph.nodes.filter(
+ const inputBlocks = graph.nodes?.filter(
(node) =>
blocks.find((b) => b.id === node.block_id)?.uiType === BlockUIType.INPUT,
);
- const modifiedNodes = graph.nodes.map((node) => {
- if (inputBlocks.find((inputNode) => inputNode.id === node.id)) {
+ const modifiedNodes = graph.nodes?.map((node) => {
+ if (inputBlocks?.find((inputNode) => inputNode.id === node.id)) {
return {
...node,
input_default: {
@@ -61,7 +62,7 @@ function removeCredentials(obj: any): void {
*/
function updateBlockIDs(graph: Graph) {
graph.nodes
- .filter((node) => node.block_id in updatedBlockIDMap)
+ ?.filter((node) => node.block_id in updatedBlockIDMap)
.forEach((node) => {
node.block_id = updatedBlockIDMap[node.block_id];
});