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/9326 improve add-block placement without viewport jump (#13456)
Satyam Sethec1cde636bc3
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/AllBlocksContent/AllBlocksContent.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/AllBlocksContent/AllBlocksContent.tsxindex 9d1d0e483d..02d79b13d0 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/AllBlocksContent/AllBlocksContent.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/AllBlocksContent/AllBlocksContent.tsx@@ -6,7 +6,6 @@ import { beautifyString } from "@/lib/utils";import { useAllBlockContent } from "./useAllBlockContent";import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";import { blockMenuContainerStyle } from "../style";-import { useNodeStore } from "../../../../stores/nodeStore";export const AllBlocksContent = () => {const {@@ -19,8 +18,6 @@ export const AllBlocksContent = () => {isErrorOnLoadingMore,} = useAllBlockContent();- const addBlock = useNodeStore((state) => state.addBlock);-if (isLoading) {return (<div className={blockMenuContainerStyle}>@@ -74,7 +71,6 @@ export const AllBlocksContent = () => {key={`${category.name}-${block.id}`}title={block.name as string}description={block.name as string}- onClick={() => addBlock(block)}blockData={block}/>))}diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/Block.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/Block.tsxindex 727a17667a..40bf3ee468 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/Block.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/Block.tsx@@ -1,13 +1,13 @@import { Button } from "@/components/__legacy__/ui/button";import { Skeleton } from "@/components/__legacy__/ui/skeleton";import { beautifyString, cn } from "@/lib/utils";-import React, { ButtonHTMLAttributes, useCallback, useState } from "react";+import React, { ButtonHTMLAttributes, useState } from "react";import { highlightText } from "./helpers";import { BlockInfo } from "@/app/api/__generated__/models/blockInfo";import { useControlPanelStore } from "../../../stores/controlPanelStore";import { blockDragPreviewStyle } from "./style";-import { useReactFlow } from "@xyflow/react";import { useNodeStore } from "../../../stores/nodeStore";+import { useAddBlockToBuilder } from "./hooks/useAddBlockToBuilder";import { BlockUIType, SpecialBlockID } from "@/lib/autogpt-server-api";import {MCPToolDialog,@@ -38,76 +38,52 @@ export const Block: BlockComponent = ({const setBlockMenuOpen = useControlPanelStore((state) => state.setBlockMenuOpen,);- const { setViewport } = useReactFlow();- const { addBlock } = useNodeStore();+ const { addBlockWithPlacement } = useAddBlockToBuilder();const [mcpDialogOpen, setMcpDialogOpen] = useState(false);const isMCPBlock = blockData.uiType === BlockUIType.MCP_TOOL;- const addBlockAndCenter = useCallback(- (block: BlockInfo, hardcodedValues?: Record<string, any>) => {- const customNode = addBlock(block, hardcodedValues);- setTimeout(() => {- setViewport(- {- x: -customNode.position.x * 0.8 + window.innerWidth / 2,- y: -customNode.position.y * 0.8 + (window.innerHeight - 400) / 2,- zoom: 0.8,- },- { duration: 500 },- );- }, 50);- return customNode;- },- [addBlock, setViewport],- );-const updateNodeData = useNodeStore((state) => state.updateNodeData);- const handleMCPToolConfirm = useCallback(- (result: MCPToolDialogResult) => {- // Derive a display label: prefer server name, fall back to URL hostname.- let serverLabel = result.serverName;- if (!serverLabel) {- try {- serverLabel = new URL(result.serverUrl).hostname;- } catch {- serverLabel = "MCP";- }+ function handleMCPToolConfirm(result: MCPToolDialogResult) {+ let serverLabel = result.serverName;+ if (!serverLabel) {+ try {+ serverLabel = new URL(result.serverUrl).hostname;+ } catch {+ serverLabel = "MCP";}+ }- const customNode = addBlockAndCenter(blockData, {- server_url: result.serverUrl,- server_name: serverLabel,- selected_tool: result.selectedTool,- tool_input_schema: result.toolInputSchema,- available_tools: result.availableTools,- credentials: result.credentials ?? undefined,+ const customNode = addBlockWithPlacement(blockData, {+ server_url: result.serverUrl,+ server_name: serverLabel,+ selected_tool: result.selectedTool,+ tool_input_schema: result.toolInputSchema,+ available_tools: result.availableTools,+ credentials: result.credentials ?? undefined,+ });+ if (customNode) {+ const displayName = result.selectedTool+ ? `${serverLabel}: ${beautifyString(result.selectedTool)}`+ : undefined;+ updateNodeData(customNode.id, {+ metadata: {+ ...customNode.data.metadata,+ credentials_optional: true,+ ...(displayName && { customized_name: displayName }),+ },});- if (customNode) {- const title = result.selectedTool- ? `${serverLabel}: ${beautifyString(result.selectedTool)}`- : undefined;- updateNodeData(customNode.id, {- metadata: {- ...customNode.data.metadata,- credentials_optional: true,- ...(title && { customized_name: title }),- },- });- }- setMcpDialogOpen(false);- },- [addBlockAndCenter, blockData, updateNodeData],- );+ }+ setMcpDialogOpen(false);+ }- const handleClick = () => {+ function handleClick() {if (isMCPBlock) {setMcpDialogOpen(true);return;}- const customNode = addBlockAndCenter(blockData);- // Set customized_name for agent blocks so the agent's name persists+ const customNode = addBlockWithPlacement(blockData);if (customNode && blockData.id === SpecialBlockID.AGENT) {updateNodeData(customNode.id, {metadata: {@@ -116,16 +92,15 @@ export const Block: BlockComponent = ({},});}- };+ }- const handleDragStart = (e: React.DragEvent<HTMLButtonElement>) => {+ function handleDragStart(e: React.DragEvent<HTMLButtonElement>) {if (isMCPBlock) return;e.dataTransfer.effectAllowed = "copy";e.dataTransfer.setData("application/reactflow", JSON.stringify(blockData));setBlockMenuOpen(false);- // preview when user drags itconst dragPreview = document.createElement("div");dragPreview.style.cssText = blockDragPreviewStyle;dragPreview.textContent = beautifyString(title || "").replace(@@ -137,9 +112,8 @@ export const Block: BlockComponent = ({e.dataTransfer.setDragImage(dragPreview, 0, 0);setTimeout(() => document.body.removeChild(dragPreview), 0);- };+ }- // Generate a data-id from the block id (e.g., "AgentInputBlock" -> "block-card-AgentInputBlock")const blockDataId = blockData.id? `block-card-${blockData.id.replace(/[^a-zA-Z0-9]/g, "")}`: undefined;diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/IntergrationBlock.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/IntergrationBlock.tsxindex 79020ba0d9..7cb8ff730c 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/IntergrationBlock.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/IntergrationBlock.tsx@@ -6,8 +6,7 @@ import React, { ButtonHTMLAttributes } from "react";import { highlightText } from "./helpers";import { Button } from "@/components/atoms/Button/Button";import { useControlPanelStore } from "../../../stores/controlPanelStore";-import { useReactFlow } from "@xyflow/react";-import { useNodeStore } from "../../../stores/nodeStore";+import { useAddBlockToBuilder } from "./hooks/useAddBlockToBuilder";import { BlockInfo } from "@/app/api/__generated__/models/blockInfo";import { blockDragPreviewStyle } from "./style";@@ -35,30 +34,18 @@ export const IntegrationBlock: IntegrationBlockComponent = ({const setBlockMenuOpen = useControlPanelStore((state) => state.setBlockMenuOpen,);- const { setViewport } = useReactFlow();- const { addBlock } = useNodeStore();+ const { addBlockWithPlacement } = useAddBlockToBuilder();- const handleClick = () => {- const customNode = addBlock(blockData);- setTimeout(() => {- setViewport(- {- x: -customNode.position.x * 0.8 + window.innerWidth / 2,- y: -customNode.position.y * 0.8 + (window.innerHeight - 400) / 2,- zoom: 0.8,- },- { duration: 500 },- );- }, 50);- };+ function handleClick() {+ addBlockWithPlacement(blockData);+ }- const handleDragStart = (e: React.DragEvent<HTMLButtonElement>) => {+ function handleDragStart(e: React.DragEvent<HTMLButtonElement>) {e.dataTransfer.effectAllowed = "copy";e.dataTransfer.setData("application/reactflow", JSON.stringify(blockData));setBlockMenuOpen(false);- // preview when user drags itconst dragPreview = document.createElement("div");dragPreview.style.cssText = blockDragPreviewStyle;dragPreview.textContent = beautifyString(title || "").replace(@@ -70,7 +57,7 @@ export const IntegrationBlock: IntegrationBlockComponent = ({e.dataTransfer.setDragImage(dragPreview, 0, 0);setTimeout(() => document.body.removeChild(dragPreview), 0);- };+ }return (<Buttondiff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/hooks/__tests__/useAddBlockToBuilder.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/hooks/__tests__/useAddBlockToBuilder.test.tsxnew file mode 100644index 0000000000..80227be551--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/hooks/__tests__/useAddBlockToBuilder.test.tsx@@ -0,0 +1,179 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { fireEvent, render, renderHook, screen } from "@testing-library/react";+import type { ToastProps } from "@/components/molecules/Toast/use-toast";++const mockDismiss = vi.fn();+const mockToast = vi.fn((_props: ToastProps) => ({ dismiss: mockDismiss }));+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: (props: ToastProps) => mockToast(props),+}));++const mockGetViewport = vi.fn(() => ({ x: 0, y: 0, zoom: 1 }));+const flowState = { width: 1000, height: 800 };+const mockFitView = vi.fn();++vi.mock("@xyflow/react", () => ({+ useReactFlow: () => ({ getViewport: mockGetViewport, fitView: mockFitView }),+ useStoreApi: () => ({ getState: () => flowState }),+ useStore: (selector: (state: { width: number; height: number }) => number) =>+ selector(flowState),+}));++const mockAddBlock = vi.fn((block, _hv, position) => {+ const node = {+ id: `node-${nodeState.nodes.length + 1}`,+ position,+ data: { uiType: block.uiType },+ };+ nodeState.nodes = [...nodeState.nodes, node];+ return node;+});++const nodeState = {+ addBlock: mockAddBlock,+ nodes: [] as Array<{+ position: { x: number; y: number };+ width?: number;+ measured?: { width: number; height: number };+ data: { uiType: string };+ }>,+};++vi.mock("@/app/(platform)/build/stores/nodeStore", () => ({+ useNodeStore: Object.assign(+ (selector: (state: typeof nodeState) => unknown) => selector(nodeState),+ { getState: () => nodeState },+ ),+}));++import { useAddBlockToBuilder } from "../useAddBlockToBuilder";+import { BlockUIType } from "@/app/(platform)/build/components/types";++function makeBlock(uiType = BlockUIType.STANDARD) {+ return {+ id: "test-block",+ name: "Test Block",+ description: "",+ inputSchema: {},+ outputSchema: {},+ uiType,+ } as Parameters<+ ReturnType<typeof useAddBlockToBuilder>["addBlockWithPlacement"]+ >[0];+}++describe("useAddBlockToBuilder", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ nodeState.nodes = [];+ flowState.width = 1000;+ flowState.height = 800;+ mockGetViewport.mockReturnValue({ x: 0, y: 0, zoom: 1 });+ });++ it("places a block on an empty canvas", () => {+ const { result } = renderHook(() => useAddBlockToBuilder());++ result.current.addBlockWithPlacement(makeBlock());++ expect(mockAddBlock).toHaveBeenCalledOnce();+ const position = mockAddBlock.mock.calls[0][2];+ expect(position).toEqual({ x: 70, y: 70 });+ });++ it("avoids overlapping existing nodes", () => {+ nodeState.nodes = [+ {+ position: { x: 70, y: 70 },+ measured: { width: 400, height: 400 },+ data: { uiType: BlockUIType.STANDARD },+ },+ ];++ const { result } = renderHook(() => useAddBlockToBuilder());+ result.current.addBlockWithPlacement(makeBlock());++ const position = mockAddBlock.mock.calls[0][2];+ expect(position.x).not.toBe(70);+ });++ it("uses the newly inserted node when two blocks are added before rerender", () => {+ const { result } = renderHook(() => useAddBlockToBuilder());++ const first = result.current.addBlockWithPlacement(makeBlock());+ const second = result.current.addBlockWithPlacement(makeBlock());++ expect(second.position).not.toEqual(first.position);+ expect(mockFitView).not.toHaveBeenCalled();+ });++ it("reads current canvas dimensions when adding after a resize", () => {+ const { result } = renderHook(() => useAddBlockToBuilder());+ flowState.width = 440;+ flowState.height = 490;++ const node = result.current.addBlockWithPlacement(makeBlock());++ expect(node.position.x).toBeGreaterThanOrEqual(40);+ expect(node.position.x + 350).toBeLessThanOrEqual(400);+ expect(node.position.y + 400).toBeLessThanOrEqual(450);+ });++ it("uses smaller dimensions for note blocks", () => {+ const { result } = renderHook(() => useAddBlockToBuilder());++ result.current.addBlockWithPlacement(makeBlock(BlockUIType.NOTE));++ expect(mockAddBlock).toHaveBeenCalledOnce();+ });++ it("passes hardcoded values through to addBlock", () => {+ const { result } = renderHook(() => useAddBlockToBuilder());+ const hardcoded = { key: "value" };++ result.current.addBlockWithPlacement(makeBlock(), hardcoded);++ expect(mockAddBlock).toHaveBeenCalledWith(+ expect.anything(),+ hardcoded,+ expect.any(Object),+ );+ });++ it("moves the camera only when the user chooses Show block", () => {+ flowState.width = 300;+ const { result } = renderHook(() => useAddBlockToBuilder());+ const node = result.current.addBlockWithPlacement(makeBlock());++ expect(mockFitView).not.toHaveBeenCalled();+ render(<>{mockToast.mock.calls[0][0].action}</>);+ fireEvent.click(screen.getByRole("button", { name: "Show block" }));++ expect(mockFitView).toHaveBeenCalledWith(+ expect.objectContaining({ nodes: [{ id: node.id }], maxZoom: 1 }),+ );+ expect(mockDismiss).toHaveBeenCalledOnce();+ });++ it("ignores Show block after the inserted block has been removed", () => {+ flowState.width = 300;+ const { result } = renderHook(() => useAddBlockToBuilder());+ result.current.addBlockWithPlacement(makeBlock());+ nodeState.nodes = [];+ render(<>{mockToast.mock.calls[0][0].action}</>);++ fireEvent.click(screen.getByRole("button", { name: "Show block" }));++ expect(mockFitView).not.toHaveBeenCalled();+ });++ it("uses the latest pan and zoom at insertion", () => {+ const { result } = renderHook(() => useAddBlockToBuilder());+ mockGetViewport.mockReturnValue({ x: -1000, y: -500, zoom: 2 });++ const node = result.current.addBlockWithPlacement(makeBlock());++ expect(node.position.x).toBeGreaterThanOrEqual(520);+ expect(node.position.y).toBeGreaterThanOrEqual(270);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/hooks/useAddAgentToBuilder.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/hooks/useAddAgentToBuilder.tsindex b07e3a1437..135b714fc0 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/hooks/useAddAgentToBuilder.ts+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/hooks/useAddAgentToBuilder.ts@@ -1,15 +1,12 @@-import { useNodeStore } from "@/app/(platform)/build/stores/nodeStore";-import { useShallow } from "zustand/react/shallow";-import { useReactFlow } from "@xyflow/react";import { convertLibraryAgentIntoCustomNode } from "../helpers";import { LibraryAgent } from "@/app/api/__generated__/models/libraryAgent";import { getV2GetLibraryAgent } from "@/app/api/__generated__/endpoints/library/library";+import { useAddBlockToBuilder } from "./useAddBlockToBuilder";-export const useAddAgentToBuilder = () => {- const addBlock = useNodeStore(useShallow((state) => state.addBlock));- const { setViewport } = useReactFlow();+export function useAddAgentToBuilder() {+ const { addBlockWithPlacement } = useAddBlockToBuilder();- const addAgentToBuilder = (libraryAgent: LibraryAgent) => {+ function addAgentToBuilder(libraryAgent: LibraryAgent) {const { input_schema, output_schema } = libraryAgent;const { block, hardcodedValues } = convertLibraryAgentIntoCustomNode(@@ -18,23 +15,10 @@ export const useAddAgentToBuilder = () => {output_schema,);- const customNode = addBlock(block, hardcodedValues);+ return addBlockWithPlacement(block, hardcodedValues);+ }- setTimeout(() => {- setViewport(- {- x: -customNode.position.x * 0.8 + window.innerWidth / 2,- y: -customNode.position.y * 0.8 + (window.innerHeight - 400) / 2,- zoom: 0.8,- },- { duration: 500 },- );- }, 50);-- return customNode;- };-- const addLibraryAgentToBuilder = async (agent: LibraryAgent) => {+ async function addLibraryAgentToBuilder(agent: LibraryAgent) {const response = await getV2GetLibraryAgent(agent.id);if (!response.data) {@@ -43,10 +27,10 @@ export const useAddAgentToBuilder = () => {const libraryAgent = response.data as LibraryAgent;return addAgentToBuilder(libraryAgent);- };+ }return {addAgentToBuilder,addLibraryAgentToBuilder,};-};+}diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/hooks/useAddBlockToBuilder.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/hooks/useAddBlockToBuilder.tsxnew file mode 100644index 0000000000..fc031e8310--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/hooks/useAddBlockToBuilder.tsx@@ -0,0 +1,73 @@+import { BlockInfo } from "@/app/api/__generated__/models/blockInfo";+import { useReactFlow, useStoreApi } from "@xyflow/react";+import { useNodeStore } from "@/app/(platform)/build/stores/nodeStore";+import { Button } from "@/components/atoms/Button/Button";+import { toast } from "@/components/molecules/Toast/use-toast";+import {+ findFreePosition,+ fitsInViewport,+ getBlockPlacementDimensions,+ getFlowViewportBounds,+} from "@/app/(platform)/build/components/placementHelpers";+import { CustomNode } from "@/app/(platform)/build/components/FlowEditor/nodes/CustomNode/CustomNode";++const PLACEMENT_MARGIN = 30;++export function useAddBlockToBuilder() {+ const { getViewport, fitView } = useReactFlow();+ const flowStore = useStoreApi();++ function addBlockWithPlacement(+ block: BlockInfo,+ hardcodedValues?: Record<string, unknown>,+ ): CustomNode {+ const { width: flowWidth, height: flowHeight } = flowStore.getState();+ const viewportBounds = getFlowViewportBounds(+ getViewport(),+ flowWidth,+ flowHeight,+ );+ const dimensions = getBlockPlacementDimensions(block.uiType);+ const { nodes, addBlock } = useNodeStore.getState();+ const position = findFreePosition(+ nodes,+ dimensions.width,+ PLACEMENT_MARGIN,+ viewportBounds,+ dimensions.height,+ );+ const node = addBlock(block, hardcodedValues, position);++ if (+ viewportBounds &&+ !fitsInViewport({ ...position, ...dimensions }, viewportBounds)+ ) {+ function handleShowBlock() {+ if (+ !useNodeStore.getState().nodes.some((item) => item.id === node.id)+ ) {+ return;+ }+ void fitView({+ nodes: [{ id: node.id }],+ maxZoom: getViewport().zoom,+ duration: 300,+ padding: 0.2,+ });+ notification.dismiss();+ }+ const notification = toast({+ title: "Block added outside the current view",+ action: (+ <Button variant="secondary" size="small" onClick={handleShowBlock}>+ Show block+ </Button>+ ),+ });+ }++ return node;+ }++ return { addBlockWithPlacement };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/__tests__/placementHelpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/__tests__/placementHelpers.test.tsnew file mode 100644index 0000000000..490cf04e3b--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/__tests__/placementHelpers.test.ts@@ -0,0 +1,188 @@+import { describe, expect, it } from "vitest";+import { BlockUIType } from "../types";+import {+ findFreePosition,+ getFlowViewportBounds,+ getNodeDimensions,+ type ExistingNodeForPlacement,+} from "../placementHelpers";++const viewport = getFlowViewportBounds({ x: 0, y: 0, zoom: 1 }, 1000, 800, 0)!;++function node(+ x: number,+ y: number,+ width = 500,+ height = 400,+): ExistingNodeForPlacement {+ return {+ position: { x, y },+ measured: { width, height },+ };+}++describe("getFlowViewportBounds", () => {+ it.each([0, -1, Infinity, NaN])(+ "falls back before the viewport has a usable zoom %s",+ (zoom) => {+ expect(+ getFlowViewportBounds({ x: 0, y: 0, zoom }, 1000, 800),+ ).toBeUndefined();+ },+ );++ it("falls back before the canvas has dimensions", () => {+ expect(+ getFlowViewportBounds({ x: 0, y: 0, zoom: 1 }, 0, 0),+ ).toBeUndefined();+ });+ it("maps screen corners to flow coordinates", () => {+ expect(+ getFlowViewportBounds({ x: -100, y: -50, zoom: 0.5 }, 1200, 900, 0),+ ).toEqual({+ minX: 200,+ minY: 100,+ maxX: 2600,+ maxY: 1900,+ });+ });+});++describe("findFreePosition", () => {+ it("anchors an oversized first block inside a small viewport", () => {+ expect(+ findFreePosition(+ [],+ 350,+ 30,+ { minX: 40, minY: 40, maxX: 200, maxY: 200 },+ 400,+ ),+ ).toEqual({ x: 40, y: 40 });+ });+ it("returns default origin when there are no nodes", () => {+ expect(findFreePosition([])).toEqual({ x: 100, y: 100 });+ });++ it("places the first block inside the viewport when bounds are provided", () => {+ expect(findFreePosition([], 400, 30, viewport)).toEqual({ x: 30, y: 30 });+ });++ it("places a block to the right of the most recent node when space is available", () => {+ expect(findFreePosition([node(100, 100)], 400, 30)).toEqual({+ x: 630,+ y: 100,+ });+ });++ it("prefers a visible grid slot over an off-screen adjacent slot", () => {+ const crowdedCanvas = [node(5000, 5000)];++ const position = findFreePosition(crowdedCanvas, 400, 30, viewport);++ expect(position.x).toBeGreaterThanOrEqual(viewport.minX);+ expect(position.y).toBeGreaterThanOrEqual(viewport.minY);+ expect(position.x + 400).toBeLessThanOrEqual(viewport.maxX);+ expect(position.y + 400).toBeLessThanOrEqual(viewport.maxY);+ });++ it("does not jump far to the right when the viewport is full", () => {+ const gridNodes: ExistingNodeForPlacement[] = [];+ for (let row = 0; row < 3; row++) {+ for (let col = 0; col < 3; col++) {+ gridNodes.push(node(col * 430, row * 430, 400, 400));+ }+ }++ const position = findFreePosition(gridNodes, 400, 30, viewport);++ expect(position).toEqual({ x: 30, y: 1290 });+ });++ it("uses adjacent placement without viewport bounds when canvas is not crowded", () => {+ expect(findFreePosition([node(200, 150)], 400, 30)).toEqual({+ x: 730,+ y: 150,+ });+ });++ it("uses default dimensions for nodes without measured property", () => {+ const unmeasuredNode: ExistingNodeForPlacement = {+ position: { x: 0, y: 0 },+ };+ const position = findFreePosition([unmeasuredNode], 400, 30);++ expect(position).toEqual({ x: 380, y: 0 });+ });++ it("picks an adjacent candidate visible in the viewport", () => {+ const nodes = [node(0, 0, 400, 400)];+ const smallViewport = getFlowViewportBounds(+ { x: 0, y: 0, zoom: 1 },+ 900,+ 900,+ 0,+ )!;+ const position = findFreePosition(nodes, 400, 30, smallViewport, 400);++ expect(position.x + 400).toBeLessThanOrEqual(smallViewport.maxX);+ expect(position.y + 400).toBeLessThanOrEqual(smallViewport.maxY);+ });++ it("falls back to last-node position when no viewport and all adjacent spots blocked", () => {+ const tightCluster = [+ node(0, 0, 400, 400),+ node(430, 0, 400, 400),+ node(-430, 0, 400, 400),+ node(0, 430, 400, 400),+ ];++ const position = findFreePosition(tightCluster, 400, 30, undefined, 400);++ expect(position.x).toBeGreaterThanOrEqual(0);+ });++ it("finds adjacent gap when grid scan misses it due to alignment", () => {+ const smallNode = node(0, 0, 100, 100);+ const narrowViewport = getFlowViewportBounds(+ { x: 0, y: 0, zoom: 1 },+ 350,+ 350,+ 0,+ )!;+ const position = findFreePosition(+ [smallNode],+ 200,+ 30,+ narrowViewport,+ 200,+ );++ expect(position).toEqual({ x: 130, y: 0 });+ });+});++describe("getNodeDimensions", () => {+ it("returns measured dimensions when available", () => {+ const dims = getNodeDimensions({ measured: { width: 300, height: 200 } });+ expect(dims).toEqual({ width: 300, height: 200 });+ });++ it("prefers node.width over measured width", () => {+ const dims = getNodeDimensions({+ width: 600,+ measured: { width: 300, height: 200 },+ });+ expect(dims.width).toBe(600);+ });++ it("falls back to default dimensions for unmeasured nodes", () => {+ const dims = getNodeDimensions({});+ expect(dims).toEqual({ width: 350, height: 400 });+ });++ it("uses the note dimensions until measured", () => {+ const dims = getNodeDimensions({ data: { uiType: BlockUIType.NOTE } });+ expect(dims).toEqual({ width: 304, height: 304 });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/helper.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/helper.tsindex 00c151d35b..e2285b115f 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/helper.ts+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/helper.ts@@ -8,7 +8,6 @@ import { NodeModel } from "@/app/api/__generated__/models/nodeModel";import { NodeModelMetadata } from "@/app/api/__generated__/models/nodeModelMetadata";import { Link } from "@/app/api/__generated__/models/link";import { CustomEdge } from "./FlowEditor/edges/CustomEdge";-import { XYPosition } from "@xyflow/react";export const convertBlockInfoIntoCustomNodeData = (block: BlockInfo,@@ -122,107 +121,3 @@ export const isCostFilterMatch = (): costFilter === inputValues;};--// ----- Position related helpers -------export interface NodeDimensions {- x: number;- y: number;- width: number;- height: number;-}--function rectanglesOverlap(- rect1: NodeDimensions,- rect2: NodeDimensions,-): boolean {- const x1 = rect1.x,- y1 = rect1.y,- w1 = rect1.width,- h1 = rect1.height;- const x2 = rect2.x,- y2 = rect2.y,- w2 = rect2.width,- h2 = rect2.height;-- return !(x1 + w1 <= x2 || x1 >= x2 + w2 || y1 + h1 <= y2 || y1 >= y2 + h2);-}--export function findFreePosition(- existingNodes: Array<{- position: XYPosition;- measured?: { width: number; height: number };- }>,- newNodeWidth: number = 500,- margin: number = 60,-): XYPosition {- if (existingNodes.length === 0) {- return { x: 100, y: 100 }; // Default starting position- }-- // Start from the most recently added node- for (let i = existingNodes.length - 1; i >= 0; i--) {- const lastNode = existingNodes[i];- const lastNodeWidth = lastNode.measured?.width ?? 500;- const lastNodeHeight = lastNode.measured?.height ?? 400;-- // Try right- const candidate = {- x: lastNode.position.x + lastNodeWidth + margin,- y: lastNode.position.y,- width: newNodeWidth,- height: 400, // Estimated height- };-- if (- !existingNodes.some((n) =>- rectanglesOverlap(candidate, {- x: n.position.x,- y: n.position.y,- width: n.measured?.width ?? 500,- height: n.measured?.height ?? 400,- }),- )- ) {- return { x: candidate.x, y: candidate.y };- }-- // Try left- candidate.x = lastNode.position.x - newNodeWidth - margin;- if (- !existingNodes.some((n) =>- rectanglesOverlap(candidate, {- x: n.position.x,- y: n.position.y,- width: n.measured?.width ?? 500,- height: n.measured?.height ?? 400,- }),- )- ) {- return { x: candidate.x, y: candidate.y };- }-- // Try below- candidate.x = lastNode.position.x;- candidate.y = lastNode.position.y + lastNodeHeight + margin;- if (- !existingNodes.some((n) =>- rectanglesOverlap(candidate, {- x: n.position.x,- y: n.position.y,- width: n.measured?.width ?? 500,- height: n.measured?.height ?? 400,- }),- )- ) {- return { x: candidate.x, y: candidate.y };- }- }-- // Fallback: place it far to the right- const lastNode = existingNodes[existingNodes.length - 1];- return {- x: lastNode.position.x + 600,- y: lastNode.position.y,- };-}diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/placementHelpers.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/placementHelpers.tsnew file mode 100644index 0000000000..0f51923503--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/placementHelpers.ts@@ -0,0 +1,225 @@+import { XYPosition } from "@xyflow/react";+import { BlockUIType } from "./types";++export interface NodeDimensions {+ x: number;+ y: number;+ width: number;+ height: number;+}++export type FlowViewportBounds = {+ minX: number;+ minY: number;+ maxX: number;+ maxY: number;+};++export type ExistingNodeForPlacement = {+ position: XYPosition;+ width?: number;+ height?: number;+ measured?: { width?: number; height?: number };+ data?: { uiType?: string };+};++const DEFAULT_NODE_WIDTH = 350;+const DEFAULT_NODE_HEIGHT = 400;++export function getBlockPlacementDimensions(uiType?: string) {+ return uiType === BlockUIType.NOTE+ ? { width: 304, height: 304 }+ : { width: DEFAULT_NODE_WIDTH, height: DEFAULT_NODE_HEIGHT };+}++function rectanglesOverlap(a: NodeDimensions, b: NodeDimensions): boolean {+ return !(+ a.x + a.width <= b.x ||+ a.x >= b.x + b.width ||+ a.y + a.height <= b.y ||+ a.y >= b.y + b.height+ );+}++function nodeToRect(node: ExistingNodeForPlacement): NodeDimensions {+ return {+ x: node.position.x,+ y: node.position.y,+ ...getNodeDimensions(node),+ };+}++function overlapsAnyNode(+ candidate: NodeDimensions,+ nodes: ExistingNodeForPlacement[],+): boolean {+ return nodes.some((n) => rectanglesOverlap(candidate, nodeToRect(n)));+}++export function fitsInViewport(+ rect: NodeDimensions,+ bounds: FlowViewportBounds,+): boolean {+ return (+ rect.x >= bounds.minX &&+ rect.y >= bounds.minY &&+ rect.x + rect.width <= bounds.maxX &&+ rect.y + rect.height <= bounds.maxY+ );+}++export function getFlowViewportBounds(+ viewport: { x: number; y: number; zoom: number },+ screenWidth: number,+ screenHeight: number,+ padding = 40,+): FlowViewportBounds | undefined {+ const { x, y, zoom } = viewport;+ if (+ ![x, y, zoom, screenWidth, screenHeight, padding].every(Number.isFinite) ||+ zoom <= 0 ||+ screenWidth <= 0 ||+ screenHeight <= 0+ ) {+ return undefined;+ }+ const inset = Math.max(+ 0,+ Math.min(padding, screenWidth / 4, screenHeight / 4),+ );+ return {+ minX: (-x + inset) / zoom,+ minY: (-y + inset) / zoom,+ maxX: (screenWidth - x - inset) / zoom,+ maxY: (screenHeight - y - inset) / zoom,+ };+}++function scanViewportGrid(+ nodes: ExistingNodeForPlacement[],+ width: number,+ height: number,+ margin: number,+ bounds: FlowViewportBounds,+): XYPosition | null {+ const stepX = width + margin;+ const stepY = height + margin;+ let attempts = 0;++ for (let y = bounds.minY; y + height <= bounds.maxY; y += stepY) {+ for (let x = bounds.minX; x + width <= bounds.maxX; x += stepX) {+ if (attempts++ >= 1000) return null;+ const candidate: NodeDimensions = { x, y, width, height };+ if (!overlapsAnyNode(candidate, nodes)) {+ return { x, y };+ }+ }+ }++ return null;+}++function findAdjacentPosition(+ nodes: ExistingNodeForPlacement[],+ width: number,+ height: number,+ margin: number,+ bounds?: FlowViewportBounds,+): XYPosition | undefined {+ for (let i = nodes.length - 1; i >= 0; i--) {+ const rect = nodeToRect(nodes[i]);++ const candidates: XYPosition[] = [+ { x: rect.x + rect.width + margin, y: rect.y },+ { x: rect.x - width - margin, y: rect.y },+ { x: rect.x, y: rect.y + rect.height + margin },+ ];++ for (const pos of candidates) {+ const rect = { ...pos, width, height };+ if (+ (!bounds || fitsInViewport(rect, bounds)) &&+ !overlapsAnyNode(rect, nodes)+ ) {+ return pos;+ }+ }+ }++ return undefined;+}++export function getNodeDimensions(node: {+ width?: number;+ height?: number;+ measured?: { width?: number; height?: number };+ data?: { uiType?: string };+}): { width: number; height: number } {+ const fallback = getBlockPlacementDimensions(node.data?.uiType);+ return {+ width: node.width ?? node.measured?.width ?? fallback.width,+ height: node.height ?? node.measured?.height ?? fallback.height,+ };+}++export function findFreePosition(+ existingNodes: ExistingNodeForPlacement[],+ newNodeWidth: number = DEFAULT_NODE_WIDTH,+ margin: number = 60,+ viewportBounds?: FlowViewportBounds,+ newNodeHeight: number = DEFAULT_NODE_HEIGHT,+): XYPosition {+ if (existingNodes.length === 0) {+ if (viewportBounds) {+ return {+ x: Math.max(+ viewportBounds.minX,+ Math.min(+ viewportBounds.minX + margin,+ viewportBounds.maxX - newNodeWidth,+ ),+ ),+ y: Math.max(+ viewportBounds.minY,+ Math.min(+ viewportBounds.minY + margin,+ viewportBounds.maxY - newNodeHeight,+ ),+ ),+ };+ }+ return { x: 100, y: 100 };+ }++ // First try: find an open slot in the visible viewport grid+ if (viewportBounds) {+ const gridSlot = scanViewportGrid(+ existingNodes,+ newNodeWidth,+ newNodeHeight,+ margin,+ viewportBounds,+ );+ if (gridSlot) return gridSlot;+ }++ // Second try: adjacent to existing nodes (right, left, below)+ const adjacent = findAdjacentPosition(+ existingNodes,+ newNodeWidth,+ newNodeHeight,+ margin,+ viewportBounds,+ );+ if (adjacent) return adjacent;++ const lastRect = nodeToRect(existingNodes[existingNodes.length - 1]);+ const bottom = existingNodes.reduce((max, node) => {+ const rect = nodeToRect(node);+ return Math.max(max, rect.y + rect.height);+ }, viewportBounds?.maxY ?? -Infinity);+ return {+ x: viewportBounds ? viewportBounds.minX + margin : lastRect.x,+ y: bottom + margin,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/build/stores/nodeStore.ts b/autogpt_platform/frontend/src/app/(platform)/build/stores/nodeStore.tsindex f7a52636f3..08924f7939 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/stores/nodeStore.ts+++ b/autogpt_platform/frontend/src/app/(platform)/build/stores/nodeStore.ts@@ -3,10 +3,11 @@ import { NodeChange, XYPosition, applyNodeChanges } from "@xyflow/react";import { CustomNode } from "../components/FlowEditor/nodes/CustomNode/CustomNode";import { CustomEdge } from "../components/FlowEditor/edges/CustomEdge";import { BlockInfo } from "@/app/api/__generated__/models/blockInfo";+import { convertBlockInfoIntoCustomNodeData } from "../components/helper";import {- convertBlockInfoIntoCustomNodeData,findFreePosition,-} from "../components/helper";+ getBlockPlacementDimensions,+} from "../components/placementHelpers";import { Node } from "@/app/api/__generated__/models/node";import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";import { NodeExecutionResult } from "@/app/api/__generated__/models/nodeExecutionResult";@@ -222,21 +223,15 @@ export const useNodeStore = create<NodeStore>((set, get) => ({get().incrementNodeCounter();const nodeNumber = get().nodeCounter;+ const dimensions = getBlockPlacementDimensions(block.uiType);const nodePosition =position ||findFreePosition(- get().nodes.map((node) => ({- position: node.position,- measured: {- width:- node.width ??- node.measured?.width ??- (node.data.uiType === BlockUIType.NOTE ? 300 : 500),- height: node.height ?? node.measured?.height ?? 400,- },- })),- block.uiType === BlockUIType.NOTE ? 300 : 400,+ get().nodes,+ dimensions.width,30,+ undefined,+ dimensions.height,);const customNode: CustomNode = {