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.
feat(blocks): update Slant3D integration for API v2 (#14452)
Nicholas Tindle6fa5fca7b155
diff --git a/.secrets.baseline b/.secrets.baselineindex a25d4c071f..bb24923f75 100644--- a/.secrets.baseline+++ b/.secrets.baseline@@ -276,7 +276,7 @@"filename": "autogpt_platform/backend/backend/blocks/slant3d/webhook.py","hashed_secret": "36263c76947443b2f6e6b78153967ac4a7da99f9","is_verified": false,- "line_number": 100+ "line_number": 108}],"autogpt_platform/backend/backend/blocks/stripe/example_payloads/customer.subscription.created.json": [@@ -578,5 +578,5 @@}]},- "generated_at": "2026-09-04T21:56:43Z"+ "generated_at": "2026-09-08T19:37:28Z"}diff --git a/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py b/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.pyindex e5e02b9de6..c38f7b6600 100644--- a/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py+++ b/autogpt_platform/backend/backend/api/features/integrations/webhook_ingress_test.py@@ -10,7 +10,7 @@ signature checks to each manager's `verify_signature`. This file pins:base64-decoded `config["mac_secret"]`).* Generic webhook honors an optional `secret_token` on the triggered block:passes through when unset, enforces when set.-* Providers without a signing scheme (Compass, Slant3D) pass through.+* Unsigned Compass and legacy Slant3D subscriptions pass through; Slant3D v2 verifies signatures.* A webhook registered under one provider can't be processed via a differentprovider's ingress path (the manager is selected from the URL provider).* `verify_signature` runs before `validate_payload` (call ordering).@@ -19,6 +19,7 @@ signature checks to each manager's `verify_signature`. This file pins:import base64import hashlibimport hmac+import timefrom contextlib import ExitStackfrom unittest.mock import AsyncMock, MagicMock, patch@@ -169,17 +170,14 @@ def _run(webhook, provider_path: str, **kwargs):class TestUnsignedProvidersPassThrough:- """Compass and Slant3D have no upstream signing scheme. The router must- not 403 their deliveries — the default no-op `verify_signature` covers- them, and 403'ing here would break every legitimate delivery from those- devices/services."""+ """Compass and legacy Slant3D subscriptions accept unsigned deliveries."""def test_compass_accepts_unsigned_request(self):webhook = _make_webhook(ProviderName.COMPASS)resp = _run(webhook, "compass")assert resp.status_code != 403, resp.text- def test_slant3d_accepts_unsigned_request(self):+ def test_legacy_slant3d_accepts_unsigned_request(self):webhook = _make_webhook(ProviderName.SLANT3D)# Use a Slant3D-shaped payload so the provider's own payload check# doesn't 500; the assertion is about signature, not schema.@@ -190,6 +188,32 @@ class TestUnsignedProvidersPassThrough:assert resp.status_code != 403, resp.text+class TestSlant3DV2Signatures:+ def test_missing_signature_is_rejected(self):+ webhook = _make_webhook(ProviderName.SLANT3D, config={"api_version": 2})+ response = _run(webhook, "slant3d")+ assert response.status_code == 403++ def test_signed_delivery_passes_ingress(self):+ webhook = _make_webhook(ProviderName.SLANT3D, config={"api_version": 2})+ webhook.resource = "platform-1"+ body = b'{"platform_id":"platform-1","event_type":"order.shipped","data":{"order":{"public_id":"SLANT_123","status":"SHIPPED","tracking_number":"track-1"}}}'+ timestamp = str(int(time.time() * 1000))+ digest = hmac.new(+ WEBHOOK_SECRET.encode(), timestamp.encode() + b"." + body, hashlib.sha256+ ).hexdigest()+ response = _run(+ webhook,+ "slant3d",+ body=body,+ headers={+ "X-Webhook-Timestamp": timestamp,+ "X-Webhook-Signature-256": f"sha256={digest}",+ },+ )+ assert response.status_code == 200, response.text++# ---------------------------------------------------------------------------# Always-signed providers (GitHub, Telegram): existing contract is intact.# ---------------------------------------------------------------------------diff --git a/autogpt_platform/backend/backend/blocks/slant3d/README.md b/autogpt_platform/backend/backend/blocks/slant3d/README.mdnew file mode 100644index 0000000000..8432996a19--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/slant3d/README.md@@ -0,0 +1,25 @@+# Slant3D blocks++These blocks use the [Slant3D v2 API](https://slant3dapi.com/documentation/introduction), updated following the [September 8, 2026 announcement](https://x.com/slant3d/status/2097393736254959819).++## Setup and ordering++1. Connect a Slant3D v2 API key and create a platform in the Slant3D dashboard. Order drafts require a payment method on the Slant3D account, but do not charge it.+2. Supply `platform_id` for orders and file uploads. It can be omitted when the account has exactly one enabled platform.+3. Get filaments and use a filament's `publicId` as `filament_id`. Filters support PLA, PETG, OPM, and color names. Existing color/profile inputs still work when they identify exactly one available filament.+4. Use the Slicer block to upload an STL URL, workspace attachment, or data URI and estimate its cost. Its `file_id` output can be reused in order items. Order items also accept these formats in `file_url`, uploading and confirming each file before drafting.+5. Estimate Order and Estimate Shipping create uncharged drafts and return `order_id`. Pass that ID to Process Order to charge the account's payment method and submit the draft to production. Create Order combines drafting and processing.++## Compatibility++Existing block IDs and output names are retained. Order IDs are now Slant3D public IDs such as `SLANT_1234567890`. Quantity accepts existing numeric strings and sends a positive integer. `order_number` is stored as `metadata.orderNumber`; the v1 phone and residential-address inputs remain accepted but are not sent in the v2 address contract.++The Filament block retains `filament`, `hexColor`, and `colorTag`, and adds the v2 public ID, material, color, and availability fields. Slicer additionally returns the uploaded file ID. It rejects estimates priced for a different quantity instead of presenting a single-unit price as a bulk total. Order listing follows pagination; tracking reads the order's fulfillment information.++New webhook subscriptions require an explicit platform ID and verify Slant3D's HMAC-SHA256 signature with a millisecond timestamp. Registration is serialized per platform to prevent competing callback URLs. Each platform has one webhook URL, so use a dedicated platform if another application already has a subscription. Existing v1 subscriptions retain their legacy payload and unsigned-delivery behavior, using the unguessable callback URL as a bearer credential. Keep that URL private. Reconnect the trigger with a v2 key and platform ID to migrate it. Carrier codes are empty when the provider does not supply them; dummy deliveries do not trigger workflows.++## API contracts and validation++The refreshed [human-readable documentation](https://slant3dapi.com/documentation/introduction) takes precedence where the [OpenAPI specification](https://slant3dapi.com/v2/api/openapi.json) still describes earlier v2 shapes: draft requests put `platformId` inside `customer`, draft prices come from `data.totals`, processing returns the order directly in `data`, and Get Order wraps it in `data.order`.++Run `poetry run pytest backend/blocks/slant3d -q` from the backend directory. Tests mock HTTP boundaries and exercise all block examples, including upload confirmation, pricing, pagination, payment failure, and webhook authentication. They do not place real orders.diff --git a/autogpt_platform/backend/backend/blocks/slant3d/_api.py b/autogpt_platform/backend/backend/blocks/slant3d/_api.pyindex d952662e78..f7019a723b 100644--- a/autogpt_platform/backend/backend/blocks/slant3d/_api.py+++ b/autogpt_platform/backend/backend/blocks/slant3d/_api.py@@ -1,10 +1,11 @@from enum import Enumfrom typing import Literal-from pydantic import BaseModel, SecretStr+from pydantic import BaseModel, Field, SecretStr, model_validatorfrom backend.data.model import APIKeyCredentials, CredentialsField, CredentialsMetaInputfrom backend.integrations.providers import ProviderName+from backend.util.type import MediaFileTypeSlant3DCredentialsInput = CredentialsMetaInput[Literal[ProviderName.SLANT3D], Literal["api_key"]@@ -12,7 +13,7 @@ Slant3DCredentialsInput = CredentialsMetaInput[def Slant3DCredentialsField() -> Slant3DCredentialsInput:- return CredentialsField(description="Slant3D API key for authentication")+ return CredentialsField(description="Slant3D v2 API key for Bearer authentication")TEST_CREDENTIALS = APIKeyCredentials(@@ -34,13 +35,14 @@ TEST_CREDENTIALS_INPUT = {class CustomerDetails(BaseModel):name: stremail: str- phone: str+ phone: str = ""address: strcity: strstate: strzip: strcountry_iso: str = "US"is_residential: bool = True+ address_line2: str = ""class Color(Enum):@@ -51,20 +53,40 @@ class Color(Enum):class Profile(Enum):PLA = "PLA"PETG = "PETG"+ OPM = "OPM"class OrderItem(BaseModel):- # filename: str- file_url: str- quantity: str # String as per API spec- color: Color = Color.WHITE+ file_url: MediaFileType = Field(+ default=MediaFileType(""),+ description="STL file URL, workspace file, or data URI; ignored when file_id is set",+ )+ file_id: str = Field(+ default="", description="Uploaded Slant3D public file service ID"+ )+ quantity: int = Field(ge=1)+ color: str = "white"profile: Profile = Profile.PLA- # image_url: str = ""- # sku: str = ""+ filament_id: str = Field(+ default="", description="Filament public ID; overrides color and profile"+ )++ @model_validator(mode="after")+ def require_file(self):+ if not self.file_id and not self.file_url:+ raise ValueError("Provide file_id or file_url for each print item")+ return selfclass Filament(BaseModel):+ publicId: str+ name: str+ provider: str+ profile: str+ color: str+ hexValue: str+ available: bool | None = None+ imageURL: str | None = Nonefilament: strhexColor: strcolorTag: str- profile: strdiff --git a/autogpt_platform/backend/backend/blocks/slant3d/_order.py b/autogpt_platform/backend/backend/blocks/slant3d/_order.pynew file mode 100644index 0000000000..b57ed61ddc--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/slant3d/_order.py@@ -0,0 +1,54 @@+import uuid++from backend.blocks._base import BlockSchemaInput+from backend.data.model import SchemaField++from ._api import (+ TEST_CREDENTIALS_INPUT,+ CustomerDetails,+ OrderItem,+ Slant3DCredentialsField,+ Slant3DCredentialsInput,+)+++class OrderInput(BlockSchemaInput):+ credentials: Slant3DCredentialsInput = Slant3DCredentialsField()+ platform_id: str = SchemaField(+ default="",+ description="Slant3D platform ID; may be omitted when the account has one enabled platform",+ )+ order_number: str = SchemaField(+ description="Your custom order reference, stored as orderNumber in Slant3D metadata",+ default_factory=lambda: str(uuid.uuid4()),+ )+ customer: CustomerDetails = SchemaField(description="Customer shipping details")+ items: list[OrderItem] = SchemaField(description="Items to print", min_length=1)+++TEST_ORDER_INPUT = {+ "credentials": TEST_CREDENTIALS_INPUT,+ "platform_id": "55555555-5555-4555-8555-555555555555",+ "order_number": "TEST-001",+ "customer": {+ "name": "John Doe",+ "email": "[email protected]",+ "phone": "123-456-7890",+ "address": "123 Test St",+ "city": "Test City",+ "state": "TS",+ "zip": "12345",+ },+ "items": [+ {+ "file_id": "22222222-2222-4222-8222-222222222222",+ "filament_id": "33333333-3333-4333-8333-333333333333",+ "quantity": 1,+ }+ ],+}++TEST_DRAFT = {+ "order": {"publicId": "SLANT_1234567890", "status": "DRAFT"},+ "totals": {"printingCost": 3.75, "deliveryCost": 5.56, "totalCost": 9.31},+}diff --git a/autogpt_platform/backend/backend/blocks/slant3d/api_test.py b/autogpt_platform/backend/backend/blocks/slant3d/api_test.pynew file mode 100644index 0000000000..27b67af6fd--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/slant3d/api_test.py@@ -0,0 +1,271 @@+from unittest.mock import ANY, AsyncMock, Mock, patch++import pytest++from backend.blocks.slant3d._api import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from backend.blocks.slant3d.filament import Slant3DFilamentBlock+from backend.blocks.slant3d.order import (+ Slant3DCreateOrderBlock,+ Slant3DEstimateOrderBlock,+)+from backend.data.execution import ExecutionContext++CUSTOMER = {+ "name": "John Doe",+ "email": "[email protected]",+ "phone": "123-456-7890",+ "address": "123 Test St",+ "city": "Test City",+ "state": "TS",+ "zip": "12345",+}+ORDER_INPUT = {+ "credentials": TEST_CREDENTIALS_INPUT,+ "platform_id": "platform-1",+ "order_number": "TEST-001",+ "customer": CUSTOMER,+ "items": [{"file_id": "file-1", "filament_id": "filament-1", "quantity": "2"}],+}+DRAFT = {+ "order": {"publicId": "SLANT_123", "status": "DRAFT"},+ "totals": {"printingCost": 3.75, "deliveryCost": 5.56, "totalCost": 9.31},+}+++TEST_EXECUTION_CONTEXT = ExecutionContext(user_id="user-1", graph_exec_id="run-1")+++async def test_v2_auth_and_response_envelope():+ block = Slant3DFilamentBlock()+ response = Mock(ok=True, status=200)+ response.json.return_value = {"success": True, "message": "OK", "data": []}+ with patch("backend.blocks.slant3d.base.Requests") as requests:+ requests.return_value.request = AsyncMock(return_value=response)+ assert await block._make_request("GET", "filaments", "key") == response.json()+ requests.return_value.request.assert_awaited_once_with(+ method="GET",+ url="https://slant3dapi.com/v2/api/filaments",+ headers={"Authorization": "Bearer key", "Content-Type": "application/json"},+ )+++async def test_estimate_uses_draft_totals_without_processing():+ block = Slant3DEstimateOrderBlock()+ with patch.object(+ block, "_make_request", AsyncMock(return_value={"data": DRAFT})+ ) as request:+ result = dict(+ [+ output+ async for output in block.run(+ block.Input(**ORDER_INPUT),+ credentials=TEST_CREDENTIALS,+ execution_context=TEST_EXECUTION_CONTEXT,+ )+ ]+ )+ assert result == {+ "total_price": 9.31,+ "shipping_cost": 5.56,+ "printing_cost": 3.75,+ "order_id": "SLANT_123",+ }+ request.assert_awaited_once()+ assert request.call_args.args[:2] == ("POST", "orders")+ body = request.call_args.kwargs["json"]+ assert body["customer"] == {+ "platformId": "platform-1",+ "details": {+ "email": "[email protected]",+ "address": {+ "name": "John Doe",+ "line1": "123 Test St",+ "line2": "",+ "city": "Test City",+ "state": "TS",+ "zip": "12345",+ "country": "US",+ },+ },+ }+ assert body["items"] == [+ {+ "type": "PRINT",+ "quantity": 2,+ "publicFileServiceId": "file-1",+ "filamentId": "filament-1",+ }+ ]+ assert body["metadata"] == {"orderNumber": "TEST-001"}+++async def test_create_drafts_then_processes_order():+ block = Slant3DCreateOrderBlock()+ with patch.object(+ block,+ "_make_request",+ AsyncMock(+ side_effect=[+ {"data": DRAFT},+ {"data": {"publicId": "SLANT_123", "status": "PAID"}},+ ]+ ),+ ) as request:+ result = dict(+ [+ output+ async for output in block.run(+ block.Input(**ORDER_INPUT),+ credentials=TEST_CREDENTIALS,+ execution_context=TEST_EXECUTION_CONTEXT,+ )+ ]+ )+ assert result == {"order_id": "SLANT_123"}+ assert [call.args[:2] for call in request.await_args_list] == [+ ("POST", "orders"),+ ("POST", "orders/SLANT_123"),+ ]+ assert block.is_sensitive_action+++ "status,payload",+ [+ (400, {"success": False, "error": {"message": "Invalid filament"}}),+ (200, {"success": False, "message": "Invalid filament"}),+ (500, {"error": "Invalid filament"}),+ ],+)+async def test_api_errors_are_raised(status, payload):+ response = Mock(ok=status < 400, status=status)+ response.json.return_value = payload+ with patch("backend.blocks.slant3d.base.Requests") as requests:+ requests.return_value.request = AsyncMock(return_value=response)+ with pytest.raises(+ RuntimeError, match="^Slant3D API request failed: Invalid filament$"+ ):+ await Slant3DFilamentBlock()._make_request("POST", "orders", "key")+ assert requests.call_args.kwargs["retry_max_attempts"] == 1+++async def test_non_json_errors_are_readable():+ response = Mock(ok=False, status=502)+ response.json.side_effect = ValueError("HTML response")+ with patch("backend.blocks.slant3d.base.Requests") as requests:+ requests.return_value.request = AsyncMock(return_value=response)+ with pytest.raises(RuntimeError, match="HTTP 502"):+ await Slant3DFilamentBlock()._make_request("GET", "filaments", "key")+++ "platforms,expected",+ [+ ([{"id": "one", "enabled": True}], "one"),+ ([{"id": "one", "enabled": True}, {"id": "two", "enabled": False}], "one"),+ ([], None),+ ([{"id": "one"}, {"id": "two"}], None),+ ],+)+async def test_platform_selection_is_unambiguous(platforms, expected):+ block = Slant3DFilamentBlock()+ with patch.object(+ block, "_make_request", AsyncMock(return_value={"data": platforms})+ ):+ if expected:+ assert await block._resolve_platform_id("", "key") == expected+ else:+ with pytest.raises(ValueError, match="platform_id"):+ await block._resolve_platform_id("", "key")+++async def test_upload_confirms_exact_placeholder_without_forwarding_api_key(tmp_path):+ source = tmp_path / "model.stl"+ source.write_bytes(b"STL bytes")+ uploaded = []++ async def put(url, **kwargs):+ uploaded.append(kwargs["data"].read())++ block = Slant3DFilamentBlock()+ placeholder = {+ "publicFileServiceId": "file-1",+ "name": "model.stl",+ "platformId": "platform-1",+ }+ with patch.object(+ block,+ "_make_request",+ AsyncMock(+ side_effect=[+ {+ "data": {+ "presignedUrl": "https://upload.example.com/object",+ "filePlaceholder": placeholder,+ }+ },+ {"data": {"publicFileServiceId": "file-1"}},+ ]+ ),+ ) as api, patch("backend.blocks.slant3d.base.Requests") as requests, patch(+ "backend.blocks.slant3d.base.store_media_file",+ AsyncMock(return_value=str(source)),+ ) as media:+ requests.return_value.put = AsyncMock(side_effect=put)+ assert (+ await block._upload_file(+ "https://files.example.com/model.stl?download=1",+ "platform-1",+ "secret",+ execution_context=TEST_EXECUTION_CONTEXT,+ )+ == "file-1"+ )+ media.assert_awaited_once_with(+ file="https://files.example.com/model.stl?download=1",+ execution_context=TEST_EXECUTION_CONTEXT,+ return_format="for_local_processing",+ )+ requests.return_value.put.assert_awaited_once_with(+ "https://upload.example.com/object",+ data=ANY,+ headers={"Content-Type": "application/octet-stream"},+ )+ assert uploaded == [b"STL bytes"]+ assert api.await_args_list[0].kwargs["json"] == {+ "name": "model.stl",+ "platformId": "platform-1",+ }+ assert api.await_args_list[1].args[:2] == ("POST", "files/confirm-upload")+ assert api.await_args_list[1].kwargs["json"]["filePlaceholder"] is placeholder+++async def test_failed_upload_is_not_confirmed(tmp_path):+ source = tmp_path / "model.stl"+ source.write_bytes(b"STL bytes")+ block = Slant3DFilamentBlock()+ with patch.object(+ block,+ "_make_request",+ AsyncMock(+ return_value={+ "data": {+ "presignedUrl": "https://upload.example.com/object",+ "filePlaceholder": {},+ }+ }+ ),+ ) as api, patch("backend.blocks.slant3d.base.Requests") as requests, patch(+ "backend.blocks.slant3d.base.store_media_file",+ AsyncMock(return_value=str(source)),+ ) as media:+ requests.return_value.put = AsyncMock(side_effect=RuntimeError("Upload failed"))+ with pytest.raises(RuntimeError, match="Upload failed"):+ await block._upload_file(+ "https://example.com/model.stl",+ "platform-1",+ "key",+ execution_context=TEST_EXECUTION_CONTEXT,+ )+ media.assert_awaited_once()+ api.assert_awaited_once()diff --git a/autogpt_platform/backend/backend/blocks/slant3d/base.py b/autogpt_platform/backend/backend/blocks/slant3d/base.pyindex 3ce24f8ddc..fa11d31c54 100644--- a/autogpt_platform/backend/backend/blocks/slant3d/base.py+++ b/autogpt_platform/backend/backend/blocks/slant3d/base.py@@ -1,62 +1,129 @@-from typing import Any, Dict+import asyncio+from pathlib import Path+from shutil import copyfileobj+from tempfile import TemporaryFile+from urllib.parse import quotefrom backend.blocks._base import Block+from backend.data.execution import ExecutionContext+from backend.util.file import get_exec_file_path, store_media_filefrom backend.util.request import Requests+from backend.util.type import MediaFileType-from ._api import Color, CustomerDetails, OrderItem, Profile+from ._api import CustomerDetails, OrderItem, Profileclass Slant3DBlockBase(Block):- """Base block class for Slant3D API interactions"""+ BASE_URL = "https://slant3dapi.com/v2/api"- BASE_URL = "https://www.slant3dapi.com/api"-- def _get_headers(self, api_key: str) -> Dict[str, str]:- return {"api-key": api_key, "Content-Type": "application/json"}+ def _get_headers(self, api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Content-Type": "application/json",+ }async def _make_request(self, method: str, endpoint: str, api_key: str, **kwargs- ) -> Dict:- url = f"{self.BASE_URL}/{endpoint}"- response = await Requests().request(- method=method, url=url, headers=self._get_headers(api_key), **kwargs+ ) -> dict:+ response = await Requests(+ raise_for_status=False, retry_max_attempts=3 if method == "GET" else 1+ ).request(+ method=method,+ url=f"{self.BASE_URL}/{endpoint}",+ headers=self._get_headers(api_key),+ **kwargs,)- resp = response.json()-- if not response.ok:- error_msg = resp.get("error", "Unknown error")- raise RuntimeError(f"API request failed: {error_msg}")+ try:+ result = response.json()+ except ValueError as exc:+ raise RuntimeError(+ f"Slant3D returned an invalid response (HTTP {response.status})"+ ) from exc+ if not response.ok or result.get("success") is False:+ error = result.get("error") or result.get("message") or "Unknown error"+ match error:+ case {"message": str(message)}:+ error = message+ raise RuntimeError(f"Slant3D API request failed: {error}")+ return result- return resp+ async def _resolve_platform_id(self, platform_id: str, api_key: str) -> str:+ if platform_id:+ return platform_id+ response = await self._make_request("GET", "platforms", api_key)+ platforms = [p for p in response["data"] if p.get("enabled", True)]+ if len(platforms) != 1:+ raise ValueError(+ "Set platform_id to an enabled Slant3D platform ID. "+ "Automatic selection requires exactly one enabled platform."+ )+ return platforms[0]["id"]- async def _check_valid_color(- self, profile: Profile, color: Color, api_key: str+ async def _resolve_filament_id(+ self, profile: Profile, color: str, api_key: str) -> str:response = await self._make_request("GET",- "filament",+ "filaments",api_key,- params={"profile": profile.value, "color": color.value},+ params={"profile": profile.value, "color": color},)- if profile == Profile.PLA:- color_tag = color.value- else:- color_tag = f"{profile.value.lower()}{color.value.capitalize()}"- valid_tags = [filament["colorTag"] for filament in response["filaments"]]-- if color_tag not in valid_tags:+ matches = [+ filament+ for filament in response["data"]+ if filament["profile"].casefold() == profile.value.casefold()+ and filament["color"].casefold() == color.casefold()+ and filament.get("available") is not False+ ]+ if len(matches) != 1:raise ValueError(- f"""Invalid color profile combination {color_tag}.-Valid colors for {profile.value} are:-{','.join([filament['colorTag'].replace(profile.value.lower(), '') for filament in response['filaments'] if filament['profile'] == profile.value])}-"""+ f"No unique available filament for {profile.value} {color}. "+ "Choose a filament_id from the Slant3D Filament block.")- return color_tag+ return matches[0]["publicId"]- async def _convert_to_color(- self, profile: Profile, color: Color, api_key: str+ async def _upload_file(+ self,+ file_url: MediaFileType,+ platform_id: str,+ api_key: str,+ *,+ execution_context: ExecutionContext,+ staging_lock: asyncio.Lock | None = None,) -> str:- return await self._check_valid_color(profile, color, api_key)+ graph_exec_id = execution_context.graph_exec_id+ if not graph_exec_id:+ raise ValueError("execution_context.graph_exec_id is required")+ with TemporaryFile() as content:+ async with staging_lock or asyncio.Lock():+ local_path = await store_media_file(+ file=file_url,+ execution_context=execution_context,+ return_format="for_local_processing",+ )+ path = Path(get_exec_file_path(graph_exec_id, local_path))+ with path.open("rb") as source:+ await asyncio.to_thread(copyfileobj, source, content)+ content.seek(0)+ upload = await self._make_request(+ "POST",+ "files/direct-upload",+ api_key,+ json={"name": path.name, "platformId": platform_id},+ )+ data = upload["data"]+ await Requests(retry_max_attempts=1).put(+ data["presignedUrl"],+ data=content,+ headers={"Content-Type": "application/octet-stream"},+ )+ confirmed = await self._make_request(+ "POST",+ "files/confirm-upload",+ api_key,+ json={"filePlaceholder": data["filePlaceholder"]},+ )+ return confirmed["data"]["publicFileServiceId"]async def _format_order_data(self,@@ -64,37 +131,99 @@ Valid colors for {profile.value} are:order_number: str,items: list[OrderItem],api_key: str,- ) -> list[dict[str, Any]]:- """Helper function to format order data for API requests"""- orders = []- for item in items:- color_tag = await self._convert_to_color(item.profile, item.color, api_key)- order_data = {- "email": customer.email,- "phone": customer.phone,- "name": customer.name,- "orderNumber": order_number,- "filename": item.file_url,- "fileURL": item.file_url,- "bill_to_street_1": customer.address,- "bill_to_city": customer.city,- "bill_to_state": customer.state,- "bill_to_zip": customer.zip,- "bill_to_country_as_iso": customer.country_iso,- "bill_to_is_US_residential": str(customer.is_residential).lower(),- "ship_to_name": customer.name,- "ship_to_street_1": customer.address,- "ship_to_city": customer.city,- "ship_to_state": customer.state,- "ship_to_zip": customer.zip,- "ship_to_country_as_iso": customer.country_iso,- "ship_to_is_US_residential": str(customer.is_residential).lower(),- "order_item_name": item.file_url,- "order_quantity": item.quantity,- "order_image_url": "",- "order_sku": "NOT_USED",- "order_item_color": color_tag,- "profile": item.profile.value,- }- orders.append(order_data)- return orders+ platform_id: str = "",+ *,+ execution_context: ExecutionContext,+ ) -> dict:+ platform_id = await self._resolve_platform_id(platform_id, api_key)+ return {+ "customer": {+ "platformId": platform_id,+ "details": {+ "email": customer.email,+ "address": {+ "name": customer.name,+ "line1": customer.address,+ "line2": customer.address_line2,+ "city": customer.city,+ "state": customer.state,+ "zip": customer.zip,+ "country": customer.country_iso,+ },+ },+ },+ "items": await self._format_order_items(+ items, platform_id, api_key, execution_context=execution_context+ ),+ "metadata": {"orderNumber": order_number},+ }++ async def _format_order_items(+ self,+ items: list[OrderItem],+ platform_id: str,+ api_key: str,+ *,+ execution_context: ExecutionContext,+ ) -> list[dict]:+ filaments: dict[tuple[Profile, str], asyncio.Task[str]] = {}+ staging_lock = asyncio.Lock()+ concurrency = asyncio.Semaphore(4)++ async def prepare(item: OrderItem) -> dict:+ async with concurrency:+ filament_id = item.filament_id+ if not filament_id:+ key = (item.profile, item.color.casefold())+ if key not in filaments:+ filaments[key] = asyncio.create_task(+ self._resolve_filament_id(item.profile, item.color, api_key)+ )+ filament_id = await filaments[key]+ return await self._format_order_item(+ item.model_copy(update={"filament_id": filament_id}),+ platform_id,+ api_key,+ execution_context=execution_context,+ staging_lock=staging_lock,+ )++ tasks = [asyncio.create_task(prepare(item)) for item in items]+ try:+ return await asyncio.gather(*tasks)+ except BaseException:+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ raise++ async def _format_order_item(+ self,+ item: OrderItem,+ platform_id: str,+ api_key: str,+ *,+ execution_context: ExecutionContext,+ staging_lock: asyncio.Lock | None = None,+ ) -> dict:+ filament_id = item.filament_id or await self._resolve_filament_id(+ item.profile, item.color, api_key+ )+ file_id = item.file_id or await self._upload_file(+ item.file_url,+ platform_id,+ api_key,+ execution_context=execution_context,+ staging_lock=staging_lock,+ )+ return {+ "type": "PRINT",+ "publicFileServiceId": file_id,+ "filamentId": filament_id,+ "quantity": item.quantity,+ }++ async def _process_order(self, order_id: str, api_key: str) -> dict:+ return await self._make_request(+ "POST", f"orders/{quote(order_id, safe='')}", api_key+ )diff --git a/autogpt_platform/backend/backend/blocks/slant3d/conftest.py b/autogpt_platform/backend/backend/blocks/slant3d/conftest.pynew file mode 100644index 0000000000..bf36439d77--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/slant3d/conftest.py@@ -0,0 +1,13 @@+from collections.abc import AsyncIterator++import pytest_asyncio+++@pytest_asyncio.fixture(scope="session", loop_scope="session")+async def server() -> None:+ return None+++@pytest_asyncio.fixture(scope="session", loop_scope="session", autouse=True)+async def graph_cleanup() -> AsyncIterator[None]:+ yielddiff --git a/autogpt_platform/backend/backend/blocks/slant3d/examples_test.py b/autogpt_platform/backend/backend/blocks/slant3d/examples_test.pynew file mode 100644index 0000000000..c6f67cb40f--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/slant3d/examples_test.py@@ -0,0 +1,36 @@+import pytest++from backend.blocks.slant3d.filament import Slant3DFilamentBlock+from backend.blocks.slant3d.order import (+ Slant3DCreateOrderBlock,+ Slant3DEstimateOrderBlock,+ Slant3DEstimateShippingBlock,+)+from backend.blocks.slant3d.order_status import (+ Slant3DCancelOrderBlock,+ Slant3DGetOrdersBlock,+ Slant3DProcessOrderBlock,+ Slant3DTrackingBlock,+)+from backend.blocks.slant3d.slicing import Slant3DSlicerBlock+from backend.blocks.slant3d.webhook import Slant3DOrderWebhookBlock+from backend.util.test import execute_block_test+++ "block_class",+ [+ Slant3DFilamentBlock,+ Slant3DCreateOrderBlock,+ Slant3DEstimateOrderBlock,+ Slant3DEstimateShippingBlock,+ Slant3DCancelOrderBlock,+ Slant3DGetOrdersBlock,+ Slant3DProcessOrderBlock,+ Slant3DTrackingBlock,+ Slant3DSlicerBlock,+ Slant3DOrderWebhookBlock,+ ],+)+async def test_block_examples(block_class):+ await execute_block_test(block_class())diff --git a/autogpt_platform/backend/backend/blocks/slant3d/filament.py b/autogpt_platform/backend/backend/blocks/slant3d/filament.pyindex 723ebff59e..a32c92f20a 100644--- a/autogpt_platform/backend/backend/blocks/slant3d/filament.py+++ b/autogpt_platform/backend/backend/blocks/slant3d/filament.py@@ -1,5 +1,3 @@-from typing import List-from backend.blocks._base import BlockOutput, BlockSchemaInput, BlockSchemaOutputfrom backend.data.model import APIKeyCredentials, SchemaField@@ -7,27 +5,46 @@ from ._api import (TEST_CREDENTIALS,TEST_CREDENTIALS_INPUT,Filament,+ Profile,Slant3DCredentialsField,Slant3DCredentialsInput,)from .base import Slant3DBlockBase+TEST_FILAMENT = {+ "publicId": "33333333-3333-4333-8333-333333333333",+ "name": "PLA BLACK",+ "provider": "Tangled",+ "profile": "PLA",+ "color": "black",+ "hexValue": "#000000",+}-class Slant3DFilamentBlock(Slant3DBlockBase):- """Block for retrieving available filaments"""+class Slant3DFilamentBlock(Slant3DBlockBase):class Input(BlockSchemaInput):credentials: Slant3DCredentialsInput = Slant3DCredentialsField()+ profiles: list[Profile] = SchemaField(+ default_factory=list, description="Filter materials; empty returns all"+ )+ colors: list[str] = SchemaField(+ default_factory=list, description="Filter color names; empty returns all"+ )class Output(BlockSchemaOutput):- filaments: List[Filament] = SchemaField(- description="List of available filaments"+ filaments: list[Filament] = SchemaField(+ description="Available filaments; use publicId as filament_id")def __init__(self):super().__init__(id="7cc416f4-f305-4606-9b3b-452b8a81031c",- description="Get list of available filaments",+ description=(+ "Find available materials and colors for quoting or ordering physical 3D-printed parts from Slant3D. "+ "Returns filament public IDs, material, color, and availability. "+ "Use a specific filament_id when a material or color matches more than one filament. "+ "Slant3D Slicer uses default black PLA when no filament is selected."+ ),input_schema=self.Input,output_schema=self.Output,test_input={"credentials": TEST_CREDENTIALS_INPUT},@@ -37,48 +54,45 @@ class Slant3DFilamentBlock(Slant3DBlockBase):"filaments",[{+ **TEST_FILAMENT,"filament": "PLA BLACK","hexColor": "000000","colorTag": "black",- "profile": "PLA",- },- {- "filament": "PLA WHITE",- "hexColor": "ffffff",- "colorTag": "white",- "profile": "PLA",- },+ }],)],test_mock={- "_make_request": lambda *args, **kwargs: {- "filaments": [- {- "filament": "PLA BLACK",- "hexColor": "000000",- "colorTag": "black",- "profile": "PLA",- },- {- "filament": "PLA WHITE",- "hexColor": "ffffff",- "colorTag": "white",- "profile": "PLA",- },- ]- }+ "_make_request": lambda *args, **kwargs: {"data": [TEST_FILAMENT]}},)async def run(self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs) -> BlockOutput:- try:- result = await self._make_request(- "GET", "filament", credentials.api_key.get_secret_value()+ params = {}+ if input_data.profiles:+ params["profile"] = ",".join(+ profile.value for profile in input_data.profiles)- yield "filaments", result["filaments"]- except Exception as e:- yield "error", str(e)- raise+ if input_data.colors:+ params["color"] = ",".join(input_data.colors)+ result = await self._make_request(+ "GET",+ "filaments",+ credentials.api_key.get_secret_value(),+ params=params,+ )+ yield "filaments", [+ {+ **filament,+ "filament": filament["name"],+ "hexColor": filament["hexValue"].removeprefix("#"),+ "colorTag": (+ filament["color"]+ if filament["profile"].casefold() == "pla"+ else f"{filament['profile'].lower()}{filament['color'].capitalize()}"+ ),+ }+ for filament in result["data"]+ ]diff --git a/autogpt_platform/backend/backend/blocks/slant3d/order.py b/autogpt_platform/backend/backend/blocks/slant3d/order.pyindex 9eb155d168..709a4e4927 100644--- a/autogpt_platform/backend/backend/blocks/slant3d/order.py+++ b/autogpt_platform/backend/backend/blocks/slant3d/order.py@@ -1,408 +1,179 @@-import uuid-from typing import List--from backend.blocks._base import BlockOutput, BlockSchemaInput, BlockSchemaOutput+from backend.blocks._base import BlockOutput, BlockSchemaOutput+from backend.data.execution import ExecutionContextfrom backend.data.model import APIKeyCredentials, SchemaField-from backend.util.settings import BehaveAs, Settings-from ._api import (- TEST_CREDENTIALS,- TEST_CREDENTIALS_INPUT,- CustomerDetails,- OrderItem,- Slant3DCredentialsField,- Slant3DCredentialsInput,-)+from ._api import TEST_CREDENTIALS+from ._order import TEST_DRAFT, TEST_ORDER_INPUT, OrderInputfrom .base import Slant3DBlockBase-settings = Settings()-class Slant3DCreateOrderBlock(Slant3DBlockBase):- """Block for creating new orders"""-- class Input(BlockSchemaInput):- credentials: Slant3DCredentialsInput = Slant3DCredentialsField()- order_number: str = SchemaField(- description="Your custom order number (or leave blank for a random one)",- default_factory=lambda: str(uuid.uuid4()),- )- customer: CustomerDetails = SchemaField(- description="Customer details for where to ship the item",- advanced=False,- )- items: List[OrderItem] = SchemaField(- description="List of items to print",- advanced=False,- )+ Input = OrderInputclass Output(BlockSchemaOutput):- order_id: str = SchemaField(description="Slant3D order ID")+ order_id: str = SchemaField(description="Slant3D public order ID")def __init__(self):super().__init__(id="f73007d6-f48f-4aaf-9e6b-6883998a09b4",- description="Create a new print order",+ description=(+ "Order physical 3D-printed parts from Slant3D for manufacturing and delivery. "+ "Accepts multiple STL URLs, workspace attachments, or uploaded file IDs with per-part material and quantity, "+ "including complete project part sets. Creates a draft, charges the connected payment method, "+ "and submits the parts to production. Use only with real customer shipping details and order approval. "+ "For a printing-only quote without shipping or billing details, use Slant3D Slicer first."+ ),input_schema=self.Input,output_schema=self.Output,- test_input={- "credentials": TEST_CREDENTIALS_INPUT,- "order_number": "TEST-001",- "customer": {- "name": "John Doe",- "email": "[email protected]",- "phone": "123-456-7890",- "address": "123 Test St",- "city": "Test City",- "state": "TS",- "zip": "12345",- },- "items": [- {- "file_url": "https://example.com/model.stl",- "quantity": "1",- "color": "black",- "profile": "PLA",- }- ],- },+ test_input=TEST_ORDER_INPUT,test_credentials=TEST_CREDENTIALS,- test_output=[("order_id", "314144241")],+ test_output=[("order_id", "SLANT_1234567890")],test_mock={- "_make_request": lambda *args, **kwargs: {"orderId": "314144241"},- "_convert_to_color": lambda *args, **kwargs: "black",+ "_make_request": lambda *args, **kwargs: {"data": TEST_DRAFT},+ "_process_order": lambda *args, **kwargs: {+ "data": {"publicId": "SLANT_1234567890"}+ },},is_sensitive_action=True,)async def run(- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ self,+ input_data: Input,+ *,+ credentials: APIKeyCredentials,+ execution_context: ExecutionContext,+ **kwargs,) -> BlockOutput:+ api_key = credentials.api_key.get_secret_value()+ order_data = await self._format_order_data(+ input_data.customer,+ input_data.order_number,+ input_data.items,+ api_key,+ input_data.platform_id,+ execution_context=execution_context,+ )+ result = await self._make_request("POST", "orders", api_key, json=order_data)+ order_id = result["data"]["order"]["publicId"]try:- order_data = await self._format_order_data(- input_data.customer,- input_data.order_number,- input_data.items,- credentials.api_key.get_secret_value(),- )- result = await self._make_request(- "POST", "order", credentials.api_key.get_secret_value(), json=order_data- )- yield "order_id", result["orderId"]- except Exception as e:- yield "error", str(e)- raise+ await self._process_order(order_id, api_key)+ except Exception as exc:+ raise RuntimeError(+ f"Could not confirm processing of draft {order_id}. "+ "Check its status before retrying to avoid a duplicate order."+ ) from exc+ yield "order_id", order_idclass Slant3DEstimateOrderBlock(Slant3DBlockBase):- """Block for getting order cost estimates"""-- class Input(BlockSchemaInput):- credentials: Slant3DCredentialsInput = Slant3DCredentialsField()- order_number: str = SchemaField(- description="Your custom order number (or leave blank for a random one)",- default_factory=lambda: str(uuid.uuid4()),- )- customer: CustomerDetails = SchemaField(- description="Customer details for where to ship the item",- advanced=False,- )- items: List[OrderItem] = SchemaField(- description="List of items to print",- advanced=False,- )+ Input = OrderInputclass Output(BlockSchemaOutput):total_price: float = SchemaField(description="Total price in USD")- shipping_cost: float = SchemaField(description="Shipping cost")- printing_cost: float = SchemaField(description="Printing cost")+ shipping_cost: float = SchemaField(description="Shipping cost in USD")+ printing_cost: float = SchemaField(description="Printing cost in USD")+ order_id: str = SchemaField(+ description="Uncharged draft ID; pass to Process Order to place it"+ )def __init__(self):super().__init__(id="bf8823d6-b42a-48c7-b558-d7c117f2ae85",- description="Get order cost estimate",+ description=(+ "Quote a 3D-printed parts order including shipping by creating an uncharged Slant3D draft. "+ "Accepts multiple STL files or uploaded file IDs with per-part quantities. "+ "Requires real customer shipping details and an account payment method; do not invent an address. "+ "For printing-only part or project quotes without shipping details, use Slant3D Slicer for each file instead. "+ "Returns a draft ID that Process Order can submit after approval."+ ),input_schema=self.Input,output_schema=self.Output,- test_input={- "credentials": TEST_CREDENTIALS_INPUT,- "order_number": "TEST-001",- "customer": {- "name": "John Doe",- "email": "[email protected]",- "phone": "123-456-7890",- "address": "123 Test St",- "city": "Test City",- "state": "TS",- "zip": "12345",- },- "items": [- {- "file_url": "https://example.com/model.stl",- "quantity": "1",- "color": "black",- "profile": "PLA",- }- ],- },+ test_input=TEST_ORDER_INPUT,test_credentials=TEST_CREDENTIALS,test_output=[("total_price", 9.31),("shipping_cost", 5.56),("printing_cost", 3.75),+ ("order_id", "SLANT_1234567890"),],- test_mock={- "_make_request": lambda *args, **kwargs: {- "totalPrice": 9.31,- "shippingCost": 5.56,- "printingCost": 3.75,- },- "_convert_to_color": lambda *args, **kwargs: "black",- },+ test_mock={"_make_request": lambda *args, **kwargs: {"data": TEST_DRAFT}},)async def run(- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ self,+ input_data: Input,+ *,+ credentials: APIKeyCredentials,+ execution_context: ExecutionContext,+ **kwargs,) -> BlockOutput:+ api_key = credentials.api_key.get_secret_value()order_data = await self._format_order_data(input_data.customer,input_data.order_number,input_data.items,- credentials.api_key.get_secret_value(),- )- result = await self._make_request(- "POST",- "order/estimate",- credentials.api_key.get_secret_value(),- json=order_data,+ api_key,+ input_data.platform_id,+ execution_context=execution_context,)- yield "total_price", result["totalPrice"]- yield "shipping_cost", result["shippingCost"]- yield "printing_cost", result["printingCost"]+ result = await self._make_request("POST", "orders", api_key, json=order_data)+ draft = result["data"]+ yield "total_price", float(draft["totals"]["totalCost"])+ yield "shipping_cost", float(draft["totals"]["deliveryCost"])+ yield "printing_cost", float(draft["totals"]["printingCost"])+ yield "order_id", draft["order"]["publicId"]class Slant3DEstimateShippingBlock(Slant3DBlockBase):- """Block for getting shipping cost estimates"""-- class Input(BlockSchemaInput):- credentials: Slant3DCredentialsInput = Slant3DCredentialsField()- order_number: str = SchemaField(- description="Your custom order number (or leave blank for a random one)",- default_factory=lambda: str(uuid.uuid4()),- )- customer: CustomerDetails = SchemaField(- description="Customer details for where to ship the item"- )- items: List[OrderItem] = SchemaField(- description="List of items to print",- advanced=False,- )+ Input = OrderInputclass Output(BlockSchemaOutput):- shipping_cost: float = SchemaField(description="Estimated shipping cost")- currency_code: str = SchemaField(description="Currency code (e.g., 'usd')")-- def __init__(self):- super().__init__(- id="00aae2a1-caf6-4a74-8175-39a0615d44e1",- description="Get shipping cost estimate",- input_schema=self.Input,- output_schema=self.Output,- test_input={- "credentials": TEST_CREDENTIALS_INPUT,- "order_number": "TEST-001",- "customer": {- "name": "John Doe",- "email": "[email protected]",- "phone": "123-456-7890",- "address": "123 Test St",- "city": "Test City",- "state": "TS",- "zip": "12345",- },- "items": [- {- "file_url": "https://example.com/model.stl",- "quantity": "1",- "color": "black",- "profile": "PLA",- }- ],- },- test_credentials=TEST_CREDENTIALS,- test_output=[("shipping_cost", 4.81), ("currency_code", "usd")],- test_mock={- "_make_request": lambda *args, **kwargs: {- "shippingCost": 4.81,- "currencyCode": "usd",- },- "_convert_to_color": lambda *args, **kwargs: "black",- },+ shipping_cost: float = SchemaField(description="Estimated shipping cost in USD")+ currency_code: str = SchemaField(description="Currency code")+ order_id: str = SchemaField(+ description="Uncharged draft ID; pass to Process Order to place it")- async def run(- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs- ) -> BlockOutput:- try:- order_data = await self._format_order_data(- input_data.customer,- input_data.order_number,- input_data.items,- credentials.api_key.get_secret_value(),- )- result = await self._make_request(- "POST",- "order/estimateShipping",- credentials.api_key.get_secret_value(),- json=order_data,- )- yield "shipping_cost", result["shippingCost"]- yield "currency_code", result["currencyCode"]- except Exception as e:- yield "error", str(e)- raise---class Slant3DGetOrdersBlock(Slant3DBlockBase):- """Block for retrieving all orders"""-- class Input(BlockSchemaInput):- credentials: Slant3DCredentialsInput = Slant3DCredentialsField()-- class Output(BlockSchemaOutput):- orders: List[str] = SchemaField(description="List of orders with their details")-def __init__(self):super().__init__(- id="42283bf5-8a32-4fb4-92a2-60a9ea48e105",- description="Get all orders for the account",+ id="00aae2a1-caf6-4a74-8175-39a0615d44e1",+ description=(+ "Estimate delivery costs for physical 3D-printed parts by creating an uncharged Slant3D order draft. "+ "Requires real customer shipping details and an account payment method. "+ "For printing-only quotes without an address or billing setup, use Slant3D Slicer instead. "+ "Returns shipping cost and the draft ID; does not charge or submit the order."+ ),input_schema=self.Input,output_schema=self.Output,- # This block is disabled for cloud hosted because it allows access to all orders for the account- disabled=settings.config.behave_as == BehaveAs.CLOUD,- test_input={"credentials": TEST_CREDENTIALS_INPUT},+ test_input=TEST_ORDER_INPUT,test_credentials=TEST_CREDENTIALS,test_output=[- (- "orders",- [- "1234567890",- ],- )+ ("shipping_cost", 5.56),+ ("currency_code", "usd"),+ ("order_id", "SLANT_1234567890"),],- test_mock={- "_make_request": lambda *args, **kwargs: {- "ordersData": [- {- "orderId": 1234567890,- "orderTimestamp": {- "_seconds": 1719510986,- "_nanoseconds": 710000000,- },- }- ]- }- },- )-- async def run(- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs- ) -> BlockOutput:- try:- result = await self._make_request(- "GET", "order", credentials.api_key.get_secret_value()- )- yield "orders", [str(order["orderId"]) for order in result["ordersData"]]- except Exception as e:- yield "error", str(e)- raise---class Slant3DTrackingBlock(Slant3DBlockBase):- """Block for tracking order status and shipping"""-- class Input(BlockSchemaInput):- credentials: Slant3DCredentialsInput = Slant3DCredentialsField()- order_id: str = SchemaField(description="Slant3D order ID to track")-- class Output(BlockSchemaOutput):- status: str = SchemaField(description="Order status")- tracking_numbers: List[str] = SchemaField(- description="List of tracking numbers"- )-- def __init__(self):- super().__init__(- id="dd7c0293-c5af-4551-ba3e-fc162fb1fb89",- description="Track order status and shipping",- input_schema=self.Input,- output_schema=self.Output,- test_input={- "credentials": TEST_CREDENTIALS_INPUT,- "order_id": "314144241",- },- test_credentials=TEST_CREDENTIALS,- test_output=[("status", "awaiting_shipment"), ("tracking_numbers", [])],- test_mock={- "_make_request": lambda *args, **kwargs: {- "status": "awaiting_shipment",- "trackingNumbers": [],- }- },+ test_mock={"_make_request": lambda *args, **kwargs: {"data": TEST_DRAFT}},)async def run(- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ self,+ input_data: Input,+ *,+ credentials: APIKeyCredentials,+ execution_context: ExecutionContext,+ **kwargs,) -> BlockOutput:- try:- result = await self._make_request(- "GET",- f"order/{input_data.order_id}/get-tracking",- credentials.api_key.get_secret_value(),- )- yield "status", result["status"]- yield "tracking_numbers", result["trackingNumbers"]- except Exception as e:- yield "error", str(e)- raise---class Slant3DCancelOrderBlock(Slant3DBlockBase):- """Block for canceling orders"""-- class Input(BlockSchemaInput):- credentials: Slant3DCredentialsInput = Slant3DCredentialsField()- order_id: str = SchemaField(description="Slant3D order ID to cancel")-- class Output(BlockSchemaOutput):- status: str = SchemaField(description="Cancellation status message")-- def __init__(self):- super().__init__(- id="54de35e1-407f-450b-b5fa-3b5e2eba8185",- description="Cancel an existing order",- input_schema=self.Input,- output_schema=self.Output,- test_input={- "credentials": TEST_CREDENTIALS_INPUT,- "order_id": "314144241",- },- test_credentials=TEST_CREDENTIALS,- test_output=[("status", "Order cancelled")],- test_mock={- "_make_request": lambda *args, **kwargs: {"status": "Order cancelled"}- },- )-- async def run(- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs- ) -> BlockOutput:- try:- result = await self._make_request(- "DELETE",- f"order/{input_data.order_id}",- credentials.api_key.get_secret_value(),- )- yield "status", result["status"]- except Exception as e:- yield "error", str(e)- raise+ api_key = credentials.api_key.get_secret_value()+ order_data = await self._format_order_data(+ input_data.customer,+ input_data.order_number,+ input_data.items,+ api_key,+ input_data.platform_id,+ execution_context=execution_context,+ )+ result = await self._make_request("POST", "orders", api_key, json=order_data)+ yield "shipping_cost", float(result["data"]["totals"]["deliveryCost"])+ yield "currency_code", "usd"+ yield "order_id", result["data"]["order"]["publicId"]diff --git a/autogpt_platform/backend/backend/blocks/slant3d/order_preparation_test.py b/autogpt_platform/backend/backend/blocks/slant3d/order_preparation_test.pynew file mode 100644index 0000000000..243f7e18a5--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/slant3d/order_preparation_test.py@@ -0,0 +1,288 @@+import asyncio+from unittest.mock import AsyncMock, Mock, patch++import pytest++from backend.blocks.slant3d._api import TEST_CREDENTIALS, OrderItem, Profile+from backend.blocks.slant3d._order import TEST_ORDER_INPUT, OrderInput+from backend.blocks.slant3d.order import Slant3DCreateOrderBlock+from backend.data.execution import ExecutionContext++CONTEXT = ExecutionContext(user_id="user-1", graph_exec_id="run-1")+++async def test_order_uploads_overlap_and_keep_input_order():+ block = Slant3DCreateOrderBlock()+ inputs = OrderInput(**TEST_ORDER_INPUT)+ items = [+ OrderItem(file_url=f"https://example.com/{i}.stl", quantity=i + 1)+ for i in range(3)+ ]+ started = asyncio.Event()+ release = [asyncio.Event() for _ in items]+ finished = [asyncio.Event() for _ in items]+ uploads = []++ async def upload(file_url, *args, **kwargs):+ index = int(file_url.rsplit("/", 1)[1].split(".")[0])+ uploads.append(index)+ if len(uploads) == len(items):+ started.set()+ await release[index].wait()+ finished[index].set()+ return f"file-{index}"++ with (+ patch.object(block, "_resolve_filament_id", AsyncMock(return_value="filament")),+ patch.object(block, "_upload_file", AsyncMock(side_effect=upload)),+ ):+ task = asyncio.create_task(+ block._format_order_data(+ inputs.customer,+ inputs.order_number,+ items,+ "key",+ inputs.platform_id,+ execution_context=CONTEXT,+ )+ )+ try:+ await asyncio.wait_for(started.wait(), 2)+ for index in reversed(range(len(items))):+ release[index].set()+ await asyncio.wait_for(finished[index].wait(), 2)+ result = await task+ finally:+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ assert result["items"] == [+ {+ "type": "PRINT",+ "publicFileServiceId": f"file-{index}",+ "filamentId": "filament",+ "quantity": index + 1,+ }+ for index in range(3)+ ]+++async def test_filament_lookups_are_shared_per_pair_and_isolated_per_order():+ block = Slant3DCreateOrderBlock()+ inputs = OrderInput(**TEST_ORDER_INPUT)+ items = [+ OrderItem(file_id="one", quantity=1, color="black"),+ OrderItem(file_id="two", quantity=2, color="BLACK"),+ OrderItem(file_id="three", quantity=1, color="black", profile=Profile.PETG),+ OrderItem(file_id="four", quantity=1, color="white"),+ OrderItem(file_id="five", quantity=1, filament_id="explicit"),+ ]++ async def request(method, endpoint, api_key, **kwargs):+ assert (method, endpoint) == ("GET", "filaments")+ profile, color = kwargs["params"]["profile"], kwargs["params"]["color"]+ return {+ "data": [+ {+ "profile": profile,+ "color": color,+ "publicId": f"{api_key}-{profile}-{color.casefold()}",+ }+ ]+ }++ with (+ patch.object(block, "_make_request", AsyncMock(side_effect=request)) as api,+ patch.object(block, "_upload_file", AsyncMock()) as upload,+ ):+ results = await asyncio.gather(+ *(+ block._format_order_data(+ inputs.customer,+ inputs.order_number,+ items,+ key,+ inputs.platform_id,+ execution_context=CONTEXT,+ )+ for key in ("first", "second")+ )+ )+ results.append(+ await block._format_order_data(+ inputs.customer,+ inputs.order_number,+ items,+ "first",+ inputs.platform_id,+ execution_context=CONTEXT,+ )+ )+ assert api.await_count == 9+ upload.assert_not_awaited()+ for key, result in zip(("first", "second", "first"), results):+ assert [item["filamentId"] for item in result["items"]] == [+ f"{key}-PLA-black",+ f"{key}-PLA-black",+ f"{key}-PETG-black",+ f"{key}-PLA-white",+ "explicit",+ ]+ assert [item.filament_id for item in items] == ["", "", "", "", "explicit"]+++async def test_preparation_failure_cancels_uploads_without_drafting():+ block = Slant3DCreateOrderBlock()+ started = asyncio.Event()+ cancelled = asyncio.Event()++ async def upload(file_url, *args, **kwargs):+ if file_url.endswith("bad.stl"):+ await started.wait()+ raise ValueError("Upload rejected")+ started.set()+ try:+ await asyncio.Event().wait()+ finally:+ cancelled.set()++ inputs = block.Input(+ **{+ **TEST_ORDER_INPUT,+ "items": [+ {"file_url": f"https://example.com/{name}.stl", "quantity": 1}+ for name in ("bad", "pending")+ ],+ }+ )+ with (+ patch.object(block, "_resolve_filament_id", AsyncMock(return_value="filament")),+ patch.object(block, "_upload_file", AsyncMock(side_effect=upload)),+ patch.object(block, "_make_request", AsyncMock()) as api,+ patch.object(block, "_process_order", AsyncMock()) as process,+ ):+ with pytest.raises(ValueError, match="Upload rejected"):+ await asyncio.wait_for(+ anext(+ block.run(+ inputs, credentials=TEST_CREDENTIALS, execution_context=CONTEXT+ )+ ),+ 2,+ )+ assert cancelled.is_set()+ api.assert_not_awaited()+ process.assert_not_awaited()+++async def test_parallel_uploads_preserve_different_files_with_the_same_name(tmp_path):+ block = Slant3DCreateOrderBlock()+ inputs = OrderInput(**TEST_ORDER_INPUT)+ started = asyncio.Event()+ uploaded = []+ count = 0++ async def request(method, endpoint, api_key, **kwargs):+ nonlocal count+ if endpoint == "files/direct-upload":+ count += 1+ index = count+ if count == 2:+ started.set()+ await started.wait()+ return {+ "data": {+ "presignedUrl": f"https://upload.example.com/{index}",+ "filePlaceholder": index,+ }+ }+ assert endpoint == "files/confirm-upload"+ return {"data": {"publicFileServiceId": str(kwargs["json"]["filePlaceholder"])}}++ async def put(url, **kwargs):+ uploaded.append(kwargs["data"].read())++ downloader = Mock()+ downloader.get = AsyncMock(+ side_effect=[Mock(content=b"first STL"), Mock(content=b"second STL")]+ )+ with (+ patch("backend.util.file.TEMP_DIR", tmp_path),+ patch(+ "backend.util.file.get_cloud_storage_handler",+ AsyncMock(return_value=Mock(is_cloud_path=Mock(return_value=False))),+ ),+ patch("backend.util.file.scan_content_safe", AsyncMock()),+ patch("backend.util.file.Requests", return_value=downloader),+ patch("backend.blocks.slant3d.base.Requests") as requests,+ patch.object(block, "_make_request", AsyncMock(side_effect=request)),+ ):+ requests.return_value.put = AsyncMock(side_effect=put)+ await asyncio.wait_for(+ block._format_order_data(+ inputs.customer,+ inputs.order_number,+ [+ OrderItem(+ file_url=f"https://example.com/{folder}/part.stl",+ filament_id="filament",+ quantity=1,+ )+ for folder in ("one", "two")+ ],+ "key",+ inputs.platform_id,+ execution_context=CONTEXT,+ ),+ 2,+ )+ assert sorted(uploaded) == [b"first STL", b"second STL"]+++async def test_large_orders_limit_active_uploads():+ block = Slant3DCreateOrderBlock()+ inputs = OrderInput(**TEST_ORDER_INPUT)+ started = asyncio.Event()+ release = asyncio.Event()+ active = 0+ maximum = 0++ async def upload(file_url, *args, **kwargs):+ nonlocal active, maximum+ active += 1+ maximum = max(maximum, active)+ if active == 4:+ started.set()+ try:+ await release.wait()+ return file_url.rsplit("/", 1)[-1]+ finally:+ active -= 1++ with patch.object(block, "_upload_file", AsyncMock(side_effect=upload)):+ task = asyncio.create_task(+ block._format_order_data(+ inputs.customer,+ inputs.order_number,+ [+ OrderItem(+ file_url=f"https://example.com/{i}.stl",+ filament_id="filament",+ quantity=1,+ )+ for i in range(12)+ ],+ "key",+ inputs.platform_id,+ execution_context=CONTEXT,+ )+ )+ try:+ await asyncio.wait_for(started.wait(), 2)+ assert active == 4+ release.set()+ result = await task+ finally:+ task.cancel()+ await asyncio.gather(task, return_exceptions=True)+ assert len(result["items"]) == 12+ assert maximum == 4diff --git a/autogpt_platform/backend/backend/blocks/slant3d/order_status.py b/autogpt_platform/backend/backend/blocks/slant3d/order_status.pynew file mode 100644index 0000000000..c246eaa178--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/slant3d/order_status.py@@ -0,0 +1,191 @@+from urllib.parse import quote++from backend.blocks._base import BlockOutput, BlockSchemaInput, BlockSchemaOutput+from backend.data.model import APIKeyCredentials, SchemaField+from backend.util.settings import BehaveAs, Settings++from ._api import (+ TEST_CREDENTIALS,+ TEST_CREDENTIALS_INPUT,+ Slant3DCredentialsField,+ Slant3DCredentialsInput,+)+from .base import Slant3DBlockBase++PAGE_LIMIT = 100+++class Slant3DGetOrdersBlock(Slant3DBlockBase):+ class Input(BlockSchemaInput):+ credentials: Slant3DCredentialsInput = Slant3DCredentialsField()++ class Output(BlockSchemaOutput):+ orders: list[str] = SchemaField(+ description="Public IDs of all orders for the account"+ )++ def __init__(self):+ super().__init__(+ id="42283bf5-8a32-4fb4-92a2-60a9ea48e105",+ description="Get all orders for the account",+ input_schema=self.Input,+ output_schema=self.Output,+ disabled=Settings().config.behave_as == BehaveAs.CLOUD,+ test_input={"credentials": TEST_CREDENTIALS_INPUT},+ test_credentials=TEST_CREDENTIALS,+ test_output=[("orders", ["SLANT_1234567890"])],+ test_mock={+ "_make_request": lambda *args, **kwargs: {+ "data": [{"publicId": "SLANT_1234567890"}],+ "pagination": {"totalPages": 1},+ }+ },+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ page = 1+ orders = []+ while True:+ result = await self._make_request(+ "GET",+ "orders",+ credentials.api_key.get_secret_value(),+ params={"page": page, "limit": PAGE_LIMIT},+ )+ orders.extend(order["publicId"] for order in result["data"])+ total_pages = result.get("pagination", {}).get("totalPages")+ if not result["data"] or (total_pages is not None and page >= total_pages):+ break+ if total_pages is None and len(result["data"]) < PAGE_LIMIT:+ break+ page += 1+ yield "orders", orders+++class Slant3DTrackingBlock(Slant3DBlockBase):+ class Input(BlockSchemaInput):+ credentials: Slant3DCredentialsInput = Slant3DCredentialsField()+ order_id: str = SchemaField(description="Slant3D public order ID to track")++ class Output(BlockSchemaOutput):+ status: str = SchemaField(description="Order status")+ tracking_numbers: list[str] = SchemaField(+ description="Shipment tracking numbers"+ )++ def __init__(self):+ super().__init__(+ id="dd7c0293-c5af-4551-ba3e-fc162fb1fb89",+ description="Track order status and shipping",+ input_schema=self.Input,+ output_schema=self.Output,+ test_input={+ "credentials": TEST_CREDENTIALS_INPUT,+ "order_id": "SLANT_1234567890",+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[("status", "PAID"), ("tracking_numbers", [])],+ test_mock={+ "_make_request": lambda *args, **kwargs: {+ "data": {"order": {"status": "PAID", "fulfillment": None}}+ }+ },+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ result = await self._make_request(+ "GET",+ f"orders/{quote(input_data.order_id, safe='')}",+ credentials.api_key.get_secret_value(),+ )+ order = result["data"]["order"]+ yield "status", order["status"]+ yield "tracking_numbers", (order.get("fulfillment") or {}).get(+ "trackingNumbers"+ ) or []+++class Slant3DCancelOrderBlock(Slant3DBlockBase):+ class Input(BlockSchemaInput):+ credentials: Slant3DCredentialsInput = Slant3DCredentialsField()+ order_id: str = SchemaField(description="Slant3D public order ID to cancel")++ class Output(BlockSchemaOutput):+ status: str = SchemaField(description="Cancellation status message")++ def __init__(self):+ super().__init__(+ id="54de35e1-407f-450b-b5fa-3b5e2eba8185",+ description="Cancel an order before production starts",+ input_schema=self.Input,+ output_schema=self.Output,+ test_input={+ "credentials": TEST_CREDENTIALS_INPUT,+ "order_id": "SLANT_1234567890",+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[("status", "Order cancelled")],+ test_mock={+ "_make_request": lambda *args, **kwargs: {+ "success": True,+ "message": "Order cancelled",+ }+ },+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ result = await self._make_request(+ "DELETE",+ f"orders/{quote(input_data.order_id, safe='')}",+ credentials.api_key.get_secret_value(),+ )+ yield "status", result.get("message") or "Order cancelled"+++class Slant3DProcessOrderBlock(Slant3DBlockBase):+ class Input(BlockSchemaInput):+ credentials: Slant3DCredentialsInput = Slant3DCredentialsField()+ order_id: str = SchemaField(+ description="Uncharged draft order ID from an estimate block"+ )++ class Output(BlockSchemaOutput):+ order_id: str = SchemaField(description="Processed Slant3D public order ID")++ def __init__(self):+ super().__init__(+ id="f46fe306-86d8-4da4-8043-ad93614ed2b7",+ description=(+ "Submit an approved Slant3D draft to order physical 3D-printed parts for manufacturing and delivery. "+ "Uses the order_id from Estimate Order or Estimate Shipping, charges the connected payment method, "+ "and starts production. Run only after the customer approves the quoted order."+ ),+ input_schema=self.Input,+ output_schema=self.Output,+ test_input={+ "credentials": TEST_CREDENTIALS_INPUT,+ "order_id": "SLANT_1234567890",+ },+ test_credentials=TEST_CREDENTIALS,+ test_output=[("order_id", "SLANT_1234567890")],+ test_mock={+ "_make_request": lambda *args, **kwargs: {+ "data": {"publicId": "SLANT_1234567890"}+ }+ },+ is_sensitive_action=True,+ )++ async def run(+ self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ ) -> BlockOutput:+ result = await self._process_order(+ input_data.order_id, credentials.api_key.get_secret_value()+ )+ yield "order_id", result["data"]["publicId"]diff --git a/autogpt_platform/backend/backend/blocks/slant3d/slant3d_blocks_test.py b/autogpt_platform/backend/backend/blocks/slant3d/slant3d_blocks_test.pynew file mode 100644index 0000000000..883def0cb1--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/slant3d/slant3d_blocks_test.py@@ -0,0 +1,320 @@+from unittest.mock import AsyncMock, patch++import pytest+from pydantic import ValidationError++from backend.blocks.slant3d._api import (+ TEST_CREDENTIALS,+ TEST_CREDENTIALS_INPUT,+ OrderItem,+ Profile,+)+from backend.blocks.slant3d._order import TEST_DRAFT, TEST_ORDER_INPUT, OrderInput+from backend.blocks.slant3d.filament import TEST_FILAMENT, Slant3DFilamentBlock+from backend.blocks.slant3d.order import (+ Slant3DCreateOrderBlock,+ Slant3DEstimateShippingBlock,+)+from backend.blocks.slant3d.order_status import (+ Slant3DCancelOrderBlock,+ Slant3DGetOrdersBlock,+ Slant3DProcessOrderBlock,+ Slant3DTrackingBlock,+)+from backend.blocks.slant3d.slicing import Slant3DSlicerBlock+from backend.data.execution import ExecutionContext++TEST_EXECUTION_CONTEXT = ExecutionContext(user_id="user-1", graph_exec_id="run-1")+++async def test_filament_filters_and_legacy_output_fields():+ block = Slant3DFilamentBlock()+ with patch.object(+ block, "_make_request", AsyncMock(return_value={"data": [TEST_FILAMENT]})+ ) as request:+ result = dict(+ [+ out+ async for out in block.run(+ block.Input(+ credentials=TEST_CREDENTIALS_INPUT,+ profiles=[Profile.PLA, Profile.OPM],+ colors=["black", "blue"],+ ),+ credentials=TEST_CREDENTIALS,+ execution_context=TEST_EXECUTION_CONTEXT,+ )+ ]+ )+ assert request.call_args.args[:2] == ("GET", "filaments")+ assert request.call_args.kwargs["params"] == {+ "profile": "PLA,OPM",+ "color": "black,blue",+ }+ assert result["filaments"][0]["publicId"] == TEST_FILAMENT["publicId"]+ assert result["filaments"][0]["colorTag"] == "black"+ assert result["filaments"][0]["hexColor"] == "000000"+++async def test_exact_filament_match_ignores_partial_and_unavailable_matches():+ block = Slant3DFilamentBlock()+ filaments = [+ {**TEST_FILAMENT, "publicId": "matte", "color": "matte black"},+ {**TEST_FILAMENT, "publicId": "unavailable", "available": False},+ TEST_FILAMENT,+ ]+ with patch.object(+ block, "_make_request", AsyncMock(return_value={"data": filaments})+ ):+ assert (+ await block._resolve_filament_id(Profile.PLA, "black", "key")+ == TEST_FILAMENT["publicId"]+ )+++ "filaments",+ [[], [{**TEST_FILAMENT, "available": False}], [TEST_FILAMENT, TEST_FILAMENT]],+)+async def test_unavailable_or_ambiguous_filaments_require_explicit_choice(filaments):+ block = Slant3DFilamentBlock()+ with patch.object(+ block, "_make_request", AsyncMock(return_value={"data": filaments})+ ):+ with pytest.raises(ValueError, match="filament_id"):+ await block._resolve_filament_id(Profile.PLA, "black", "key")++[email protected]("quantity", [0, -1, "invalid", 1.5])+def test_invalid_print_quantity_is_rejected(quantity):+ with pytest.raises(ValidationError):+ OrderItem(file_id="file-1", quantity=quantity)+++def test_missing_file_and_empty_orders_are_rejected():+ with pytest.raises(ValidationError, match="file_id or file_url"):+ OrderItem(quantity=1)+ with pytest.raises(ValidationError):+ OrderInput(**{**TEST_ORDER_INPUT, "items": []})+++async def test_legacy_url_items_are_uploaded_and_use_numeric_quantity():+ block = Slant3DCreateOrderBlock()+ item = OrderItem(+ file_url="https://example.com/model.stl", quantity="2", color="black"+ )+ with patch.object(+ block, "_resolve_filament_id", AsyncMock(return_value="filament-1")+ ) as filament, patch.object(+ block, "_upload_file", AsyncMock(return_value="file-1")+ ) as upload:+ result = await block._format_order_item(+ item, "platform-1", "key", execution_context=TEST_EXECUTION_CONTEXT+ )+ filament.assert_awaited_once_with(Profile.PLA, "black", "key")+ upload.assert_awaited_once_with(+ "https://example.com/model.stl",+ "platform-1",+ "key",+ execution_context=TEST_EXECUTION_CONTEXT,+ staging_lock=None,+ )+ assert result == {+ "type": "PRINT",+ "quantity": 2,+ "publicFileServiceId": "file-1",+ "filamentId": "filament-1",+ }+++async def test_order_processing_failure_identifies_draft_and_does_not_retry():+ block = Slant3DCreateOrderBlock()+ with patch.object(+ block,+ "_make_request",+ AsyncMock(side_effect=[{"data": TEST_DRAFT}, RuntimeError("Payment failed")]),+ ) as request:+ with pytest.raises(RuntimeError, match="SLANT_1234567890.*Check its status"):+ _ = [+ out+ async for out in block.run(+ block.Input(**TEST_ORDER_INPUT),+ credentials=TEST_CREDENTIALS,+ execution_context=TEST_EXECUTION_CONTEXT,+ )+ ]+ assert request.await_count == 2+++async def test_shipping_estimate_does_not_process_order():+ block = Slant3DEstimateShippingBlock()+ with patch.object(+ block, "_make_request", AsyncMock(return_value={"data": TEST_DRAFT})+ ) as request:+ result = dict(+ [+ out+ async for out in block.run(+ block.Input(**TEST_ORDER_INPUT),+ credentials=TEST_CREDENTIALS,+ execution_context=TEST_EXECUTION_CONTEXT,+ )+ ]+ )+ assert result == {+ "shipping_cost": 5.56,+ "currency_code": "usd",+ "order_id": "SLANT_1234567890",+ }+ assert request.await_count == 1+ assert request.call_args.args[:2] == ("POST", "orders")+++async def test_get_orders_fetches_every_page():+ block = Slant3DGetOrdersBlock()+ with patch.object(+ block,+ "_make_request",+ AsyncMock(+ side_effect=[+ {"data": [{"publicId": "one"}], "pagination": {"totalPages": 2}},+ {"data": [{"publicId": "two"}], "pagination": {"totalPages": 2}},+ ]+ ),+ ) as request:+ result = dict(+ [+ out+ async for out in block.run(+ block.Input(credentials=TEST_CREDENTIALS_INPUT),+ credentials=TEST_CREDENTIALS,+ execution_context=TEST_EXECUTION_CONTEXT,+ )+ ]+ )+ assert result == {"orders": ["one", "two"]}+ assert [call.kwargs["params"]["page"] for call in request.await_args_list] == [1, 2]+++ "fulfillment,tracking",+ [(None, []), ({"trackingNumbers": ["track-1"]}, ["track-1"])],+)+async def test_tracking_reads_fulfillment(fulfillment, tracking):+ block = Slant3DTrackingBlock()+ with patch.object(+ block,+ "_make_request",+ AsyncMock(+ return_value={+ "data": {"order": {"status": "SHIPPED", "fulfillment": fulfillment}}+ }+ ),+ ) as request:+ result = dict(+ [+ out+ async for out in block.run(+ block.Input(+ credentials=TEST_CREDENTIALS_INPUT, order_id="SLANT_123"+ ),+ credentials=TEST_CREDENTIALS,+ execution_context=TEST_EXECUTION_CONTEXT,+ )+ ]+ )+ assert request.call_args.args[:2] == ("GET", "orders/SLANT_123")+ assert result == {"status": "SHIPPED", "tracking_numbers": tracking}+++async def test_cancellation_reads_envelope_message():+ block = Slant3DCancelOrderBlock()+ with patch.object(+ block,+ "_make_request",+ AsyncMock(return_value={"success": True, "message": "Order cancelled"}),+ ) as request:+ result = dict(+ [+ out+ async for out in block.run(+ block.Input(+ credentials=TEST_CREDENTIALS_INPUT, order_id="SLANT_123"+ ),+ credentials=TEST_CREDENTIALS,+ execution_context=TEST_EXECUTION_CONTEXT,+ )+ ]+ )+ assert request.call_args.args[:2] == ("DELETE", "orders/SLANT_123")+ assert result == {"status": "Order cancelled"}+++async def test_process_existing_draft_is_sensitive_and_does_not_create_another():+ block = Slant3DProcessOrderBlock()+ with patch.object(+ block,+ "_make_request",+ AsyncMock(return_value={"data": {"publicId": "SLANT_123"}}),+ ) as request:+ result = dict(+ [+ out+ async for out in block.run(+ block.Input(+ credentials=TEST_CREDENTIALS_INPUT, order_id="SLANT_123"+ ),+ credentials=TEST_CREDENTIALS,+ execution_context=TEST_EXECUTION_CONTEXT,+ )+ ]+ )+ request.assert_awaited_once_with(+ "POST", "orders/SLANT_123", TEST_CREDENTIALS.api_key.get_secret_value()+ )+ assert result == {"order_id": "SLANT_123"}+ assert block.is_sensitive_action++[email protected]("use_existing", [True, False])+async def test_slicer_upload_or_reuse_and_quantity(use_existing):+ block = Slant3DSlicerBlock()+ inputs = (+ {"file_id": "file-1"}+ if use_existing+ else {"file_url": "https://example.com/file.stl", "platform_id": "platform-1"}+ )+ with patch.object(+ block,+ "_make_request",+ AsyncMock(+ return_value={+ "message": "File Price Estimated",+ "data": {"total": 17.75, "quantity": 5},+ }+ ),+ ) as request, patch.object(+ block, "_upload_file", AsyncMock(return_value="file-1")+ ) as upload:+ result = dict(+ [+ out+ async for out in block.run(+ block.Input(+ credentials=TEST_CREDENTIALS_INPUT,+ quantity=5,+ filament_id="filament-1",+ **inputs+ ),+ credentials=TEST_CREDENTIALS,+ execution_context=TEST_EXECUTION_CONTEXT,+ )+ ]+ )+ assert upload.await_count == (0 if use_existing else 1)+ assert request.call_args.args[:2] == ("POST", "files/file-1/estimate")+ assert request.call_args.kwargs["json"] == {+ "options": {"filamentId": "filament-1", "quantity": 5}+ }+ assert result["price"] == 17.75+ assert result["file_id"] == "file-1"diff --git a/autogpt_platform/backend/backend/blocks/slant3d/slant3d_review_test.py b/autogpt_platform/backend/backend/blocks/slant3d/slant3d_review_test.pynew file mode 100644index 0000000000..3dcfce377f--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/slant3d/slant3d_review_test.py@@ -0,0 +1,238 @@+import asyncio+from unittest.mock import AsyncMock, patch++import pytest+from aiohttp import web++from backend.blocks.slant3d._api import (+ TEST_CREDENTIALS,+ TEST_CREDENTIALS_INPUT,+ OrderItem,+)+from backend.blocks.slant3d.filament import TEST_FILAMENT, Slant3DFilamentBlock+from backend.blocks.slant3d.order import Slant3DCreateOrderBlock+from backend.blocks.slant3d.order_status import Slant3DCancelOrderBlock+from backend.blocks.slant3d.slicing import Slant3DSlicerBlock+from backend.data.execution import ExecutionContext+from backend.util.request import Requests++CONTEXT = ExecutionContext(user_id="user-1", graph_exec_id="run-1")+++async def test_lowercase_pla_keeps_legacy_color_tag():+ block = Slant3DFilamentBlock()+ with patch.object(+ block,+ "_make_request",+ AsyncMock(return_value={"data": [{**TEST_FILAMENT, "profile": "pla"}]}),+ ):+ outputs = dict(+ [+ x+ async for x in block.run(+ block.Input(credentials=TEST_CREDENTIALS_INPUT),+ credentials=TEST_CREDENTIALS,+ )+ ]+ )+ assert outputs["filaments"][0]["colorTag"] == "black"+++ "response", [{"success": True}, {"success": True, "message": None}]+)+async def test_cancellation_without_message_returns_success(response):+ block = Slant3DCancelOrderBlock()+ with patch.object(block, "_make_request", AsyncMock(return_value=response)):+ outputs = dict(+ [+ x+ async for x in block.run(+ block.Input(+ credentials=TEST_CREDENTIALS_INPUT, order_id="SLANT_123"+ ),+ credentials=TEST_CREDENTIALS,+ )+ ]+ )+ assert outputs == {"status": "Order cancelled"}++[email protected]("quantity", [1, 2])+async def test_missing_total_is_rejected_before_outputs(quantity):+ block = Slant3DSlicerBlock()+ with patch.object(+ block,+ "_make_request",+ AsyncMock(+ return_value={"message": "Estimated", "data": {"quantity": quantity}}+ ),+ ):+ outputs = block.run(+ block.Input(+ credentials=TEST_CREDENTIALS_INPUT, file_id="file-1", quantity=quantity+ ),+ credentials=TEST_CREDENTIALS,+ execution_context=CONTEXT,+ )+ with pytest.raises(ValueError, match="printing total"):+ await anext(outputs)+++async def test_item_failure_cancels_inflight_filament_lookup():+ block = Slant3DCreateOrderBlock()+ lookup_started = asyncio.Event()+ lookup_cancelled = asyncio.Event()++ async def lookup(*args):+ lookup_started.set()+ try:+ await asyncio.Event().wait()+ finally:+ lookup_cancelled.set()++ async def upload(*args, **kwargs):+ await lookup_started.wait()+ raise ValueError("Upload rejected")++ with patch.object(+ block, "_resolve_filament_id", AsyncMock(side_effect=lookup)+ ) as resolver, patch.object(block, "_upload_file", AsyncMock(side_effect=upload)):+ with pytest.raises(ValueError, match="Upload rejected"):+ await asyncio.wait_for(+ block._format_order_items(+ [+ OrderItem(+ file_url="https://example.com/failure.stl",+ quantity=1,+ filament_id="explicit",+ ),+ OrderItem(file_id="existing", quantity=1),+ ],+ "platform-1",+ "key",+ execution_context=CONTEXT,+ ),+ 2,+ )+ assert lookup_cancelled.is_set()+ resolver.assert_awaited_once()+++async def test_upload_passes_a_stream_and_closes_it(tmp_path):+ path = tmp_path / "model.stl"+ content = b"x" * 131073+ path.write_bytes(content)+ block = Slant3DSlicerBlock()+ streams = []++ async def put(url, *, data, headers):+ streams.append(data)+ chunks = []+ while chunk := data.read(65536):+ chunks.append(chunk)+ assert b"".join(chunks) == content+ assert len(chunks) == 3+ assert headers["Content-Type"] == "application/octet-stream"++ with patch(+ "backend.blocks.slant3d.base.store_media_file",+ AsyncMock(return_value="model.stl"),+ ), patch(+ "backend.blocks.slant3d.base.get_exec_file_path", return_value=str(path)+ ), patch(+ "backend.blocks.slant3d.base.Requests"+ ) as requests, patch.object(+ block,+ "_make_request",+ AsyncMock(+ side_effect=[+ {+ "data": {+ "presignedUrl": "https://example.com/upload",+ "filePlaceholder": "placeholder",+ }+ },+ {"data": {"publicFileServiceId": "uploaded"}},+ ]+ ),+ ):+ requests.return_value.put = AsyncMock(side_effect=put)+ result = await block._upload_file(+ "https://example.com/model.stl",+ "platform-1",+ "key",+ execution_context=CONTEXT,+ )+ assert result == "uploaded"+ assert streams[0].closed+ assert path.read_bytes() == content++[email protected]("execution_id", [None, ""])+async def test_upload_requires_execution_id(execution_id):+ block = Slant3DSlicerBlock()+ context = ExecutionContext(user_id="user-1", graph_exec_id=execution_id)+ with patch.object(block, "_make_request", AsyncMock()) as api:+ with pytest.raises(ValueError, match="graph_exec_id is required"):+ await block._upload_file(+ "https://example.com/model.stl",+ "platform-1",+ "key",+ execution_context=context,+ )+ api.assert_not_awaited()+++async def test_stream_upload_uses_content_length_and_preserves_bytes(tmp_path):+ path = tmp_path / "model.stl"+ content = b"stl" * 50000+ path.write_bytes(content)+ received = {}++ async def receive(request):+ received["body"] = await request.read()+ received["headers"] = request.headers+ return web.Response()++ app = web.Application()+ app.router.add_put("/upload", receive)+ runner = web.AppRunner(app)+ await runner.setup()+ await web.TCPSite(runner, "127.0.0.1", 0).start()+ url = f"http://127.0.0.1:{runner.addresses[0][1]}/upload"+ block = Slant3DSlicerBlock()+ try:+ with patch(+ "backend.blocks.slant3d.base.store_media_file",+ AsyncMock(return_value="model.stl"),+ ), patch(+ "backend.blocks.slant3d.base.get_exec_file_path", return_value=str(path)+ ), patch(+ "backend.blocks.slant3d.base.Requests",+ return_value=Requests(trusted_origins=["127.0.0.1"], retry_max_attempts=1),+ ), patch.object(+ block,+ "_make_request",+ AsyncMock(+ side_effect=[+ {"data": {"presignedUrl": url, "filePlaceholder": "placeholder"}},+ {"data": {"publicFileServiceId": "uploaded"}},+ ]+ ),+ ):+ assert (+ await block._upload_file(+ "https://example.com/model.stl",+ "platform-1",+ "key",+ execution_context=CONTEXT,+ )+ == "uploaded"+ )+ finally:+ await runner.cleanup()+ assert received["body"] == content+ assert received["headers"]["Content-Length"] == str(len(content))+ assert "Authorization" not in received["headers"]+ assert "Transfer-Encoding" not in received["headers"]diff --git a/autogpt_platform/backend/backend/blocks/slant3d/slant3d_webhook_review_test.py b/autogpt_platform/backend/backend/blocks/slant3d/slant3d_webhook_review_test.pynew file mode 100644index 0000000000..c21be9df83--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/slant3d/slant3d_webhook_review_test.py@@ -0,0 +1,191 @@+import asyncio+import json+from unittest.mock import AsyncMock, Mock, patch++import pytest+from fastapi import Request+from pydantic import ValidationError++from backend.blocks.slant3d._api import TEST_CREDENTIALS+from backend.data import integrations+from backend.integrations.webhooks import _base, slant3d+from backend.integrations.webhooks.slant3d import Slant3DWebhooksManager+from backend.util.exceptions import (+ WebhookRegistrationError,+ WebhookSetupUnavailableError,+)++[email protected]("event", [None, "", 123, {}])+async def test_invalid_event_type_is_a_validation_error(event):+ payload = {"platform_id": "platform-1", "event_type": event}+ if event is None:+ payload.pop("event_type")+ request = Request(+ {"type": "http", "headers": []},+ receive=AsyncMock(+ return_value={+ "type": "http.request",+ "body": json.dumps(payload).encode(),+ "more_body": False,+ }+ ),+ )+ webhook = integrations.Webhook.model_construct(+ resource="platform-1", config={"api_version": 2}+ )+ with pytest.raises(ValidationError, match="event_type"):+ await Slant3DWebhooksManager.validate_payload(webhook, request, None)++[email protected]("second_user", ["user-1", "user-2"])+async def test_registration_serializes_the_external_platform(second_user):+ lock = asyncio.Lock()+ started = asyncio.Event()+ release = asyncio.Event()+ created = []+ lock_keys = []+ platform_url = ""++ class Mutex:+ def __init__(self, redis):+ self.owned = False++ async def acquire(self, key):+ lock_keys.append(key)+ await lock.acquire()+ self.owned = True++ async def release(self, key):+ if self.owned:+ self.owned = False+ lock.release()++ async def find(**kwargs):+ return next(+ (+ w+ for w in created+ if w.user_id == kwargs["user_id"]+ and w.credentials_id == kwargs["credentials_id"]+ and w.resource == kwargs["resource"]+ and w.organization_id == kwargs.get("organization_id")+ and w.team_id == kwargs.get("team_id")+ and set(kwargs.get("events") or []).issubset(w.events)+ ),+ None,+ )++ async def platform_request(method, resource, credentials, **kwargs):+ nonlocal platform_url+ if method == "GET":+ snapshot = {"data": {"webhookURL": platform_url}}+ started.set()+ await release.wait()+ return snapshot+ assert method == "PATCH"+ platform_url = kwargs["json"]["webhookURL"]+ return {"data": {}}++ async def create(webhook):+ created.append(webhook)+ return webhook++ with patch.object(+ slant3d, "AsyncRedisKeyedMutex", Mutex, create=True+ ), patch.object(+ slant3d, "get_redis_async", AsyncMock(return_value=object()), create=True+ ), patch.object(+ _base.app_config, "platform_base_url", "https://example.com"+ ), patch.object(+ integrations,+ "find_webhook_by_credentials_and_props",+ AsyncMock(side_effect=find),+ ), patch.object(+ integrations,+ "find_webhook_by_credentials_and_props_any_tenant",+ AsyncMock(side_effect=find),+ ), patch.object(+ integrations, "create_webhook", AsyncMock(side_effect=create)+ ), patch.object(+ Slant3DWebhooksManager,+ "_platform_request",+ AsyncMock(side_effect=platform_request),+ ) as api:+ first = asyncio.create_task(+ Slant3DWebhooksManager().get_suitable_auto_webhook(+ "user-1", TEST_CREDENTIALS, "orders", "platform-1", ["order.shipped"]+ )+ )+ await asyncio.wait_for(started.wait(), 2)+ second = asyncio.create_task(+ Slant3DWebhooksManager().get_suitable_auto_webhook(+ second_user, TEST_CREDENTIALS, "orders", "platform-1", ["order.shipped"]+ )+ )+ await asyncio.sleep(0)+ release.set()+ results = await asyncio.wait_for(+ asyncio.gather(first, second, return_exceptions=True), 2+ )+ assert len(created) == 1+ assert sum(c.args[0] == "PATCH" for c in api.await_args_list) == 1+ assert len(lock_keys) == 2 and lock_keys[0] == lock_keys[1]+ if second_user == "user-1":+ assert results[0].id == results[1].id+ else:+ assert isinstance(results[1], WebhookRegistrationError)+ assert not lock.locked()++[email protected]("failure", ["redis", "acquire"])+async def test_lock_failure_prevents_registration(failure):+ mutex = Mock(+ acquire=AsyncMock(+ side_effect=(+ RuntimeError("Redis unavailable") if failure == "acquire" else None+ )+ ),+ release=AsyncMock(),+ )+ with patch.object(+ slant3d,+ "get_redis_async",+ AsyncMock(+ side_effect=(+ RuntimeError("Redis unavailable") if failure == "redis" else None+ )+ ),+ create=True,+ ), patch.object(+ slant3d, "AsyncRedisKeyedMutex", return_value=mutex, create=True+ ), patch.object(+ _base.BaseWebhooksManager, "get_suitable_auto_webhook", AsyncMock()+ ) as register:+ with pytest.raises(WebhookSetupUnavailableError):+ await Slant3DWebhooksManager().get_suitable_auto_webhook(+ "user-1", TEST_CREDENTIALS, "orders", "platform-1", []+ )+ register.assert_not_awaited()+ if failure == "acquire":+ mutex.release.assert_awaited_once()+++async def test_release_failure_preserves_successful_registration():+ webhook = integrations.Webhook.model_construct(id="webhook-1")+ mutex = Mock(+ acquire=AsyncMock(),+ release=AsyncMock(side_effect=RuntimeError("Redis offline")),+ )+ with patch.object(+ slant3d, "get_redis_async", AsyncMock(return_value=object())+ ), patch.object(slant3d, "AsyncRedisKeyedMutex", return_value=mutex), patch.object(+ _base.BaseWebhooksManager,+ "get_suitable_auto_webhook",+ AsyncMock(return_value=webhook),+ ):+ result = await Slant3DWebhooksManager().get_suitable_auto_webhook(+ "user-1", TEST_CREDENTIALS, "orders", "platform-1", []+ )+ assert result is webhook+ mutex.release.assert_awaited_once()diff --git a/autogpt_platform/backend/backend/blocks/slant3d/slicer_quantity_test.py b/autogpt_platform/backend/backend/blocks/slant3d/slicer_quantity_test.pynew file mode 100644index 0000000000..af0bc7e59c--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/slant3d/slicer_quantity_test.py@@ -0,0 +1,37 @@+from unittest.mock import AsyncMock, patch++import pytest++from backend.blocks.slant3d._api import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from backend.blocks.slant3d.slicing import Slant3DSlicerBlock+from backend.data.execution import ExecutionContext+++ "requested_quantity,data",+ [+ (10, {"total": 1.37, "quantity": 1}),+ (10, {"total": 1.37}),+ (1, {"total": 10.2, "quantity": 2}),+ ],+)+async def test_slicer_rejects_prices_for_a_different_quantity(requested_quantity, data):+ block = Slant3DSlicerBlock()+ with patch.object(+ block,+ "_make_request",+ AsyncMock(return_value={"message": "File Price Estimated", "data": data}),+ ):+ outputs = block.run(+ block.Input(+ credentials=TEST_CREDENTIALS_INPUT,+ file_id="file-1",+ quantity=requested_quantity,+ ),+ credentials=TEST_CREDENTIALS,+ execution_context=ExecutionContext(user_id="user-1", graph_exec_id="run-1"),+ )+ with pytest.raises(+ ValueError, match=rf"print.*{requested_quantity} were requested"+ ):+ await anext(outputs)diff --git a/autogpt_platform/backend/backend/blocks/slant3d/slicing.py b/autogpt_platform/backend/backend/blocks/slant3d/slicing.pyindex 8740f9504f..7fdda8a264 100644--- a/autogpt_platform/backend/backend/blocks/slant3d/slicing.py+++ b/autogpt_platform/backend/backend/blocks/slant3d/slicing.py@@ -1,5 +1,11 @@+from urllib.parse import quote++from pydantic import model_validator+from backend.blocks._base import BlockOutput, BlockSchemaInput, BlockSchemaOutput+from backend.data.execution import ExecutionContextfrom backend.data.model import APIKeyCredentials, SchemaField+from backend.util.type import MediaFileTypefrom ._api import (TEST_CREDENTIALS,@@ -11,50 +17,118 @@ from .base import Slant3DBlockBaseclass Slant3DSlicerBlock(Slant3DBlockBase):- """Block for slicing 3D model files"""-class Input(BlockSchemaInput):credentials: Slant3DCredentialsInput = Slant3DCredentialsField()- file_url: str = SchemaField(- description="URL of the 3D model file to slice (STL)"+ file_url: MediaFileType = SchemaField(+ default=MediaFileType(""),+ description="STL file URL, workspace file, or data URI; ignored when file_id is set",+ )+ file_id: str = SchemaField(+ default="", description="Previously uploaded Slant3D public file service ID"+ )+ platform_id: str = SchemaField(+ default="",+ description="Platform ID for uploads; may be omitted with one enabled platform",+ )+ filament_id: str = SchemaField(+ default="",+ description="Filament public ID; defaults to Slant3D's PLA Black",+ )+ quantity: int = SchemaField(+ default=1, ge=1, description="Number of prints to estimate")+ @model_validator(mode="after")+ def require_file(self):+ if not self.file_id and not self.file_url:+ raise ValueError("Provide file_id or file_url")+ return self+class Output(BlockSchemaOutput):message: str = SchemaField(description="Response message")- price: float = SchemaField(description="Calculated price for printing")+ price: float = SchemaField(+ description="Estimated printing price for the requested quantity in USD"+ )+ file_id: str = SchemaField(+ description="Slant3D public file service ID for order items"+ )def __init__(self):super().__init__(id="f8a12c8d-3e4b-4d5f-b6a7-8c9d0e1f2g3h",- description="Slice a 3D model file and get pricing information",+ description=(+ "Get a live 3D printing quote for physical parts from STL URLs or attached workspace files. "+ "Use this to price printable parts and complete project part sets before ordering from Slant3D, "+ "which manufactures and ships the parts. Binary STL URLs are accepted directly; no browser upload is needed. "+ "For complete projects, first read the assembly bill of materials: include repeated parts across subassemblies, "+ "select a design variant for alternative parts while keeping the required number of copies, "+ "and exclude reference assembly meshes. "+ "One copy of each STL is not necessarily a complete set. "+ "Quote each required file with its full assembly quantity and sum the returned prices, which already include quantity. "+ "Before reporting a complete quote, reconcile all quoted files and quantities against the parts list. "+ "Printing-only quotes need no shipping address or payment method. "+ "Returns a reusable file_id for ordering; this block does not place or charge an order."+ ),input_schema=self.Input,output_schema=self.Output,test_input={"credentials": TEST_CREDENTIALS_INPUT,- "file_url": "https://example.com/model.stl",+ "file_id": "22222222-2222-4222-8222-222222222222",},test_credentials=TEST_CREDENTIALS,- test_output=[("message", "Slicing successful"), ("price", 8.23)],+ test_output=[+ ("message", "File Price Estimated"),+ ("price", 8.23),+ ("file_id", "22222222-2222-4222-8222-222222222222"),+ ],test_mock={"_make_request": lambda *args, **kwargs: {- "message": "Slicing successful",- "data": {"price": 8.23},+ "message": "File Price Estimated",+ "data": {"total": 8.23},}},)async def run(- self, input_data: Input, *, credentials: APIKeyCredentials, **kwargs+ self,+ input_data: Input,+ *,+ credentials: APIKeyCredentials,+ execution_context: ExecutionContext,+ **kwargs,) -> BlockOutput:- try:- result = await self._make_request(- "POST",- "slicer",- credentials.api_key.get_secret_value(),- json={"fileURL": input_data.file_url},+ api_key = credentials.api_key.get_secret_value()+ file_id = input_data.file_id+ if not file_id:+ platform_id = await self._resolve_platform_id(+ input_data.platform_id, api_key+ )+ file_id = await self._upload_file(+ input_data.file_url,+ platform_id,+ api_key,+ execution_context=execution_context,+ )+ options: dict[str, str | int] = {"quantity": input_data.quantity}+ if input_data.filament_id:+ options["filamentId"] = input_data.filament_id+ result = await self._make_request(+ "POST",+ f"files/{quote(file_id, safe='')}/estimate",+ api_key,+ json={"options": options},+ )+ quoted_quantity = result["data"].get("quantity", 1)+ if quoted_quantity != input_data.quantity:+ raise ValueError(+ f"Slant3D returned a price for {quoted_quantity} print(s), "+ f"but {input_data.quantity} were requested. "+ "No valid total was returned for the requested quantity.")- yield "message", result["message"]- yield "price", result["data"]["price"]- except Exception as e:- yield "error", str(e)- raise+ total = result["data"].get("total")+ if total is None:+ raise ValueError("Slant3D did not return a printing total")+ price = float(total)+ yield "message", result["message"]+ yield "price", price+ yield "file_id", file_iddiff --git a/autogpt_platform/backend/backend/blocks/slant3d/upload_test.py b/autogpt_platform/backend/backend/blocks/slant3d/upload_test.pynew file mode 100644index 0000000000..b42b97b40c--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/slant3d/upload_test.py@@ -0,0 +1,91 @@+from unittest.mock import ANY, AsyncMock, Mock, patch++import pytest++from backend.blocks.slant3d._api import TEST_CREDENTIALS, TEST_CREDENTIALS_INPUT+from backend.blocks.slant3d.slicing import Slant3DSlicerBlock+from backend.data.execution import ExecutionContext++[email protected]("read_error", [None, PermissionError("Access denied")])+async def test_slicer_loads_workspace_attachment_with_user_context(+ tmp_path, read_error+):+ uploaded = []++ async def put(url, **kwargs):+ uploaded.append(kwargs["data"].read())++ context = ExecutionContext(+ user_id="user-1",+ graph_exec_id="run-1",+ workspace_id="workspace-1",+ session_id="session-1",+ )+ block = Slant3DSlicerBlock()+ workspace = Mock()+ workspace.read_file_by_id = AsyncMock(+ return_value=b"STL bytes", side_effect=read_error+ )+ workspace.get_file_info = AsyncMock(return_value=Mock(name="file-info"))+ workspace.get_file_info.return_value.name = "CalibrationCube.stl"+ with (+ patch("backend.util.file.TEMP_DIR", tmp_path),+ patch("backend.util.file.get_cloud_storage_handler", AsyncMock()),+ patch(+ "backend.util.workspace.WorkspaceManager", return_value=workspace+ ) as manager,+ patch("backend.util.file.scan_content_safe", AsyncMock()) as scan,+ patch("backend.blocks.slant3d.base.Requests") as requests,+ patch.object(+ block,+ "_make_request",+ AsyncMock(+ side_effect=[+ {+ "data": {+ "presignedUrl": "https://upload.example.com/model",+ "filePlaceholder": {"id": "placeholder"},+ }+ },+ {"data": {"publicFileServiceId": "file-1"}},+ {"message": "File Price Estimated", "data": {"total": 1.37}},+ ]+ ),+ ) as api,+ ):+ requests.return_value.get = AsyncMock(+ side_effect=ValueError("URL scheme 'workspace' is not allowed")+ )+ requests.return_value.put = AsyncMock(side_effect=put)+ outputs = block.run(+ block.Input(+ credentials=TEST_CREDENTIALS_INPUT,+ file_url="workspace://attachment-1",+ platform_id="platform-1",+ ),+ credentials=TEST_CREDENTIALS,+ execution_context=context,+ )+ if read_error:+ with pytest.raises(PermissionError, match="Access denied"):+ _ = [item async for item in outputs]+ api.assert_not_awaited()+ requests.return_value.put.assert_not_awaited()+ return+ result = dict([item async for item in outputs])+ manager.assert_called_once_with("user-1", "workspace-1", "session-1", scope=None)+ workspace.read_file_by_id.assert_awaited_once_with("attachment-1")+ scan.assert_awaited_once_with(b"STL bytes", filename="CalibrationCube.stl")+ requests.return_value.get.assert_not_awaited()+ requests.return_value.put.assert_awaited_once_with(+ "https://upload.example.com/model",+ data=ANY,+ headers={"Content-Type": "application/octet-stream"},+ )+ assert uploaded == [b"STL bytes"]+ assert api.await_args_list[0].kwargs["json"] == {+ "name": "CalibrationCube.stl",+ "platformId": "platform-1",+ }+ assert result["price"] == 1.37diff --git a/autogpt_platform/backend/backend/blocks/slant3d/webhook.py b/autogpt_platform/backend/backend/blocks/slant3d/webhook.pyindex f2cb86ec09..e21a058bb0 100644--- a/autogpt_platform/backend/backend/blocks/slant3d/webhook.py+++ b/autogpt_platform/backend/backend/blocks/slant3d/webhook.py@@ -48,13 +48,18 @@ class Slant3DOrderWebhookBlock(Slant3DTriggerBase, Block):"""Block for handling Slant3D order webhooks"""class Input(Slant3DTriggerBase.Input):- class EventsFilter(BaseModel):- """- Currently Slant3D only supports 'SHIPPED' status updates- Could be expanded in the future with more status types- """+ platform_id: str = SchemaField(+ default="",+ description="Required for new v2 subscriptions; retained v1 subscriptions may omit this platform ID. Use a platform without another webhook.",+ )+ class EventsFilter(BaseModel):shipped: bool = True+ created: bool = False+ updated: bool = False+ cancelled: bool = False+ delivered: bool = False+ error: bool = Falseevents: EventsFilter = SchemaField(title="Events",@@ -65,9 +70,11 @@ class Slant3DOrderWebhookBlock(Slant3DTriggerBase, Block):class Output(Slant3DTriggerBase.Output):status: str = SchemaField(description="The new status of the order")tracking_number: str = SchemaField(- description="The tracking number for the shipment"+ description="Shipment tracking number, empty before shipment"+ )+ carrier_code: str = SchemaField(+ description="Carrier code when supplied by Slant3D, otherwise empty")- carrier_code: str = SchemaField(description="The carrier code (e.g., 'usps')")def __init__(self):super().__init__(@@ -86,13 +93,14 @@ class Slant3DOrderWebhookBlock(Slant3DTriggerBase, Block):output_schema=self.Output,webhook_config=BlockWebhookConfig(provider=ProviderName.SLANT3D,- webhook_type="orders", # Only one type for now- resource_format="", # No resource format needed+ webhook_type="orders",+ resource_format="{platform_id}",event_filter_input="events",event_format="order.{event}",),test_input={"credentials": TEST_CREDENTIALS_INPUT,+ "platform_id": "55555555-5555-4555-8555-555555555555","events": {"shipped": True},"payload": {"orderId": "1234567890",@@ -119,7 +127,7 @@ class Slant3DOrderWebhookBlock(Slant3DTriggerBase, Block):],)- async def run(self, input_data: Input, **kwargs) -> BlockOutput: # type: ignore+ async def run(self, input_data: Slant3DTriggerBase.Input, **kwargs) -> BlockOutput:async for name, value in super().run(input_data, **kwargs):yield name, valuediff --git a/autogpt_platform/backend/backend/blocks/slant3d/webhook_test.py b/autogpt_platform/backend/backend/blocks/slant3d/webhook_test.pynew file mode 100644index 0000000000..3c9fc23a2a--- /dev/null+++ b/autogpt_platform/backend/backend/blocks/slant3d/webhook_test.py@@ -0,0 +1,232 @@+import hashlib+import hmac+import json+import time+from unittest.mock import AsyncMock, Mock, patch++import pytest+from fastapi import HTTPException, Request++from backend.blocks.slant3d._api import TEST_CREDENTIALS+from backend.data.integrations import Webhook+from backend.integrations.webhooks.slant3d import Slant3DWebhooksManager++SECRET = "s" * 64+ENDPOINT = "https://example.com/slant3d/webhook"+PAYLOAD = {+ "event_type": "order.shipped",+ "service": "order-service",+ "platform_id": "platform-1",+ "data": {+ "order": {+ "public_id": "SLANT_123",+ "status": "SHIPPED",+ "tracking_number": "track-1",+ }+ },+}+++def webhook(version=2):+ return Webhook.model_construct(+ id="webhook-1",+ resource="platform-1",+ secret=SECRET,+ config={"api_version": version, "endpoint": ENDPOINT},+ )+++def request_for(payload, *, timestamp=None, secret=SECRET, signed=True):+ body = json.dumps(payload).encode()+ timestamp = timestamp or str(int(time.time() * 1000))+ digest = hmac.new(+ secret.encode(), timestamp.encode() + b"." + body, hashlib.sha256+ ).hexdigest()+ headers = (+ [+ (b"x-webhook-timestamp", timestamp.encode()),+ (b"x-webhook-signature-256", f"sha256={digest}".encode()),+ ]+ if signed+ else []+ )+ return Request(+ {"type": "http", "headers": headers},+ receive=AsyncMock(+ return_value={"type": "http.request", "body": body, "more_body": False}+ ),+ )+++async def test_registration_configures_platform_with_signing_secret():+ manager = Slant3DWebhooksManager()+ with patch.object(+ manager,+ "_platform_request",+ AsyncMock(return_value={"data": {"webhookURL": ""}}),+ ) as request:+ provider_id, config = await manager._register_webhook(+ TEST_CREDENTIALS,+ "orders",+ "platform-1",+ ["order.shipped"],+ ENDPOINT,+ SECRET,+ )+ assert provider_id == "platform-1"+ assert config["api_version"] == 2+ assert config["endpoint"] == ENDPOINT+ assert request.await_args_list[1].args[:2] == ("PATCH", "platform-1")+ assert request.await_args_list[1].kwargs["json"] == {+ "webhookURL": ENDPOINT,+ "webhookSecret": SECRET,+ }+++async def test_registration_does_not_overwrite_another_subscription():+ manager = Slant3DWebhooksManager()+ with patch.object(+ manager,+ "_platform_request",+ AsyncMock(return_value={"data": {"webhookURL": "https://another.example.com"}}),+ ) as request:+ with pytest.raises(ValueError, match="different webhook URL"):+ await manager._register_webhook(+ TEST_CREDENTIALS, "orders", "platform-1", [], ENDPOINT, SECRET+ )+ request.assert_awaited_once()+++async def test_registration_requires_platform():+ with pytest.raises(ValueError, match="platform_id"):+ await Slant3DWebhooksManager()._register_webhook(+ TEST_CREDENTIALS, "orders", "", [], ENDPOINT, SECRET+ )+++async def test_platform_request_uses_v2_bearer_auth():+ response = Mock(ok=True)+ response.json.return_value = {"success": True, "data": {"id": "platform-1"}}+ with patch("backend.integrations.webhooks.slant3d.Requests") as requests:+ requests.return_value.request = AsyncMock(return_value=response)+ await Slant3DWebhooksManager()._platform_request(+ "GET", "platform-1", TEST_CREDENTIALS+ )+ requests.return_value.request.assert_awaited_once_with(+ "GET",+ "https://slant3dapi.com/v2/api/platforms/platform-1",+ headers={+ "Authorization": f"Bearer {TEST_CREDENTIALS.api_key.get_secret_value()}",+ "Content-Type": "application/json",+ },+ )+++async def test_signature_and_v2_payload_normalization():+ request = request_for(PAYLOAD)+ await Slant3DWebhooksManager.verify_signature(webhook(), request)+ payload, event = await Slant3DWebhooksManager.validate_payload(+ webhook(), request, None+ )+ assert event == "order.shipped"+ assert payload["orderId"] == "SLANT_123"+ assert payload["trackingNumber"] == "track-1"+ assert payload["carrierCode"] == ""+ assert payload["data"] == PAYLOAD["data"]++[email protected]("timestamp_offset", [-301_000, 301_000])+async def test_expired_and_future_signatures_are_rejected(timestamp_offset):+ request = request_for(+ PAYLOAD, timestamp=str(int(time.time() * 1000) + timestamp_offset)+ )+ with pytest.raises(HTTPException) as error:+ await Slant3DWebhooksManager.verify_signature(webhook(), request)+ assert error.value.status_code == 403+++ "options", [{"signed": False}, {"secret": "wrong"}, {"timestamp": "invalid"}]+)+async def test_missing_invalid_or_wrong_signatures_are_rejected(options):+ with pytest.raises(HTTPException) as error:+ await Slant3DWebhooksManager.verify_signature(+ webhook(), request_for(PAYLOAD, **options)+ )+ assert error.value.status_code == 403+++async def test_body_tampering_is_rejected():+ request = request_for(PAYLOAD)+ body = await request.body()+ tampered = Request(+ {"type": "http", "headers": request.scope["headers"]},+ receive=AsyncMock(+ return_value={+ "type": "http.request",+ "body": body + b" ",+ "more_body": False,+ }+ ),+ )+ with pytest.raises(HTTPException):+ await Slant3DWebhooksManager.verify_signature(webhook(), tampered)+++async def test_payload_cannot_select_another_platform():+ with pytest.raises(ValueError, match="platform does not match"):+ await Slant3DWebhooksManager.validate_payload(+ webhook(), request_for({**PAYLOAD, "platform_id": "another-platform"}), None+ )+++async def test_test_deliveries_do_not_trigger_order_events():+ _, event = await Slant3DWebhooksManager.validate_payload(+ webhook(), request_for({**PAYLOAD, "dummy": True}), None+ )+ assert event == "dummy"+++async def test_non_order_notifications_can_be_filtered_without_parsing_an_order():+ payload = {+ **PAYLOAD,+ "event_type": "filament.updated",+ "data": {"filaments": {"added": ["filament-1"]}},+ }+ result, event = await Slant3DWebhooksManager.validate_payload(+ webhook(), request_for(payload), None+ )+ assert result == payload+ assert event == "filament.updated"+++async def test_existing_legacy_subscriptions_remain_compatible():+ payload = {+ "orderId": "123",+ "status": "SHIPPED",+ "trackingNumber": "track-1",+ "carrierCode": "usps",+ }+ request = request_for(payload, signed=False)+ await Slant3DWebhooksManager.verify_signature(webhook(version=1), request)+ result, event = await Slant3DWebhooksManager.validate_payload(+ webhook(version=1), request, None+ )+ assert result == payload+ assert event == "order.shipped"+++ "current_url,expected_calls", [(ENDPOINT, 2), ("https://another.example.com", 1)]+)+async def test_deregistration_only_clears_its_own_url(current_url, expected_calls):+ manager = Slant3DWebhooksManager()+ with patch.object(+ manager,+ "_platform_request",+ AsyncMock(return_value={"data": {"webhookURL": current_url}}),+ ) as request:+ await manager._deregister_webhook(webhook(), TEST_CREDENTIALS)+ assert request.await_count == expected_calls+ if expected_calls == 2:+ assert request.call_args.kwargs["json"] == {"webhookURL": ""}diff --git a/autogpt_platform/backend/backend/integrations/webhooks/_base.py b/autogpt_platform/backend/backend/integrations/webhooks/_base.pyindex 000f1291a5..379e4a71e1 100644--- a/autogpt_platform/backend/backend/integrations/webhooks/_base.py+++ b/autogpt_platform/backend/backend/integrations/webhooks/_base.py@@ -186,7 +186,7 @@ class BaseWebhooksManager(ABC, Generic[WT]):Verify the authenticity of an incoming webhook request.Default is a no-op: not every provider's webhook protocol supports- signing, so unsigned providers (e.g. Compass, Slant3D) don't override+ signing, so unsigned providers (e.g. Compass) don't overridethis. Providers whose protocol does sign deliveries (GitHub, Telegram,Exa, Airtable) override and raise `fastapi.HTTPException(403)` onmissing or invalid signatures, using `hmac.compare_digest` for anydiff --git a/autogpt_platform/backend/backend/integrations/webhooks/slant3d.py b/autogpt_platform/backend/backend/integrations/webhooks/slant3d.pyindex 049e94f87e..a62d42546f 100644--- a/autogpt_platform/backend/backend/integrations/webhooks/slant3d.py+++ b/autogpt_platform/backend/backend/integrations/webhooks/slant3d.py@@ -1,21 +1,71 @@+import asyncio+import hashlib+import hmacimport logging+import time+from urllib.parse import quote-from fastapi import Request+from autogpt_libs.utils.synchronize import AsyncRedisKeyedMutex+from fastapi import HTTPException, Request+from pydantic import BaseModel, Fieldfrom backend.data import integrationsfrom backend.data.model import APIKeyCredentials, Credentials+from backend.data.redis_client import get_redis_asyncfrom backend.integrations.providers import ProviderNamefrom backend.integrations.webhooks._base import BaseWebhooksManager+from backend.util.exceptions import WebhookSetupUnavailableErrorfrom backend.util.request import Requestslogger = logging.getLogger(__name__)-class Slant3DWebhooksManager(BaseWebhooksManager):- """Manager for Slant3D webhooks"""+class _WebhookEvent(BaseModel):+ event_type: str = Field(min_length=1)++class Slant3DWebhooksManager(BaseWebhooksManager):PROVIDER_NAME = ProviderName.SLANT3D- BASE_URL = "https://www.slant3dapi.com/api"+ BASE_URL = "https://slant3dapi.com/v2/api"++ async def get_suitable_auto_webhook(+ self,+ user_id: str,+ credentials: Credentials,+ webhook_type: str,+ resource: str,+ events: list[str],+ organization_id: str | None = None,+ team_id: str | None = None,+ ) -> integrations.Webhook:+ lock_key = ("webhook-setup", self.PROVIDER_NAME.value, resource)+ try:+ mutex = AsyncRedisKeyedMutex(await get_redis_async())+ except Exception as exc:+ raise WebhookSetupUnavailableError(+ "Could not safely lock Slant3D webhook setup"+ ) from exc+ try:+ try:+ await asyncio.wait_for(mutex.acquire(lock_key), timeout=10)+ except Exception as exc:+ raise WebhookSetupUnavailableError(+ "Could not safely lock Slant3D webhook setup"+ ) from exc+ return await super().get_suitable_auto_webhook(+ user_id=user_id,+ credentials=credentials,+ webhook_type=webhook_type,+ resource=resource,+ events=events,+ organization_id=organization_id,+ team_id=team_id,+ )+ finally:+ try:+ await mutex.release(lock_key)+ except Exception:+ logger.exception("Failed to release Slant3D webhook setup lock")async def _register_webhook(self,@@ -26,35 +76,48 @@ class Slant3DWebhooksManager(BaseWebhooksManager):ingress_url: str,secret: str,) -> tuple[str, dict]:- """Register a new webhook with Slant3D"""-- if not isinstance(credentials, APIKeyCredentials):- raise ValueError("API key is required to register a webhook")-- headers = {- "api-key": credentials.api_key.get_secret_value(),- "Content-Type": "application/json",- }-- # Slant3D's API doesn't use events list, just register for all order updates- payload = {"endPoint": ingress_url}-- response = await Requests(raise_for_status=False).post(- f"{self.BASE_URL}/customer/webhookSubscribe", headers=headers, json=payload+ if not resource:+ raise ValueError("Set platform_id to register a Slant3D v2 webhook")+ platform = await self._platform_request("GET", resource, credentials)+ if platform["data"].get("webhookURL") not in (None, "", ingress_url):+ raise ValueError(+ "This Slant3D platform already has a different webhook URL. "+ "Choose a dedicated platform or remove its existing webhook first."+ )+ await self._platform_request(+ "PATCH",+ resource,+ credentials,+ json={"webhookURL": ingress_url, "webhookSecret": secret},)-- if not response.ok:- error = response.json().get("error", "Unknown error")- raise ValueError(f"Slant3D returned error: {error}")-- webhook_config = {+ return resource, {"endpoint": ingress_url,+ "api_version": 2,"provider": self.PROVIDER_NAME,- "events": ["order.shipped"], # Currently the only supported event+ "events": events,"type": webhook_type,}- return "", webhook_config+ @classmethod+ async def verify_signature(+ cls, webhook: integrations.Webhook, request: Request+ ) -> None:+ if webhook.config.get("api_version") != 2:+ return+ timestamp = request.headers.get("X-Webhook-Timestamp", "")+ signature = request.headers.get("X-Webhook-Signature-256", "")+ try:+ age = abs(time.time() * 1000 - int(timestamp))+ except ValueError:+ raise HTTPException(403, "Invalid Slant3D webhook timestamp")+ if not webhook.secret or age > 5 * 60 * 1000:+ raise HTTPException(403, "Invalid or expired Slant3D webhook signature")+ signed_payload = timestamp.encode() + b"." + await request.body()+ digest = hmac.new(+ webhook.secret.encode(), signed_payload, hashlib.sha256+ ).hexdigest()+ if not hmac.compare_digest(signature, f"sha256={digest}"):+ raise HTTPException(403, "Invalid Slant3D webhook signature")@classmethodasync def validate_payload(@@ -63,40 +126,64 @@ class Slant3DWebhooksManager(BaseWebhooksManager):request: Request,credentials: Credentials | None,) -> tuple[dict, str]:- """Validate incoming webhook payload from Slant3D"""-payload = await request.json()-- # Validate required fields from Slant3D API spec- required_fields = ["orderId", "status", "trackingNumber", "carrierCode"]- missing_fields = [field for field in required_fields if field not in payload]-- if missing_fields:- raise ValueError(f"Missing required fields: {', '.join(missing_fields)}")-- # Normalize payload structure- normalized_payload = {- "orderId": payload["orderId"],- "status": payload["status"],- "trackingNumber": payload["trackingNumber"],- "carrierCode": payload["carrierCode"],- }-- # Currently Slant3D only sends shipping notifications- # Convert status to lowercase for event format compatibility- event_type = f"order.{payload['status'].lower()}"-- return normalized_payload, event_type+ if webhook.config.get("api_version") == 2:+ if payload.get("platform_id") != webhook.resource:+ raise ValueError(+ "Slant3D webhook platform does not match the subscription"+ )+ if payload.get("dummy"):+ return payload, "dummy"+ event = _WebhookEvent.model_validate(payload).event_type+ if not event.startswith("order."):+ return payload, event+ order = payload["data"]["order"]+ return {+ **payload,+ "orderId": order["public_id"],+ "status": order.get("status", event.removeprefix("order.").upper()),+ "trackingNumber": order.get("tracking_number") or "",+ "carrierCode": order.get("carrier_code") or "",+ }, event+ required = ["orderId", "status", "trackingNumber", "carrierCode"]+ missing = [field for field in required if field not in payload]+ if missing:+ raise ValueError(f"Missing required fields: {', '.join(missing)}")+ return {+ field: payload[field] for field in required+ }, f"order.{payload['status'].lower()}"async def _deregister_webhook(self, webhook: integrations.Webhook, credentials: Credentials) -> None:- """- Note: Slant3D API currently doesn't provide a deregistration endpoint.- This would need to be handled through support.- """- # Log warning since we can't properly deregister- logger.warning(- f"Warning: Manual deregistration required for webhook {webhook.id}"+ if webhook.config.get("api_version") != 2:+ logger.warning(+ f"Manual deregistration required for legacy Slant3D webhook {webhook.id}"+ )+ return+ platform = await self._platform_request("GET", webhook.resource, credentials)+ if platform["data"].get("webhookURL") == webhook.config["endpoint"]:+ await self._platform_request(+ "PATCH", webhook.resource, credentials, json={"webhookURL": ""}+ )++ async def _platform_request(+ self, method: str, platform_id: str, credentials: Credentials, **kwargs+ ) -> dict:+ if not isinstance(credentials, APIKeyCredentials):+ raise ValueError("API key is required for Slant3D webhooks")+ response = await Requests(raise_for_status=False, retry_max_attempts=1).request(+ method,+ f"{self.BASE_URL}/platforms/{quote(platform_id, safe='')}",+ headers={+ "Authorization": f"Bearer {credentials.api_key.get_secret_value()}",+ "Content-Type": "application/json",+ },+ **kwargs,)- pass+ result = response.json()+ if not response.ok or result.get("success") is False:+ raise ValueError(+ f"Slant3D returned error: {result.get('error') or result.get('message')}"+ )+ return resultdiff --git a/docs/integrations/README.md b/docs/integrations/README.mdindex 1d1dde57b1..88a6867595 100644--- a/docs/integrations/README.md+++ b/docs/integrations/README.md@@ -77,14 +77,15 @@ Below is a comprehensive list of all available blocks, categorized by their prim| [Reverse List Order](block-integrations/basic.md#reverse-list-order) | Reverses the order of elements in a list || [Search Memory](block-integrations/basic.md#search-memory) | Search memories in Mem0 by user || [Search Store Agents](block-integrations/system/store_operations.md#search-store-agents) | Search for agents in the store |-| [Slant3D Cancel Order](block-integrations/slant3d/order.md#slant3d-cancel-order) | Cancel an existing order |-| [Slant3D Create Order](block-integrations/slant3d/order.md#slant3d-create-order) | Create a new print order |-| [Slant3D Estimate Order](block-integrations/slant3d/order.md#slant3d-estimate-order) | Get order cost estimate |-| [Slant3D Estimate Shipping](block-integrations/slant3d/order.md#slant3d-estimate-shipping) | Get shipping cost estimate |-| [Slant3D Filament](block-integrations/slant3d/filament.md#slant3d-filament) | Get list of available filaments |-| [Slant3D Get Orders](block-integrations/slant3d/order.md#slant3d-get-orders) | Get all orders for the account |-| [Slant3D Slicer](block-integrations/slant3d/slicing.md#slant3d-slicer) | Slice a 3D model file and get pricing information |-| [Slant3D Tracking](block-integrations/slant3d/order.md#slant3d-tracking) | Track order status and shipping |+| [Slant3D Cancel Order](block-integrations/slant3d/order_status.md#slant3d-cancel-order) | Cancel an order before production starts |+| [Slant3D Create Order](block-integrations/slant3d/order.md#slant3d-create-order) | Order physical 3D-printed parts from Slant3D for manufacturing and delivery |+| [Slant3D Estimate Order](block-integrations/slant3d/order.md#slant3d-estimate-order) | Quote a 3D-printed parts order including shipping by creating an uncharged Slant3D draft |+| [Slant3D Estimate Shipping](block-integrations/slant3d/order.md#slant3d-estimate-shipping) | Estimate delivery costs for physical 3D-printed parts by creating an uncharged Slant3D order draft |+| [Slant3D Filament](block-integrations/slant3d/filament.md#slant3d-filament) | Find available materials and colors for quoting or ordering physical 3D-printed parts from Slant3D |+| [Slant3D Get Orders](block-integrations/slant3d/order_status.md#slant3d-get-orders) | Get all orders for the account |+| [Slant3D Process Order](block-integrations/slant3d/order_status.md#slant3d-process-order) | Submit an approved Slant3D draft to order physical 3D-printed parts for manufacturing and delivery |+| [Slant3D Slicer](block-integrations/slant3d/slicing.md#slant3d-slicer) | Get a live 3D printing quote for physical parts from STL URLs or attached workspace files |+| [Slant3D Tracking](block-integrations/slant3d/order_status.md#slant3d-tracking) | Track order status and shipping || [Store Value](block-integrations/basic.md#store-value) | Holds or receives a value and outputs it statically so that it can be used multiple times within the same agent run || [Universal Type Converter](block-integrations/basic.md#universal-type-converter) | This block is used to convert a value to a universal type || [XML Parser](block-integrations/basic.md#xml-parser) | Parses XML using gravitasml to tokenize and coverts it to dict |diff --git a/docs/integrations/SUMMARY.md b/docs/integrations/SUMMARY.mdindex 2d6f777a90..379dcde5ad 100644--- a/docs/integrations/SUMMARY.md+++ b/docs/integrations/SUMMARY.md@@ -119,6 +119,7 @@* [Slack Blocks](block-integrations/slack/blocks.md)* [Slant3D Filament](block-integrations/slant3d/filament.md)* [Slant3D Order](block-integrations/slant3d/order.md)+* [Slant3D Order Status](block-integrations/slant3d/order_status.md)* [Slant3D Slicing](block-integrations/slant3d/slicing.md)* [Slant3D Webhook](block-integrations/slant3d/webhook.md)* [Smartlead Campaign](block-integrations/smartlead/campaign.md)diff --git a/docs/integrations/block-integrations/slant3d/filament.md b/docs/integrations/block-integrations/slant3d/filament.mdindex d6a39b112b..ed107c224d 100644--- a/docs/integrations/block-integrations/slant3d/filament.md+++ b/docs/integrations/block-integrations/slant3d/filament.md@@ -6,7 +6,7 @@ Blocks for getting available filament options from Slant3D.## Slant3D Filament### What it is-Get list of available filaments+Find available materials and colors for quoting or ordering physical 3D-printed parts from Slant3D. Returns filament public IDs, material, color, and availability. Use a specific filament_id when a material or color matches more than one filament. Slant3D Slicer uses default black PLA when no filament is selected.### How it works<!-- MANUAL: how_it_works -->@@ -15,12 +15,19 @@ This block queries the Slant3D API to retrieve a list of all available filamentUse this to populate filament selection dropdowns or validate filament choices before placing orders.<!-- END MANUAL -->+### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| profiles | Filter materials; empty returns all | List["PLA" \| "PETG" \| "OPM"] | No |+| colors | Filter color names; empty returns all | List[str] | No |+### Outputs| Output | Description | Type ||--------|-------------|------|| error | Error message if the operation failed | str |-| filaments | List of available filaments | List[Filament] |+| filaments | Available filaments; use publicId as filament_id | List[Filament] |### Possible use case<!-- MANUAL: use_case -->diff --git a/docs/integrations/block-integrations/slant3d/order.md b/docs/integrations/block-integrations/slant3d/order.mdindex 0d82191c70..26fff6cc90 100644--- a/docs/integrations/block-integrations/slant3d/order.md+++ b/docs/integrations/block-integrations/slant3d/order.md@@ -3,68 +3,33 @@Blocks for managing 3D print orders through Slant3D.<!-- END MANUAL -->-## Slant3D Cancel Order--### What it is-Cancel an existing order--### How it works-<!-- MANUAL: how_it_works -->-This block cancels an existing order in the Slant3D system using the order ID. The cancellation request is sent to the Slant3D API and returns a status message confirming the cancellation.--Orders can only be cancelled before they enter production. Check order status before attempting cancellation.-<!-- END MANUAL -->--### Inputs--| Input | Description | Type | Required |-|-------|-------------|------|----------|-| order_id | Slant3D order ID to cancel | str | Yes |--### Outputs--| Output | Description | Type |-|--------|-------------|------|-| error | Error message if the operation failed | str |-| status | Cancellation status message | str |--### Possible use case-<!-- MANUAL: use_case -->-**Customer Cancellations**: Allow customers to cancel orders through your interface.--**Error Recovery**: Cancel orders placed with incorrect details or specifications.--**Order Management**: Implement cancellation functionality in order management dashboards.-<!-- END MANUAL -->------## Slant3D Create Order### What it is-Create a new print order+Order physical 3D-printed parts from Slant3D for manufacturing and delivery. Accepts multiple STL URLs, workspace attachments, or uploaded file IDs with per-part material and quantity, including complete project part sets. Creates a draft, charges the connected payment method, and submits the parts to production. Use only with real customer shipping details and order approval. For a printing-only quote without shipping or billing details, use Slant3D Slicer first.### How it works<!-- MANUAL: how_it_works -->-This block creates a new 3D print order through the Slant3D API. Provide customer shipping details and a list of items to print (STL files with specifications). Each item includes file URL, quantity, and filament selection.+This block prepares each print item, creates a draft, then processes it to charge the Slant3D account payment method and start production. An item can reuse `file_id` or upload an STL URL, workspace attachment, or data URI. Supply customer shipping details, a positive `quantity`, and a `filament_id`; legacy color/profile values work only when they identify one available filament.-The block returns the Slant3D order ID which you can use for tracking and status updates.+Set `platform_id`, or omit it only when the account has exactly one enabled platform. Invalid items, inaccessible files, ambiguous materials, and provider errors stop the workflow. If processing cannot be confirmed, the error identifies the draft: check its status before retrying to avoid a duplicate charge. Use Estimate Order first when the customer needs to approve a quote.<!-- END MANUAL -->### Inputs| Input | Description | Type | Required ||-------|-------------|------|----------|-| order_number | Your custom order number (or leave blank for a random one) | str | No |-| customer | Customer details for where to ship the item | CustomerDetails | Yes |-| items | List of items to print | List[OrderItem] | Yes |+| platform_id | Slant3D platform ID; may be omitted when the account has one enabled platform | str | No |+| order_number | Your custom order reference, stored as orderNumber in Slant3D metadata | str | No |+| customer | Customer shipping details | CustomerDetails | Yes |+| items | Items to print | List[OrderItem] | Yes |### Outputs| Output | Description | Type ||--------|-------------|------|| error | Error message if the operation failed | str |-| order_id | Slant3D order ID | str |+| order_id | Slant3D public order ID | str |### Possible use case<!-- MANUAL: use_case -->@@ -80,22 +45,23 @@ The block returns the Slant3D order ID which you can use for tracking and status## Slant3D Estimate Order### What it is-Get order cost estimate+Quote a 3D-printed parts order including shipping by creating an uncharged Slant3D draft. Accepts multiple STL files or uploaded file IDs with per-part quantities. Requires real customer shipping details and an account payment method; do not invent an address. For printing-only part or project quotes without shipping details, use Slant3D Slicer for each file instead. Returns a draft ID that Process Order can submit after approval.### How it works<!-- MANUAL: how_it_works -->-This block calculates a cost estimate for a potential order without actually placing it. Provide the same details as a create order request, and receive a breakdown of printing and shipping costs.+This block creates an uncharged draft and returns its `order_id`, printing cost, shipping cost, and total cost. Provide the same customer and item details as Create Order. Slant3D requires an account payment method for drafts, but estimating does not charge it or start production.-Use this for price quotes before customers commit to orders.+Empty item lists and nonpositive quantities are rejected. File-upload, platform-selection, filament-resolution, shipping-detail, and provider failures surface as errors instead of a completed quote. After customer approval, pass the returned ID, such as `order_id="SLANT_1234567890"`, to Process Order.<!-- END MANUAL -->### Inputs| Input | Description | Type | Required ||-------|-------------|------|----------|-| order_number | Your custom order number (or leave blank for a random one) | str | No |-| customer | Customer details for where to ship the item | CustomerDetails | Yes |-| items | List of items to print | List[OrderItem] | Yes |+| platform_id | Slant3D platform ID; may be omitted when the account has one enabled platform | str | No |+| order_number | Your custom order reference, stored as orderNumber in Slant3D metadata | str | No |+| customer | Customer shipping details | CustomerDetails | Yes |+| items | Items to print | List[OrderItem] | Yes |### Outputs@@ -103,8 +69,9 @@ Use this for price quotes before customers commit to orders.|--------|-------------|------|| error | Error message if the operation failed | str || total_price | Total price in USD | float |-| shipping_cost | Shipping cost | float |-| printing_cost | Printing cost | float |+| shipping_cost | Shipping cost in USD | float |+| printing_cost | Printing cost in USD | float |+| order_id | Uncharged draft ID; pass to Process Order to place it | str |### Possible use case<!-- MANUAL: use_case -->@@ -120,30 +87,32 @@ Use this for price quotes before customers commit to orders.## Slant3D Estimate Shipping### What it is-Get shipping cost estimate+Estimate delivery costs for physical 3D-printed parts by creating an uncharged Slant3D order draft. Requires real customer shipping details and an account payment method. For printing-only quotes without an address or billing setup, use Slant3D Slicer instead. Returns shipping cost and the draft ID; does not charge or submit the order.### How it works<!-- MANUAL: how_it_works -->-This block calculates shipping costs for a potential order based on the destination and items. It provides an estimate before placing the full order.+This block creates an uncharged draft from the destination and print items, then returns its shipping cost, `currency_code`, and `order_id`. Slant3D requires an account payment method for drafts, but estimating does not charge it or start production.-Use this to display shipping costs at checkout or calculate delivery options for customers.+Invalid quantities, inaccessible files, ambiguous platform/material selections, invalid addresses, and provider failures stop the estimate. Use real destination details, such as `country_iso="US"`, and process the returned draft only after the customer approves the order.<!-- END MANUAL -->### Inputs| Input | Description | Type | Required ||-------|-------------|------|----------|-| order_number | Your custom order number (or leave blank for a random one) | str | No |-| customer | Customer details for where to ship the item | CustomerDetails | Yes |-| items | List of items to print | List[OrderItem] | Yes |+| platform_id | Slant3D platform ID; may be omitted when the account has one enabled platform | str | No |+| order_number | Your custom order reference, stored as orderNumber in Slant3D metadata | str | No |+| customer | Customer shipping details | CustomerDetails | Yes |+| items | Items to print | List[OrderItem] | Yes |### Outputs| Output | Description | Type ||--------|-------------|------|| error | Error message if the operation failed | str |-| shipping_cost | Estimated shipping cost | float |-| currency_code | Currency code (e.g., 'usd') | str |+| shipping_cost | Estimated shipping cost in USD | float |+| currency_code | Currency code | str |+| order_id | Uncharged draft ID; pass to Process Order to place it | str |### Possible use case<!-- MANUAL: use_case -->@@ -155,70 +124,3 @@ Use this to display shipping costs at checkout or calculate delivery options for<!-- END MANUAL -->-----## Slant3D Get Orders--### What it is-Get all orders for the account--### How it works-<!-- MANUAL: how_it_works -->-This block retrieves all orders associated with your Slant3D account. It returns a list of orders with their current status and details.--Use this for order management dashboards or to sync order data with your systems.-<!-- END MANUAL -->--### Outputs--| Output | Description | Type |-|--------|-------------|------|-| error | Error message if the operation failed | str |-| orders | List of orders with their details | List[str] |--### Possible use case-<!-- MANUAL: use_case -->-**Order Dashboard**: Build dashboards showing all orders and their current status.--**Sync Operations**: Regularly sync Slant3D orders with your internal order management system.--**Reporting**: Generate reports on order volume and status distribution.-<!-- END MANUAL -->-------## Slant3D Tracking--### What it is-Track order status and shipping--### How it works-<!-- MANUAL: how_it_works -->-This block retrieves the current status and shipping tracking information for a specific order. It returns the order status and any available tracking numbers.--Use this to provide customers with real-time order status updates.-<!-- END MANUAL -->--### Inputs--| Input | Description | Type | Required |-|-------|-------------|------|----------|-| order_id | Slant3D order ID to track | str | Yes |--### Outputs--| Output | Description | Type |-|--------|-------------|------|-| error | Error message if the operation failed | str |-| status | Order status | str |-| tracking_numbers | List of tracking numbers | List[str] |--### Possible use case-<!-- MANUAL: use_case -->-**Order Status Page**: Display current order status to customers on your website.--**Shipping Notifications**: Get tracking numbers to send shipping notifications to customers.--**Customer Support**: Look up order status quickly for customer service inquiries.-<!-- END MANUAL -->-----diff --git a/docs/integrations/block-integrations/slant3d/order_status.md b/docs/integrations/block-integrations/slant3d/order_status.mdnew file mode 100644index 0000000000..b6dec8e6d5--- /dev/null+++ b/docs/integrations/block-integrations/slant3d/order_status.md@@ -0,0 +1,143 @@+# Slant3D Order Status+<!-- MANUAL: file_description -->+Blocks for processing, listing, tracking, and cancelling Slant3D orders.+<!-- END MANUAL -->++## Slant3D Cancel Order++### What it is+Cancel an order before production starts++### How it works+<!-- MANUAL: how_it_works -->+This block requests cancellation of an existing order using its public ID, such as `order_id="SLANT_1234567890"`. It returns the provider's status message, or `Order cancelled` when a successful response omits that optional message.++An invalid ID, an order that cannot be cancelled at its current production stage, or a provider failure produces an error. Check the order status before cancelling; failed cancellation requests are not automatically retried.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| order_id | Slant3D public order ID to cancel | str | Yes |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| status | Cancellation status message | str |++### Possible use case+<!-- MANUAL: use_case -->+**Customer Cancellations**: Allow customers to cancel orders through your interface.++**Error Recovery**: Cancel orders placed with incorrect details or specifications.++**Order Management**: Implement cancellation functionality in order management dashboards.+<!-- END MANUAL -->++---++## Slant3D Get Orders++### What it is+Get all orders for the account++### How it works+<!-- MANUAL: how_it_works -->+This block collects the public IDs of all orders associated with the Slant3D account. It requests pages of 100 orders and stops at the reported final page, an empty page, or a short page when pagination metadata is absent. An empty account returns `orders=[]`.++Provider failures stop pagination and surface as an error instead of returning a partial list. The output contains IDs such as `SLANT_1234567890`; use Tracking to retrieve an order's status and tracking numbers.+<!-- END MANUAL -->++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| orders | Public IDs of all orders for the account | List[str] |++### Possible use case+<!-- MANUAL: use_case -->+**Order Dashboard**: Build dashboards showing all orders and their current status.++**Sync Operations**: Regularly sync Slant3D orders with your internal order management system.++**Reporting**: Generate reports on order volume and status distribution.+<!-- END MANUAL -->++---++## Slant3D Process Order++### What it is+Submit an approved Slant3D draft to order physical 3D-printed parts for manufacturing and delivery. Uses the order_id from Estimate Order or Estimate Shipping, charges the connected payment method, and starts production. Run only after the customer approves the quoted order.++### How it works+<!-- MANUAL: how_it_works -->+This block processes an approved, uncharged draft identified by its public `order_id`, for example `order_id="SLANT_1234567890"` from Estimate Order or Estimate Shipping. Processing charges the connected Slant3D payment method and submits the order to production. The output is the processed order ID.++The provider rejects invalid IDs and drafts that cannot be processed, including already-processed orders. If a provider or connection failure prevents confirmation, the block reports an error with the draft ID. Check that order's status before retrying because payment may have completed; processing requests are not automatically retried.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| order_id | Uncharged draft order ID from an estimate block | str | Yes |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| order_id | Processed Slant3D public order ID | str |++### Possible use case+<!-- MANUAL: use_case -->+**Approved Quote Fulfillment**: Process the draft returned by a pricing block after a customer confirms the cost and shipping details.++**Scheduled Production**: Submit an approved draft when its planned manufacturing date arrives.++**Purchase Approval Workflow**: Process a prepared draft after an internal purchaser approves its cost.+<!-- END MANUAL -->++---++## Slant3D Tracking++### What it is+Track order status and shipping++### How it works+<!-- MANUAL: how_it_works -->+This block retrieves the current status and available tracking numbers for one public order ID, such as `order_id="SLANT_1234567890"`. Before fulfillment, missing shipment information returns `tracking_numbers=[]`.++Invalid or inaccessible order IDs and provider failures surface as errors. Use the returned status and tracking-number list for order-status pages and shipment notifications.+<!-- END MANUAL -->++### Inputs++| Input | Description | Type | Required |+|-------|-------------|------|----------|+| order_id | Slant3D public order ID to track | str | Yes |++### Outputs++| Output | Description | Type |+|--------|-------------|------|+| error | Error message if the operation failed | str |+| status | Order status | str |+| tracking_numbers | Shipment tracking numbers | List[str] |++### Possible use case+<!-- MANUAL: use_case -->+**Order Status Page**: Display current order status to customers on your website.++**Shipping Notifications**: Get tracking numbers to send shipping notifications to customers.++**Customer Support**: Look up order status quickly for customer service inquiries.+<!-- END MANUAL -->++---diff --git a/docs/integrations/block-integrations/slant3d/slicing.md b/docs/integrations/block-integrations/slant3d/slicing.mdindex a008379480..8a20f9bd12 100644--- a/docs/integrations/block-integrations/slant3d/slicing.md+++ b/docs/integrations/block-integrations/slant3d/slicing.md@@ -6,20 +6,24 @@ Blocks for slicing 3D models and getting pricing information from Slant3D.## Slant3D Slicer### What it is-Slice a 3D model file and get pricing information+Get a live 3D printing quote for physical parts from STL URLs or attached workspace files. Use this to price printable parts and complete project part sets before ordering from Slant3D, which manufactures and ships the parts. Binary STL URLs are accepted directly; no browser upload is needed. For complete projects, first read the assembly bill of materials: include repeated parts across subassemblies, select a design variant for alternative parts while keeping the required number of copies, and exclude reference assembly meshes. One copy of each STL is not necessarily a complete set. Quote each required file with its full assembly quantity and sum the returned prices, which already include quantity. Before reporting a complete quote, reconcile all quoted files and quantities against the parts list. Printing-only quotes need no shipping address or payment method. Returns a reusable file_id for ordering; this block does not place or charge an order.### How it works<!-- MANUAL: how_it_works -->-This block sends an STL file to Slant3D's slicing service to analyze the 3D model. The slicer calculates print parameters and returns pricing information based on the model's complexity, size, and material requirements.+This block loads an STL URL, workspace attachment, or data URI through the shared media loader, streams it through Slant3D's signed upload flow, confirms the upload, and requests a printing estimate. Supply `file_id` to reuse an upload. Set `platform_id`, or omit it only when the account has exactly one enabled platform.-Provide the URL to your STL file, and the block returns the calculated price for printing the model.+The USD price includes the requested positive `quantity` and excludes shipping. A `filament_id` selects a material; omitting it uses default black PLA. Missing file inputs, inaccessible files, invalid quantities, ambiguous platforms, and provider failures surface as errors. A missing total or a response priced for a different quantity is rejected before any output. Reuse the returned `file_id` when preparing an order.<!-- END MANUAL -->### Inputs| Input | Description | Type | Required ||-------|-------------|------|----------|-| file_url | URL of the 3D model file to slice (STL) | str | Yes |+| file_url | STL file URL, workspace file, or data URI; ignored when file_id is set | str (file) | No |+| file_id | Previously uploaded Slant3D public file service ID | str | No |+| platform_id | Platform ID for uploads; may be omitted with one enabled platform | str | No |+| filament_id | Filament public ID; defaults to Slant3D's PLA Black | str | No |+| quantity | Number of prints to estimate | int | No |### Outputs@@ -27,7 +31,8 @@ Provide the URL to your STL file, and the block returns the calculated price for|--------|-------------|------|| error | Error message if the operation failed | str || message | Response message | str |-| price | Calculated price for printing | float |+| price | Estimated printing price for the requested quantity in USD | float |+| file_id | Slant3D public file service ID for order items | str |### Possible use case<!-- MANUAL: use_case -->diff --git a/docs/integrations/block-integrations/slant3d/webhook.md b/docs/integrations/block-integrations/slant3d/webhook.mdindex 9d5a9d7d47..a9471da667 100644--- a/docs/integrations/block-integrations/slant3d/webhook.md+++ b/docs/integrations/block-integrations/slant3d/webhook.md@@ -10,15 +10,16 @@ This block triggers on Slant3D order status updates and outputs the event detail### How it works<!-- MANUAL: how_it_works -->-This block subscribes to Slant3D webhook events for order status updates. When an order's status changes (e.g., printing, shipped, delivered), Slant3D sends a webhook notification that triggers your workflow.+This block subscribes to order events on a Slant3D platform. New v2 subscriptions require `platform_id="your-platform-id"`; only retained v1 subscriptions may omit it. Registration is serialized per platform to prevent competing callbacks. Each platform has one webhook URL, so an existing callback belonging to another application requires a dedicated platform. V2 deliveries must include `X-Webhook-Signature-256: sha256=<digest>` and a fresh millisecond `X-Webhook-Timestamp`; invalid signatures, platform mismatches, and invalid event types are rejected.-The payload includes order details and, when applicable, shipping information like tracking numbers and carrier codes for fulfillment tracking.+The block outputs order details and available tracking information. Missing carrier codes become empty strings, and dummy deliveries do not trigger workflows. Retained v1 callbacks have no signature scheme and rely on their unguessable callback URL as a bearer credential: keep that URL private. Reconnect with a v2 key and platform ID to migrate to signed delivery.<!-- END MANUAL -->### Inputs| Input | Description | Type | Required ||-------|-------------|------|----------|+| platform_id | Required for new v2 subscriptions; retained v1 subscriptions may omit this platform ID. Use a platform without another webhook. | str | No || events | Order status events to subscribe to | Events | No |### Outputs@@ -29,8 +30,8 @@ The payload includes order details and, when applicable, shipping information li| payload | The complete webhook payload received from Slant3D | Dict[str, Any] || order_id | The ID of the affected order | str || status | The new status of the order | str |-| tracking_number | The tracking number for the shipment | str |-| carrier_code | The carrier code (e.g., 'usps') | str |+| tracking_number | Shipment tracking number, empty before shipment | str |+| carrier_code | Carrier code when supplied by Slant3D, otherwise empty | str |### Possible use case<!-- MANUAL: use_case -->