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.

perf(frontend/builder): by-id node reads, memo viewers, ref-driven beads (#15711)

Abhimanyu Yadav04db8d6b52ef
diff --git a/autogpt_platform/frontend/scripts/perf/scenarios/builder-run-beads.ts b/autogpt_platform/frontend/scripts/perf/scenarios/builder-run-beads.ts
new file mode 100644
index 0000000000..9512052fa0
--- /dev/null
+++ b/autogpt_platform/frontend/scripts/perf/scenarios/builder-run-beads.ts
@@ -0,0 +1,71 @@
+import { BuildPage } from "../../../src/playwright/pages/build.page";
+import { createBuilderFixture } from "../lib/builder-fixture";
+import { installRoutes } from "../lib/routes";
+import { settle, type Scenario } from "../lib/scenario";
+import { routeExecutionSocket, withTimeout } from "./builder-run-events";
+
+const FIRST_RERUN_NODE = 30;
+const EVENT_INTERVAL_MS = 150;
+const READY_TIMEOUT_MS = 60_000;
+const FINISHED_AT = "2026-01-05T09:00:05.000Z";
+
+type Execution = ReturnType<typeof createBuilderFixture>["execution"];
+
+/**
+ * A second, finished execution of each of the 10 nodes from node 30 on. Each
+ * has a new node_exec_id and input data, so every edge into a StoreValue node
+ * among them gets a new bead that travels the edge and is removed on arrival.
+ */
+function rerunEvents(execution: Execution) {
+ return execution.node_executions
+ .slice(FIRST_RERUN_NODE)
+ .map((nodeExecution, index) => ({
+ ...nodeExecution,
+ node_exec_id: `00000000-0000-4000-b000-${String(index).padStart(12, "0")}`,
+ status: "COMPLETED",
+ start_time: nodeExecution.queue_time,
+ end_time: FINISHED_AT,
+ output_data: { output: [`rerun ${index}`] },
+ }));
+}
+
+export const builderRunBeads: Scenario = {
+ name: "builder-run-beads",
+ description:
+ "A 50-node workflow's RUNNING run receives 10 new node executions over the websocket, one every 150 ms; each sends a bead along the edge into its node.",
+ readyWhen:
+ "all 50 nodes are on the canvas with the running execution loaded and the websocket subscribe acknowledged, then network idle + 1 s",
+ windowMs: 2_000,
+ async setup(ctx) {
+ const { page } = ctx;
+ const fixture = createBuilderFixture(ctx.userID);
+ await installRoutes(page, fixture.handlers);
+ const socket = await routeExecutionSocket(page, fixture.execution.id);
+ const builder = new BuildPage(page);
+ await page.goto(
+ `/build?flowID=${fixture.graph.id}&flowExecutionID=${fixture.execution.id}`,
+ );
+ await builder.closeTutorial();
+ await page
+ .locator('[data-id^="custom-node-"]')
+ .nth(fixture.graph.nodes.length - 1)
+ .waitFor({ state: "attached", timeout: READY_TIMEOUT_MS });
+ await withTimeout(
+ socket.subscribed,
+ READY_TIMEOUT_MS,
+ "websocket subscribe",
+ );
+ await settle(page);
+ const events = rerunEvents(fixture.execution);
+ return {
+ async run() {
+ for (const event of events) {
+ // The poll sees what the websocket has sent, as with the real backend.
+ fixture.execution.node_executions.push(event);
+ socket.send("node_execution_event", event);
+ await page.waitForTimeout(EVENT_INTERVAL_MS);
+ }
+ },
+ };
+ },
+};
diff --git a/autogpt_platform/frontend/scripts/perf/scenarios/builder-run-events.ts b/autogpt_platform/frontend/scripts/perf/scenarios/builder-run-events.ts
index f28fb3d5ba..d24a485dcb 100644
--- a/autogpt_platform/frontend/scripts/perf/scenarios/builder-run-events.ts
+++ b/autogpt_platform/frontend/scripts/perf/scenarios/builder-run-events.ts
@@ -40,7 +40,7 @@ function nodeEvents(execution: Execution) {
* subscribe for the fixture run, which the harness acknowledges itself (the
* backend has no such run and would reject it).
*/
-async function routeExecutionSocket(page: Page, executionID: string) {
+export async function routeExecutionSocket(page: Page, executionID: string) {
let socket: WebSocketRoute | null = null;
let markSubscribed: () => void = () => undefined;
const subscribed = new Promise<void>((resolve) => {
@@ -76,7 +76,11 @@ async function routeExecutionSocket(page: Page, executionID: string) {
};
}
-async function withTimeout<T>(promise: Promise<T>, ms: number, what: string) {
+export async function withTimeout<T>(
+ promise: Promise<T>,
+ ms: number,
+ what: string,
+) {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
diff --git a/autogpt_platform/frontend/scripts/perf/scenarios/registry.ts b/autogpt_platform/frontend/scripts/perf/scenarios/registry.ts
index 6c92b53281..573658d09f 100644
--- a/autogpt_platform/frontend/scripts/perf/scenarios/registry.ts
+++ b/autogpt_platform/frontend/scripts/perf/scenarios/registry.ts
@@ -2,6 +2,7 @@ import type { Scenario } from "../lib/scenario";
import { builderConnectEdge } from "./builder-connect-edge";
import { builderDragRunning } from "./builder-drag-running";
import { builderRunEvents } from "./builder-run-events";
+import { builderRunBeads } from "./builder-run-beads";
import { copilotBackgroundStream } from "./copilot-background-stream";
import { copilotIdle } from "./copilot-idle";
import { copilotResizeDrag } from "./copilot-resize-drag";
@@ -27,6 +28,7 @@ export const SCENARIOS: Scenario[] = [
builderRunEvents,
copilotToolWait,
copilotResizeDrag,
+ builderRunBeads,
];
export function findScenario(name: string) {
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/__tests__/nodeStore.byId.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/nodeStore.byId.test.tsx
new file mode 100644
index 0000000000..81113b9e35
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/nodeStore.byId.test.tsx
@@ -0,0 +1,183 @@
+import { Profiler } from "react";
+import { act, render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { useNodeStore } from "../stores/nodeStore";
+import { useEdgeStore } from "../stores/edgeStore";
+import { useHistoryStore } from "../stores/historyStore";
+import { BlockUIType } from "../components/types";
+import { NodeContainer } from "../components/FlowEditor/nodes/CustomNode/components/NodeContainer";
+import type { CustomNode } from "../components/FlowEditor/nodes/CustomNode/CustomNode";
+import type { NodeExecutionResult } from "@/app/api/__generated__/models/nodeExecutionResult";
+
+function createNode(id: string, title = "Store Value"): CustomNode {
+ return {
+ id,
+ type: "custom",
+ position: { x: 0, y: 0 },
+ data: {
+ hardcodedValues: { input: `value ${id}` },
+ title,
+ description: "",
+ inputSchema: {},
+ outputSchema: {},
+ uiType: BlockUIType.STANDARD,
+ block_id: "block-1",
+ costs: [],
+ categories: [],
+ },
+ };
+}
+
+function createResult(
+ nodeId: string,
+ status: NodeExecutionResult["status"],
+): NodeExecutionResult {
+ return {
+ user_id: "user-1",
+ graph_id: "graph-1",
+ graph_version: 1,
+ graph_exec_id: "graph-exec-1",
+ node_exec_id: `exec-${nodeId}`,
+ node_id: nodeId,
+ block_id: "block-1",
+ status,
+ input_data: {},
+ output_data: { output: [`out ${nodeId}`] },
+ add_time: new Date("2026-01-05T09:00:00.000Z"),
+ queue_time: new Date("2026-01-05T09:00:00.000Z"),
+ start_time: new Date("2026-01-05T09:00:01.000Z"),
+ end_time: null,
+ };
+}
+
+beforeEach(() => {
+ useNodeStore.setState({
+ nodes: [],
+ latestNodeInputData: {},
+ latestNodeOutputData: {},
+ accumulatedNodeInputData: {},
+ accumulatedNodeOutputData: {},
+ });
+ useEdgeStore.setState({ edges: [] });
+ useHistoryStore.setState({ past: [], future: [] });
+});
+
+describe("nodeStore lookups by id", () => {
+ it("does not scan the nodes array for each node's read", () => {
+ const nodes = Array.from({ length: 50 }, (_, index) =>
+ createNode(String(index)),
+ );
+ const findSpy = vi.spyOn(nodes, "find");
+ const findIndexSpy = vi.spyOn(nodes, "findIndex");
+ useNodeStore.getState().setNodes(nodes);
+
+ const { getNodeStatus, getNodeErrors, getHardCodedValues } =
+ useNodeStore.getState();
+ for (const node of nodes) {
+ getNodeStatus(node.id);
+ getNodeErrors(node.id);
+ expect(getHardCodedValues(node.id)).toEqual({
+ input: `value ${node.id}`,
+ });
+ }
+
+ expect(findSpy).not.toHaveBeenCalled();
+ expect(findIndexSpy).not.toHaveBeenCalled();
+ });
+
+ it("reads the current values after every kind of write", () => {
+ const store = useNodeStore.getState();
+ store.setNodes([createNode("1"), createNode("2")]);
+ expect(store.getNodeStatus("1")).toBeUndefined();
+
+ store.applyNodeExecutionEvent("1", createResult("1", "RUNNING"));
+ expect(useNodeStore.getState().getNodeStatus("1")).toBe("RUNNING");
+ expect(useNodeStore.getState().getNodeExecutionResults("1")).toHaveLength(
+ 1,
+ );
+ expect(
+ useNodeStore.getState().getLatestNodeExecutionResult("1")?.status,
+ ).toBe("RUNNING");
+
+ store.updateNodeErrors("2", { input: "Required" });
+ expect(useNodeStore.getState().getNodeErrors("2")).toEqual({
+ input: "Required",
+ });
+ store.clearNodeErrors("2");
+ expect(useNodeStore.getState().getNodeErrors("2")).toBeUndefined();
+
+ store.updateNodeData("2", { hardcodedValues: { input: "edited" } });
+ expect(useNodeStore.getState().getHardCodedValues("2")).toEqual({
+ input: "edited",
+ });
+
+ store.cleanNodesStatuses();
+ expect(useNodeStore.getState().getNodeStatus("1")).toBeUndefined();
+
+ store.onNodesChange([{ type: "remove", id: "1" }]);
+ expect(useNodeStore.getState().getNodeStatus("1")).toBeUndefined();
+ expect(useNodeStore.getState().getHardCodedValues("1")).toEqual({});
+ expect(useNodeStore.getState().getNodeExecutionResults("1")).toEqual([]);
+ });
+
+ it("reads a node the caller replaced in an array it sets again", () => {
+ const nodes = [createNode("1")];
+ useNodeStore.getState().setNodes(nodes);
+ expect(useNodeStore.getState().getNodeStatus("1")).toBeUndefined();
+
+ const replaced = createNode("1");
+ replaced.data.status = "COMPLETED";
+ nodes[0] = replaced;
+ useNodeStore.getState().setNodes(nodes);
+
+ expect(useNodeStore.getState().getNodeStatus("1")).toBe("COMPLETED");
+ });
+
+ it("returns the first node when two share an id, as find did", () => {
+ const first = createNode("1", "First");
+ const second = createNode("1", "Second");
+ first.data.status = "COMPLETED";
+ second.data.status = "FAILED";
+ useNodeStore.getState().setNodes([first, second]);
+
+ expect(useNodeStore.getState().getNodeStatus("1")).toBe("COMPLETED");
+ });
+});
+
+describe("NodeContainer", () => {
+ it("re-renders only the node whose status changed", () => {
+ useNodeStore.getState().setNodes([createNode("A"), createNode("B")]);
+ const renders: Record<string, number> = { A: 0, B: 0 };
+
+ render(
+ <>
+ {["A", "B"].map((nodeId) => (
+ <Profiler
+ key={nodeId}
+ id={nodeId}
+ onRender={() => {
+ renders[nodeId] += 1;
+ }}
+ >
+ <NodeContainer nodeId={nodeId} selected={false}>
+ <span>{`node ${nodeId}`}</span>
+ </NodeContainer>
+ </Profiler>
+ ))}
+ </>,
+ );
+ expect(renders).toEqual({ A: 1, B: 1 });
+
+ act(() => {
+ useNodeStore.getState().updateNodeStatus("B", "RUNNING");
+ });
+
+ expect(renders).toEqual({ A: 1, B: 2 });
+ expect(screen.getByText("node B").parentElement?.className).toContain(
+ "ring-amber-300",
+ );
+ expect(screen.getByText("node A").parentElement?.className).not.toContain(
+ "ring-amber-300",
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/edges/components/JSBeads.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/edges/components/JSBeads.tsx
index de77c609ac..94085852ae 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/edges/components/JSBeads.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/edges/components/JSBeads.tsx
@@ -1,16 +1,18 @@
// This component uses JS animation [It's replica of legacy builder]
-// Problem - It lags at real time updates, because of state change
+// Bead positions advance every animation frame. They live in a ref and are
+// written straight to the circles, so React re-renders only when a bead is
+// created or removed, not once per frame.
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
import {
getLengthOfPathInPixels,
- getPointAtT,
getTForDistance,
setTargetPositions,
} from "../helpers";
const BEAD_DIAMETER = 10;
const ANIMATION_DURATION = 500;
+const FIRST_FRAME_MS = 16;
interface Bead {
t: number;
@@ -18,6 +20,18 @@ interface Bead {
startTime: number;
}
+interface BeadState {
+ beads: Bead[];
+ created: number;
+ destroyed: number;
+}
+
+interface MeasuredPath {
+ d: string;
+ element: SVGPathElement;
+ length: number;
+}
+
interface BeadsProps {
beadUp: number;
beadDown: number;
@@ -32,69 +46,86 @@ export const JSBeads = ({
edgePath,
beadsKey,
}: BeadsProps) => {
- const [beads, setBeads] = useState<{
- beads: Bead[];
- created: number;
- destroyed: number;
- }>({ beads: [], created: 0, destroyed: 0 });
-
- const beadsRef = useRef(beads);
- const totalLength = getLengthOfPathInPixels(edgePath);
+ const [beadCount, setBeadCount] = useState(0);
+ const stateRef = useRef<BeadState>({ beads: [], created: 0, destroyed: 0 });
+ const circlesRef = useRef<(SVGCircleElement | null)[]>([]);
+ const edgePathRef = useRef(edgePath);
+ const pathRef = useRef<MeasuredPath | null>(null);
const animationFrameRef = useRef<number | null>(null);
const lastFrameTimeRef = useRef<number>(0);
- const pathRef = useRef<SVGPathElement | null>(null);
-
- const getPointAtTWrapper = (t: number) => {
- return getPointAtT(t, edgePath, pathRef);
- };
-
- const getTForDistanceWrapper = (distanceFromEnd: number) => {
- return getTForDistance(distanceFromEnd, totalLength);
- };
-
- const setTargetPositionsWrapper = useCallback(
- (beads: Bead[]) => {
- return setTargetPositions(beads, BEAD_DIAMETER, getTForDistanceWrapper);
- },
- [getTForDistanceWrapper],
- );
-
- beadsRef.current = beads;
-
- useEffect(() => {
- pathRef.current = null;
- }, [edgePath]);
+ // Measured lazily, once per distinct path: most edges carry no beads.
+ function getPath() {
+ if (pathRef.current?.d !== edgePathRef.current) {
+ pathRef.current = measurePath(edgePathRef.current);
+ }
+ return pathRef.current;
+ }
+
+ function getTForDistanceFromEnd(distanceFromEnd: number) {
+ return getTForDistance(distanceFromEnd, getPath().length);
+ }
+
+ function positionCircles() {
+ const { beads } = stateRef.current;
+ if (beads.length === 0) return;
+ const path = getPath();
+ beads.forEach((bead, index) => {
+ const circle = circlesRef.current[index];
+ if (!circle) return;
+ const point = path.element.getPointAtLength(bead.t * path.length);
+ circle.setAttribute("cx", String(point.x));
+ circle.setAttribute("cy", String(point.y));
+ });
+ }
+
+ function commit(next: BeadState) {
+ const countChanged = next.beads.length !== stateRef.current.beads.length;
+ stateRef.current = next;
+ if (countChanged) setBeadCount(next.beads.length);
+ positionCircles();
+ }
+
+ useLayoutEffect(() => {
+ edgePathRef.current = edgePath;
+ positionCircles();
+ });
useEffect(() => {
+ const current = stateRef.current;
if (
beadUp === 0 &&
beadDown === 0 &&
- (beads.created > 0 || beads.destroyed > 0)
+ (current.created > 0 || current.destroyed > 0)
) {
- setBeads({ beads: [], created: 0, destroyed: 0 });
+ commit({ beads: [], created: 0, destroyed: 0 });
return;
}
// Adding beads
- if (beadUp > beads.created) {
- setBeads(({ beads, created, destroyed }) => {
- const newBeads = [];
- for (let i = 0; i < beadUp - created; i++) {
- newBeads.push({ t: 0, targetT: 0, startTime: Date.now() });
- }
-
- const b = setTargetPositionsWrapper([...beads, ...newBeads]);
- return { beads: b, created: beadUp, destroyed };
+ if (beadUp > current.created) {
+ const newBeads = Array.from({ length: beadUp - current.created }, () => ({
+ t: 0,
+ targetT: 0,
+ startTime: Date.now(),
+ }));
+ commit({
+ beads: setTargetPositions(
+ [...current.beads, ...newBeads],
+ BEAD_DIAMETER,
+ getTForDistanceFromEnd,
+ ),
+ created: beadUp,
+ destroyed: current.destroyed,
});
}
- const animate = (currentTime: number) => {
- const beads = beadsRef.current;
+ function animate(currentTime: number) {
+ const { beads, created, destroyed } = stateRef.current;
if (
- (beadUp === beads.created && beads.created === beads.destroyed) ||
- beads.beads.every((bead) => bead.t >= bead.targetT)
+ (beadUp === created && created === destroyed) ||
+ beads.every((bead) => bead.t >= bead.targetT)
) {
animationFrameRef.current = null;
return;
@@ -102,40 +133,20 @@ export const JSBeads = ({
const deltaTime = lastFrameTimeRef.current
? currentTime - lastFrameTimeRef.current
- : 16;
+ : FIRST_FRAME_MS;
lastFrameTimeRef.current = currentTime;
- setBeads(({ beads, created, destroyed }) => {
- let destroyedCount = 0;
-
- const newBeads = beads
- .map((bead) => {
- const progressIncrement = deltaTime / ANIMATION_DURATION;
- const t = Math.min(
- bead.t + bead.targetT * progressIncrement,
- bead.targetT,
- );
-
- return { ...bead, t };
- })
- .filter((bead, index) => {
- const removeCount = beadDown - destroyed;
- if (bead.t >= bead.targetT && index < removeCount) {
- destroyedCount++;
- return false;
- }
- return true;
- });
-
- return {
- beads: setTargetPositionsWrapper(newBeads),
- created,
- destroyed: destroyed + destroyedCount,
- };
- });
+ commit(
+ advanceBeads(
+ stateRef.current,
+ deltaTime,
+ beadDown,
+ getTForDistanceFromEnd,
+ ),
+ );
animationFrameRef.current = requestAnimationFrame(animate);
- };
+ }
lastFrameTimeRef.current = 0;
animationFrameRef.current = requestAnimationFrame(animate);
@@ -146,22 +157,63 @@ export const JSBeads = ({
animationFrameRef.current = null;
}
};
- }, [beadUp, beadDown, setTargetPositionsWrapper]);
+ }, [beadUp, beadDown]);
return (
<>
- {beads.beads.map((bead, index) => {
- const pos = getPointAtTWrapper(bead.t);
- return (
- <circle
- key={`${beadsKey}-${index}`}
- cx={pos.x}
- cy={pos.y}
- r={BEAD_DIAMETER / 2}
- fill="#8d8d95"
- />
- );
- })}
+ {Array.from({ length: beadCount }, (_, index) => (
+ <circle
+ key={`${beadsKey}-${index}`}
+ ref={(circle) => {
+ circlesRef.current[index] = circle;
+ }}
+ r={BEAD_DIAMETER / 2}
+ fill="#8d8d95"
+ />
+ ))}
</>
);
};
+
+function measurePath(d: string): MeasuredPath {
+ const element = document.createElementNS(
+ "http://www.w3.org/2000/svg",
+ "path",
+ );
+ element.setAttribute("d", d);
+ return { d, element, length: getLengthOfPathInPixels(d) };
+}
+
+function advanceBeads(
+ { beads, created, destroyed }: BeadState,
+ deltaTime: number,
+ beadDown: number,
+ getTForDistanceFromEnd: (distanceFromEnd: number) => number,
+): BeadState {
+ let destroyedCount = 0;
+
+ const newBeads = beads
+ .map((bead) => {
+ const progressIncrement = deltaTime / ANIMATION_DURATION;
+ const t = Math.min(
+ bead.t + bead.targetT * progressIncrement,
+ bead.targetT,
+ );
+
+ return { ...bead, t };
+ })
+ .filter((bead, index) => {
+ const removeCount = beadDown - destroyed;
+ if (bead.t >= bead.targetT && index < removeCount) {
+ destroyedCount++;
+ return false;
+ }
+ return true;
+ });
+
+ return {
+ beads: setTargetPositions(newBeads, BEAD_DIAMETER, getTForDistanceFromEnd),
+ created,
+ destroyed: destroyed + destroyedCount,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/edges/components/__tests__/JSBeads.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/edges/components/__tests__/JSBeads.test.tsx
new file mode 100644
index 0000000000..f3f3bac3ad
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/edges/components/__tests__/JSBeads.test.tsx
@@ -0,0 +1,134 @@
+import { Profiler } from "react";
+import { act, render } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { getLengthOfPathInPixels } from "../../helpers";
+import { JSBeads } from "../JSBeads";
+
+vi.mock("../../helpers", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../helpers")>();
+ return {
+ ...actual,
+ getLengthOfPathInPixels: vi.fn((path: string) =>
+ path === LONG_PATH ? 200 : 100,
+ ),
+ };
+});
+
+const SHORT_PATH = "M0,0 L100,0";
+const LONG_PATH = "M0,0 L200,0";
+const FRAME_MS = 16;
+
+interface Props {
+ beadUp: number;
+ beadDown: number;
+ edgePath?: string;
+}
+
+let commits = 0;
+
+function Beads({ beadUp, beadDown, edgePath = SHORT_PATH }: Props) {
+ return (
+ <svg>
+ <Profiler
+ id="beads"
+ onRender={() => {
+ commits += 1;
+ }}
+ >
+ <JSBeads
+ beadUp={beadUp}
+ beadDown={beadDown}
+ edgePath={edgePath}
+ beadsKey="beads-edge-1"
+ />
+ </Profiler>
+ </svg>
+ );
+}
+
+function circles(container: HTMLElement) {
+ return Array.from(container.querySelectorAll("circle"));
+}
+
+function advance(ms: number) {
+ act(() => {
+ vi.advanceTimersByTime(ms);
+ });
+}
+
+// One act per frame, so React commits each frame's updates as a browser would.
+function advanceFrames(count: number) {
+ for (let frame = 0; frame < count; frame++) advance(FRAME_MS);
+}
+
+beforeEach(() => {
+ commits = 0;
+ vi.mocked(getLengthOfPathInPixels).mockClear();
+ vi.useFakeTimers({
+ toFake: ["requestAnimationFrame", "cancelAnimationFrame"],
+ });
+ // happy-dom has no SVG geometry: a straight path along the x axis.
+ const pathPrototype = Object.getPrototypeOf(
+ document.createElementNS("http://www.w3.org/2000/svg", "path"),
+ );
+ pathPrototype.getPointAtLength = (length: number) => ({ x: length, y: 0 });
+ pathPrototype.getTotalLength = function (this: SVGPathElement) {
+ return this.getAttribute("d") === LONG_PATH ? 200 : 100;
+ };
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("JSBeads", () => {
+ it("moves a bead along the edge and removes it on arrival, without a render per frame", () => {
+ const { container } = render(<Beads beadUp={1} beadDown={1} />);
+ expect(circles(container)).toHaveLength(1);
+
+ advanceFrames(10);
+ const x = Number(circles(container)[0].getAttribute("cx"));
+ expect(x).toBeGreaterThan(0);
+ expect(x).toBeLessThan(90);
+
+ advanceFrames(60);
+ expect(circles(container)).toHaveLength(0);
+ // Mount, bead created, bead removed: not one commit per animation frame.
+ expect(commits).toBeLessThanOrEqual(3);
+ });
+
+ it("parks a bead one diameter before the end until its node takes it", () => {
+ const { container, rerender } = render(<Beads beadUp={1} beadDown={0} />);
+
+ advance(1_000);
+ expect(circles(container)).toHaveLength(1);
+ expect(circles(container)[0].getAttribute("cx")).toBe("90");
+ expect(circles(container)[0].getAttribute("cy")).toBe("0");
+
+ rerender(<Beads beadUp={0} beadDown={0} />);
+ advance(FRAME_MS);
+ expect(circles(container)).toHaveLength(0);
+ });
+
+ it("measures each distinct edge path once and follows the edge when it moves", () => {
+ const { container, rerender } = render(<Beads beadUp={1} beadDown={0} />);
+ advance(1_000);
+
+ rerender(<Beads beadUp={1} beadDown={0} />);
+ rerender(<Beads beadUp={1} beadDown={0} />);
+ expect(getLengthOfPathInPixels).toHaveBeenCalledTimes(1);
+
+ rerender(<Beads beadUp={1} beadDown={0} edgePath={LONG_PATH} />);
+ rerender(<Beads beadUp={1} beadDown={0} edgePath={LONG_PATH} />);
+ expect(getLengthOfPathInPixels).toHaveBeenCalledTimes(2);
+ expect(circles(container)[0].getAttribute("cx")).toBe("180");
+ });
+
+ it("does not measure an edge that carries no beads", () => {
+ const { rerender } = render(<Beads beadUp={0} beadDown={0} />);
+ rerender(<Beads beadUp={0} beadDown={0} edgePath={LONG_PATH} />);
+ advance(FRAME_MS * 5);
+
+ expect(getLengthOfPathInPixels).not.toHaveBeenCalled();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeContainer.tsx
index 00004c3a8a..3057dd4a5d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeContainer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeContainer.tsx
@@ -2,7 +2,6 @@ import { cn } from "@/lib/utils";
import { nodeStyleBasedOnStatus } from "../helpers";
import { useNodeStore } from "@/app/(platform)/build/stores/nodeStore";
-import { useShallow } from "zustand/react/shallow";
import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";
export const NodeContainer = ({
@@ -16,9 +15,7 @@ export const NodeContainer = ({
selected: boolean;
hasErrors?: boolean;
}) => {
- const status = useNodeStore(
- useShallow((state) => state.getNodeStatus(nodeId)),
- );
+ const status = useNodeStore((state) => state.getNodeStatus(nodeId));
return (
<div
className={cn(
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeOutput/components/NodeDataViewer/__tests__/useNodeDataViewer.test.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeOutput/components/NodeDataViewer/__tests__/useNodeDataViewer.test.ts
new file mode 100644
index 0000000000..92098232f5
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeOutput/components/NodeDataViewer/__tests__/useNodeDataViewer.test.ts
@@ -0,0 +1,115 @@
+import { renderHook } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { NodeExecutionResult } from "@/app/api/__generated__/models/nodeExecutionResult";
+import * as helpers from "../../../helpers";
+import { useNodeDataViewer } from "../useNodeDataViewer";
+
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ useToast: () => ({ toast: vi.fn() }),
+}));
+
+vi.mock("../../../helpers", async (importOriginal) => {
+ const actual = await importOriginal<typeof helpers>();
+ return { ...actual, createOutputItems: vi.fn(actual.createOutputItems) };
+});
+
+function createResult(execId: string, output: unknown[]): NodeExecutionResult {
+ return {
+ user_id: "user-1",
+ graph_id: "graph-1",
+ graph_version: 1,
+ graph_exec_id: "graph-exec-1",
+ node_exec_id: execId,
+ node_id: "1",
+ block_id: "block-1",
+ status: "COMPLETED",
+ input_data: {},
+ output_data: { result: output },
+ add_time: new Date("2026-01-05T09:00:00.000Z"),
+ queue_time: new Date("2026-01-05T09:00:00.000Z"),
+ start_time: new Date("2026-01-05T09:00:01.000Z"),
+ end_time: new Date("2026-01-05T09:00:02.000Z"),
+ };
+}
+
+interface Props {
+ data: unknown;
+ executionResults: NodeExecutionResult[];
+}
+
+function renderViewer(initialProps: Props) {
+ return renderHook(
+ ({ data, executionResults }: Props) =>
+ useNodeDataViewer(data, "result", "exec-2", executionResults, "output"),
+ { initialProps },
+ );
+}
+
+beforeEach(() => {
+ vi.mocked(helpers.createOutputItems).mockClear();
+});
+
+describe("useNodeDataViewer", () => {
+ it("builds the items newest execution first", () => {
+ const executionResults = [
+ createResult("exec-1", ["first"]),
+ createResult("exec-2", ["second", "third"]),
+ ];
+ const { result } = renderViewer({
+ data: ["second", "third"],
+ executionResults,
+ });
+
+ expect(result.current.outputItems.map((item) => item.value)).toEqual([
+ "second",
+ "third",
+ ]);
+ expect(result.current.outputItems[0].label).toBe("Result");
+ expect(result.current.groupedExecutions.map((g) => g.execId)).toEqual([
+ "exec-2",
+ "exec-1",
+ ]);
+ expect(result.current.totalGroupedItems).toBe(3);
+ });
+
+ it("does not rebuild the items when its node re-renders with the same data", () => {
+ const data = ["value"];
+ const executionResults = [createResult("exec-1", ["value"])];
+ const { result, rerender } = renderViewer({ data, executionResults });
+ const callsAfterMount = vi.mocked(helpers.createOutputItems).mock.calls
+ .length;
+ const firstItems = result.current.outputItems;
+
+ rerender({ data, executionResults });
+ rerender({ data, executionResults });
+
+ expect(vi.mocked(helpers.createOutputItems).mock.calls.length).toBe(
+ callsAfterMount,
+ );
+ expect(result.current.outputItems).toBe(firstItems);
+ });
+
+ it("rebuilds the items when new output arrives", () => {
+ const { result, rerender } = renderViewer({
+ data: ["first"],
+ executionResults: [createResult("exec-1", ["first"])],
+ });
+
+ rerender({
+ data: ["first", "second"],
+ executionResults: [
+ createResult("exec-1", ["first"]),
+ createResult("exec-2", ["second"]),
+ ],
+ });
+
+ expect(result.current.outputItems.map((item) => item.value)).toEqual([
+ "first",
+ "second",
+ ]);
+ expect(result.current.groupedExecutions.map((g) => g.execId)).toEqual([
+ "exec-2",
+ "exec-1",
+ ]);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeOutput/components/NodeDataViewer/useNodeDataViewer.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeOutput/components/NodeDataViewer/useNodeDataViewer.ts
index 818d1266c1..d9bb0537a6 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeOutput/components/NodeDataViewer/useNodeDataViewer.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/CustomNode/components/NodeOutput/components/NodeDataViewer/useNodeDataViewer.ts
@@ -1,7 +1,7 @@
import { downloadOutputs } from "@/components/contextual/OutputRenderers/utils/download";
import { useToast } from "@/components/molecules/Toast/use-toast";
import { beautifyString } from "@/lib/utils";
-import { useState } from "react";
+import { useMemo, useState } from "react";
import type { NodeExecutionResult } from "@/app/api/__generated__/models/nodeExecutionResult";
import {
NodeDataType,
@@ -27,39 +27,28 @@ export const useNodeDataViewer = (
const [copiedIndex, setCopiedIndex] = useState<number | null>(null);
const [copiedKey, setCopiedKey] = useState<string | null>(null);
- const dataArray = Array.isArray(data) ? data : [data];
-
- const outputItems =
- !dataArray || dataArray.length === 0
- ? []
- : createOutputItems(dataArray).map((item, index) => ({
- ...item,
- label: index === 0 ? beautifyString(pinName) : "",
- }));
-
- const groupedExecutions =
- !executionResults || executionResults.length === 0
- ? []
- : [...executionResults].reverse().map((result) => {
- const rawData = getExecutionData(
- result,
- dataType || "output",
- pinName,
- );
- let dataArray: unknown[];
- if (dataType === "input") {
- dataArray =
- rawData !== undefined && rawData !== null ? [rawData] : [];
- } else {
- dataArray = normalizeToArray(rawData);
- }
-
- const outputItems = createOutputItems(dataArray);
- return {
- execId: result.node_exec_id,
- outputItems,
- };
- });
+ // Every node with output renders up to three closed viewers, and each one
+ // re-renders with its node; only rebuild the items when their inputs change.
+ const dataArray = useMemo(
+ () => (Array.isArray(data) ? data : [data]),
+ [data],
+ );
+
+ const outputItems = useMemo(
+ () =>
+ dataArray.length === 0
+ ? []
+ : createOutputItems(dataArray).map((item, index) => ({
+ ...item,
+ label: index === 0 ? beautifyString(pinName) : "",
+ })),
+ [dataArray, pinName],
+ );
+
+ const groupedExecutions = useMemo(
+ () => groupExecutions(executionResults, pinName, dataType),
+ [executionResults, pinName, dataType],
+ );
const totalGroupedItems = groupedExecutions.reduce(
(total, execution) => total + execution.outputItems.length,
@@ -163,3 +152,25 @@ export const useNodeDataViewer = (
copiedKey,
};
};
+
+function groupExecutions(
+ executionResults: NodeExecutionResult[] | undefined,
+ pinName: string,
+ dataType: NodeDataType | undefined,
+): GroupedExecution[] {
+ if (!executionResults || executionResults.length === 0) return [];
+ return [...executionResults].reverse().map((result) => {
+ const rawData = getExecutionData(result, dataType || "output", pinName);
+ let dataArray: unknown[];
+ if (dataType === "input") {
+ dataArray = rawData !== undefined && rawData !== null ? [rawData] : [];
+ } else {
+ dataArray = normalizeToArray(rawData);
+ }
+
+ return {
+ execId: result.node_exec_id,
+ outputItems: createOutputItems(dataArray),
+ };
+ });
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/stores/nodeStore.ts b/autogpt_platform/frontend/src/app/(platform)/build/stores/nodeStore.ts
index 086fa7f70e..a96e66d8dc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/stores/nodeStore.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/build/stores/nodeStore.ts
@@ -128,7 +128,11 @@ type NodeStore = {
export const useNodeStore = create<NodeStore>((set, get) => ({
nodes: [],
- setNodes: (nodes) => set({ nodes }),
+ setNodes: (nodes) => {
+ // The caller may have changed the array it passes in since it was indexed.
+ nodeIndexes.delete(nodes);
+ set({ nodes });
+ },
nodeCounter: 0,
setNodeCounter: (nodeCounter) => set({ nodeCounter }),
nodeAdvancedStates: {},
@@ -289,9 +293,7 @@ export const useNodeStore = create<NodeStore>((set, get) => ({
});
},
getHardCodedValues: (nodeId: string) => {
- return (
- get().nodes.find((n) => n.id === nodeId)?.data?.hardcodedValues || {}
- );
+ return findNodeById(get().nodes, nodeId)?.data?.hardcodedValues || {};
},
convertCustomNodeToBackendNode: (node: CustomNode) => {
return {
@@ -318,7 +320,7 @@ export const useNodeStore = create<NodeStore>((set, get) => ({
set((state) => applyExecutionUpdate(state, nodeId, { status }));
},
getNodeStatus: (nodeId: string) => {
- return get().nodes.find((n) => n.id === nodeId)?.data?.status;
+ return findNodeById(get().nodes, nodeId)?.data?.status;
},
cleanNodesStatuses: () => {
@@ -340,9 +342,7 @@ export const useNodeStore = create<NodeStore>((set, get) => ({
useEdgeStore.getState().updateEdgeBeads(nodeId, result);
},
getNodeExecutionResults: (nodeId: string) => {
- return (
- get().nodes.find((n) => n.id === nodeId)?.data?.nodeExecutionResults || []
- );
+ return findNodeById(get().nodes, nodeId)?.data?.nodeExecutionResults || [];
},
getLatestNodeInputData: (nodeId: string) => {
return get().latestNodeInputData[nodeId];
@@ -358,8 +358,7 @@ export const useNodeStore = create<NodeStore>((set, get) => ({
},
getLatestNodeExecutionResult: (nodeId: string) => {
const results =
- get().nodes.find((n) => n.id === nodeId)?.data?.nodeExecutionResults ||
- [];
+ findNodeById(get().nodes, nodeId)?.data?.nodeExecutionResults || [];
return results.length > 0 ? results[results.length - 1] : undefined;
},
clearAllNodeExecutionResults: () => {
@@ -406,7 +405,7 @@ export const useNodeStore = create<NodeStore>((set, get) => ({
},
getNodeErrors: (nodeId: string) => {
- return get().nodes.find((n) => n.id === nodeId)?.data?.errors;
+ return findNodeById(get().nodes, nodeId)?.data?.errors;
},
setNodeErrorsForBackendId: (
@@ -585,6 +584,27 @@ export const useNodeStore = create<NodeStore>((set, get) => ({
},
}));
+const nodeIndexes = new WeakMap<CustomNode[], Map<string, CustomNode>>();
+
+/**
+ * O(1) lookup by id. Every node subscribes with a by-id selector, so a `find`
+ * per selector costs O(nodes²) per store update; the index is built once per
+ * `nodes` array instead. Store writes always replace the array, never mutate
+ * it, and `setNodes` drops the index of the array it is given, so an index
+ * can never go stale. The first match wins, as with `find`.
+ */
+function findNodeById(nodes: CustomNode[], nodeId: string) {
+ let index = nodeIndexes.get(nodes);
+ if (!index) {
+ index = new Map();
+ for (const node of nodes) {
+ if (!index.has(node.id)) index.set(node.id, node);
+ }
+ nodeIndexes.set(nodes, index);
+ }
+ return index.get(nodeId);
+}
+
/**
* Applies a status and/or an execution result to one node in a single write.
* Returns `state` itself when nothing changes, so subscribers are not notified.
diff --git a/docs/engineering/frontend-perf-baseline.md b/docs/engineering/frontend-perf-baseline.md
index 2ca24f14da..e1319548f8 100644
--- a/docs/engineering/frontend-perf-baseline.md
+++ b/docs/engineering/frontend-perf-baseline.md
@@ -629,3 +629,52 @@ Added with the scenario (SECRT-2999): `dev` at `6d793e53d`, same machine type, 1
| `PopperAnchor props:children` | 20,955 |
| `PopperProvider props:children` | 20,955 |
| `TooltipProvider props:children` | 20,949 |
+
+## builder-run-beads · baseline — median of 5 runs
+
+Added with SECRT-3009: `dev` app code at `6d793e53d` on a similar 16 GB cloud sandbox, 2 warm-ups and 5 saved runs. On this code every bead re-renders `JSBeads` once per animation frame (about 150 `JSBeads state#0` renders in the window); the heavy commits are the nodes re-rendering on each new execution.
+
+
+| metric | median | range | spread |
+| --- | --- | --- | --- |
+| commits | 84 | 79 – 85 | 7.1% |
+| total renders | 54,037 | 53,947 – 54,078 | 0.2% |
+| renders per commit | 642.7 | 636.2 – 684.0 | 7.4% |
+| max renders in one commit | 7,285 | 7,285 – 7,285 | 0.0% |
+| script time (ms) | 2,332 | 2,142 – 2,505 | 15.6% |
+| task time (ms) | 2,791 | 2,567 – 3,057 | 17.6% |
+| layout time (ms) | 39 | 38 – 43 | 13.0% |
+| style recalc time (ms) | 31 | 29 – 32 | 10.9% |
+| long tasks (≥ 50 ms) | 16 | 11 – 17 | 37.5% |
+| long task total (ms) | 2,274 | 2,069 – 2,613 | 23.9% |
+| heap used after GC (MB) | 99.4 | 97.1 – 103.1 | 6.0% |
+
+**Top components (median renders)**
+
+| name | renders |
+| --- | --- |
+| `Text` | 2,954 |
+| `TooltipProvider` | 2,819 |
+| `HugeiconsIcon` | 2,675 |
+| `Icon` | 2,675 |
+| `Primitive.div` | 2,411 |
+| `Tooltip` | 2,322 |
+| `TooltipContent` | 2,322 |
+| `Presence` | 1,561 |
+| `SelectItem` | 1,512 |
+| `Primitive.div.Slot` | 1,427 |
+
+**Top render causes (median renders)**
+
+| name | renders |
+| --- | --- |
+| `TooltipProvider props:children` | 2,759 |
+| `HugeiconsIcon parent-same-props<-Icon` | 2,323 |
+| `Tooltip props:children` | 2,282 |
+| `SelectItem props:onMouseDown,children` | 1,512 |
+| `Presence props:children` | 1,461 |
+| `Primitive.div props:children` | 1,437 |
+| `Primitive.div.Slot props:children` | 1,407 |
+| `Primitive.div.SlotClone props:children` | 1,407 |
+| `Popper props:children` | 1,269 |
+| `PopperAnchor props:children` | 1,269 |
diff --git a/docs/engineering/frontend-perf-measurement.md b/docs/engineering/frontend-perf-measurement.md
index b723c668e5..b0cc20db55 100644
--- a/docs/engineering/frontend-perf-measurement.md
+++ b/docs/engineering/frontend-perf-measurement.md
@@ -125,6 +125,7 @@ Names come from the component function. Third-party code bundled already minifie
| `builder-run-events` | Open the same 50-node workflow with its RUNNING run; the harness answers the websocket subscribe for that run itself | 40 node execution events over the websocket, one every 50 ms: the 10 unfinished nodes go RUNNING then COMPLETED, each event sent twice. The execution GET returns what has been sent so far, as the backend would | 2 s after the last event |
| `copilot-tool-wait` | Open the 200-message chat, send "go", and wait until the reply's one tool call shows "Running Perf lookup…". The reply then sends only `: heartbeat` comments, so the turn stays on that tool | Nothing | 20 s |
| `copilot-resize-drag` | Open the 200-message chat and click "Open files" so the files panel docks on the right | Drag the panel's resize handle 120 px wider with 60 pointer moves over 1 s | 1 s after the drop |
+| `builder-run-beads` | Open the same 50-node workflow with its RUNNING run; the harness answers the websocket subscribe for that run itself | 10 new node executions over the websocket (a second, finished run of nodes 30 to 39 with new `node_exec_id`s), one every 150 ms, so each edge into one of those StoreValue nodes gets a new bead that travels the edge and is removed on arrival | 2 s after the last event |
Each scenario's `readyWhen` field says exactly what setup waits for before the window opens. Most wait for the page's own content, then for network idle (at most 15 s, because some pages poll), then one more second.