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.

fix(frontend/builder): prevent appliedActionKeys desync after global undo

Zamil Majdy907518bfc3ec
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/useBuilderChatPanel.test.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/useBuilderChatPanel.test.ts
index 93babeb6d9..ae5143ebd7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/useBuilderChatPanel.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/__tests__/useBuilderChatPanel.test.ts
@@ -10,22 +10,17 @@ vi.mock("zustand/react/shallow", () => ({
const mockNodes: unknown[] = [];
const mockEdges: unknown[] = [];
-const mockUpdateNodeData = vi.fn();
const mockSetNodes = vi.fn();
-const mockAddEdge = vi.fn();
const mockSetEdges = vi.fn();
-const mockRemoveEdge = vi.fn();
vi.mock("../../../stores/nodeStore", () => {
const useNodeStore = (selector: (s: unknown) => unknown) =>
selector({
nodes: mockNodes,
- updateNodeData: mockUpdateNodeData,
setNodes: mockSetNodes,
});
useNodeStore.getState = () => ({
nodes: mockNodes,
- updateNodeData: mockUpdateNodeData,
setNodes: mockSetNodes,
});
return { useNodeStore };
@@ -35,15 +30,11 @@ vi.mock("../../../stores/edgeStore", () => {
const useEdgeStore = (selector: (s: unknown) => unknown) =>
selector({
edges: mockEdges,
- addEdge: mockAddEdge,
setEdges: mockSetEdges,
- removeEdge: mockRemoveEdge,
});
useEdgeStore.getState = () => ({
edges: mockEdges,
- addEdge: mockAddEdge,
setEdges: mockSetEdges,
- removeEdge: mockRemoveEdge,
});
return { useEdgeStore };
});
@@ -112,11 +103,8 @@ beforeEach(() => {
mockEdges.length = 0;
mockChatMessages = [];
mockChatStatus = "ready";
- mockUpdateNodeData.mockClear();
mockSetNodes.mockClear();
- mockAddEdge.mockClear();
mockSetEdges.mockClear();
- mockRemoveEdge.mockClear();
mockPostV2CreateSession.mockClear();
mockInvalidateQueries.mockClear();
mockSendMessage.mockClear();
@@ -353,7 +341,7 @@ describe("useBuilderChatPanel – apply does not trigger cache refetch", () => {
});
describe("useBuilderChatPanel – handleApplyAction", () => {
- it("update_node_input: calls updateNodeData with merged hardcodedValues", () => {
+ it("update_node_input: calls setNodes with merged hardcodedValues (bypasses history)", () => {
mockNodes.push({
id: "node-1",
data: { hardcodedValues: { existing: "value" } },
@@ -369,9 +357,12 @@ describe("useBuilderChatPanel – handleApplyAction", () => {
});
});
- expect(mockUpdateNodeData).toHaveBeenCalledWith("node-1", {
- hardcodedValues: { existing: "value", query: "AI news" },
- });
+ expect(mockSetNodes).toHaveBeenCalledWith([
+ {
+ id: "node-1",
+ data: { hardcodedValues: { existing: "value", query: "AI news" } },
+ },
+ ]);
});
it("update_node_input: shows toast when node not found", () => {
@@ -386,13 +377,13 @@ describe("useBuilderChatPanel – handleApplyAction", () => {
});
});
- expect(mockUpdateNodeData).not.toHaveBeenCalled();
+ expect(mockSetNodes).not.toHaveBeenCalled();
expect(mockToast).toHaveBeenCalledWith(
expect.objectContaining({ variant: "destructive" }),
);
});
- it("connect_nodes: calls addEdge when both nodes exist", () => {
+ it("connect_nodes: calls setEdges with new edge appended (bypasses history)", () => {
mockNodes.push({ id: "src", data: {} }, { id: "tgt", data: {} });
const { result } = renderHook(() => useBuilderChatPanel());
@@ -406,17 +397,21 @@ describe("useBuilderChatPanel – handleApplyAction", () => {
});
});
- expect(mockAddEdge).toHaveBeenCalledWith({
- id: "src:output->tgt:input",
- source: "src",
- target: "tgt",
- sourceHandle: "output",
- targetHandle: "input",
- type: "custom",
- });
+ expect(mockSetEdges).toHaveBeenCalledWith(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: "src:output->tgt:input",
+ source: "src",
+ target: "tgt",
+ sourceHandle: "output",
+ targetHandle: "input",
+ type: "custom",
+ }),
+ ]),
+ );
});
- it("connect_nodes: shows toast and does NOT call addEdge when source node is missing", () => {
+ it("connect_nodes: shows toast and does NOT call setEdges when source node is missing", () => {
mockNodes.push({ id: "tgt", data: {} });
const { result } = renderHook(() => useBuilderChatPanel());
@@ -430,13 +425,13 @@ describe("useBuilderChatPanel – handleApplyAction", () => {
});
});
- expect(mockAddEdge).not.toHaveBeenCalled();
+ expect(mockSetEdges).not.toHaveBeenCalled();
expect(mockToast).toHaveBeenCalledWith(
expect.objectContaining({ variant: "destructive" }),
);
});
- it("connect_nodes: shows toast and does NOT call addEdge when target node is missing", () => {
+ it("connect_nodes: shows toast and does NOT call setEdges when target node is missing", () => {
mockNodes.push({ id: "src", data: {} });
const { result } = renderHook(() => useBuilderChatPanel());
@@ -450,7 +445,7 @@ describe("useBuilderChatPanel – handleApplyAction", () => {
});
});
- expect(mockAddEdge).not.toHaveBeenCalled();
+ expect(mockSetEdges).not.toHaveBeenCalled();
expect(mockToast).toHaveBeenCalledWith(
expect.objectContaining({ variant: "destructive" }),
);
@@ -475,7 +470,7 @@ describe("useBuilderChatPanel – handleApplyAction", () => {
});
});
- expect(mockUpdateNodeData).not.toHaveBeenCalled();
+ expect(mockSetNodes).not.toHaveBeenCalled();
expect(mockToast).toHaveBeenCalledWith(
expect.objectContaining({ variant: "destructive" }),
);
@@ -500,9 +495,15 @@ describe("useBuilderChatPanel – handleApplyAction", () => {
});
});
- expect(mockUpdateNodeData).toHaveBeenCalledWith("node-1", {
- hardcodedValues: { query: "AI news" },
- });
+ expect(mockSetNodes).toHaveBeenCalledWith([
+ {
+ id: "node-1",
+ data: {
+ hardcodedValues: { query: "AI news" },
+ inputSchema: { properties: { query: {} } },
+ },
+ },
+ ]);
});
it("connect_nodes: rejects sourceHandle not in outputSchema", () => {
@@ -522,7 +523,7 @@ describe("useBuilderChatPanel – handleApplyAction", () => {
});
});
- expect(mockAddEdge).not.toHaveBeenCalled();
+ expect(mockSetEdges).not.toHaveBeenCalled();
expect(mockToast).toHaveBeenCalledWith(
expect.objectContaining({ variant: "destructive" }),
);
@@ -545,13 +546,13 @@ describe("useBuilderChatPanel – handleApplyAction", () => {
});
});
- expect(mockAddEdge).not.toHaveBeenCalled();
+ expect(mockSetEdges).not.toHaveBeenCalled();
expect(mockToast).toHaveBeenCalledWith(
expect.objectContaining({ variant: "destructive" }),
);
});
- it("connect_nodes: calls addEdge when both handles are valid according to schemas", () => {
+ it("connect_nodes: calls setEdges when both handles are valid according to schemas", () => {
mockNodes.push(
{ id: "src", data: { outputSchema: { properties: { result: {} } } } },
{ id: "tgt", data: { inputSchema: { properties: { input: {} } } } },
@@ -568,14 +569,18 @@ describe("useBuilderChatPanel – handleApplyAction", () => {
});
});
- expect(mockAddEdge).toHaveBeenCalledWith({
- id: "src:result->tgt:input",
- source: "src",
- target: "tgt",
- sourceHandle: "result",
- targetHandle: "input",
- type: "custom",
- });
+ expect(mockSetEdges).toHaveBeenCalledWith(
+ expect.arrayContaining([
+ expect.objectContaining({
+ id: "src:result->tgt:input",
+ source: "src",
+ target: "tgt",
+ sourceHandle: "result",
+ targetHandle: "input",
+ type: "custom",
+ }),
+ ]),
+ );
});
it("adds action key to appliedActionKeys after successful apply", () => {
@@ -618,8 +623,7 @@ describe("useBuilderChatPanel – undo", () => {
expect(result.current.undoStack).toHaveLength(1);
- // Clear call history so we can verify undo only uses setNodes (not updateNodeData)
- mockUpdateNodeData.mockClear();
+ // Clear call history so we can verify undo uses setNodes with the original snapshot
mockSetNodes.mockClear();
act(() => {
@@ -628,8 +632,6 @@ describe("useBuilderChatPanel – undo", () => {
// setNodes is called with the captured snapshot to bypass the global history store
expect(mockSetNodes).toHaveBeenCalledWith([initialNode]);
- // updateNodeData must NOT be called during undo to avoid pushing to history store
- expect(mockUpdateNodeData).not.toHaveBeenCalled();
expect(result.current.undoStack).toHaveLength(0);
});
@@ -673,16 +675,17 @@ describe("useBuilderChatPanel – undo", () => {
});
});
- expect(mockAddEdge).toHaveBeenCalledOnce();
+ expect(mockSetEdges).toHaveBeenCalledOnce();
expect(result.current.undoStack).toHaveLength(1);
+ mockSetEdges.mockClear();
+
act(() => {
result.current.handleUndoLastAction();
});
- // setEdges is called with the captured snapshot to bypass the global history store
+ // setEdges is called with the original captured snapshot to bypass the global history store
expect(mockSetEdges).toHaveBeenCalledWith([initialEdge]);
- expect(mockRemoveEdge).not.toHaveBeenCalled();
expect(result.current.undoStack).toHaveLength(0);
expect(result.current.appliedActionKeys.size).toBe(0);
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/helpers.ts
index fc1593028e..d4f31e1a0b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/helpers.ts
@@ -5,6 +5,10 @@ import type { CustomEdge } from "../FlowEditor/edges/CustomEdge";
const MAX_NODES = 100;
/** Maximum edges serialized into the AI context to prevent token overruns. */
const MAX_EDGES = 200;
+/** Maximum characters of a node description included in the seed prompt. */
+const MAX_DESC_CHARS = 500;
+/** Matches fenced JSON code blocks in AI responses. Module-scoped to avoid recompilation. */
+const JSON_BLOCK_REGEX = /```(?:json)?\s*\n?([\s\S]*?)\n?```/g;
/** Escapes XML special characters in user-controlled strings before embedding in prompts. */
function sanitizeForXml(s: string): string {
@@ -58,9 +62,8 @@ export function serializeGraphForChat(
const visibleNodes = nodes.slice(0, MAX_NODES);
const nodeLines = visibleNodes.map((n) => {
const name = sanitizeForXml(getNodeDisplayName(n, ""));
- const desc = n.data.description
- ? ` — ${sanitizeForXml(n.data.description)}`
- : "";
+ const rawDesc = n.data.description?.slice(0, MAX_DESC_CHARS) ?? "";
+ const desc = rawDesc ? ` — ${sanitizeForXml(rawDesc)}` : "";
return `- Node ${n.id}: "${name}"${desc}`;
});
@@ -183,10 +186,10 @@ export function extractTextFromParts(
*/
export function parseGraphActions(text: string): GraphAction[] {
const actions: GraphAction[] = [];
- const jsonBlockRegex = /```(?:json)?\s*\n?([\s\S]*?)\n?```/g;
+ JSON_BLOCK_REGEX.lastIndex = 0;
let match: RegExpExecArray | null;
- while ((match = jsonBlockRegex.exec(text)) !== null) {
+ while ((match = JSON_BLOCK_REGEX.exec(text)) !== null) {
try {
const parsed = JSON.parse(match[1]) as unknown;
if (
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/useBuilderChatPanel.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/useBuilderChatPanel.ts
index 64582e9213..9b11da363f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/useBuilderChatPanel.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderChatPanel/useBuilderChatPanel.ts
@@ -64,10 +64,8 @@ export function useBuilderChatPanel({
const nodes = useNodeStore(useShallow((s) => s.nodes));
const edges = useEdgeStore(useShallow((s) => s.edges));
- const updateNodeData = useNodeStore(useShallow((s) => s.updateNodeData));
- const setNodes = useNodeStore(useShallow((s) => s.setNodes));
- const addEdge = useEdgeStore(useShallow((s) => s.addEdge));
- const setEdges = useEdgeStore(useShallow((s) => s.setEdges));
+ const setNodes = useNodeStore((s) => s.setNodes);
+ const setEdges = useEdgeStore((s) => s.setEdges);
// Reset session and seed-sent guard when the user navigates to a different
// graph so the new graph's context is sent to the AI on next open.
@@ -267,11 +265,25 @@ export function useBuilderChatPanel({
});
return;
}
- // Capture a full nodes snapshot before mutating. The restore function
- // uses setNodes (not updateNodeData) to bypass the history store —
- // otherwise the global Ctrl+Z undo would conflict with the chat panel's
- // own undo stack by re-applying the just-undone change.
+ // Capture a full nodes snapshot before mutating. Both the apply and the
+ // restore use setNodes (not updateNodeData) to bypass the global history
+ // store — this keeps chat-panel changes completely separate from Ctrl+Z,
+ // preventing the "Applied" badge from going stale after a global undo.
const prevNodes = useNodeStore.getState().nodes;
+ const nextNodes = prevNodes.map((n) =>
+ n.id === action.nodeId
+ ? {
+ ...n,
+ data: {
+ ...n.data,
+ hardcodedValues: {
+ ...n.data.hardcodedValues,
+ [action.key]: action.value,
+ },
+ },
+ }
+ : n,
+ );
const key = getActionKey(action);
setUndoStack((prev) => [
...prev,
@@ -287,12 +299,7 @@ export function useBuilderChatPanel({
},
},
]);
- updateNodeData(action.nodeId, {
- hardcodedValues: {
- ...node.data.hardcodedValues,
- [action.key]: action.value,
- },
- });
+ setNodes(nextNodes);
} else if (action.type === "connect_nodes") {
const sourceNode = nodes.find((n) => n.id === action.source);
const targetNode = nodes.find((n) => n.id === action.target);
@@ -324,9 +331,9 @@ export function useBuilderChatPanel({
return;
}
const edgeId = `${action.source}:${action.sourceHandle}->${action.target}:${action.targetHandle}`;
- // Capture a full edges snapshot before mutating. The restore function
- // uses setEdges (not removeEdge) to bypass the history store —
- // otherwise the global Ctrl+Z undo would re-add the just-removed edge.
+ // Capture a full edges snapshot before mutating. Both the apply and the
+ // restore use setEdges (not addEdge/removeEdge) to bypass the global
+ // history store — keeps chat-panel changes separate from Ctrl+Z.
const prevEdges = useEdgeStore.getState().edges;
const key = getActionKey(action);
setUndoStack((prev) => [
@@ -343,14 +350,17 @@ export function useBuilderChatPanel({
},
},
]);
- addEdge({
- id: edgeId,
- source: action.source,
- target: action.target,
- sourceHandle: action.sourceHandle,
- targetHandle: action.targetHandle,
- type: "custom",
- });
+ setEdges([
+ ...prevEdges,
+ {
+ id: edgeId,
+ source: action.source,
+ target: action.target,
+ sourceHandle: action.sourceHandle,
+ targetHandle: action.targetHandle,
+ type: "custom",
+ },
+ ]);
} else {
// Exhaustiveness guard — TypeScript ensures all GraphAction types are handled above.
const _: never = action;