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(Builder): Implement undo/redo functionality (#7559)

Bently2e2c6fed5232
diff --git a/rnd/autogpt_builder/src/components/CustomNode.tsx b/rnd/autogpt_builder/src/components/CustomNode.tsx
index 1765a3de20..076a991cba 100644
--- a/rnd/autogpt_builder/src/components/CustomNode.tsx
+++ b/rnd/autogpt_builder/src/components/CustomNode.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useEffect, FC, memo, useCallback } from 'react';
+import React, { useState, useEffect, FC, memo, useCallback, useRef } from 'react';
import { NodeProps, useReactFlow } from 'reactflow';
import 'reactflow/dist/style.css';
import './customnode.css';
@@ -10,6 +10,7 @@ import { Switch } from "@/components/ui/switch"
import NodeHandle from './NodeHandle';
import NodeInputField from './NodeInputField';
import { Copy, Trash2 } from 'lucide-react';
+import { history } from './history';
export type CustomNodeData = {
blockType: string;
@@ -41,6 +42,8 @@ const CustomNode: FC<NodeProps<CustomNodeData>> = ({ data, id }) => {
const { getNode, setNodes, getEdges, setEdges } = useReactFlow();
+ const outputDataRef = useRef<HTMLDivElement>(null);
+ const isInitialSetup = useRef(true);
useEffect(() => {
if (data.output_data || data.status) {
@@ -56,6 +59,10 @@ const CustomNode: FC<NodeProps<CustomNodeData>> = ({ data, id }) => {
data.setIsAnyModalOpen?.(isModalOpen || isOutputModalOpen);
}, [isModalOpen, isOutputModalOpen, data]);
+ useEffect(() => {
+ isInitialSetup.current = false;
+ }, []);
+
const toggleOutput = (checked: boolean) => {
setIsOutputOpen(checked);
};
@@ -92,6 +99,16 @@ const CustomNode: FC<NodeProps<CustomNodeData>> = ({ data, id }) => {
current[keys[keys.length - 1]] = value;
console.log(`Updating hardcoded values for node ${id}:`, newValues);
+
+ if (!isInitialSetup.current) {
+ history.push({
+ type: 'UPDATE_INPUT',
+ payload: { nodeId: id, oldValues: data.hardcodedValues, newValues },
+ undo: () => data.setHardcodedValues(data.hardcodedValues),
+ redo: () => data.setHardcodedValues(newValues),
+ });
+ }
+
data.setHardcodedValues(newValues);
const errors = data.errors || {};
// Remove error with the same key
diff --git a/rnd/autogpt_builder/src/components/Flow.tsx b/rnd/autogpt_builder/src/components/Flow.tsx
index c03759d28e..2aa0201c54 100644
--- a/rnd/autogpt_builder/src/components/Flow.tsx
+++ b/rnd/autogpt_builder/src/components/Flow.tsx
@@ -1,5 +1,5 @@
"use client";
-import React, { useState, useCallback, useEffect, useMemo } from 'react';
+import React, { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import ReactFlow, {
addEdge,
useNodesState,
@@ -21,10 +21,15 @@ import { Input } from './ui/input';
import { ChevronRight, ChevronLeft } from "lucide-react";
import { deepEquals, getTypeColor, removeEmptyStringsAndNulls, setNestedProperty } from '@/lib/utils';
import { beautifyString } from '@/lib/utils';
+import { history } from './history';
import { CustomEdge, CustomEdgeData } from './CustomEdge';
import ConnectionLine from './ConnectionLine';
import Ajv from 'ajv';
+// This is for the history, this is the minimum distance a block must move before it is logged
+// It helps to prevent spamming the history with small movements especially when pressing on a input in a block
+const MINIMUM_MOVE_BEFORE_LOG = 50;
+
const Sidebar: React.FC<{ isOpen: boolean, availableNodes: Block[], addNode: (id: string, name: string) => void }> =
({ isOpen, availableNodes, addNode }) => {
const [searchQuery, setSearchQuery] = useState('');
@@ -75,6 +80,8 @@ const FlowEditor: React.FC<{
const apiUrl = process.env.AGPT_SERVER_URL!;
const api = useMemo(() => new AutoGPTServerAPI(apiUrl), [apiUrl]);
+ const initialPositionRef = useRef<{ [key: string]: { x: number; y: number } }>({});
+ const isDragging = useRef(false);
useEffect(() => {
api.connectWebSocket()
@@ -107,9 +114,97 @@ const FlowEditor: React.FC<{
.then(graph => loadGraph(graph));
}, [flowID, template, availableNodes]);
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;
+ const isUndo = (isMac ? event.metaKey : event.ctrlKey) && event.key === 'z';
+ const isRedo = (isMac ? event.metaKey : event.ctrlKey) && (event.key === 'y' || (event.shiftKey && event.key === 'Z'));
+
+ if (isUndo) {
+ event.preventDefault();
+ handleUndo();
+ }
+
+ if (isRedo) {
+ event.preventDefault();
+ handleRedo();
+ }
+ };
+
+ window.addEventListener('keydown', handleKeyDown);
+
+ return () => {
+ window.removeEventListener('keydown', handleKeyDown);
+ };
+ }, []);
+
+
const nodeTypes: NodeTypes = useMemo(() => ({ custom: CustomNode }), []);
const edgeTypes: EdgeTypes = useMemo(() => ({ custom: CustomEdge }), []);
+ const onNodesChangeStart = (event: MouseEvent, node: Node) => {
+ initialPositionRef.current[node.id] = { ...node.position };
+ isDragging.current = true;
+ };
+
+ const onNodesChangeEnd = (event: MouseEvent, node: Node | null) => {
+ if (!node) return;
+
+ isDragging.current = false;
+ const oldPosition = initialPositionRef.current[node.id];
+ const newPosition = node.position;
+
+ // Calculate the movement distance
+ if (!oldPosition || !newPosition) return;
+
+ const distanceMoved = Math.sqrt(
+ Math.pow(newPosition.x - oldPosition.x, 2) +
+ Math.pow(newPosition.y - oldPosition.y, 2)
+ );
+
+ if (distanceMoved > MINIMUM_MOVE_BEFORE_LOG) { // Minimum movement threshold
+ history.push({
+ type: 'UPDATE_NODE_POSITION',
+ payload: { nodeId: node.id, oldPosition, newPosition },
+ undo: () => setNodes((nds) => nds.map(n => n.id === node.id ? { ...n, position: oldPosition } : n)),
+ redo: () => setNodes((nds) => nds.map(n => n.id === node.id ? { ...n, position: newPosition } : n)),
+ });
+ }
+ delete initialPositionRef.current[node.id];
+ };
+
+
+ const updateNodesOnEdgeChange = (edge: Edge<CustomEdgeData>, action: 'add' | 'remove') => {
+ setNodes((nds) =>
+ nds.map((node) => {
+ if (node.id === edge.source || node.id === edge.target) {
+ const connections = action === 'add'
+ ? [
+ ...node.data.connections,
+ {
+ source: edge.source,
+ sourceHandle: edge.sourceHandle!,
+ target: edge.target,
+ targetHandle: edge.targetHandle!,
+ }
+ ]
+ : node.data.connections.filter(
+ (conn) =>
+ !(conn.source === edge.source && conn.target === edge.target && conn.sourceHandle === edge.sourceHandle && conn.targetHandle === edge.targetHandle)
+ );
+ return {
+ ...node,
+ data: {
+ ...node.data,
+ connections,
+ },
+ };
+ }
+ return node;
+ })
+ );
+ };
+
const getOutputType = (id: string, handleId: string) => {
const node = nodes.find((node) => node.id === id);
if (!node) return 'unknown';
@@ -143,40 +238,62 @@ const FlowEditor: React.FC<{
);
}, [setNodes]);
- const onConnect: OnConnect = (connection: Connection) => {
- const edgeColor = getTypeColor(getOutputType(connection.source!, connection.sourceHandle!));
- const sourcePos = getNodePos(connection.source!)
- console.log('sourcePos', sourcePos);
- setEdges((eds) => addEdge({
- type: 'custom',
- markerEnd: { type: MarkerType.ArrowClosed, strokeWidth: 2, color: edgeColor },
- data: { edgeColor, sourcePos },
- ...connection
- }, eds));
- setNodes((nds) =>
- nds.map((node) => {
- if (node.id === connection.target || node.id === connection.source) {
- return {
- ...node,
- data: {
- ...node.data,
- connections: [
- ...node.data.connections,
- {
- source: connection.source,
- sourceHandle: connection.sourceHandle,
- target: connection.target,
- targetHandle: connection.targetHandle,
- } as { source: string; sourceHandle: string; target: string; targetHandle: string },
- ],
- },
- };
- }
- return node;
- })
- );
+ const onConnect: OnConnect = useCallback(
+ (connection: Connection) => {
+ const edgeColor = getTypeColor(getOutputType(connection.source!, connection.sourceHandle!));
+ const sourcePos = getNodePos(connection.source!)
+ console.log('sourcePos', sourcePos);
+ const newEdge = {
+ id: `${connection.source}_${connection.sourceHandle}_${connection.target}_${connection.targetHandle}`,
+ type: 'custom',
+ markerEnd: { type: MarkerType.ArrowClosed, strokeWidth: 2, color: edgeColor },
+ data: { edgeColor, sourcePos },
+ ...connection
+ };
+
+ setEdges((eds) => {
+ const newEdges = addEdge(newEdge, eds);
+ history.push({
+ type: 'ADD_EDGE',
+ payload: newEdge,
+ undo: () => {
+ setEdges((prevEdges) => prevEdges.filter(edge => edge.id !== newEdge.id));
+ updateNodesOnEdgeChange(newEdge, 'remove');
+ },
+ redo: () => {
+ setEdges((prevEdges) => addEdge(newEdge, prevEdges));
+ updateNodesOnEdgeChange(newEdge, 'add');
+ }
+ });
+ updateNodesOnEdgeChange(newEdge, 'add');
+ return newEdges;
+ });
+ setNodes((nds) =>
+ nds.map((node) => {
+ if (node.id === connection.target || node.id === connection.source) {
+ return {
+ ...node,
+ data: {
+ ...node.data,
+ connections: [
+ ...node.data.connections,
+ {
+ source: connection.source,
+ sourceHandle: connection.sourceHandle,
+ target: connection.target,
+ targetHandle: connection.targetHandle,
+ } as { source: string; sourceHandle: string; target: string; targetHandle: string },
+ ],
+ },
+ };
+ }
+ return node;
+ })
+ );
clearNodesStatusAndOutput(); // Clear status and output on connection change
- }
+ },
+ [nodes]
+ );
const onEdgesDelete = useCallback(
(edgesToDelete: Edge<CustomEdgeData>[]) => {
@@ -191,8 +308,8 @@ const FlowEditor: React.FC<{
(edge) =>
edge.source === conn.source &&
edge.target === conn.target &&
- edge.sourceHandle === conn.sourceHandle &&
- edge.targetHandle === conn.targetHandle
+ edge.sourceHandle === edge.sourceHandle &&
+ edge.targetHandle === edge.targetHandle
)
),
},
@@ -203,13 +320,13 @@ const FlowEditor: React.FC<{
[setNodes, clearNodesStatusAndOutput]
);
- const addNode = (blockId: string, nodeType: string) => {
+ const addNode = useCallback((blockId: string, nodeType: string) => {
const nodeSchema = availableNodes.find(node => node.id === blockId);
if (!nodeSchema) {
console.error(`Schema not found for block ID: ${blockId}`);
return;
}
-
+
const newNode: Node<CustomNodeData> = {
id: nodeId.toString(),
type: 'custom',
@@ -220,12 +337,12 @@ const FlowEditor: React.FC<{
inputSchema: nodeSchema.inputSchema,
outputSchema: nodeSchema.outputSchema,
hardcodedValues: {},
- setHardcodedValues: (values: { [key: string]: any }) => {
- setNodes((nds) => nds.map((node) =>
- node.id === newNode.id
- ? { ...node, data: { ...node.data, hardcodedValues: values } }
- : node
- ));
+ setHardcodedValues: (values) => {
+ setNodes((nds) =>
+ nds.map((node) =>
+ node.id === newNode.id ? { ...node, data: { ...node.data, hardcodedValues: values } } : node
+ )
+ );
},
connections: [],
isOutputOpen: false,
@@ -240,10 +357,26 @@ const FlowEditor: React.FC<{
}
},
};
-
+
setNodes((nds) => [...nds, newNode]);
setNodeId((prevId) => prevId + 1);
clearNodesStatusAndOutput(); // Clear status and output when a new node is added
+
+ history.push({
+ type: 'ADD_NODE',
+ payload: newNode,
+ undo: () => setNodes((nds) => nds.filter(node => node.id !== newNode.id)),
+ redo: () => setNodes((nds) => [...nds, newNode])
+ });
+ }, [nodeId, availableNodes]);
+
+
+ const handleUndo = () => {
+ history.undo();
+ };
+
+ const handleRedo = () => {
+ history.redo();
};
function loadGraph(graph: Graph) {
@@ -625,6 +758,8 @@ const FlowEditor: React.FC<{
onNodesDelete={onNodesDelete}
onEdgesDelete={onEdgesDelete}
deleteKeyCode={["Backspace", "Delete"]}
+ onNodeDragStart={onNodesChangeStart}
+ onNodeDragStop={onNodesChangeEnd}
>
<div style={{ position: 'absolute', right: 10, zIndex: 4 }}>
<Input
@@ -649,6 +784,10 @@ const FlowEditor: React.FC<{
{!savedAgent &&
<Button onClick={() => saveAgent(true)}>Save as Template</Button>
}
+ <div>
+ <Button onClick={handleUndo} disabled={!history.canUndo()} style={{ marginRight: '10px' }}>Undo</Button>
+ <Button onClick={handleRedo} disabled={!history.canRedo()}>Redo</Button>
+ </div>
</div>
</div>
</ReactFlow>
diff --git a/rnd/autogpt_builder/src/components/history.ts b/rnd/autogpt_builder/src/components/history.ts
new file mode 100644
index 0000000000..5323944f2b
--- /dev/null
+++ b/rnd/autogpt_builder/src/components/history.ts
@@ -0,0 +1,89 @@
+// history.ts
+import { CustomNodeData } from './CustomNode';
+import { CustomEdgeData } from './CustomEdge';
+import { Edge } from 'reactflow';
+
+type ActionType =
+ | 'ADD_NODE'
+ | 'DELETE_NODE'
+ | 'ADD_EDGE'
+ | 'DELETE_EDGE'
+ | 'UPDATE_NODE'
+ | 'MOVE_NODE'
+ | 'UPDATE_INPUT'
+ | 'UPDATE_NODE_POSITION';
+
+type AddNodePayload = { node: CustomNodeData };
+type DeleteNodePayload = { nodeId: string };
+type AddEdgePayload = { edge: Edge<CustomEdgeData> };
+type DeleteEdgePayload = { edgeId: string };
+type UpdateNodePayload = { nodeId: string; newData: Partial<CustomNodeData> };
+type MoveNodePayload = { nodeId: string; position: { x: number; y: number } };
+type UpdateInputPayload = { nodeId: string; oldValues: { [key: string]: any }; newValues: { [key: string]: any } };
+type UpdateNodePositionPayload = { nodeId: string; oldPosition: { x: number; y: number }; newPosition: { x: number; y: number } };
+
+type ActionPayload =
+ | AddNodePayload
+ | DeleteNodePayload
+ | AddEdgePayload
+ | DeleteEdgePayload
+ | UpdateNodePayload
+ | MoveNodePayload
+ | UpdateInputPayload
+ | UpdateNodePositionPayload;
+
+type Action = {
+ type: ActionType;
+ payload: ActionPayload;
+ undo: () => void;
+ redo: () => void;
+};
+
+class History {
+ private past: Action[] = [];
+ private future: Action[] = [];
+
+ push(action: Action) {
+ this.past.push(action);
+ this.future = [];
+ }
+
+ undo() {
+ const action = this.past.pop();
+ if (action) {
+ action.undo();
+ this.future.push(action);
+ }
+ }
+
+ redo() {
+ const action = this.future.pop();
+ if (action) {
+ action.redo();
+ this.past.push(action);
+ }
+ }
+
+ canUndo(): boolean {
+ return this.past.length > 0;
+ }
+
+ canRedo(): boolean {
+ return this.future.length > 0;
+ }
+
+ clear() {
+ this.past = [];
+ this.future = [];
+ }
+
+ getHistoryState() {
+ return {
+ past: [...this.past],
+ future: [...this.future],
+ };
+ }
+
+}
+
+export const history = new History();
\ No newline at end of file