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(platform): name the missing field when a graph can't be saved (#15438)
Nicholas Tindle8d248cd9b00c
diff --git a/.github/scripts/test_e2e_seed_cache_contract.py b/.github/scripts/test_e2e_seed_cache_contract.pyindex 7e18145b51..35eb0f1dd0 100644--- a/.github/scripts/test_e2e_seed_cache_contract.py+++ b/.github/scripts/test_e2e_seed_cache_contract.py@@ -133,7 +133,7 @@ class E2ECoverageContractTests(unittest.TestCase):).read_text(encoding="utf-8")self.assertIn("--min-tests ${{ matrix.min_tests }}", workflow)self.assertEqual(_matrix_leg(workflow, "smoke")["min_tests"], "28")- self.assertEqual(_matrix_leg(workflow, "journeys")["min_tests"], "9")+ self.assertEqual(_matrix_leg(workflow, "journeys")["min_tests"], "11")# Smoke stays strict: no test.fail() known failures.self.assertEqual(_matrix_leg(workflow, "smoke")["known_failures"], "false")diff --git a/.github/workflows/platform-fullstack-ci.yml b/.github/workflows/platform-fullstack-ci.ymlindex 6f17ac5705..9d597890d2 100644--- a/.github/workflows/platform-fullstack-ci.yml+++ b/.github/workflows/platform-fullstack-ci.yml@@ -203,7 +203,7 @@ jobs:# selfhost-journey asserts nothing hosted-only exists; it needs a# self-hosted stack (TODO in src/playwright/journeys/README.md).playwright_args: --project hosted- min_tests: 9+ min_tests: 11embeddings: false# Journeys sign up their own users and need no seeded data.seed: falsediff --git a/autogpt_platform/backend/backend/api/features/graphs/routes.py b/autogpt_platform/backend/backend/api/features/graphs/routes.pyindex 4f5e8d7c9a..b1cd0bbd2b 100644--- a/autogpt_platform/backend/backend/api/features/graphs/routes.py+++ b/autogpt_platform/backend/backend/api/features/graphs/routes.py@@ -1,4 +1,4 @@-from typing import Annotated, Any, Sequence+from typing import Annotated, Any, Mapping, Sequencefrom autogpt_libs.auth import get_request_context, get_user_id, requires_userfrom autogpt_libs.auth.models import RequestContext@@ -107,8 +107,8 @@ async def create_new_graph(ctx: Annotated[RequestContext, Security(get_request_context)],) -> graph_db.GraphModel:graph = graph_db.make_graph_model(create_graph.graph, user_id)- graph.reassign_ids(user_id=user_id, reassign_graph_id=True)- graph.validate_graph(for_run=False)+ submitted_node_ids = graph.reassign_ids(user_id=user_id, reassign_graph_id=True)+ _validate_graph_to_save(graph, submitted_node_ids)# Validate node credentials (and clear stale optional ones) BEFORE# persisting, so a credential issue can't leave the graph/library agent@@ -171,8 +171,8 @@ async def update_graph(current_active_version = next((v for v in existing_versions if v.is_active), None)graph = graph_db.make_graph_model(graph, user_id)- graph.reassign_ids(user_id=user_id, reassign_graph_id=False)- graph.validate_graph(for_run=False)+ submitted_node_ids = graph.reassign_ids(user_id=user_id, reassign_graph_id=False)+ _validate_graph_to_save(graph, submitted_node_ids)# If this new version is going to be active, validate node credentials# BEFORE persisting so a credential issue can't leave a half-saved version@@ -370,15 +370,36 @@ async def execute_graph(except GraphValidationError as e:record_graph_operation(operation="execute", status="validation_error")# Return structured validation errors that the frontend can parse- raise HTTPException(- status_code=400,- detail={- "type": "validation_error",- "message": e.message,- # TODO: only return node-specific errors if user has access to graph- "node_errors": e.node_errors,- },- )+ # TODO: only return node-specific errors if user has access to graph+ raise HTTPException(status_code=400, detail=_validation_error_detail(e))except Exception:record_graph_operation(operation="execute", status="error")raise+++def _validate_graph_to_save(+ graph: graph_db.GraphModel, submitted_node_ids: Mapping[str, str]+) -> None:+ """Refuse an invalid graph with errors keyed by the node IDs the caller+ sent, not the fresh ones `reassign_ids` gave it, so the builder can mark+ the fields on its own nodes."""+ try:+ graph.validate_graph(for_run=False)+ except GraphValidationError as e:+ raise HTTPException(+ status_code=400, detail=_validation_error_detail(e, submitted_node_ids)+ ) from e+++def _validation_error_detail(+ error: GraphValidationError, node_ids: Mapping[str, str] | None = None+) -> dict[str, Any]:+ node_ids = node_ids or {}+ return {+ "type": "validation_error",+ "message": error.message,+ "node_errors": {+ node_ids.get(node_id, node_id): field_errors+ for node_id, field_errors in error.node_errors.items()+ },+ }diff --git a/autogpt_platform/backend/backend/api/features/graphs/routes_test.py b/autogpt_platform/backend/backend/api/features/graphs/routes_test.pyindex 8baed45211..62a60440e1 100644--- a/autogpt_platform/backend/backend/api/features/graphs/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/graphs/routes_test.py@@ -14,7 +14,9 @@ from pytest_snapshot.plugin import Snapshotfrom backend.api.features.graphs.routes import routerfrom backend.api.rest_api import app as real_appfrom backend.api.rest_api import handle_internal_http_error+from backend.blocks.basic import StoreValueBlockfrom backend.blocks.google.sheets import GoogleSheetsReadBlock+from backend.blocks.io import AgentInputBlock, AgentOutputBlockfrom backend.data import execution as execution_dbfrom backend.data.execution import ExecutionStatusfrom backend.data.graph import GraphModel@@ -695,6 +697,107 @@ def test_create_new_graph_reassigns_ids_and_persists_in_order(assert response.json()["id"] != "submitted-id"+def _unnamed_output_graph() -> dict:+ """Store Value wired into an Agent Output whose required Name is empty."""+ return {+ "name": "Unnamed output",+ "description": "",+ "nodes": [+ {+ "id": "value",+ "block_id": StoreValueBlock().id,+ "input_default": {"input": "hi"},+ },+ {"id": "output", "block_id": AgentOutputBlock().id, "input_default": {}},+ ],+ "links": [+ {+ "source_id": "value",+ "sink_id": "output",+ "source_name": "output",+ "sink_name": "value",+ }+ ],+ }+++def test_create_new_graph_names_the_missing_field_on_the_submitted_node(+ mocker: pytest_mock.MockFixture,+) -> None:+ """Saving used to answer "'Input' object has no attribute 'name'". The+ builder needs the field, keyed by the node id it sent rather than the+ fresh one the graph is given, to mark it on the canvas."""+ create_graph_mock = mocker.patch(+ "backend.api.features.graphs.routes.graph_db.create_graph", new=AsyncMock()+ )++ response = client.post("/graphs", json={"graph": _unnamed_output_graph()})++ assert response.status_code == 400+ assert response.json()["detail"] == {+ "type": "validation_error",+ "message": "Agent Output › Name: This field is required",+ "node_errors": {"output": {"name": "This field is required"}},+ }+ create_graph_mock.assert_not_awaited()+++ "block,title",+ [(AgentInputBlock, "Agent Input"), (AgentOutputBlock, "Agent Output")],+ ids=["input", "output"],+)[email protected]("name", [None, "", " "], ids=["null", "empty", "whitespace"])+def test_create_new_graph_refuses_a_blank_input_or_output_name(+ mocker: pytest_mock.MockFixture, block: type, title: str, name: str | None+) -> None:+ """A name that is there but blank names nothing either; it would add a+ nameless field to the graph's inputs or outputs."""+ create_graph_mock = mocker.patch(+ "backend.api.features.graphs.routes.graph_db.create_graph", new=AsyncMock()+ )+ graph = {+ "name": "Blank name",+ "description": "",+ "nodes": [+ {"id": "io", "block_id": block().id, "input_default": {"name": name}}+ ],+ "links": [],+ }++ response = client.post("/graphs", json={"graph": graph})++ assert response.status_code == 400+ assert response.json()["detail"] == {+ "type": "validation_error",+ "message": f"{title} › Name: This field is required",+ "node_errors": {"io": {"name": "This field is required"}},+ }+ create_graph_mock.assert_not_awaited()+++def test_update_graph_names_the_missing_field_on_the_submitted_node(+ mocker: pytest_mock.MockFixture,+) -> None:+ mocker.patch(+ "backend.api.features.graphs.routes.graph_db.get_graph_all_versions",+ new=AsyncMock(return_value=[Mock(version=1, is_active=True)]),+ )+ create_graph_mock = mocker.patch(+ "backend.api.features.graphs.routes.graph_db.create_graph", new=AsyncMock()+ )++ response = client.put(+ "/graphs/graph-1", json={"id": "graph-1", **_unnamed_output_graph()}+ )++ assert response.status_code == 400+ assert response.json()["detail"]["node_errors"] == {+ "output": {"name": "This field is required"}+ }+ create_graph_mock.assert_not_awaited()++def _sheets_read_graph(credentials_id: str) -> dict:"""A Google Sheets Read agent whose spreadsheet was chosen in the Drivepicker, which embeds the credential it used as `_credentials_id`."""diff --git a/autogpt_platform/backend/backend/data/graph.py b/autogpt_platform/backend/backend/data/graph.pyindex c42120a035..b302b215b4 100644--- a/autogpt_platform/backend/backend/data/graph.py+++ b/autogpt_platform/backend/backend/data/graph.py@@ -2,7 +2,7 @@ import asyncioimport loggingimport uuidfrom collections import defaultdict-from collections.abc import Container+from collections.abc import Container, Mappingfrom datetime import datetime, timezonefrom typing import (TYPE_CHECKING,@@ -42,10 +42,15 @@ from backend.blocks.llm import LEGACY_MODEL_MAPPINGS, LLMModelfrom backend.data.tenancy import get_user_team_ids, visibility_filterfrom backend.integrations.providers import ProviderNamefrom backend.util import type as type_utils-from backend.util.exceptions import GraphNotAccessibleError, GraphNotInLibraryError+from backend.util.exceptions import (+ GraphNotAccessibleError,+ GraphNotInLibraryError,+ GraphValidationError,+)from backend.util.json import SafeJsonfrom backend.util.models import Paginationfrom backend.util.request import parse_url+from backend.util.text import split_camelcasefrom .block import BlockInputfrom .db import BaseDbModel, execute_raw_with_schema, query_raw_with_schema, transaction@@ -368,6 +373,10 @@ class BaseGraph(GraphBaseMeta):) -> dict[str, Any]:schema_fields: list[AgentInputBlock.Input | AgentOutputBlock.Input] = []for type_class, input_default in props:+ # An input or output without a name isn't part of the graph's+ # interface yet; validate_graph reports the missing name.+ if not str(input_default.get("name") or "").strip():+ continuetry:schema_fields.append(type_class.model_construct(**input_default))except Exception as e:@@ -792,10 +801,13 @@ class GraphModel(Graph, GraphMeta):if v[0].is_auto_credential}- def reassign_ids(self, user_id: str, reassign_graph_id: bool = False):+ def reassign_ids(+ self, user_id: str, reassign_graph_id: bool = False+ ) -> dict[str, str]:"""Reassigns all IDs in the graph to new UUIDs.This method can be used before storing a new graph to the database.+ Returns each new node ID mapped to the node ID it replaced."""if reassign_graph_id:graph_id_map = {@@ -805,16 +817,17 @@ class GraphModel(Graph, GraphMeta):else:graph_id_map = {}- self._reassign_ids(self, user_id, graph_id_map)+ replaced_node_ids = self._reassign_ids(self, user_id, graph_id_map)for sub_graph in self.sub_graphs:- self._reassign_ids(sub_graph, user_id, graph_id_map)+ replaced_node_ids |= self._reassign_ids(sub_graph, user_id, graph_id_map)+ return replaced_node_ids@staticmethoddef _reassign_ids(graph: BaseGraph,user_id: str,graph_id_map: dict[str, str],- ):+ ) -> dict[str, str]:# Reassign Graph IDif graph.id in graph_id_map:graph.id = graph_id_map[graph.id]@@ -842,6 +855,8 @@ class GraphModel(Graph, GraphMeta):) and graph_id in graph_id_map:node.input_default["graph_id"] = graph_id_map[graph_id]+ return {new_id: old_id for old_id, new_id in id_map.items()}+def clear_auto_credentials(self, keep_ids: Container[str] = frozenset()) -> list[tuple[Node, str, Any]]:@@ -903,10 +918,9 @@ class GraphModel(Graph, GraphMeta):graph, for_run, nodes_input_masks)if errors:- # Just raise the first error for backward compatibility- first_error = next(iter(errors.values()))- first_field_error = next(iter(first_error.values()))- raise ValueError(first_field_error)+ raise GraphValidationError(+ _describe_node_errors(graph, errors), node_errors=errors+ )def validate_graph_get_errors(self,@@ -978,7 +992,11 @@ class GraphModel(Graph, GraphMeta):nodes_input_masks.get(node.id, {}) if nodes_input_masks else {})provided_inputs = set(- [sanitize_pin_name(name) for name in node.input_default]+ [+ sanitize_pin_name(name)+ for name, value in node.input_default.items()+ if not _is_blank_io_name(block, name, value)+ ]+ [sanitize_pin_name(link.sink_name)for link in input_links.get(node.id, [])@@ -1299,6 +1317,44 @@ class GraphModel(Graph, GraphMeta):return GraphModelWithoutNodes.model_validate(self, from_attributes=True)+def _describe_node_errors(+ graph: BaseGraph, node_errors: Mapping[str, Mapping[str, str]]+) -> str:+ """The first problem in the builder's words, e.g. "Agent Output › Name:+ This field is required", and how many more there are."""+ nodes = {node.id: node for node in graph.nodes}+ problems = [+ f"{_node_title(nodes[node_id])} › {_field_title(nodes[node_id], field)}: "+ f"{error}"+ for node_id, field_errors in node_errors.items()+ for field, error in field_errors.items()+ ]+ if len(problems) > 1:+ return f"{problems[0]} (and {len(problems) - 1} more)"+ return problems[0]+++def _is_blank_io_name(block: "AnyBlockSchema", field: str, value: Any) -> bool:+ """An input or output named "" has no name, and the graph's interface needs+ one; one wired in from a link still counts."""+ return (+ field == "name"+ and block.block_type in (BlockType.INPUT, BlockType.OUTPUT)+ and not str(value or "").strip()+ )+++def _node_title(node: Node) -> str:+ if customized_name := node.metadata.get("customized_name"):+ return str(customized_name)+ return split_camelcase(node.block.name.removesuffix("Block"))+++def _field_title(node: Node, field: str) -> str:+ properties = node.block.input_schema.jsonschema().get("properties", {})+ return properties.get(field, {}).get("title") or field++class GraphModelWithoutNodes(GraphModel):"""GraphModel variant that excludes nodes, links, and sub-graphs from serialization.diff --git a/autogpt_platform/backend/backend/data/graph_test.py b/autogpt_platform/backend/backend/data/graph_test.pyindex 33c9d6d13a..1c8b297c3d 100644--- a/autogpt_platform/backend/backend/data/graph_test.py+++ b/autogpt_platform/backend/backend/data/graph_test.py@@ -7,12 +7,14 @@ from uuid import UUID, uuid4import fastapi.exceptionsimport prismaimport pytest+from autogpt_libs.auth.models import RequestContextfrom prisma.enums import ResourceVisibility, SubmissionStatusfrom prisma.models import AgentGraph, AgentNode, LibraryAgent, Userfrom pytest_snapshot.plugin import Snapshotimport backend.api.features.library.db as library_dbimport backend.api.features.store.model as store+from backend.api.features.graphs import routes as graphs_routesfrom backend.api.model import CreateGraphfrom backend.blocks._base import BlockSchema, BlockSchemaInputfrom backend.blocks.autopilot import AUTOPILOT_BLOCK_ID, AutoPilotTransport@@ -911,6 +913,106 @@ async def test_fork_graph_clears_picked_files(await delete_graph(forked.id, user_id=DEFAULT_USER_ID)+def _value_to_output_graph(+ output_input: dict[str, Any], value_id: str = "value", output_id: str = "output"+) -> Graph:+ return Graph(+ name=f"Value to output {uuid4()}",+ description="",+ nodes=[+ Node(+ id=value_id,+ block_id=StoreValueBlock().id,+ input_default={"input": "hi"},+ ),+ Node(+ id=output_id, block_id=AgentOutputBlock().id, input_default=output_input+ ),+ ],+ links=[+ Link(+ source_id=value_id,+ sink_id=output_id,+ source_name="output",+ sink_name="value",+ )+ ],+ )++[email protected](loop_scope="session")+async def test_saving_an_unnamed_output_names_the_field_and_saves_nothing(+ server: SpinTestServer,+):+ """+ Saving an Agent Output whose required Name is empty answered with a raw+ "'Input' object has no attribute 'name'". The caller now hears which field+ is missing on which of the nodes it sent, and nothing is written.+ """+ graph = _value_to_output_graph({})++ with pytest.raises(fastapi.exceptions.HTTPException) as refused:+ await server.agent_server.test_create_graph(+ CreateGraph(graph=graph), DEFAULT_USER_ID+ )++ assert refused.value.status_code == 400+ assert refused.value.detail == {+ "type": "validation_error",+ "message": "Agent Output › Name: This field is required",+ "node_errors": {"output": {"name": "This field is required"}},+ }+ assert await AgentGraph.prisma().find_first(where={"name": graph.name}) is None++ graph.nodes[1].input_default["name"] = "greeting"+ saved = await server.agent_server.test_create_graph(+ CreateGraph(graph=graph), DEFAULT_USER_ID+ )+ assert list(saved.output_schema["properties"]) == ["greeting"]++[email protected](loop_scope="session")+async def test_an_edit_that_unnames_an_output_keeps_the_saved_version(+ server: SpinTestServer,+):+ created = await server.agent_server.test_create_graph(+ CreateGraph(graph=_value_to_output_graph({"name": "greeting"})),+ DEFAULT_USER_ID,+ )+ value_node, output_node = sorted(+ created.nodes, key=lambda node: node.block_id != StoreValueBlock().id+ )+ # The builder sends back the node ids it loaded.+ edited = _value_to_output_graph({}, value_node.id, output_node.id)+ edited.id = created.id++ with pytest.raises(fastapi.exceptions.HTTPException) as refused:+ await graphs_routes.update_graph(+ created.id, edited, DEFAULT_USER_ID, _owner_context(DEFAULT_USER_ID)+ )++ assert refused.value.status_code == 400+ assert refused.value.detail["node_errors"] == {+ output_node.id: {"name": "This field is required"}+ }+ versions = await get_graph_all_versions(created.id, user_id=DEFAULT_USER_ID)+ assert [version.version for version in versions] == [created.version]+++def _owner_context(user_id: str) -> RequestContext:+ return RequestContext(+ user_id=user_id,+ org_id=f"test-org-{user_id}",+ team_id=None,+ is_org_owner=True,+ is_org_admin=True,+ is_org_billing_manager=False,+ is_team_admin=True,+ is_team_billing_manager=False,+ seat_status="ACTIVE",+ )++# ============================================================================# Tests for discriminate() field propagationdef test_discriminate_preserves_is_auto_credential_flag():@@ -2410,21 +2512,30 @@ async def test_get_graph_settings_resolves_against_the_running_version(# ============================================================================-# Tests for _generate_schema AttributeError → ValueError conversion+# Tests for _generate_schema with an unnamed input or output# ============================================================================-def test_generate_schema_raises_value_error_when_name_missing():- """AgentInputBlock.Input constructed without 'name' should raise ValueError.+def test_a_blank_output_name_wired_from_a_link_still_counts():+ """Only the node's own blank value is discounted; a name a link brings in+ is still provided."""+ graph = make_graph_model(_value_to_output_graph({"name": ""}), user_id="user-1")+ graph.links[0].sink_name = "name"- model_construct() skips validation, so the Input object is created without- a 'name' attribute. The dict comprehension in _generate_schema then hits an- AttributeError when it accesses p.name. That AttributeError must be caught- and re-raised as ValueError so the existing 400 handler in rest_api.py fires- instead of falling through to the 500 catch-all.- """- with pytest.raises(ValueError):- GraphModel._generate_schema((AgentInputBlock.Input, {}))+ assert graph.validate_graph_get_errors() == {}+++def test_generate_schema_leaves_out_an_input_without_a_name():+ """An unnamed input isn't part of the graph's interface yet, so it isn't in+ the schema. The schema is computed whenever the graph is dumped, before+ validate_graph can tell the user which name is missing, so it must not+ fail: raising here is how "'Input' object has no attribute 'name'" reached+ the builder as the whole save error."""+ assert GraphModel._generate_schema((AgentInputBlock.Input, {})) == {+ "type": "object",+ "properties": {},+ "required": [],+ }# ============================================================================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.tsxindex 12a56510f3..8c4b2b2815 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useSaveGraph.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/build/__tests__/useSaveGraph.test.tsx@@ -33,8 +33,16 @@ vi.mock("@/app/api/__generated__/endpoints/graphs/graphs", () => ({}),}));+const mockSetNodeErrorsForBackendId = vi.fn();+const mockClearAllNodeErrors = vi.fn();vi.mock("@/app/(platform)/build/stores/nodeStore", () => ({- useNodeStore: { getState: () => ({ getBackendNodes: () => [] }) },+ useNodeStore: {+ getState: () => ({+ getBackendNodes: () => [],+ setNodeErrorsForBackendId: mockSetNodeErrorsForBackendId,+ clearAllNodeErrors: mockClearAllNodeErrors,+ }),+ },}));vi.mock("@/app/(platform)/build/stores/edgeStore", () => ({useEdgeStore: { getState: () => ({ getBackendLinks: () => [] }) },@@ -60,6 +68,7 @@ vi.mock("@/services/builder-draft/draft-service", () => ({clearTempFlowId: vi.fn(),}));+import { ApiError } from "@/lib/autogpt-server-api/helpers";import { useSaveGraph } from "../hooks/useSaveGraph";describe("useSaveGraph", () => {@@ -191,4 +200,61 @@ describe("useSaveGraph", () => {expect(mockCreate).not.toHaveBeenCalled();expect(returned).toBe(mockCurrentGraph);});++ it("names the invalid field and marks it on its node when the backend refuses the graph", async () => {+ mockCreate.mockRejectedValue(+ new ApiError("Agent Output › Name: This field is required", 400, {+ detail: {+ type: "validation_error",+ message: "Agent Output › Name: This field is required",+ node_errors: { "node-2": { name: "This field is required" } },+ },+ }),+ );++ const { result } = renderHook(() => useSaveGraph({ showToast: true }));++ let returned: unknown;+ await act(async () => {+ returned = await result.current.saveGraph();+ });++ expect(returned).toBeNull();+ expect(mockClearAllNodeErrors).toHaveBeenCalledBefore(+ mockSetNodeErrorsForBackendId,+ );+ expect(mockSetNodeErrorsForBackendId).toHaveBeenCalledWith("node-2", {+ name: "This field is required",+ });+ expect(mockToast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Couldn't save your agent",+ description: expect.stringContaining(+ "Agent Output › Name: This field is required",+ ),+ variant: "destructive",+ }),+ );+ });++ it("reports any other failed save instead of throwing it", async () => {+ mockCurrentGraph = { id: "graph-1", name: "Agent", version: 1 };+ mockUpdate.mockRejectedValue(new Error("Network unreachable"));++ const { result } = renderHook(() => useSaveGraph({ showToast: false }));++ let returned: unknown;+ await act(async () => {+ returned = await result.current.saveGraph();+ });++ expect(returned).toBeNull();+ expect(mockSetNodeErrorsForBackendId).not.toHaveBeenCalled();+ expect(mockToast).toHaveBeenCalledWith(+ expect.objectContaining({+ title: "Error saving graph",+ description: "Network unreachable",+ }),+ );+ });});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.tsxindex 3f9d688f6d..00c609c296 100644--- 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@@ -142,6 +142,21 @@ describe("useRunGraph", () => {);});+ it("does not run anything when the save is refused", async () => {+ // A refused save resolves to null after telling the user why; running+ // the URL's version would run the graph from before their edits.+ mockSaveGraph.mockResolvedValue(null);++ const { result } = renderHook(() => useRunGraph());++ await act(async () => {+ await result.current.handleRunGraph();+ });++ expect(mockExecuteGraph).not.toHaveBeenCalled();+ expect(graphState.setIsGraphRunning).not.toHaveBeenCalled();+ });+it("records a successful real run with its builder surface", async () => {mockSaveGraph.mockResolvedValue({ id: "graph-1", version: 1 });const { result } = renderHook(() => useRunGraph());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.tsindex f721a435a4..b158c86711 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@@ -152,6 +152,7 @@ export const useRunGraph = () => {// 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 (!savedGraph) return;if (!dryRun && (hasInputs() || hasCredentials())) {// Hand the freshly-saved version to the dialog so it runs THIS version,diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/ScheduleGraph/useScheduleGraph.test.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/ScheduleGraph/useScheduleGraph.test.tsxnew file mode 100644index 0000000000..61f04eaa1a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/ScheduleGraph/useScheduleGraph.test.tsx@@ -0,0 +1,51 @@+import { act, renderHook } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mockSaveGraph = vi.fn();+vi.mock("@/app/(platform)/build/hooks/useSaveGraph", () => ({+ useSaveGraph: () => ({ saveGraph: mockSaveGraph, isSaving: false }),+}));++const graphState = {+ hasInputs: () => false,+ hasCredentials: () => false,+};+vi.mock("@/app/(platform)/build/stores/graphStore", () => ({+ useGraphStore: (selector: (s: typeof graphState) => unknown) =>+ selector(graphState),+}));++import { useScheduleGraph } from "./useScheduleGraph";++describe("useScheduleGraph", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it("opens the scheduler once the graph is saved", async () => {+ mockSaveGraph.mockResolvedValue({ id: "graph-1", version: 2 });++ const { result } = renderHook(() => useScheduleGraph());++ await act(async () => {+ await result.current.handleScheduleGraph();+ });++ expect(result.current.openCronSchedulerDialog).toBe(true);+ });++ it("schedules nothing when the save is refused", async () => {+ // A refused save resolves to null after telling the user why; scheduling+ // would schedule the graph from before their edits.+ mockSaveGraph.mockResolvedValue(null);++ const { result } = renderHook(() => useScheduleGraph());++ await act(async () => {+ await result.current.handleScheduleGraph();+ });++ expect(result.current.openCronSchedulerDialog).toBe(false);+ expect(result.current.openScheduleInputDialog).toBe(false);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/ScheduleGraph/useScheduleGraph.ts b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/ScheduleGraph/useScheduleGraph.tsindex 4334bf6229..e7a3bbaea5 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/ScheduleGraph/useScheduleGraph.ts+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/BuilderActions/components/ScheduleGraph/useScheduleGraph.ts@@ -15,7 +15,7 @@ export const useScheduleGraph = () => {const [openCronSchedulerDialog, setOpenCronSchedulerDialog] = useState(false);const handleScheduleGraph = async () => {- await saveGraph(undefined);+ if (!(await saveGraph(undefined))) return;if (hasInputs() || hasCredentials()) {setOpenScheduleInputDialog(true);} else {diff --git a/autogpt_platform/frontend/src/app/(platform)/build/helpers/saveGraphError.ts b/autogpt_platform/frontend/src/app/(platform)/build/helpers/saveGraphError.tsnew file mode 100644index 0000000000..0e98b0eeb0--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/build/helpers/saveGraphError.ts@@ -0,0 +1,39 @@+import { ApiError } from "@/lib/autogpt-server-api/helpers";+import type { GraphValidationErrorResponse } from "@/lib/autogpt-server-api/types";+import { useNodeStore } from "../stores/nodeStore";++// A graph the backend refuses to save comes back as a structured validation+// error naming each node's bad fields, e.g. "Agent Output › Name: This field+// is required"; anything else is shown as it arrives.+export function describeSaveError(error: unknown) {+ if (isValidationError(error)) {+ return {+ title: "Couldn't save your agent",+ description: `${error.response.detail.message}. Fix the highlighted fields and save again.`,+ variant: "destructive" as const,+ };+ }+ return {+ title: "Error saving graph",+ description:+ error instanceof Error ? error.message : "An unexpected error occurred.",+ variant: "destructive" as const,+ };+}++// Like a refused run, the latest refusal replaces whatever was marked before.+export function markInvalidFields(error: unknown) {+ if (!isValidationError(error)) return;+ const { clearAllNodeErrors, setNodeErrorsForBackendId } =+ useNodeStore.getState();+ clearAllNodeErrors();+ Object.entries(error.response.detail.node_errors).forEach(+ ([nodeID, fieldErrors]) => setNodeErrorsForBackendId(nodeID, fieldErrors),+ );+}++function isValidationError(+ error: unknown,+): error is ApiError<GraphValidationErrorResponse> {+ return error instanceof ApiError && error.isGraphValidationError();+}diff --git a/autogpt_platform/frontend/src/app/(platform)/build/hooks/useSaveGraph.ts b/autogpt_platform/frontend/src/app/(platform)/build/hooks/useSaveGraph.tsindex 92c49f278a..3978a99c24 100644--- a/autogpt_platform/frontend/src/app/(platform)/build/hooks/useSaveGraph.ts+++ b/autogpt_platform/frontend/src/app/(platform)/build/hooks/useSaveGraph.ts@@ -23,6 +23,10 @@ import {getTempFlowId,} from "@/services/builder-draft/draft-service";import { retryUnlessClientError } from "../helpers/graphLoadError";+import {+ describeSaveError,+ markInvalidFields,+} from "../helpers/saveGraphError";export type SaveGraphOptions = {showToast?: boolean;@@ -83,15 +87,6 @@ export const useSaveGraph = ({});}},- onError: (error) => {- onError?.(error);- toast({- title: "Error saving graph",- description:- (error as any).message ?? "An unexpected error occurred.",- variant: "destructive",- });- },},});@@ -119,19 +114,10 @@ export const useSaveGraph = ({});}},- onError: (error) => {- onError?.(error);- toast({- title: "Error saving graph",- description:- (error as any).message ?? "An unexpected error occurred.",- variant: "destructive",- });- },},});- const saveGraph = useCallback(+ const persistGraph = useCallback(async (values?: { name?: string; description?: string }) => {const graphNodes = useNodeStore.getState().getBackendNodes();const graphLinks = useEdgeStore.getState().getBackendLinks();@@ -192,6 +178,24 @@ export const useSaveGraph = ({[graph, toast, createNewGraph, updateGraph],);+ // Resolves to null when the save fails; the user has been told why.+ const saveGraph = useCallback(+ async (values?: { name?: string; description?: string }) => {+ let saved: GraphModel;+ try {+ saved = await persistGraph(values);+ } catch (error) {+ onError?.(error);+ markInvalidFields(error);+ toast(describeSaveError(error));+ return null;+ }+ useNodeStore.getState().clearAllNodeErrors();+ return saved;+ },+ [persistGraph, onError, toast],+ );+return {saveGraph,isSaving: isCreating || isUpdating,diff --git a/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts b/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.tsindex 329032c1f6..095c2c9651 100644--- a/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts+++ b/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts@@ -322,6 +322,16 @@ describe("customMutator validation errors", () => {],[{ detail: "Not allowed" }, "Not allowed"],[{ detail: { reason: "Invalid input" } }, '{"reason":"Invalid input"}'],+ [+ {+ detail: {+ type: "validation_error",+ message: "Agent Output › Name: This field is required",+ node_errors: { "node-1": { name: "This field is required" } },+ },+ },+ "Agent Output › Name: This field is required",+ ],[{ detail: [{ reason: "Invalid input" }, null] },'{"reason":"Invalid input"}; null',diff --git a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.tsindex f22bc0d386..8e58a01eaf 100644--- a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts+++ b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts@@ -149,9 +149,11 @@ export const customMutator = async <.join("; "): typeof rawDetail === "string"? rawDetail- : rawDetail != null- ? JSON.stringify(rawDetail)- : undefined;+ : typeof rawDetail?.message === "string"+ ? rawDetail.message+ : rawDetail != null+ ? JSON.stringify(rawDetail)+ : undefined;const errorMessage =detail ||diff --git a/autogpt_platform/frontend/src/playwright/journeys/builder-save-journey.spec.ts b/autogpt_platform/frontend/src/playwright/journeys/builder-save-journey.spec.tsnew file mode 100644index 0000000000..c0d74d5ecd--- /dev/null+++ b/autogpt_platform/frontend/src/playwright/journeys/builder-save-journey.spec.ts@@ -0,0 +1,56 @@+import type { Page } from "@playwright/test";+import { BuildPage, createUniqueAgentName } from "../pages/build.page";+import { expect, test } from "./fixtures";++test.describe("builder save journey", () => {+ test.use({+ expectedResponses: [+ { status: 400, url: "/api/proxy/api/graphs", method: "POST" },+ ],+ });++ test("saving with a required field left empty names the field, saves nothing, and saves once it is filled", async ({+ page,+ journeyUser: _user,+ }) => {+ const buildPage = new BuildPage(page);+ const agentName = createUniqueAgentName("Journey unnamed output");+ await buildPage.open();+ await buildPage.addBlockByClick("Agent Output");+ await buildPage.waitForNodeOnCanvas(1);+ const outputNode = buildPage.getNodeLocatorByTitle("Agent Output");++ await buildPage.saveAgent(agentName, "Builder save journey");++ await expect(page.getByText("Couldn't save your agent")).toBeVisible();+ await expect(+ page.getByText(/Agent Output › Name: This field is required/),+ ).toBeVisible();+ await expect(page.getByText(/has no attribute/)).toHaveCount(0);+ await expect(+ outputNode.getByText("This field is required"),+ "the empty field should be marked on its node",+ ).toBeVisible();+ await expect(page).not.toHaveURL(/flowID=/);+ expect(await libraryAgentNames(page, agentName)).toEqual([]);++ await page.keyboard.press("Escape");+ await outputNode+ .getByRole("textbox", { name: "Name", exact: true })+ .fill("greeting");+ await buildPage.saveAgent(agentName, "Builder save journey");+ await buildPage.waitForSaveComplete();++ await expect(outputNode.getByText("This field is required")).toHaveCount(0);+ expect(await libraryAgentNames(page, agentName)).toEqual([agentName]);+ });+});++async function libraryAgentNames(page: Page, name: string) {+ const response = await page.request.get("/api/proxy/api/library/agents", {+ params: { search_term: name },+ });+ expect(response.ok(), `GET library agents: ${response.status()}`).toBe(true);+ const body = (await response.json()) as { agents: { name: string }[] };+ return body.agents.map((agent) => agent.name);+}