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.
fix(frontend/builder): Fix unnecessary graph re-saving (#11145)
Reinier van der Leer9967b3a7ce30
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/legacy-builder/CustomNode/CustomNode.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/legacy-builder/CustomNode/CustomNode.tsxindex 888b4f04c0..9be6cf4fd4 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/legacy-builder/CustomNode/CustomNode.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/legacy-builder/CustomNode/CustomNode.tsx@@ -23,6 +23,7 @@ import {import {beautifyString,cn,+ fillObjectDefaultsFromSchema,getValue,hasNonNullNonObjectValue,isObject,@@ -158,37 +159,6 @@ export const CustomNode = React.memo(setIsAnyModalOpen?.(isModalOpen || isOutputModalOpen);}, [isModalOpen, isOutputModalOpen, data, setIsAnyModalOpen]);- const fillDefaults = useCallback((obj: any, schema: any) => {- // Iterate over the schema properties- for (const key in schema.properties) {- if (schema.properties.hasOwnProperty(key)) {- const propertySchema = schema.properties[key];-- // If the property is not in the object, initialize it with the default value- if (!obj.hasOwnProperty(key)) {- if (propertySchema.default !== undefined) {- obj[key] = propertySchema.default;- } else if (propertySchema.type === "object") {- // Recursively fill defaults for nested objects- obj[key] = fillDefaults({}, propertySchema);- } else if (propertySchema.type === "array") {- // Recursively fill defaults for arrays- obj[key] = fillDefaults([], propertySchema);- }- } else {- // If the property exists, recursively fill defaults for nested objects/arrays- if (propertySchema.type === "object") {- obj[key] = fillDefaults(obj[key], propertySchema);- } else if (propertySchema.type === "array") {- obj[key] = fillDefaults(obj[key], propertySchema);- }- }- }- }-- return obj;- }, []);-const setHardcodedValues = useCallback((values: any) => {updateNodeData(id, { hardcodedValues: values });@@ -231,17 +201,19 @@ export const CustomNode = React.memo(useEffect(() => {isInitialSetup.current = false;+ if (data.backend_id) return; // don't auto-modify existing nodes+if (data.uiType === BlockUIType.AGENT) {setHardcodedValues({...data.hardcodedValues,- inputs: fillDefaults(+ inputs: fillObjectDefaultsFromSchema(data.hardcodedValues.inputs ?? {},data.inputSchema,),});} else {setHardcodedValues(- fillDefaults(data.hardcodedValues, data.inputSchema),+ fillObjectDefaultsFromSchema(data.hardcodedValues, data.inputSchema),);}}, []);@@ -857,7 +829,9 @@ export const CustomNode = React.memo(</button>)}</div>- <span className="text-xs text-gray-500">#{id.split("-")[0]}</span>+ <span className="text-xs text-gray-500">+ #{(data.backend_id || id).split("-")[0]}+ </span><div className="w-auto grow" />diff --git a/autogpt_platform/frontend/src/hooks/useAgentGraph.tsx b/autogpt_platform/frontend/src/hooks/useAgentGraph.tsxindex a0e27d5f6c..801c23e941 100644--- a/autogpt_platform/frontend/src/hooks/useAgentGraph.tsx+++ b/autogpt_platform/frontend/src/hooks/useAgentGraph.tsx@@ -21,11 +21,7 @@ import {Node,} from "@/lib/autogpt-server-api";import { useBackendAPI } from "@/lib/autogpt-server-api/context";-import {- deepEquals,- getTypeColor,- removeEmptyStringsAndNulls,-} from "@/lib/utils";+import { deepEquals, getTypeColor, pruneEmptyValues } from "@/lib/utils";import { MarkerType } from "@xyflow/react";import { default as NextLink } from "next/link";import { usePathname, useRouter, useSearchParams } from "next/navigation";@@ -601,7 +597,10 @@ export default function useAgentGraph(return {};}- return rebuildObjectUsingSchema(blockSchema, node.data.hardcodedValues);+ return rebuildObjectUsingSchema(+ blockSchema,+ pruneEmptyValues(node.data.hardcodedValues),+ );},[availableBlocks],);@@ -610,6 +609,7 @@ export default function useAgentGraph(const links = xyEdges.map((edge): LinkCreatable => {let sourceName = edge.sourceHandle || "";const sourceNode = xyNodes.find((node) => node.id === edge.source);+ const sinkNode = xyNodes.find((node) => node.id === edge.target);// Special case for SmartDecisionMakerBlockif (@@ -619,8 +619,8 @@ export default function useAgentGraph(sourceName = `tools_^_${normalizeToolName(getToolFuncName(edge.target))}_~_${normalizeToolName(edge.targetHandle || "")}`;}return {- source_id: edge.source,- sink_id: edge.target,+ source_id: sourceNode?.data.backend_id ?? edge.source,+ sink_id: sinkNode?.data.backend_id ?? edge.target,source_name: sourceName,sink_name: edge.targetHandle || "",};@@ -632,7 +632,7 @@ export default function useAgentGraph(recommended_schedule_cron: agentRecommendedScheduleCron || null,nodes: xyNodes.map((node): NodeCreatable => ({- id: node.id,+ id: node.data.backend_id ?? node.id,block_id: node.data.block_id,input_default: prepareNodeInputData(node),metadata: {@@ -698,8 +698,9 @@ export default function useAgentGraph(// Update the node IDs on the frontendsetSavedAgent(newSavedAgent);- setXYNodes((prev) => {- return newSavedAgent.nodes++ setXYNodes((prev) =>+ newSavedAgent.nodes.map((backendNode) => {const key = `${backendNode.block_id}_${backendNode.metadata.position.x}_${backendNode.metadata.position.y}`;const frontendNodeID = blockIDToNodeIDMap[key];@@ -712,22 +713,26 @@ export default function useAgentGraph(position,data: {...frontendNode.data,- hardcodedValues: removeEmptyStringsAndNulls(- frontendNode.data.hardcodedValues,- ),- status: undefined,+ // NOTE: we don't update `node.id` because it would also require+ // updating many references in other places. Instead, we keep the+ // backend node ID in `node.data.backend_id`.backend_id: backendNode.id,- executionResults: [],metadata,++ // Reset & close node output+ isOutputOpen: false,+ status: undefined,+ executionResults: undefined,},} satisfies CustomNode): _backendNodeToXYNode(backendNode, newSavedAgent); // fallback})- .filter((node) => node !== null);- });+ .filter((node) => node !== null),+ );+// Reset bead count- setXYEdges((edges) => {- return edges.map(+ setXYEdges((edges) =>+ edges.map((edge): CustomEdge => ({...edge,data: {@@ -738,8 +743,8 @@ export default function useAgentGraph(beadData: new Map(),},}),- );- });+ ),+ );return newSavedAgent;}, [api,diff --git a/autogpt_platform/frontend/src/lib/utils.ts b/autogpt_platform/frontend/src/lib/utils.tsindex 8fb3fed3d8..b05375bb83 100644--- a/autogpt_platform/frontend/src/lib/utils.ts+++ b/autogpt_platform/frontend/src/lib/utils.ts@@ -2,7 +2,11 @@ import { type ClassValue, clsx } from "clsx";import { isEmpty as _isEmpty } from "lodash";import { twMerge } from "tailwind-merge";-import { Category } from "@/lib/autogpt-server-api/types";+import {+ BlockIOObjectSubSchema,+ BlockIORootSchema,+ Category,+} from "@/lib/autogpt-server-api/types";import { NodeDimension } from "@/app/(platform)/build/components/legacy-builder/Flow/Flow";export function cn(...inputs: ClassValue[]) {@@ -177,32 +181,73 @@ export function setNestedProperty(obj: any, path: string, value: any) {current[keys[keys.length - 1]] = value;}-export function removeEmptyStringsAndNulls(obj: any): any {+export function pruneEmptyValues(+ obj: any,+ removeEmptyStrings: boolean = true,+): any {if (Array.isArray(obj)) {// If obj is an array, recursively check each element,// but element removal is avoided to prevent index changes.return obj.map((item) =>item === undefined || item === null? ""- : removeEmptyStringsAndNulls(item),+ : pruneEmptyValues(item, removeEmptyStrings),);} else if (typeof obj === "object" && obj !== null) {// If obj is an object, recursively remove empty strings and nulls from its propertiesfor (const key in obj) {- if (obj.hasOwnProperty(key)) {- const value = obj[key];- if (- value === null ||- value === undefined ||- (typeof value === "string" && value === "")- ) {- delete obj[key];- } else {- obj[key] = removeEmptyStringsAndNulls(value);+ if (!obj.hasOwnProperty(key)) continue;++ const value = obj[key];+ if (+ value === null ||+ value === undefined ||+ (typeof value === "string" && value === "" && removeEmptyStrings)+ ) {+ delete obj[key];+ } else if (typeof value === "object") {+ obj[key] = pruneEmptyValues(value, removeEmptyStrings);+ }+ }+ }+ return obj;+}++export function fillObjectDefaultsFromSchema(+ obj: Record<any, any>,+ schema: BlockIORootSchema | BlockIOObjectSubSchema,+) {+ for (const key in schema.properties) {+ if (!schema.properties.hasOwnProperty(key)) continue;++ const propertySchema = schema.properties[key];++ if ("default" in propertySchema && propertySchema.default !== undefined) {+ // Apply simple default values+ obj[key] ??= propertySchema.default;+ } else if (+ propertySchema.type === "object" &&+ "properties" in propertySchema+ ) {+ // Recursively fill defaults for nested objects+ obj[key] = fillObjectDefaultsFromSchema(obj[key] ?? {}, propertySchema);+ } else if (propertySchema.type === "array") {+ obj[key] ??= [];+ // If the array items are objects, fill their defaults as well+ if (+ Array.isArray(obj[key]) &&+ propertySchema.items?.type === "object" &&+ "properties" in propertySchema.items+ ) {+ for (const item of obj[key]) {+ if (typeof item === "object" && item !== null) {+ fillObjectDefaultsFromSchema(item, propertySchema.items);+ }}}}}+return obj;}