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): run freshly-saved graph version on save-and-run (#13482)

Abhimanyu Yadav31e00ef224f5
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/__tests__/RunGraph.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/RunGraph.test.tsx
index 9337ad872f..0388c04746 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/__tests__/RunGraph.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/RunGraph.test.tsx
@@ -36,6 +36,7 @@ function createMockReturnValue(
isExecutingGraph: false,
isTerminatingGraph: false,
isSaving: false,
+ runTarget: null,
...overrides,
};
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useSaveGraph.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useSaveGraph.test.tsx
new file mode 100644
index 0000000000..4e3c1fc9c8
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useSaveGraph.test.tsx
@@ -0,0 +1,140 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mockToast = vi.fn();
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ useToast: () => ({ toast: mockToast }),
+}));
+
+const mockSetQueryStates = vi.fn();
+vi.mock("nuqs", () => ({
+ parseAsString: {},
+ parseAsInteger: {},
+ useQueryStates: vi.fn(() => [
+ { flowID: "graph-1", flowVersion: 1 },
+ mockSetQueryStates,
+ ]),
+}));
+
+// The graph currently loaded for the flow — swapped per test to exercise the
+// update, create, and no-change branches.
+let mockCurrentGraph: unknown;
+const mockCreate = vi.fn();
+const mockUpdate = vi.fn();
+vi.mock("@/app/api/__generated__/endpoints/graphs/graphs", () => ({
+ useGetV1GetSpecificGraph: () => ({ data: mockCurrentGraph }),
+ usePostV1CreateNewGraph: () => ({
+ mutateAsync: mockCreate,
+ isPending: false,
+ }),
+ usePutV1UpdateGraphVersion: () => ({
+ mutateAsync: mockUpdate,
+ isPending: false,
+ }),
+}));
+
+vi.mock("@/app/(platform)/build/stores/nodeStore", () => ({
+ useNodeStore: { getState: () => ({ getBackendNodes: () => [] }) },
+}));
+vi.mock("@/app/(platform)/build/stores/edgeStore", () => ({
+ useEdgeStore: { getState: () => ({ getBackendLinks: () => [] }) },
+}));
+
+const mockSetGraphSchemas = vi.fn();
+vi.mock("@/app/(platform)/build/stores/graphStore", () => ({
+ useGraphStore: (selector: (s: { setGraphSchemas: unknown }) => unknown) =>
+ selector({ setGraphSchemas: mockSetGraphSchemas }),
+}));
+
+let mockEquivalent = false;
+vi.mock(
+ "@/app/(platform)/build/components/NewControlPanel/NewSaveControl/helpers",
+ () => ({
+ graphsEquivalent: () => mockEquivalent,
+ }),
+);
+
+vi.mock("@/services/builder-draft/draft-service", () => ({
+ draftService: { deleteDraft: vi.fn().mockResolvedValue(undefined) },
+ getTempFlowId: () => null,
+ clearTempFlowId: vi.fn(),
+}));
+
+import { useSaveGraph } from "../hooks/useSaveGraph";
+
+describe("useSaveGraph", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockCurrentGraph = undefined;
+ mockEquivalent = false;
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("returns the updated graph model when saving changes to an existing graph", async () => {
+ mockCurrentGraph = { id: "graph-1", name: "Agent", version: 1 };
+ const updated = {
+ id: "graph-1",
+ version: 2,
+ input_schema: { properties: {} },
+ credentials_input_schema: { properties: {} },
+ output_schema: { properties: {} },
+ };
+ mockUpdate.mockResolvedValue({ data: updated });
+
+ const { result } = renderHook(() => useSaveGraph({ showToast: false }));
+
+ let returned: unknown;
+ await act(async () => {
+ returned = await result.current.saveGraph();
+ });
+
+ expect(mockUpdate).toHaveBeenCalledWith({
+ graphId: "graph-1",
+ data: expect.objectContaining({ id: "graph-1" }),
+ });
+ expect(mockSetGraphSchemas).toHaveBeenCalled();
+ expect(returned).toBe(updated);
+ });
+
+ it("returns the created graph model when there is no existing graph", async () => {
+ mockCurrentGraph = undefined;
+ const created = {
+ id: "new-graph",
+ version: 1,
+ input_schema: { properties: {} },
+ credentials_input_schema: { properties: {} },
+ output_schema: { properties: {} },
+ };
+ mockCreate.mockResolvedValue({ data: created });
+
+ const { result } = renderHook(() => useSaveGraph({ showToast: false }));
+
+ let returned: unknown;
+ await act(async () => {
+ returned = await result.current.saveGraph();
+ });
+
+ expect(mockCreate).toHaveBeenCalled();
+ expect(mockUpdate).not.toHaveBeenCalled();
+ expect(returned).toBe(created);
+ });
+
+ it("returns the current graph without saving when nothing changed", async () => {
+ mockCurrentGraph = { id: "graph-1", name: "Agent", version: 1 };
+ mockEquivalent = true;
+
+ const { result } = renderHook(() => useSaveGraph({ showToast: false }));
+
+ let returned: unknown;
+ await act(async () => {
+ returned = await result.current.saveGraph();
+ });
+
+ expect(mockUpdate).not.toHaveBeenCalled();
+ expect(mockCreate).not.toHaveBeenCalled();
+ expect(returned).toBe(mockCurrentGraph);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunGraph/RunGraph.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunGraph/RunGraph.tsx
index 99e0693083..1fee22f6eb 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunGraph/RunGraph.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunGraph/RunGraph.tsx
@@ -25,6 +25,7 @@ export const RunGraph = ({ flowID }: { flowID: string | null }) => {
isExecutingGraph,
isTerminatingGraph,
isSaving,
+ runTarget,
} = useRunGraph();
const isGraphRunning = useGraphStore(
useShallow((state) => state.isGraphRunning),
@@ -109,6 +110,8 @@ export const RunGraph = ({ flowID }: { flowID: string | null }) => {
isOpen={openRunInputDialog}
setIsOpen={setOpenRunInputDialog}
purpose="run"
+ graphID={runTarget?.graphID}
+ graphVersion={runTarget?.graphVersion}
/>
</>
);
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunGraph/useRunGraph.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunGraph/useRunGraph.test.tsx
new file mode 100644
index 0000000000..f5cefeb2af
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunGraph/useRunGraph.test.tsx
@@ -0,0 +1,118 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// Stale query state: the URL still points at the version that existed BEFORE
+// this run's save (flowVersion: 1). The save below bumps it to version 2.
+const mockSetQueryStates = vi.fn();
+vi.mock("nuqs", () => ({
+ parseAsString: {},
+ parseAsInteger: {},
+ useQueryStates: vi.fn(() => [
+ { flowID: "graph-1", flowVersion: 1, flowExecutionID: null },
+ mockSetQueryStates,
+ ]),
+}));
+
+const mockToast = vi.fn();
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ useToast: () => ({ toast: mockToast }),
+}));
+
+// saveGraph returns the freshly-saved graph model (new version) — mirroring the
+// real hook. The regression is that the run must use THIS version, not the
+// stale closure value.
+const mockSaveGraph = vi.fn();
+vi.mock("@/app/(platform)/build/hooks/useSaveGraph", () => ({
+ useSaveGraph: () => ({ saveGraph: mockSaveGraph, isSaving: false }),
+}));
+
+const mockExecuteGraph = vi.fn();
+const mockStopGraph = vi.fn();
+vi.mock("@/app/api/__generated__/endpoints/graphs/graphs", () => ({
+ usePostV1ExecuteGraphAgent: () => ({
+ mutateAsync: mockExecuteGraph,
+ isPending: false,
+ }),
+ usePostV1StopGraphExecution: () => ({
+ mutateAsync: mockStopGraph,
+ isPending: false,
+ }),
+}));
+
+const graphState = {
+ hasInputs: () => false,
+ hasCredentials: () => false,
+ setIsGraphRunning: vi.fn(),
+};
+vi.mock("@/app/(platform)/build/stores/graphStore", () => ({
+ useGraphStore: (selector: (s: typeof graphState) => unknown) =>
+ selector(graphState),
+}));
+
+const nodeState = {
+ setNodeErrorsForBackendId: vi.fn(),
+ clearAllNodeErrors: vi.fn(),
+ cleanNodesStatuses: vi.fn(),
+ clearAllNodeExecutionResults: vi.fn(),
+ nodes: [],
+ updateNodeErrors: vi.fn(),
+};
+vi.mock("@/app/(platform)/build/stores/nodeStore", () => ({
+ useNodeStore: Object.assign(
+ (selector: (s: typeof nodeState) => unknown) => selector(nodeState),
+ { getState: () => nodeState },
+ ),
+}));
+
+const tutorialState = {
+ forceOpenRunInputDialog: false,
+ setForceOpenRunInputDialog: vi.fn(),
+};
+vi.mock("@/app/(platform)/build/stores/tutorialStore", () => ({
+ useTutorialStore: (selector: (s: typeof tutorialState) => unknown) =>
+ selector(tutorialState),
+}));
+
+import { useRunGraph } from "./useRunGraph";
+
+describe("useRunGraph", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("runs the version returned by the save, not the stale closure version", async () => {
+ // Save creates a new version (2) even though the closure still holds v1.
+ mockSaveGraph.mockResolvedValue({ id: "graph-1", version: 2 });
+
+ const { result } = renderHook(() => useRunGraph());
+
+ await act(async () => {
+ await result.current.handleRunGraph();
+ });
+
+ expect(mockExecuteGraph).toHaveBeenCalledWith(
+ expect.objectContaining({ graphId: "graph-1", graphVersion: 2 }),
+ );
+ });
+
+ it("runs the unchanged version when the save reports no changes", async () => {
+ // No new version created — saveGraph resolves with the existing graph
+ // (mirrors useSaveGraph's no-op branch, which returns `graph`, not
+ // undefined). The run must target that same, matching version.
+ mockSaveGraph.mockResolvedValue({ id: "graph-1", version: 1 });
+
+ const { result } = renderHook(() => useRunGraph());
+
+ await act(async () => {
+ await result.current.handleRunGraph();
+ });
+
+ expect(mockExecuteGraph).toHaveBeenCalledWith(
+ expect.objectContaining({ graphId: "graph-1", graphVersion: 1 }),
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunGraph/useRunGraph.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunGraph/useRunGraph.ts
index 0ae13b7da4..eee441bd4d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunGraph/useRunGraph.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunGraph/useRunGraph.ts
@@ -26,6 +26,10 @@ export const useRunGraph = () => {
useShallow((state) => state.setIsGraphRunning),
);
const [openRunInputDialog, setOpenRunInputDialog] = useState(false);
+ const [runTarget, setRunTarget] = useState<{
+ graphID: string;
+ graphVersion: number | null;
+ } | null>(null);
const setNodeErrorsForBackendId = useNodeStore(
useShallow((state) => state.setNodeErrorsForBackendId),
@@ -138,9 +142,18 @@ export const useRunGraph = () => {
const handleRunGraph = async ({
dryRun = false,
}: { dryRun?: boolean } = {}) => {
- await saveGraph(undefined);
+ // Use the version returned by the save, not the one captured in this
+ // closure — saving creates a new graph version and the stale closure value
+ // would run the previous (pre-edit) version. See the delete-node-then-run bug.
+ const savedGraph = await saveGraph(undefined);
if (!dryRun && (hasInputs() || hasCredentials())) {
+ // Hand the freshly-saved version to the dialog so it runs THIS version,
+ // not the stale one still in the URL (setQueryStates updates it async).
+ setRunTarget({
+ graphID: savedGraph?.id ?? flowID ?? "",
+ graphVersion: savedGraph?.version ?? flowVersion ?? null,
+ });
setOpenRunInputDialog(true);
} else {
// Clear stale results so the UI shows fresh output from this execution
@@ -149,8 +162,8 @@ export const useRunGraph = () => {
// Optimistically set running state immediately for responsive UI
setIsGraphRunning(true);
await executeGraph({
- graphId: flowID ?? "",
- graphVersion: flowVersion || null,
+ graphId: savedGraph?.id ?? flowID ?? "",
+ graphVersion: savedGraph?.version ?? flowVersion ?? null,
data: {
inputs: {},
credentials_inputs: {},
@@ -179,5 +192,6 @@ export const useRunGraph = () => {
isTerminatingGraph,
openRunInputDialog,
setOpenRunInputDialog: handleSetOpenRunInputDialog,
+ runTarget,
};
};
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/RunInputDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/RunInputDialog.tsx
index 51308a4a82..1ac522a565 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/RunInputDialog.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/RunInputDialog.tsx
@@ -16,10 +16,14 @@ export const RunInputDialog = ({
isOpen,
setIsOpen,
purpose,
+ graphID,
+ graphVersion,
}: {
isOpen: boolean;
setIsOpen: (isOpen: boolean) => void;
purpose: "run" | "schedule";
+ graphID?: string;
+ graphVersion?: number | null;
}) => {
const hasInputs = useGraphStore((state) => state.hasInputs);
const hasCredentials = useGraphStore((state) => state.hasCredentials);
@@ -36,7 +40,7 @@ export const RunInputDialog = ({
credentialValues,
handleCredentialFieldChange,
isExecutingGraph,
- } = useRunInputDialog({ setIsOpen });
+ } = useRunInputDialog({ setIsOpen, graphID, graphVersion });
// Tutorial integration - track input values for the tutorial
const setTutorialInputValues = useTutorialStore(
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/useRunInputDialog.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/useRunInputDialog.test.tsx
new file mode 100644
index 0000000000..ae3fdf0a67
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/useRunInputDialog.test.tsx
@@ -0,0 +1,111 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+// Stale query state: the URL still points at the pre-save version (flowVersion:
+// 1). A save right before opening the dialog bumps the real version to 2, but
+// setQueryStates updates the URL asynchronously — so it can still read 1 here.
+const mockSetQueryStates = vi.fn();
+vi.mock("nuqs", () => ({
+ parseAsString: {},
+ parseAsInteger: {},
+ useQueryStates: vi.fn(() => [
+ { flowID: "graph-1", flowVersion: 1, flowExecutionID: null },
+ mockSetQueryStates,
+ ]),
+}));
+
+const mockToast = vi.fn();
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ useToast: () => ({ toast: mockToast }),
+}));
+
+const mockExecuteGraph = vi.fn();
+vi.mock("@/app/api/__generated__/endpoints/graphs/graphs", () => ({
+ usePostV1ExecuteGraphAgent: () => ({
+ mutateAsync: mockExecuteGraph,
+ isPending: false,
+ }),
+}));
+
+vi.mock("@/lib/autogpt-server-api", () => {
+ class MockApiError extends Error {
+ isGraphValidationError() {
+ return false;
+ }
+ }
+ return {
+ ApiError: MockApiError,
+ CredentialsMetaInput: {},
+ GraphExecutionMeta: {},
+ };
+});
+
+const graphState = {
+ credentialsInputSchema: undefined,
+ setIsGraphRunning: vi.fn(),
+};
+vi.mock("@/app/(platform)/build/stores/graphStore", () => ({
+ useGraphStore: (selector: (s: typeof graphState) => unknown) =>
+ selector(graphState),
+}));
+
+const nodeState = {
+ clearAllNodeExecutionResults: vi.fn(),
+ cleanNodesStatuses: vi.fn(),
+ updateNodeErrors: vi.fn(),
+ nodes: [],
+};
+vi.mock("@/app/(platform)/build/stores/nodeStore", () => ({
+ useNodeStore: Object.assign(
+ (selector: (s: typeof nodeState) => unknown) => selector(nodeState),
+ { getState: () => nodeState },
+ ),
+}));
+
+vi.mock("@xyflow/react", () => ({
+ useReactFlow: () => ({ setViewport: vi.fn() }),
+}));
+
+import { useRunInputDialog } from "./useRunInputDialog";
+
+describe("useRunInputDialog", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("runs the version passed in, not the stale one in the URL", async () => {
+ const { result } = renderHook(() =>
+ useRunInputDialog({
+ setIsOpen: vi.fn(),
+ graphID: "graph-1",
+ graphVersion: 2,
+ }),
+ );
+
+ await act(async () => {
+ await result.current.handleManualRun();
+ });
+
+ expect(mockExecuteGraph).toHaveBeenCalledWith(
+ expect.objectContaining({ graphId: "graph-1", graphVersion: 2 }),
+ );
+ });
+
+ it("falls back to the URL version when no version is passed in", async () => {
+ const { result } = renderHook(() =>
+ useRunInputDialog({ setIsOpen: vi.fn() }),
+ );
+
+ await act(async () => {
+ await result.current.handleManualRun();
+ });
+
+ expect(mockExecuteGraph).toHaveBeenCalledWith(
+ expect.objectContaining({ graphId: "graph-1", graphVersion: 1 }),
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/useRunInputDialog.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/useRunInputDialog.ts
index 629d4662a9..e0a14710a8 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/useRunInputDialog.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/RunInputDialog/useRunInputDialog.ts
@@ -15,8 +15,12 @@ import type { CredentialField } from "@/components/contextual/CredentialsInput/c
export const useRunInputDialog = ({
setIsOpen,
+ graphID,
+ graphVersion,
}: {
setIsOpen: (isOpen: boolean) => void;
+ graphID?: string;
+ graphVersion?: number | null;
}) => {
const credentialsSchema = useGraphStore(
(state) => state.credentialsInputSchema,
@@ -157,8 +161,10 @@ export const useRunInputDialog = ({
useNodeStore.getState().cleanNodesStatuses();
await executeGraph({
- graphId: flowID ?? "",
- graphVersion: flowVersion || null,
+ // Prefer the freshly-saved version handed in by the caller; the URL's
+ // flowVersion is updated asynchronously and may still be stale here.
+ graphId: graphID ?? flowID ?? "",
+ graphVersion: graphVersion ?? flowVersion ?? null,
data: {
inputs: inputValues,
credentials_inputs: validCredentials,
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/hooks/useSaveGraph.ts b/autogpt_platform/frontend/src/app/(platform)/build/hooks/useSaveGraph.ts
index 505303cc1e..aab9c9478d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/hooks/useSaveGraph.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/build/hooks/useSaveGraph.ts
@@ -152,7 +152,7 @@ export const useSaveGraph = ({
variant: "default",
});
}
- return;
+ return graph;
}
const response = await updateGraph({ graphId: graph.id, data: data });
@@ -162,6 +162,7 @@ export const useSaveGraph = ({
graphData.credentials_input_schema,
graphData.output_schema,
);
+ return graphData;
} else {
const data: Graph = {
name: values?.name || `New Agent ${new Date().toISOString()}`,
@@ -179,6 +180,7 @@ export const useSaveGraph = ({
graphData.credentials_input_schema,
graphData.output_schema,
);
+ return graphData;
}
},
[graph, toast, createNewGraph, updateGraph],