Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(platform/copilot): Webhook-trigger setup + preset lifecycle management (#13298)

Reinier van der Leer150514f0502d
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index d28664a6a0..9a2fbe6cc5 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -67,6 +67,11 @@ from backend.copilot.response_model import (
)
from backend.copilot.service import strip_injected_context_for_display
from backend.copilot.tools.e2b_sandbox import kill_sandbox
+from backend.copilot.tools.manage_presets import (
+ PresetDeletedResponse,
+ PresetListResponse,
+ PresetUpdatedResponse,
+)
from backend.copilot.tools.manage_schedules import (
ScheduleDeletedResponse,
ScheduleListResponse,
@@ -1657,6 +1662,9 @@ ToolResponseUnion = (
| TaskDecompositionResponse
| ScheduleListResponse
| ScheduleDeletedResponse
+ | PresetListResponse
+ | PresetUpdatedResponse
+ | PresetDeletedResponse
| MemoryStoreResponse
| MemorySearchResponse
| MemoryForgetCandidatesResponse
diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.py
index ea2d62bc95..e9361252f5 100644
--- a/autogpt_platform/backend/backend/api/features/library/db.py
+++ b/autogpt_platform/backend/backend/api/features/library/db.py
@@ -114,6 +114,7 @@ async def list_library_agents(
folder_id: Optional[str] = None,
include_root_only: bool = False,
is_hidden: Optional[bool] = None,
+ include_nodes: bool = False,
) -> library_model.LibraryAgentResponse:
"""
Retrieves a paginated list of LibraryAgent records for a given user.
@@ -129,6 +130,12 @@ async def list_library_agents(
include_executions: Whether to include execution data for status calculation.
Defaults to False for performance (UI fetches status separately).
Set to True when accurate status/metrics are needed (e.g., agent generator).
+ include_nodes: Whether to load graph nodes. Defaults to False for
+ performance (the main library page fetches node-derived data
+ separately). Set to True when node-derived fields are needed in the
+ listing itself — e.g. ``has_external_trigger`` / ``trigger_setup_info``,
+ which are False/None without nodes (used by the copilot to recognise
+ webhook-trigger agents without re-reading the full graph).
Returns:
A LibraryAgentResponse containing the list of agents and pagination details.
@@ -193,7 +200,9 @@ async def list_library_agents(
library_agents = await prisma.models.LibraryAgent.prisma().find_many(
where=where_clause,
include=library_agent_include(
- user_id, include_nodes=False, include_executions=include_executions
+ user_id,
+ include_nodes=include_nodes,
+ include_executions=include_executions,
),
order=order_by,
skip=(page - 1) * page_size,
diff --git a/autogpt_platform/backend/backend/api/features/library/routes/presets.py b/autogpt_platform/backend/backend/api/features/library/routes/presets.py
index 89f284f658..281a9a2459 100644
--- a/autogpt_platform/backend/backend/api/features/library/routes/presets.py
+++ b/autogpt_platform/backend/backend/api/features/library/routes/presets.py
@@ -6,21 +6,20 @@ from fastapi import APIRouter, Body, Depends, HTTPException, Query, Security, st
from backend.copilot.rate_limit import enforce_payment_paywall
from backend.data.execution import GraphExecutionMeta
-from backend.data.graph import get_graph
-from backend.data.integrations import get_webhook
from backend.data.model import CredentialsMetaInput
-from backend.executor.utils import add_graph_execution, make_node_credentials_input_map
-from backend.integrations.creds_manager import IntegrationCredentialsManager
-from backend.integrations.webhooks import get_webhook_manager
-from backend.integrations.webhooks.utils import setup_webhook_for_block
-from backend.util.exceptions import NotFoundError
+from backend.executor.utils import add_graph_execution
+from backend.util.exceptions import NotFoundError, WebhookRegistrationError
from .. import db
from .. import model as models
+from ..triggers import (
+ delete_preset_with_webhook_cleanup,
+ setup_triggered_preset,
+ update_triggered_preset,
+)
logger = logging.getLogger(__name__)
-credentials_manager = IntegrationCredentialsManager()
router = APIRouter(
tags=["presets"],
dependencies=[Security(autogpt_auth_lib.requires_user)],
@@ -154,55 +153,21 @@ async def setup_trigger(
Sets up a webhook-triggered `LibraryAgentPreset` for a `LibraryAgent`.
Returns the correspondingly created `LibraryAgentPreset` with `webhook_id` set.
"""
- graph = await get_graph(
- params.graph_id, version=params.graph_version, user_id=user_id
- )
- if not graph:
- raise HTTPException(
- status.HTTP_410_GONE,
- f"Graph #{params.graph_id} not accessible (anymore)",
- )
- if not (trigger_node := graph.webhook_input_node):
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=f"Graph #{params.graph_id} does not have a webhook node",
- )
-
- trigger_config_with_credentials = {
- **params.trigger_config,
- **(
- make_node_credentials_input_map(graph, params.agent_credentials).get(
- trigger_node.id
- )
- or {}
- ),
- }
-
- new_webhook, feedback = await setup_webhook_for_block(
- user_id=user_id,
- trigger_block=trigger_node.block,
- trigger_config=trigger_config_with_credentials,
- )
- if not new_webhook:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=f"Could not set up webhook: {feedback}",
- )
-
- new_preset = await db.create_preset(
- user_id=user_id,
- preset=models.LibraryAgentPresetCreatable(
+ try:
+ return await setup_triggered_preset(
+ user_id=user_id,
graph_id=params.graph_id,
graph_version=params.graph_version,
name=params.name,
description=params.description,
- inputs=trigger_config_with_credentials,
- credentials=params.agent_credentials,
- webhook_id=new_webhook.id,
- is_active=True,
- ),
- )
- return new_preset
+ trigger_config=params.trigger_config,
+ agent_credentials=params.agent_credentials,
+ )
+ except WebhookRegistrationError as e:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail=f"Could not set up the trigger: {e}",
+ )
@router.patch(
@@ -229,84 +194,19 @@ async def update_preset(
Raises:
HTTPException: If an error occurs while updating the preset.
"""
- current = await get_preset(preset_id, user_id=user_id)
- if not current:
- raise HTTPException(status.HTTP_404_NOT_FOUND, f"Preset #{preset_id} not found")
-
- graph = await get_graph(
- current.graph_id,
- current.graph_version,
+ # Webhook re-registration + old-webhook pruning lives in the shared
+ # update_triggered_preset (see triggers.py) so the copilot update_preset tool
+ # reuses the exact same logic. NotFoundError/InvalidInputError are mapped to
+ # 404/400 by the global exception handlers.
+ return await update_triggered_preset(
user_id=user_id,
+ preset_id=preset_id,
+ inputs=preset.inputs,
+ credentials=preset.credentials,
+ name=preset.name,
+ description=preset.description,
+ is_active=preset.is_active,
)
- if not graph:
- raise HTTPException(
- status.HTTP_410_GONE,
- f"Graph #{current.graph_id} not accessible (anymore)",
- )
-
- trigger_inputs_updated, new_webhook, feedback = False, None, None
- if (trigger_node := graph.webhook_input_node) and (
- preset.inputs is not None and preset.credentials is not None
- ):
- trigger_config_with_credentials = {
- **preset.inputs,
- **(
- make_node_credentials_input_map(graph, preset.credentials).get(
- trigger_node.id
- )
- or {}
- ),
- }
- new_webhook, feedback = await setup_webhook_for_block(
- user_id=user_id,
- trigger_block=graph.webhook_input_node.block,
- trigger_config=trigger_config_with_credentials,
- for_preset_id=preset_id,
- )
- trigger_inputs_updated = True
- if not new_webhook:
- raise HTTPException(
- status_code=status.HTTP_400_BAD_REQUEST,
- detail=f"Could not update trigger configuration: {feedback}",
- )
-
- try:
- updated = await db.update_preset(
- user_id=user_id,
- preset_id=preset_id,
- inputs=preset.inputs,
- credentials=preset.credentials,
- name=preset.name,
- description=preset.description,
- is_active=preset.is_active,
- )
- except Exception as e:
- logger.exception("Preset update failed for user %s: %s", user_id, e)
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
- )
-
- # Update the webhook as well, if necessary
- if trigger_inputs_updated:
- updated = await db.set_preset_webhook(
- user_id, preset_id, new_webhook.id if new_webhook else None
- )
-
- # Clean up webhook if it is now unused
- if current.webhook_id and (
- current.webhook_id != (new_webhook.id if new_webhook else None)
- ):
- current_webhook = await get_webhook(current.webhook_id)
- credentials = (
- await credentials_manager.get(user_id, current_webhook.credentials_id)
- if current_webhook.credentials_id
- else None
- )
- await get_webhook_manager(
- current_webhook.provider
- ).prune_webhook_if_dangling(user_id, current_webhook.id, credentials)
-
- return updated
@router.delete(
@@ -329,38 +229,10 @@ async def delete_preset(
Raises:
HTTPException: If an error occurs while deleting the preset.
"""
- preset = await db.get_preset(user_id, preset_id)
- if not preset:
- raise HTTPException(
- status_code=status.HTTP_404_NOT_FOUND,
- detail=f"Preset #{preset_id} not found for user #{user_id}",
- )
-
- # Detach and clean up the attached webhook, if any
- if preset.webhook_id:
- webhook = await get_webhook(preset.webhook_id)
- await db.set_preset_webhook(user_id, preset_id, None)
-
- # Clean up webhook if it is now unused
- credentials = (
- await credentials_manager.get(user_id, webhook.credentials_id)
- if webhook.credentials_id
- else None
- )
- await get_webhook_manager(webhook.provider).prune_webhook_if_dangling(
- user_id, webhook.id, credentials
- )
-
- try:
- await db.delete_preset(user_id, preset_id)
- except Exception as e:
- logger.exception(
- "Error deleting preset %s for user %s: %s", preset_id, user_id, e
- )
- raise HTTPException(
- status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
- detail=str(e),
- )
+ # Webhook detach + prune-if-dangling lives in the shared
+ # delete_preset_with_webhook_cleanup (see triggers.py) so the copilot
+ # delete_preset tool reuses it. NotFoundError → 404 via the global handler.
+ await delete_preset_with_webhook_cleanup(user_id=user_id, preset_id=preset_id)
@router.post(
diff --git a/autogpt_platform/backend/backend/api/features/library/triggers.py b/autogpt_platform/backend/backend/api/features/library/triggers.py
new file mode 100644
index 0000000000..bbbcb22cec
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/library/triggers.py
@@ -0,0 +1,213 @@
+"""Setting up webhook-triggered presets for library agents.
+
+Shared by the ``POST /presets/setup-trigger`` route and the copilot
+``setup_agent_webhook_trigger`` tool, so the webhook-preset creation logic lives
+in one place. Exposed as a DatabaseManager RPC endpoint (see ``db_manager.py``)
+because the copilot tool runs without a connected Prisma client.
+"""
+
+import logging
+from typing import Any
+
+from backend.data.graph import get_graph
+from backend.data.integrations import get_webhook
+from backend.data.model import CredentialsMetaInput, GraphInput
+from backend.executor.utils import make_node_credentials_input_map
+from backend.integrations.creds_manager import IntegrationCredentialsManager
+from backend.integrations.webhooks import get_webhook_manager
+from backend.integrations.webhooks.utils import setup_webhook_for_block
+from backend.util.exceptions import InvalidInputError, NotFoundError
+
+from . import db
+from . import model as models
+
+logger = logging.getLogger(__name__)
+
+credentials_manager = IntegrationCredentialsManager()
+
+
+async def setup_triggered_preset(
+ *,
+ user_id: str,
+ graph_id: str,
+ graph_version: int,
+ name: str,
+ description: str,
+ trigger_config: dict[str, Any],
+ agent_credentials: dict[str, CredentialsMetaInput],
+) -> models.LibraryAgentPreset:
+ """Create a webhook-triggered ``LibraryAgentPreset`` for the given graph.
+
+ Sets up the webhook for the graph's trigger node — auto-registering it with
+ the provider for auto-setup webhooks, or just minting the ingress URL for
+ manual-setup webhooks — then creates a preset linked to that webhook. The
+ returned preset has ``.webhook`` populated, so ``preset.webhook.url`` is the
+ ingress URL to hand to the user for manual-setup webhooks.
+
+ Fetches the graph itself (rather than taking a ``GraphModel``) so it can run
+ as an RPC endpoint without serializing the whole graph across the boundary.
+
+ Raises:
+ NotFoundError: if the graph no longer exists / isn't accessible.
+ InvalidInputError: if the graph has no webhook node, or the webhook
+ backend rejects the trigger config / credentials.
+ """
+ graph = await get_graph(graph_id, version=graph_version, user_id=user_id)
+ if not graph:
+ raise NotFoundError(f"Graph #{graph_id} is not accessible (anymore)")
+ if not (trigger_node := graph.webhook_input_node):
+ raise InvalidInputError(
+ f"Graph #{graph_id} does not have a webhook trigger node"
+ )
+
+ trigger_config_with_credentials = {
+ **trigger_config,
+ **(
+ make_node_credentials_input_map(graph, agent_credentials).get(
+ trigger_node.id
+ )
+ or {}
+ ),
+ }
+
+ new_webhook, feedback = await setup_webhook_for_block(
+ user_id=user_id,
+ trigger_block=trigger_node.block,
+ trigger_config=trigger_config_with_credentials,
+ )
+ if not new_webhook:
+ raise InvalidInputError(f"Could not set up webhook: {feedback}")
+
+ return await db.create_preset(
+ user_id=user_id,
+ preset=models.LibraryAgentPresetCreatable(
+ graph_id=graph.id,
+ graph_version=graph.version,
+ name=name,
+ description=description,
+ inputs=trigger_config_with_credentials,
+ credentials=agent_credentials,
+ webhook_id=new_webhook.id,
+ is_active=True,
+ ),
+ )
+
+
+async def update_triggered_preset(
+ *,
+ user_id: str,
+ preset_id: str,
+ inputs: GraphInput | None = None,
+ credentials: dict[str, CredentialsMetaInput] | None = None,
+ name: str | None = None,
+ description: str | None = None,
+ is_active: bool | None = None,
+) -> models.LibraryAgentPreset:
+ """Update a preset, re-registering its webhook if the trigger config changed.
+
+ Shared by the ``PATCH /presets/{id}`` route and the copilot ``update_preset``
+ tool. When both ``inputs`` and ``credentials`` are provided and the preset's
+ graph has a webhook trigger node, the webhook is re-registered with the new
+ config and the previously-attached webhook is pruned if it becomes dangling.
+ Name/description/active-status changes don't touch the webhook.
+
+ Raises:
+ NotFoundError: if the preset (or, when reconfiguring, its graph) is gone.
+ InvalidInputError: if the webhook backend rejects the new trigger config.
+ """
+ current = await db.get_preset(user_id, preset_id)
+ if not current:
+ raise NotFoundError(f"Preset #{preset_id} not found")
+
+ trigger_inputs_updated, new_webhook = False, None
+ if inputs is not None and credentials is not None:
+ graph = await get_graph(
+ current.graph_id, current.graph_version, user_id=user_id
+ )
+ if not graph:
+ raise NotFoundError(
+ f"Graph #{current.graph_id} is not accessible (anymore)"
+ )
+ if trigger_node := graph.webhook_input_node:
+ trigger_config_with_credentials = {
+ **inputs,
+ **(
+ make_node_credentials_input_map(graph, credentials).get(
+ trigger_node.id
+ )
+ or {}
+ ),
+ }
+ new_webhook, feedback = await setup_webhook_for_block(
+ user_id=user_id,
+ trigger_block=trigger_node.block,
+ trigger_config=trigger_config_with_credentials,
+ for_preset_id=preset_id,
+ )
+ trigger_inputs_updated = True
+ if not new_webhook:
+ raise InvalidInputError(
+ f"Could not update trigger configuration: {feedback}"
+ )
+
+ updated = await db.update_preset(
+ user_id=user_id,
+ preset_id=preset_id,
+ inputs=inputs,
+ credentials=credentials,
+ name=name,
+ description=description,
+ is_active=is_active,
+ )
+
+ if trigger_inputs_updated:
+ new_webhook_id = new_webhook.id if new_webhook else None
+ updated = await db.set_preset_webhook(user_id, preset_id, new_webhook_id)
+ # Clean up the old webhook if it's no longer referenced.
+ if current.webhook_id and current.webhook_id != new_webhook_id:
+ await _prune_dangling_webhook(user_id, current.webhook_id)
+
+ return updated
+
+
+async def delete_preset_with_webhook_cleanup(*, user_id: str, preset_id: str) -> None:
+ """Delete a preset and prune its webhook if it becomes dangling.
+
+ Shared by the ``DELETE /presets/{id}`` route and the copilot ``delete_preset``
+ tool. Detaches the webhook from the preset first, then prunes it (deregisters
+ with the provider + deletes) if no other trigger references it.
+
+ Raises:
+ NotFoundError: if the preset doesn't exist for this user.
+ """
+ preset = await db.get_preset(user_id, preset_id)
+ if not preset:
+ raise NotFoundError(f"Preset #{preset_id} not found")
+
+ if preset.webhook_id:
+ await db.set_preset_webhook(user_id, preset_id, None)
+ await _prune_dangling_webhook(user_id, preset.webhook_id)
+
+ await db.delete_preset(user_id, preset_id)
+
+
+async def _prune_dangling_webhook(user_id: str, webhook_id: str) -> None:
+ """Deregister + delete a webhook if no trigger references it anymore.
+
+ Best-effort: webhook cleanup runs *after* the preset update/delete is
+ committed, so a failure here (e.g. provider deregister error) must not fail
+ the whole mutation — it would leave the preset state correct but raise to the
+ caller. We log and move on; at worst the webhook lingers and is pruned later.
+ """
+ try:
+ webhook = await get_webhook(webhook_id)
+ credentials = (
+ await credentials_manager.get(user_id, webhook.credentials_id)
+ if webhook.credentials_id
+ else None
+ )
+ await get_webhook_manager(webhook.provider).prune_webhook_if_dangling(
+ user_id, webhook.id, credentials
+ )
+ except Exception as e:
+ logger.warning(f"Best-effort prune of webhook #{webhook_id} failed: {e}")
diff --git a/autogpt_platform/backend/backend/api/features/library/triggers_test.py b/autogpt_platform/backend/backend/api/features/library/triggers_test.py
new file mode 100644
index 0000000000..d77f8bcd48
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/library/triggers_test.py
@@ -0,0 +1,248 @@
+"""Tests for the shared webhook-preset helpers (setup/update/delete) used by both
+the /presets routes and the copilot preset tools."""
+
+import contextlib
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.api.features.library.triggers import (
+ delete_preset_with_webhook_cleanup,
+ setup_triggered_preset,
+ update_triggered_preset,
+)
+from backend.util.exceptions import InvalidInputError, NotFoundError
+
+_USER = "test-user-triggers"
+_PATH = "backend.api.features.library.triggers"
+
+
+def _graph():
+ node = MagicMock()
+ node.id = "trigger-node"
+ graph = MagicMock()
+ graph.id = "graph-1"
+ graph.version = 1
+ graph.webhook_input_node = node
+ return graph
+
+
+def _patches(*, graph, webhook=..., feedback=None, preset=None):
+ """Patch triggers.py's collaborators. ``webhook=...`` defaults to a stub
+ webhook; pass ``webhook=None`` + ``feedback`` to exercise the rejection."""
+ new_webhook = MagicMock(id="wh-1") if webhook is ... else webhook
+ return (
+ patch(f"{_PATH}.get_graph", new=AsyncMock(return_value=graph)),
+ patch(f"{_PATH}.make_node_credentials_input_map", return_value={}),
+ patch(
+ f"{_PATH}.setup_webhook_for_block",
+ new=AsyncMock(return_value=(new_webhook, feedback)),
+ ),
+ patch(f"{_PATH}.db.create_preset", new=AsyncMock(return_value=preset)),
+ )
+
+
+async def _setup():
+ return await setup_triggered_preset(
+ user_id=_USER,
+ graph_id="graph-1",
+ graph_version=1,
+ name="My Trigger",
+ description="",
+ trigger_config={"repo": "owner/repo"},
+ agent_credentials={},
+ )
+
+
+async def test_creates_preset_on_success():
+ preset = MagicMock(id="preset-1")
+ p_graph, p_creds, p_webhook, p_create = _patches(graph=_graph(), preset=preset)
+ with p_graph, p_creds, p_webhook, p_create as create_mock:
+ result = await _setup()
+ assert result is preset
+ create_mock.assert_awaited_once()
+
+
+async def test_graph_not_found_raises():
+ p_graph, p_creds, p_webhook, p_create = _patches(graph=None)
+ with p_graph, p_creds, p_webhook, p_create:
+ with pytest.raises(NotFoundError):
+ await _setup()
+
+
+async def test_no_webhook_node_raises():
+ graph = _graph()
+ graph.webhook_input_node = None
+ p_graph, p_creds, p_webhook, p_create = _patches(graph=graph)
+ with p_graph, p_creds, p_webhook, p_create:
+ with pytest.raises(InvalidInputError):
+ await _setup()
+
+
+async def test_webhook_setup_rejected_raises():
+ p_graph, p_creds, p_webhook, p_create = _patches(
+ graph=_graph(), webhook=None, feedback="no enabled events"
+ )
+ with p_graph, p_creds, p_webhook, p_create as create_mock:
+ with pytest.raises(InvalidInputError, match="no enabled events"):
+ await _setup()
+ create_mock.assert_not_awaited()
+
+
+# ---- update_triggered_preset ----
+
+
+def _preset(*, webhook_id=None):
+ preset = MagicMock()
+ preset.id = "preset-1"
+ preset.graph_id = "graph-1"
+ preset.graph_version = 1
+ preset.webhook_id = webhook_id
+ return preset
+
+
+def _update_patches(*, current, graph=..., webhook=..., feedback=None):
+ """Patch update_triggered_preset's collaborators; yields the call mocks."""
+ new_webhook = MagicMock(id="wh-new") if webhook is ... else webhook
+ graph_val = _graph() if graph is ... else graph
+ patchers = {
+ "get_preset": patch(
+ f"{_PATH}.db.get_preset", new=AsyncMock(return_value=current)
+ ),
+ "get_graph": patch(f"{_PATH}.get_graph", new=AsyncMock(return_value=graph_val)),
+ "creds_map": patch(f"{_PATH}.make_node_credentials_input_map", return_value={}),
+ "setup": patch(
+ f"{_PATH}.setup_webhook_for_block",
+ new=AsyncMock(return_value=(new_webhook, feedback)),
+ ),
+ "update": patch(
+ f"{_PATH}.db.update_preset",
+ new=AsyncMock(return_value=MagicMock(id="preset-1")),
+ ),
+ "set_webhook": patch(
+ f"{_PATH}.db.set_preset_webhook",
+ new=AsyncMock(return_value=MagicMock(id="preset-1")),
+ ),
+ "prune": patch(f"{_PATH}._prune_dangling_webhook", new=AsyncMock()),
+ }
+ with contextlib.ExitStack() as stack:
+ yield {k: stack.enter_context(p) for k, p in patchers.items()}
+
+
+async def test_update_rename_only_skips_webhook():
+ with _update_patches(current=_preset(webhook_id="wh-old")) as m:
+ await update_triggered_preset(
+ user_id=_USER, preset_id="preset-1", name="New name"
+ )
+ m["update"].assert_awaited_once()
+ m["setup"].assert_not_awaited()
+ m["set_webhook"].assert_not_awaited()
+ m["prune"].assert_not_awaited()
+
+
+async def test_update_reconfigure_reregisters_and_prunes_old():
+ with _update_patches(current=_preset(webhook_id="wh-old")) as m:
+ await update_triggered_preset(
+ user_id=_USER,
+ preset_id="preset-1",
+ inputs={"repo": "owner/repo"},
+ credentials={},
+ )
+ m["setup"].assert_awaited_once()
+ m["set_webhook"].assert_awaited_once()
+ m["prune"].assert_awaited_once_with(_USER, "wh-old")
+
+
+async def test_update_reconfigure_webhook_rejected_raises():
+ with _update_patches(current=_preset(), webhook=None, feedback="no events") as m:
+ with pytest.raises(InvalidInputError, match="no events"):
+ await update_triggered_preset(
+ user_id=_USER,
+ preset_id="preset-1",
+ inputs={"repo": "x"},
+ credentials={},
+ )
+ m["update"].assert_not_awaited()
+
+
+async def test_update_preset_not_found_raises():
+ with _update_patches(current=None):
+ with pytest.raises(NotFoundError):
+ await update_triggered_preset(user_id=_USER, preset_id="missing", name="X")
+
+
+async def test_update_reconfigure_graph_gone_raises():
+ with _update_patches(current=_preset(), graph=None):
+ with pytest.raises(NotFoundError):
+ await update_triggered_preset(
+ user_id=_USER,
+ preset_id="preset-1",
+ inputs={"repo": "x"},
+ credentials={},
+ )
+
+
+# ---- delete_preset_with_webhook_cleanup ----
+
+
+def _delete_patches(*, preset):
+ patchers = {
+ "get_preset": patch(
+ f"{_PATH}.db.get_preset", new=AsyncMock(return_value=preset)
+ ),
+ "set_webhook": patch(f"{_PATH}.db.set_preset_webhook", new=AsyncMock()),
+ "prune": patch(f"{_PATH}._prune_dangling_webhook", new=AsyncMock()),
+ "delete": patch(f"{_PATH}.db.delete_preset", new=AsyncMock()),
+ }
+ with contextlib.ExitStack() as stack:
+ yield {k: stack.enter_context(p) for k, p in patchers.items()}
+
+
+async def test_delete_with_webhook_prunes():
+ with _delete_patches(preset=_preset(webhook_id="wh-1")) as m:
+ await delete_preset_with_webhook_cleanup(user_id=_USER, preset_id="preset-1")
+ m["set_webhook"].assert_awaited_once_with(_USER, "preset-1", None)
+ m["prune"].assert_awaited_once_with(_USER, "wh-1")
+ m["delete"].assert_awaited_once()
+
+
+async def test_delete_without_webhook_skips_prune():
+ with _delete_patches(preset=_preset(webhook_id=None)) as m:
+ await delete_preset_with_webhook_cleanup(user_id=_USER, preset_id="preset-1")
+ m["set_webhook"].assert_not_awaited()
+ m["prune"].assert_not_awaited()
+ m["delete"].assert_awaited_once()
+
+
+async def test_delete_not_found_raises():
+ with _delete_patches(preset=None):
+ with pytest.raises(NotFoundError):
+ await delete_preset_with_webhook_cleanup(user_id=_USER, preset_id="missing")
+
+
+async def test_prune_dangling_webhook_is_best_effort():
+ """Cleanup runs after state is committed, so a prune failure is swallowed
+ (logged) rather than raised — the mutation must not fail post-commit."""
+ from backend.api.features.library.triggers import _prune_dangling_webhook
+
+ with patch(
+ f"{_PATH}.get_webhook",
+ new=AsyncMock(side_effect=Exception("provider unreachable")),
+ ):
+ # Must not raise.
+ await _prune_dangling_webhook(_USER, "wh-1")
diff --git a/autogpt_platform/backend/backend/blocks/airtable/_webhook.py b/autogpt_platform/backend/backend/blocks/airtable/_webhook.py
index 452630953e..7eed7bb263 100644
--- a/autogpt_platform/backend/backend/blocks/airtable/_webhook.py
+++ b/autogpt_platform/backend/backend/blocks/airtable/_webhook.py
@@ -17,6 +17,7 @@ from backend.sdk import (
Webhook,
update_webhook,
)
+from backend.util.request import HTTPClientError, HTTPServerError
from ._api import (
WebhookFilters,
@@ -121,13 +122,18 @@ class AirtableWebhookManager(BaseWebhooksManager):
)
)
- # Create webhook
- webhook_data = await create_webhook(
- credentials=credentials,
- base_id=base_id,
- webhook_specification=webhook_specification,
- notification_url=ingress_url,
- )
+ try:
+ webhook_data = await create_webhook(
+ credentials=credentials,
+ base_id=base_id,
+ webhook_specification=webhook_specification,
+ notification_url=ingress_url,
+ )
+ except (HTTPClientError, HTTPServerError) as e:
+ raise ValueError(
+ "Airtable returned error "
+ f"for webhook registration on base '{base_id}': {e}"
+ )
webhook_id = webhook_data["id"]
mac_secret = webhook_data.get("macSecretBase64")
diff --git a/autogpt_platform/backend/backend/blocks/exa/_webhook.py b/autogpt_platform/backend/backend/blocks/exa/_webhook.py
index 725976c68c..2b248d2f12 100644
--- a/autogpt_platform/backend/backend/blocks/exa/_webhook.py
+++ b/autogpt_platform/backend/backend/blocks/exa/_webhook.py
@@ -91,7 +91,7 @@ class ExaWebhookManager(BaseWebhooksManager):
api_key = credentials.api_key.get_secret_value()
# Create webhook via Exa API
- response = await Requests().post(
+ response = await Requests(raise_for_status=False).post(
"https://api.exa.ai/v0/webhooks",
headers={"x-api-key": api_key},
json={
@@ -106,7 +106,7 @@ class ExaWebhookManager(BaseWebhooksManager):
if not response.ok:
error_data = response.json()
- raise Exception(f"Failed to create Exa webhook: {error_data}")
+ raise ValueError(f"Exa returned error: {error_data}")
webhook_data = response.json()
diff --git a/autogpt_platform/backend/backend/cli/__init__.py b/autogpt_platform/backend/backend/cli/__init__.py
index d96b0c7d49..d2198011b7 100644
--- a/autogpt_platform/backend/backend/cli/__init__.py
+++ b/autogpt_platform/backend/backend/cli/__init__.py
@@ -1 +1,6 @@
"""CLI utilities for backend development & administration"""
+
+from .main import main
+
+if __name__ == "__main__":
+ main()
diff --git a/autogpt_platform/backend/backend/cli/chat.py b/autogpt_platform/backend/backend/cli/chat.py
new file mode 100644
index 0000000000..1a0504c998
--- /dev/null
+++ b/autogpt_platform/backend/backend/cli/chat.py
@@ -0,0 +1,306 @@
+import logging
+
+import click
+
+# Default max length for rendered message content before truncation (override
+# per-call with ``full=True`` / the ``--full`` flag).
+_TRUNCATE_LENGTH = 500
+
+
+def chat():
+ """
+ Group for CoPilot chat inspection commands
+ """
+ # Suppress INFO/DEBUG logs (Prisma connection chatter, service-client
+ # setup) so they don't interleave with the rendered transcript. Use
+ # logging.disable so it can't be undone by configure_logging() running
+ # later during connect().
+ logging.disable(logging.INFO)
+
+
[email protected](name="view")
[email protected]("session_id")
[email protected]("seq_range", required=False, default=None, metavar="[RANGE]")
[email protected]("--full", "-f", is_flag=True, help="Disable truncation of long content.")
+ "--json", "as_json", is_flag=True, help="Dump the raw session+messages as JSON."
+)
+ "--limit", "-n", type=int, default=None, help="Show only the last N messages."
+)
+def chat_view(
+ session_id: str,
+ seq_range: str | None,
+ full: bool,
+ as_json: bool,
+ limit: int | None,
+):
+ """
+ Print a readable transcript of a CoPilot ChatSession by ID.
+
+ Optionally pass a message RANGE to show only those sequences: 'N' (one),
+ 'N-M' (inclusive), 'N-' (from N), '-M' (up to M). Combine with --full to
+ read them untruncated, e.g. `chat view <id> 6-10 --full`.
+ """
+ import asyncio
+
+ import prisma.models
+
+ from backend.data.db import connect, disconnect
+
+ # Parse up front so a bad value fails fast with a clean message.
+ bounds = _parse_seq_range(seq_range) if seq_range else None
+
+ async def run():
+ await connect()
+ try:
+ session = await prisma.models.ChatSession.prisma().find_unique(
+ where={"id": session_id}
+ )
+ if session is None:
+ print(f"No chat session found with id {session_id!r}")
+ return
+
+ messages = await prisma.models.ChatMessage.prisma().find_many(
+ where={"sessionId": session_id},
+ order={"sequence": "asc"},
+ )
+ if bounds is not None:
+ lo, hi = bounds
+ messages = [
+ m
+ for m in messages
+ if (lo is None or m.sequence >= lo)
+ and (hi is None or m.sequence <= hi)
+ ]
+ if limit is not None and limit > 0:
+ messages = messages[-limit:]
+
+ if as_json:
+ print(_render_session_json(session, messages))
+ else:
+ print(_render_session(session, messages, full=full))
+ finally:
+ await disconnect()
+
+ asyncio.run(run())
+
+
[email protected](name="list")
[email protected]("--user", "user_id", default=None, help="Filter by user ID.")
+ "--limit", "-n", type=int, default=20, help="Max number of sessions to list."
+)
+def chat_list(user_id: str | None, limit: int):
+ """
+ List recent CoPilot chat sessions (id, title, updatedAt, message count).
+ """
+ import asyncio
+
+ import prisma.models
+ import prisma.types
+
+ from backend.data.db import connect, disconnect
+
+ async def run():
+ await connect()
+ try:
+ where: prisma.types.ChatSessionWhereInput = {}
+ if user_id:
+ where["userId"] = user_id
+ sessions = await prisma.models.ChatSession.prisma().find_many(
+ where=where,
+ order={"updatedAt": "desc"},
+ take=limit,
+ )
+ if not sessions:
+ print("No chat sessions found")
+ return
+
+ for session in sessions:
+ count = await prisma.models.ChatMessage.prisma().count(
+ where={"sessionId": session.id}
+ )
+ title = session.title or "(untitled)"
+ print(
+ f"{session.id} "
+ f"{session.updatedAt:%Y-%m-%d %H:%M} "
+ f"{count:>4} msgs "
+ f"{title}"
+ )
+ finally:
+ await disconnect()
+
+ asyncio.run(run())
+
+
+def _parse_seq_range(text: str) -> tuple[int | None, int | None]:
+ """Parse a sequence selector into inclusive ``(lo, hi)`` bounds (``None`` =
+ open-ended): ``'N'`` -> ``(N, N)``, ``'N-M'`` -> ``(N, M)``, ``'N-'`` ->
+ ``(N, None)``, ``'-M'`` -> ``(None, M)``."""
+ raw = text.strip()
+ try:
+ if "-" not in raw:
+ n = int(raw)
+ return (n, n)
+ lo_str, hi_str = raw.split("-", 1)
+ lo = int(lo_str) if lo_str.strip() else None
+ hi = int(hi_str) if hi_str.strip() else None
+ except ValueError as e:
+ raise click.BadParameter(
+ f"Invalid --range {text!r}; use forms like '7', '6-10', '6-', '-10'."
+ ) from e
+ if lo is not None and hi is not None and lo > hi:
+ raise click.BadParameter(f"Invalid --range {text!r}: start is after end.")
+ return (lo, hi)
+
+
+def _render_session(session, messages, *, full: bool) -> str:
+ import prisma.models
+
+ s: prisma.models.ChatSession = session
+ lines: list[str] = []
+ lines.append("=" * 80)
+ lines.append(f"ChatSession {s.id}")
+ lines.append(f" title: {s.title or '(untitled)'}")
+ lines.append(f" status: {s.chatStatus}")
+ lines.append(f" user: {s.userId}")
+ lines.append(f" created: {s.createdAt:%Y-%m-%d %H:%M:%S}")
+ lines.append(f" updated: {s.updatedAt:%Y-%m-%d %H:%M:%S}")
+ lines.append(
+ f" tokens: prompt={s.totalPromptTokens} "
+ f"completion={s.totalCompletionTokens}"
+ )
+ lines.append(f" messages: {len(messages)}")
+ lines.append("=" * 80)
+
+ for msg in messages:
+ lines.append("")
+ lines.extend(_render_message(msg, full=full))
+
+ return "\n".join(lines)
+
+
+def _render_message(msg, *, full: bool) -> list[str]:
+ import prisma.models
+
+ m: prisma.models.ChatMessage = msg
+ role = m.role
+ header = f"[{m.sequence}] {role.upper()}"
+ if m.name:
+ header += f" ({m.name})"
+ if m.durationMs is not None:
+ header += f" {m.durationMs}ms"
+
+ if role == "reasoning":
+ return [header] + [f" | {line}" for line in _reasoning_lines(m, full)]
+ if role == "assistant":
+ return [header] + _assistant_lines(m, full)
+ if role == "tool":
+ return [header] + _tool_lines(m, full)
+ if role == "user":
+ return [header] + _user_lines(m, full)
+
+ body = _truncate(m.content or "", full)
+ return [header] + _indent(body)
+
+
+def _reasoning_lines(msg, full: bool) -> list[str]:
+ return (_truncate(msg.content or "", full) or "(empty)").splitlines() or ["(empty)"]
+
+
+def _assistant_lines(msg, full: bool) -> list[str]:
+ import json
+
+ lines: list[str] = []
+ if msg.content:
+ lines.extend(_indent(_truncate(msg.content, full)))
+
+ tool_calls = msg.toolCalls
+ if isinstance(tool_calls, list):
+ for call in tool_calls:
+ if not isinstance(call, dict):
+ continue
+ fn = call.get("function") or {}
+ name = fn.get("name", "?")
+ raw_args = fn.get("arguments", "")
+ try:
+ parsed = json.loads(raw_args) if isinstance(raw_args, str) else raw_args
+ except (ValueError, TypeError):
+ parsed = raw_args
+ if isinstance(parsed, dict):
+ args_str = ", ".join(f"{k}={json.dumps(v)}" for k, v in parsed.items())
+ else:
+ args_str = str(parsed)
+ lines.append(f" -> {name}({_truncate(args_str, full)})")
+
+ if not lines:
+ lines.append(" (no content)")
+ return lines
+
+
+def _tool_lines(msg, full: bool) -> list[str]:
+ import json
+
+ content = msg.content or ""
+ try:
+ parsed = json.loads(content)
+ except ValueError:
+ return _indent(_truncate(content, full))
+
+ if isinstance(parsed, dict):
+ type_field = parsed.get("type", "result")
+ summary = {k: v for k, v in parsed.items() if k != "type"}
+ summary_str = json.dumps(summary, separators=(", ", ": "))
+ return [f" <{type_field}> {_truncate(summary_str, full)}"]
+
+ return _indent(_truncate(json.dumps(parsed), full))
+
+
+def _user_lines(msg, full: bool) -> list[str]:
+ content = _strip_context_blocks(msg.content or "")
+ return _indent(_truncate(content, full) or "(empty)")
+
+
+def _strip_context_blocks(content: str) -> str:
+ import re
+
+ # The first user message wraps the real request in large preamble blocks
+ # like <available_skills>...</available_skills>, <user_context>...,
+ # <session_context>... — collapse those so only the actual request shows.
+ for tag in ("available_skills", "user_context", "session_context"):
+ content = re.sub(
+ rf"<{tag}>.*?</{tag}>\s*",
+ f"[{tag} omitted]\n",
+ content,
+ flags=re.DOTALL,
+ )
+ return content.strip()
+
+
+def _truncate(text: str, full: bool, length: int = _TRUNCATE_LENGTH) -> str:
+ text = text.strip()
+ if full or len(text) <= length:
+ return text
+ return text[:length] + " ... [truncated]"
+
+
+def _indent(text: str, prefix: str = " ") -> list[str]:
+ if not text:
+ return [f"{prefix}(empty)"]
+ return [f"{prefix}{line}" for line in text.splitlines()]
+
+
+def _render_session_json(session, messages) -> str:
+ import json
+
+ payload = {
+ "session": json.loads(session.model_dump_json()),
+ "messages": [json.loads(m.model_dump_json()) for m in messages],
+ }
+ return json.dumps(payload, indent=2, default=str)
+
+
+if __name__ == "__main__":
+ chat()
diff --git a/autogpt_platform/backend/backend/cli/main.py b/autogpt_platform/backend/backend/cli/main.py
new file mode 100644
index 0000000000..772ba87d92
--- /dev/null
+++ b/autogpt_platform/backend/backend/cli/main.py
@@ -0,0 +1,116 @@
+"""CLI utilities for backend development & administration"""
+
+import os
+import pathlib
+
+import click
+import psutil
+
+from backend.util.process import AppProcess
+
+from .chat import chat
+from .test import test
+
+
+def main():
+ """AutoGPT Server CLI Tool"""
+ pass
+
+
+main.add_command(chat)
+main.add_command(test)
+
+
+def start():
+ """
+ Starts the server in the background and saves the PID
+ """
+ # Define the path for the new directory and file
+ pid = get_pid()
+ if pid and psutil.pid_exists(pid):
+ print("Server is already running")
+ exit(1)
+ elif pid:
+ print("PID does not exist deleting file")
+ os.remove(get_pid_path())
+
+ print("Starting server")
+ pid = MainApp().start(background=True, silent=True)
+ print(f"Server running in process: {pid}")
+
+ write_pid(pid)
+ print("done")
+ os._exit(status=0)
+
+
+class MainApp(AppProcess):
+ def run(self):
+ from backend import app
+
+ app.main(silent=True)
+
+
+def get_pid() -> int | None:
+ file_path = get_pid_path()
+ if not file_path.exists():
+ return None
+
+ with open(file_path, "r", encoding="utf-8") as file:
+ pid = file.read()
+ try:
+ return int(pid)
+ except ValueError:
+ return None
+
+
+def stop():
+ """
+ Stops the server
+ """
+ pid = get_pid()
+ if not pid:
+ print("Server is not running")
+ return
+
+ os.remove(get_pid_path())
+ try:
+ process = psutil.Process(int(pid))
+ except psutil.NoSuchProcess:
+ print("Server Stopped")
+ return
+ for child in process.children(recursive=True):
+ child.terminate()
+ process.terminate()
+
+ print("Server Stopped")
+
+
+def write_pid(pid: int):
+ file_path = get_pid_path()
+ os.makedirs(file_path.parent, exist_ok=True)
+ with open(file_path, "w", encoding="utf-8") as file:
+ file.write(str(pid))
+
+
+def get_pid_path() -> pathlib.Path:
+ home_dir = pathlib.Path.home()
+ new_dir = home_dir / ".config" / "agpt"
+ file_path = new_dir / "running.tmp"
+ return file_path
+
+
+def gen_encrypt_key():
+ """
+ Generate a new encryption key
+ """
+ from cryptography.fernet import Fernet
+
+ print(Fernet.generate_key().decode())
+
+
+if __name__ == "__main__":
+ main()
diff --git a/autogpt_platform/backend/backend/cli/render_test.py b/autogpt_platform/backend/backend/cli/render_test.py
new file mode 100644
index 0000000000..3b616f39a4
--- /dev/null
+++ b/autogpt_platform/backend/backend/cli/render_test.py
@@ -0,0 +1,132 @@
+import json
+from datetime import datetime
+from types import SimpleNamespace
+
+import click
+import pytest
+
+from backend.cli.chat import _parse_seq_range, _render_message, _render_session
+
+
+def _msg(**kwargs):
+ base = {
+ "sequence": 0,
+ "role": "user",
+ "content": None,
+ "name": None,
+ "toolCalls": None,
+ "durationMs": None,
+ }
+ base.update(kwargs)
+ return SimpleNamespace(**base)
+
+
+def test_render_user_strips_context_blocks():
+ msg = _msg(
+ sequence=0,
+ role="user",
+ content=(
+ "<available_skills>lots of stuff</available_skills>\n"
+ "<user_context>name=Reinier</user_context>\n"
+ "I want to set up my notifier agent"
+ ),
+ )
+ rendered = "\n".join(_render_message(msg, full=False))
+ assert "[0] USER" in rendered
+ assert "I want to set up my notifier agent" in rendered
+ assert "lots of stuff" not in rendered
+ assert "name=Reinier" not in rendered
+ assert "[available_skills omitted]" in rendered
+
+
+def test_render_assistant_with_tool_calls():
+ msg = _msg(
+ sequence=2,
+ role="assistant",
+ content="Let me find that agent.",
+ toolCalls=[
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {
+ "name": "find_library_agent",
+ "arguments": json.dumps({"query": "GitHub PR Gmail Notifier"}),
+ },
+ }
+ ],
+ )
+ rendered = "\n".join(_render_message(msg, full=False))
+ assert "Let me find that agent." in rendered
+ assert '-> find_library_agent(query="GitHub PR Gmail Notifier")' in rendered
+
+
+def test_render_tool_summarizes_type():
+ msg = _msg(
+ sequence=3,
+ role="tool",
+ content=json.dumps(
+ {"type": "no_results", "message": "Nothing found", "name": "no_results"}
+ ),
+ )
+ rendered = "\n".join(_render_message(msg, full=False))
+ assert "<no_results>" in rendered
+ assert "Nothing found" in rendered
+
+
+def test_render_reasoning_is_prefixed():
+ msg = _msg(sequence=1, role="reasoning", content="Thinking about the request.")
+ rendered = "\n".join(_render_message(msg, full=False))
+ assert "[1] REASONING" in rendered
+ assert "| Thinking about the request." in rendered
+
+
+def test_truncation_and_full_flag():
+ long_text = "x" * 800
+ msg = _msg(sequence=0, role="user", content=long_text)
+
+ truncated = "\n".join(_render_message(msg, full=False))
+ assert "[truncated]" in truncated
+ assert len(truncated) < 800
+
+ full = "\n".join(_render_message(msg, full=True))
+ assert "[truncated]" not in full
+ assert "x" * 800 in full
+
+
+def test_parse_seq_range_forms():
+ assert _parse_seq_range("7") == (7, 7)
+ assert _parse_seq_range("6-10") == (6, 10)
+ assert _parse_seq_range("6-") == (6, None)
+ assert _parse_seq_range("-10") == (None, 10)
+ assert _parse_seq_range(" 3 - 5 ") == (3, 5)
+
+
+def test_parse_seq_range_invalid_raises():
+ with pytest.raises(click.BadParameter):
+ _parse_seq_range("abc")
+ with pytest.raises(click.BadParameter):
+ _parse_seq_range("10-6") # start after end
+
+
+def test_render_session_header_and_messages():
+ session = SimpleNamespace(
+ id="abc-123",
+ title="GitHub PR to Gmail Notifier Setup",
+ chatStatus="idle",
+ userId="user-1",
+ createdAt=datetime(2026, 6, 5, 13, 16, 54),
+ updatedAt=datetime(2026, 6, 5, 13, 18, 14),
+ totalPromptTokens=42,
+ totalCompletionTokens=7,
+ )
+ messages = [
+ _msg(sequence=0, role="user", content="Set up my agent"),
+ _msg(sequence=1, role="assistant", content="Done."),
+ ]
+ rendered = _render_session(session, messages, full=False)
+ assert "ChatSession abc-123" in rendered
+ assert "title: GitHub PR to Gmail Notifier Setup" in rendered
+ assert "tokens: prompt=42 completion=7" in rendered
+ assert "messages: 2" in rendered
+ assert "[0] USER" in rendered
+ assert "[1] ASSISTANT" in rendered
diff --git a/autogpt_platform/backend/backend/cli.py b/autogpt_platform/backend/backend/cli/test.py
old mode 100755
new mode 100644
similarity index 68%
rename from autogpt_platform/backend/backend/cli.py
rename to autogpt_platform/backend/backend/cli/test.py
index d6eaca1dd0..6c247d672a
--- a/autogpt_platform/backend/backend/cli.py
+++ b/autogpt_platform/backend/backend/cli/test.py
@@ -1,107 +1,4 @@
-"""
-The command line interface for the agent server
-"""
-
-import os
-import pathlib
-
import click
-import psutil
-
-from backend.util.process import AppProcess
-
-
-def get_pid_path() -> pathlib.Path:
- home_dir = pathlib.Path.home()
- new_dir = home_dir / ".config" / "agpt"
- file_path = new_dir / "running.tmp"
- return file_path
-
-
-def get_pid() -> int | None:
- file_path = get_pid_path()
- if not file_path.exists():
- return None
-
- os.makedirs(file_path.parent, exist_ok=True)
- with open(file_path, "r", encoding="utf-8") as file:
- pid = file.read()
- try:
- return int(pid)
- except ValueError:
- return None
-
-
-def write_pid(pid: int):
- file_path = get_pid_path()
- os.makedirs(file_path.parent, exist_ok=True)
- with open(file_path, "w", encoding="utf-8") as file:
- file.write(str(pid))
-
-
-class MainApp(AppProcess):
- def run(self):
- from backend import app
-
- app.main(silent=True)
-
-
-def main():
- """AutoGPT Server CLI Tool"""
- pass
-
-
-def start():
- """
- Starts the server in the background and saves the PID
- """
- # Define the path for the new directory and file
- pid = get_pid()
- if pid and psutil.pid_exists(pid):
- print("Server is already running")
- exit(1)
- elif pid:
- print("PID does not exist deleting file")
- os.remove(get_pid_path())
-
- print("Starting server")
- pid = MainApp().start(background=True, silent=True)
- print(f"Server running in process: {pid}")
-
- write_pid(pid)
- print("done")
- os._exit(status=0)
-
-
-def stop():
- """
- Stops the server
- """
- pid = get_pid()
- if not pid:
- print("Server is not running")
- return
-
- os.remove(get_pid_path())
- process = psutil.Process(int(pid))
- for child in process.children(recursive=True):
- child.terminate()
- process.terminate()
-
- print("Server Stopped")
-
-
-def gen_encrypt_key():
- """
- Generate a new encryption key
- """
- from cryptography.fernet import Fernet
-
- print(Fernet.generate_key().decode())
@click.group()
@@ -268,7 +165,5 @@ def websocket(server_address: str, graph_exec_id: str):
print("Testing WS")
-main.add_command(test)
-
if __name__ == "__main__":
- main()
+ test()
diff --git a/autogpt_platform/backend/backend/copilot/permissions.py b/autogpt_platform/backend/backend/copilot/permissions.py
index c2a9b0590f..8156866071 100644
--- a/autogpt_platform/backend/backend/copilot/permissions.py
+++ b/autogpt_platform/backend/backend/copilot/permissions.py
@@ -83,6 +83,7 @@ ToolName = Literal[
"customize_agent",
"decompose_goal",
"delete_folder",
+ "delete_preset",
"delete_schedule",
"delete_skill",
"delete_workspace_file",
@@ -99,6 +100,7 @@ ToolName = Literal[
"list_agent_triggers",
"list_chat_platform_channels",
"list_folders",
+ "list_presets",
"list_schedules",
"list_skills",
"list_workspace_files",
@@ -118,8 +120,10 @@ ToolName = Literal[
"schedule_followup",
"search_docs",
"search_feature_requests",
+ "setup_agent_webhook_trigger",
"store_skill",
"update_folder",
+ "update_preset",
"validate_agent_graph",
"view_agent_output",
"web_fetch",
diff --git a/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md
index 055bb7f04e..b6b73107a6 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md
+++ b/autogpt_platform/backend/backend/copilot/sdk/agent_generation_guide.md
@@ -114,8 +114,16 @@ prices from Amazon and email me daily").
### REQUIRED: AgentInputBlock and AgentOutputBlock
-Every agent MUST include at least one AgentInputBlock and one AgentOutputBlock.
-These define the agent's interface — what it accepts and what it produces.
+Every agent MUST include one AgentOutputBlock and a way to be started: EITHER
+at least one AgentInputBlock OR a webhook trigger block (never both). These
+define the agent's interface — what it accepts and what it produces.
+
+- **Regular agent**: include at least one AgentInputBlock for the values the
+ user provides at runtime.
+- **Triggered agent**: include a webhook trigger block instead — it is started
+ by an external event, so it needs NO AgentInputBlock. Do NOT add a throwaway
+ AgentInputBlock alongside a trigger; the trigger block already provides the
+ agent's entry point and event payload. See "Setting Up Webhook Triggers".
**AgentInputBlock** (ID: `c0a8e994-ebf1-4a9c-a4d8-89d09c86741b`):
- Defines a user-facing input field on the agent
@@ -139,8 +147,9 @@ These define the agent's interface — what it accepts and what it produces.
- Optional: `title`, `description`, `format` (Jinja2 template)
- Create one AgentOutputBlock per distinct result to show the user
-Without these blocks, the agent has no interface and the user cannot provide
-inputs or see outputs. NEVER skip them.
+Without an output block the user cannot see results, and without an input or
+trigger block the agent cannot be started. NEVER skip the output block, and
+always include either an input block or a trigger block.
Specialized input subclasses (`AgentDropdownInputBlock`,
`AgentGoogleDriveFileInputBlock`, `AgentShortTextInputBlock`, …) satisfy
@@ -361,6 +370,70 @@ A minimal agent with input, processing, and output:
input_default: {"name": "summary", "title": "Summary"},
input: "value" linked from Node 2's output)
+### Setting Up Webhook Triggers
+
+A **webhook trigger** runs an agent automatically when an external HTTP event
+arrives. The agent must contain a webhook trigger block (surfaced by
+`find_block(..., for_agent_generation=true)`); such an agent can only be
+triggered, not run manually.
+
+**To set up a webhook trigger:** call `setup_agent_webhook_trigger` with the
+agent's `library_agent_id` and the trigger block's `trigger_config` (the trigger
+block's configuration inputs). Read those fields from the agent's
+`trigger_info.config_schema`, which `find_library_agent` returns for any
+webhook-trigger agent — you do **not** need to fetch or parse the full graph
+(`include_graph`) for this. Config is usually empty for a generic webhook. The
+call creates a triggered preset.
+
+**Configure the trigger through the tool, NOT by editing the graph.** The trigger
+block's config (e.g. GitHub `repo` and `events`) is *not* set on the trigger node
+via `create_agent`/`edit_agent` — leave those inputs unset in the graph.
+`edit_agent` will reject any change to a trigger node's config fields and point
+you back here. The config is stored per-trigger on the **preset** and applied to
+the trigger node each time the webhook fires, so one agent can have several
+triggers (e.g. different repos) each configured independently. Always supply
+config via `setup_agent_webhook_trigger`'s `trigger_config` — never by editing
+the node.
+
+**Credentials must be chosen explicitly.** For provider webhooks (e.g. GitHub)
+the webhook is registered under a specific account, so always ask the user which
+connected account to use — never assume or auto-pick, even if only one exists.
+Call `setup_agent_webhook_trigger` without `credentials` first: it returns a
+setup card listing the available accounts per credential field. Ask the user
+which to use, then call again with `credentials={<field_name>: <credential_id>}`.
+If a field has no connected account, that **same card lets the user connect
+one** — do NOT also call `connect_integration` (that just shows a second,
+duplicate card).
+
+**Trigger config must come from the user, not a guess.** If the tool returns
+`trigger_config_required`, the trigger block needs configuration you must
+collect from the user (e.g. a GitHub repo and which events to subscribe to). Use
+the returned `config_schema` to know the fields and options, **ask the user for
+the actual values — never invent them (e.g. don't make up a repository name)** —
+then call again with `trigger_config` filled in.
+
+**Two kinds of webhook:**
+
+- **Manual-setup (generic) webhooks:** the result card shows the ingress URL with
+ a copy button for the user to paste into their external service (e.g. Typeform,
+ Zapier).
+- **Provider webhooks (e.g. GitHub):** registered automatically once the account
+ is chosen — no URL handoff is needed.
+
+To retrieve a webhook URL later, use `list_agent_triggers` — it returns the
+`webhook_url` for each webhook trigger.
+
+**Manual UI fallback** (if the user prefers to do it themselves): Library → open
+the agent → "+ New Task" → enter config → "Set up Trigger" → "Triggers" tab →
+copy the webhook URL. The URL is **not** shown in the Builder.
+
+**Managing triggers & presets after setup:** a webhook trigger is a preset — use
+`list_presets` to find it, then `update_preset` (rename / pause-resume via
+`is_active` / reconfigure) or `delete_preset`. Webhook triggers fire
+automatically on their event and **can't** be run on demand;
+`run_agent(preset_id=…)` runs only **non-webhook** presets (and `save_as_preset`
+saves a run as one). See each tool's description for arguments.
+
### Building Trigger Agents
A **trigger agent** is a scheduled agent that watches for changes in an
@@ -411,7 +484,9 @@ triggers. No explicit linking is needed.
all triggers configured for that agent — both trigger agents
(`kind="agent"`) and webhook presets (`kind="webhook"`). Use this
before adding a new trigger (to avoid duplicates) or before deleting
- one (to find the right ID).
+ one (to find the right ID). For `kind="webhook"` triggers it also
+ returns the `webhook_url` — give that to the user verbatim if they need
+ to (re)configure their external service.
**Managing schedules:**
diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.py
index ba333e3835..fa168ae2e7 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/service.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py
@@ -786,22 +786,9 @@ async def _consume_sdk_until_done(
if not isinstance(sdk_msg, StreamEvent):
loop_state.msgs_since_flush += 1
now = time.monotonic()
- has_pending_tools = (
- acc.has_appended_assistant
- and acc.accumulated_tool_calls
- and not acc.has_tool_results
- )
- adapter = state.adapter
- has_open_block = (adapter.has_started_text and not adapter.has_ended_text) or (
- adapter.has_started_reasoning and not adapter.has_ended_reasoning
- )
- if (
- not has_pending_tools
- and not has_open_block
- and (
- loop_state.msgs_since_flush >= _FLUSH_MESSAGE_THRESHOLD
- or (now - loop_state.last_flush_time) >= _FLUSH_INTERVAL_SECONDS
- )
+ if not _intermediate_flush_blocked(acc, state.adapter) and (
+ loop_state.msgs_since_flush >= _FLUSH_MESSAGE_THRESHOLD
+ or (now - loop_state.last_flush_time) >= _FLUSH_INTERVAL_SECONDS
):
try:
await asyncio.shield(upsert_chat_session(ctx.session))
@@ -840,6 +827,46 @@ _FLUSH_INTERVAL_SECONDS = 30.0
_FLUSH_MESSAGE_THRESHOLD = 10
+def _intermediate_flush_blocked(
+ acc: "_StreamAccumulator", adapter: SDKResponseAdapter
+) -> bool:
+ """Whether the periodic mid-turn session flush must be held off.
+
+ The DB save is append-only (uses ``start_sequence``), so flushing mid-turn
+ locks the trailing rows at their current sequence permanently. Hold the
+ flush while any of these is true:
+
+ - ``has_pending_tools`` — a tool call is dispatched but its result hasn't
+ been recorded yet; the ``assistant(tool_calls)`` and ``tool`` result rows
+ must persist together.
+ - ``has_unsealed_assistant`` — a live assistant row hasn't acquired
+ ``tool_calls`` yet. The model often emits a text preamble, pauses, then
+ calls a tool — text and ``tool_use`` arrive as *separate* AssistantMessage
+ events, and ``StreamToolInputAvailable`` attaches the ``tool_calls`` onto
+ this same ``acc.assistant_response`` object. Flushing now would lock the
+ row without ``tool_calls``; the later attach could never reach the DB,
+ orphaning the ``tool`` result (no call row → the tool card vanishes on
+ reload).
+ - ``has_open_block`` — text/reasoning is still streaming, so the row would
+ be locked at a truncated length.
+
+ The guaranteed turn-end persist (the ``finally`` upsert) always saves the
+ rows, so holding an intermediate flush never loses data.
+ """
+ has_pending_tools = (
+ acc.has_appended_assistant
+ and bool(acc.accumulated_tool_calls)
+ and not acc.has_tool_results
+ )
+ has_unsealed_assistant = (
+ acc.has_appended_assistant and not acc.accumulated_tool_calls
+ )
+ has_open_block = (adapter.has_started_text and not adapter.has_ended_text) or (
+ adapter.has_started_reasoning and not adapter.has_ended_reasoning
+ )
+ return has_pending_tools or has_unsealed_assistant or has_open_block
+
+
def _hidden_short_names_for_permissions(
permissions: CopilotPermissions | None,
) -> frozenset[str]:
diff --git a/autogpt_platform/backend/backend/copilot/sdk/session_persistence_test.py b/autogpt_platform/backend/backend/copilot/sdk/session_persistence_test.py
index 16c242acd2..377469f971 100644
--- a/autogpt_platform/backend/backend/copilot/sdk/session_persistence_test.py
+++ b/autogpt_platform/backend/backend/copilot/sdk/session_persistence_test.py
@@ -25,8 +25,16 @@ from backend.copilot.constants import (
STREAM_INCOMPLETE_MARKER,
)
from backend.copilot.model import ChatMessage, ChatSession
-from backend.copilot.response_model import StreamStartStep, StreamTextDelta
-from backend.copilot.sdk.service import _dispatch_response, _StreamAccumulator
+from backend.copilot.response_model import (
+ StreamStartStep,
+ StreamTextDelta,
+ StreamToolInputAvailable,
+)
+from backend.copilot.sdk.service import (
+ _dispatch_response,
+ _intermediate_flush_blocked,
+ _StreamAccumulator,
+)
from backend.copilot.session_cleanup import prune_orphan_tool_calls
_NOW = datetime(2024, 1, 1, tzinfo=timezone.utc)
@@ -460,3 +468,129 @@ class TestPruneOrphanToolCallsLogging:
assert removed == 1
assert caplog.text == ""
+
+
+def _make_adapter(
+ *, text_streaming: bool = False, reasoning_streaming: bool = False
+) -> MagicMock:
+ """Adapter whose text/reasoning blocks are closed by default, so
+ ``_intermediate_flush_blocked`` reflects only the assistant-row state."""
+ adapter = MagicMock()
+ adapter.has_started_text = True
+ adapter.has_ended_text = not text_streaming
+ adapter.has_started_reasoning = reasoning_streaming
+ adapter.has_ended_reasoning = not reasoning_streaming
+ return adapter
+
+
+def _tool_call(name: str) -> dict:
+ return {"id": "c1", "type": "function", "function": {"name": name}}
+
+
+class TestIntermediateFlushBlocked:
+ """Regression for OPEN-3168: the append-only mid-turn flush must not lock an
+ assistant row before its tool_calls arrive. The model can emit a text
+ preamble and the tool_use as *separate* AssistantMessage events; flushing
+ the text row first orphaned the tool result (no call row) so the tool card
+ vanished on reload."""
+
+ def test_unsealed_assistant_row_blocks_flush(self) -> None:
+ # Text row appended, but no tool_calls yet — a tool_use may still follow.
+ acc = _StreamAccumulator(
+ assistant_response=ChatMessage(
+ role="assistant", content="Let me set it up now."
+ ),
+ accumulated_tool_calls=[],
+ has_appended_assistant=True,
+ has_tool_results=False,
+ )
+ assert _intermediate_flush_blocked(acc, _make_adapter()) is True
+
+ def test_pending_tool_call_blocks_flush(self) -> None:
+ # tool_calls dispatched, result not yet recorded.
+ acc = _StreamAccumulator(
+ assistant_response=ChatMessage(role="assistant", content="x"),
+ accumulated_tool_calls=[_tool_call("t")],
+ has_appended_assistant=True,
+ has_tool_results=False,
+ )
+ assert _intermediate_flush_blocked(acc, _make_adapter()) is True
+
+ def test_completed_tool_round_allows_flush(self) -> None:
+ # tool_calls set AND result recorded → round sealed, safe to persist.
+ acc = _StreamAccumulator(
+ assistant_response=ChatMessage(role="assistant", content="x"),
+ accumulated_tool_calls=[_tool_call("t")],
+ has_appended_assistant=True,
+ has_tool_results=True,
+ )
+ assert _intermediate_flush_blocked(acc, _make_adapter()) is False
+
+ def test_nothing_appended_allows_flush(self) -> None:
+ acc = _StreamAccumulator(
+ assistant_response=ChatMessage(role="assistant", content=""),
+ accumulated_tool_calls=[],
+ has_appended_assistant=False,
+ has_tool_results=False,
+ )
+ assert _intermediate_flush_blocked(acc, _make_adapter()) is False
+
+ def test_open_text_block_blocks_flush(self) -> None:
+ # Even a sealed round must not flush while text is still streaming.
+ acc = _StreamAccumulator(
+ assistant_response=ChatMessage(role="assistant", content="x"),
+ accumulated_tool_calls=[_tool_call("t")],
+ has_appended_assistant=True,
+ has_tool_results=True,
+ )
+ assert (
+ _intermediate_flush_blocked(acc, _make_adapter(text_streaming=True)) is True
+ )
+
+ def test_split_text_then_tool_use_keeps_call_on_same_row(self) -> None:
+ """End-to-end: a text preamble then a tool_use (separate events). The
+ flush is held while the row is unsealed, so the tool_calls land on that
+ same still-unpersisted row instead of orphaning the tool result."""
+ session = _make_session()
+ ctx = _make_ctx(session)
+ state = _make_state()
+ acc = _StreamAccumulator(
+ assistant_response=ChatMessage(role="assistant", content=""),
+ accumulated_tool_calls=[],
+ has_appended_assistant=False,
+ has_tool_results=False,
+ )
+
+ # AssistantMessage #1 — text preamble → one assistant row appended.
+ _dispatch_response(
+ StreamTextDelta(id="t1", delta="The agent already has a webhook block."),
+ acc,
+ ctx,
+ state,
+ False,
+ "[test]",
+ )
+ assert len(session.messages) == 1
+ # The flush MUST be held here — the tool_use hasn't arrived yet.
+ assert _intermediate_flush_blocked(acc, _make_adapter()) is True
+
+ # AssistantMessage #2 — the tool_use → tool_calls attach to the SAME row.
+ _dispatch_response(
+ StreamToolInputAvailable(
+ toolCallId="toolu_01",
+ toolName="setup_agent_webhook_trigger",
+ input={"library_agent_id": "a1"},
+ ),
+ acc,
+ ctx,
+ state,
+ False,
+ "[test]",
+ )
+ # Still one assistant row, now carrying the call (not orphaned).
+ assert len(session.messages) == 1
+ assert session.messages[0].tool_calls
+ assert (
+ session.messages[0].tool_calls[0]["function"]["name"]
+ == "setup_agent_webhook_trigger"
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/__init__.py b/autogpt_platform/backend/backend/copilot/tools/__init__.py
index bd8a0b17b2..258bba3da7 100644
--- a/autogpt_platform/backend/backend/copilot/tools/__init__.py
+++ b/autogpt_platform/backend/backend/copilot/tools/__init__.py
@@ -41,6 +41,7 @@ from .manage_folders import (
MoveFolderTool,
UpdateFolderTool,
)
+from .manage_presets import DeletePresetTool, ListPresetsTool, UpdatePresetTool
from .manage_schedules import DeleteScheduleTool, ListSchedulesTool
from .platform_info import PlatformInfoTool
from .run_agent import RunAgentTool
@@ -49,6 +50,7 @@ from .run_mcp_tool import RunMCPToolTool
from .run_sub_session import RunSubSessionTool
from .schedule_followup import ScheduleFollowupTool
from .search_docs import SearchDocsTool
+from .setup_agent_webhook_trigger import SetupAgentWebhookTriggerTool
from .skills import DeleteSkillTool, ListSkillsTool, ReadSkillTool, StoreSkillTool
from .todo_write import TodoWriteTool
from .validate_agent import ValidateAgentGraphTool
@@ -97,8 +99,14 @@ TOOL_REGISTRY: dict[str, BaseTool] = {
# Proactive chat-platform output (post message / open thread on user's behalf)
"post_to_chat_platform": PostToChatPlatformTool(),
"list_chat_platform_channels": ListChatPlatformChannelsTool(),
- # Trigger discovery (parent agent → its triggers)
+ # Trigger management (parent agent → its triggers)
"list_agent_triggers": ListAgentTriggersTool(),
+ # Webhook-trigger setup (create triggered preset + return ingress URL)
+ "setup_agent_webhook_trigger": SetupAgentWebhookTriggerTool(),
+ # Preset management (list / update / delete; works for triggers too)
+ "list_presets": ListPresetsTool(),
+ "update_preset": UpdatePresetTool(),
+ "delete_preset": DeletePresetTool(),
"run_block": RunBlockTool(),
"continue_run_block": ContinueRunBlockTool(),
"run_sub_session": RunSubSessionTool(),
diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator.py
index ef7eba9ff7..c14f3a7fd5 100644
--- a/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator.py
+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator.py
@@ -5,6 +5,7 @@ import logging
import re
from typing import Any
+from backend.blocks._base import BlockType
from backend.data.dynamic_fields import DICT_SPLIT
from .helpers import (
@@ -20,6 +21,10 @@ from .helpers import (
logger = logging.getLogger(__name__)
+# uiType values (from BlockType) of blocks that start an agent on an external
+# event. A trigger node makes an agent runnable without a user-facing input.
+TRIGGER_UI_TYPES = frozenset({BlockType.WEBHOOK.value, BlockType.WEBHOOK_MANUAL.value})
+
class AgentValidator:
"""
@@ -657,21 +662,24 @@ class AgentValidator:
def _collect_io_block_ids(
self, blocks: list[dict[str, Any]]
- ) -> tuple[set[str], set[str]]:
+ ) -> tuple[set[str], set[str], set[str]]:
"""
- Build sets of all input/output block IDs from the blocks registry.
-
- Input/output blocks are identified by ``uiType`` (populated from
- ``Block.block_type`` at registration time). Specialized subclasses
- like ``AgentGoogleDriveFileInputBlock`` count as input blocks even
- though they have their own block IDs — this matches the runtime
- behavior, where any subclass of ``AgentInputBlock`` exposes a
- user-facing input. The literal base IDs are always included so the
- function works even when called with a minimal blocks list (e.g.
- unit tests).
+ Build sets of all input/output/trigger block IDs from the blocks
+ registry.
+
+ Input/output/trigger blocks are identified by ``uiType`` (populated
+ from ``Block.block_type`` at registration time). Specialized
+ subclasses like ``AgentGoogleDriveFileInputBlock`` count as input
+ blocks even though they have their own block IDs — this matches the
+ runtime behavior, where any subclass of ``AgentInputBlock`` exposes a
+ user-facing input. The literal base input/output IDs are always
+ included so the function works even when called with a minimal blocks
+ list (e.g. unit tests). Trigger blocks have no single base ID, so the
+ blocks list must carry their ``uiType`` to detect them.
"""
input_ids: set[str] = {AGENT_INPUT_BLOCK_ID}
output_ids: set[str] = {AGENT_OUTPUT_BLOCK_ID}
+ trigger_ids: set[str] = set()
for block in blocks:
block_id = block.get("id")
if not block_id:
@@ -681,41 +689,56 @@ class AgentValidator:
input_ids.add(block_id)
elif ui_type == "Output":
output_ids.add(block_id)
- return input_ids, output_ids
+ elif ui_type in TRIGGER_UI_TYPES:
+ trigger_ids.add(block_id)
+ return input_ids, output_ids, trigger_ids
def validate_io_blocks(
self, agent: AgentDict, blocks: list[dict[str, Any]] | None = None
) -> bool:
"""
- Validate that the agent has at least one input block and one output
- block. These blocks define the agent's interface.
-
- Any block whose ``uiType`` is ``"Input"`` satisfies the input
- requirement — including specialized variants like
- ``AgentGoogleDriveFileInputBlock``, ``AgentDropdownInputBlock``,
- ``AgentTableInputBlock``, etc. The equivalent applies for outputs.
- This prevents the validator from forcing agents to keep a throwaway
- base ``AgentInputBlock`` alongside a real specialized input.
-
- Returns True if both are present, False otherwise.
+ Validate that the agent has a way to be started and one output block.
+ These define the agent's interface.
+
+ Input requirement — satisfied by EITHER at least one input block OR at
+ least one trigger block:
+ - Any block whose ``uiType`` is ``"Input"`` (including specialized
+ variants like ``AgentGoogleDriveFileInputBlock``,
+ ``AgentDropdownInputBlock``, ``AgentTableInputBlock``, etc.).
+ - Any trigger block whose ``uiType`` is ``"Webhook"`` /
+ ``"Webhook (manual)"``. A triggered agent is started by an external
+ event and needs no user-facing input block; forcing one alongside
+ the trigger produces an invalid graph.
+
+ Output requirement — satisfied by at least one output block (any block
+ whose ``uiType`` is ``"Output"``). This matches the runtime behavior,
+ where any subclass of ``AgentOutputBlock`` surfaces an output, so the
+ validator never forces a throwaway base block alongside a real one.
+
+ Returns True if both requirements are met, False otherwise.
"""
valid = True
- input_ids, output_ids = self._collect_io_block_ids(blocks or [])
+ input_ids, output_ids, trigger_ids = self._collect_io_block_ids(blocks or [])
node_block_ids = {
node.get("block_id")
for node in agent.get("nodes", [])
if node.get("block_id")
}
- if not node_block_ids & input_ids:
+ has_input = bool(node_block_ids & input_ids)
+ has_trigger = bool(node_block_ids & trigger_ids)
+ if not has_input and not has_trigger:
self.add_error(
- f"Agent is missing an input block. Every agent must have at "
- f"least one input block to define user-facing inputs. Add a "
- f"node using the base AgentInputBlock (block_id: "
- f"'{AGENT_INPUT_BLOCK_ID}') or any specialized input block "
- f"subclass (e.g. AgentGoogleDriveFileInputBlock, "
- f"AgentDropdownInputBlock, AgentShortTextInputBlock). Set "
- f"input_default with 'name' and optionally 'title'."
+ f"Agent is missing an input or trigger block. Every agent must "
+ f"have at least one input block to define user-facing inputs, "
+ f"or one trigger block to be started by an external event. For "
+ f"a regular agent, add a node using the base AgentInputBlock "
+ f"(block_id: '{AGENT_INPUT_BLOCK_ID}') or any specialized input "
+ f"block subclass (e.g. AgentGoogleDriveFileInputBlock, "
+ f"AgentDropdownInputBlock, AgentShortTextInputBlock) and set "
+ f"input_default with 'name' and optionally 'title'. For a "
+ f"triggered agent, add a webhook trigger block instead — do not "
+ f"add a separate input block."
)
valid = False
diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator_test.py b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator_test.py
index 939ca521ce..85338f69d9 100644
--- a/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/agent_generator/validator_test.py
@@ -583,6 +583,71 @@ class TestValidateIoBlocks:
assert v.validate_io_blocks(agent, [input_block, custom_output_block]) is True
assert v.errors == []
+ def test_trigger_block_satisfies_input_requirement(self):
+ # A webhook trigger replaces the input block: a triggered agent is
+ # started by an external event and needs no user-facing input block.
+ v = AgentValidator()
+ trigger_block = _make_block(
+ block_id="webhook-trigger-id",
+ name="GithubTriggerBlock",
+ ui_type="Webhook",
+ )
+ output_block = _make_block(
+ block_id=AGENT_OUTPUT_BLOCK_ID,
+ name="AgentOutputBlock",
+ ui_type="Output",
+ )
+ trigger_node = _make_node(block_id="webhook-trigger-id")
+ output_node = _make_node(block_id=AGENT_OUTPUT_BLOCK_ID)
+ agent = _make_agent(nodes=[trigger_node, output_node])
+
+ assert v.validate_io_blocks(agent, [trigger_block, output_block]) is True
+ assert v.errors == []
+
+ def test_manual_webhook_trigger_satisfies_input_requirement(self):
+ v = AgentValidator()
+ trigger_block = _make_block(
+ block_id="manual-webhook-id",
+ name="ManualWebhookTriggerBlock",
+ ui_type="Webhook (manual)",
+ )
+ output_block = _make_block(
+ block_id=AGENT_OUTPUT_BLOCK_ID,
+ name="AgentOutputBlock",
+ ui_type="Output",
+ )
+ trigger_node = _make_node(block_id="manual-webhook-id")
+ output_node = _make_node(block_id=AGENT_OUTPUT_BLOCK_ID)
+ agent = _make_agent(nodes=[trigger_node, output_node])
+
+ assert v.validate_io_blocks(agent, [trigger_block, output_block]) is True
+ assert v.errors == []
+
+ def test_trigger_does_not_satisfy_output_requirement(self):
+ # The trigger only covers the input side; an output block is still
+ # required.
+ v = AgentValidator()
+ trigger_block = _make_block(
+ block_id="webhook-trigger-id",
+ name="GithubTriggerBlock",
+ ui_type="Webhook",
+ )
+ trigger_node = _make_node(block_id="webhook-trigger-id")
+ agent = _make_agent(nodes=[trigger_node])
+
+ assert v.validate_io_blocks(agent, [trigger_block]) is False
+ assert len(v.errors) == 1
+ assert "AgentOutputBlock" in v.errors[0]
+
+ def test_missing_input_error_mentions_trigger_alternative(self):
+ v = AgentValidator()
+ node = _make_node(block_id=AGENT_OUTPUT_BLOCK_ID)
+ agent = _make_agent(nodes=[node])
+
+ assert v.validate_io_blocks(agent) is False
+ assert len(v.errors) == 1
+ assert "trigger block" in v.errors[0]
+
# ============================================================================
# validate (integration)
diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_search.py b/autogpt_platform/backend/backend/copilot/tools/agent_search.py
index e7381334d4..027941a128 100644
--- a/autogpt_platform/backend/backend/copilot/tools/agent_search.py
+++ b/autogpt_platform/backend/backend/copilot/tools/agent_search.py
@@ -155,6 +155,10 @@ async def _search_library(
# (parent-coupled, single-purpose). AutoPilot accesses
# them via list_agent_triggers instead.
is_hidden=False,
+ # Load nodes so has_external_trigger / trigger_setup_info are
+ # populated — lets AutoPilot recognise (and set up) webhook
+ # triggers from the listing without re-reading the full graph.
+ include_nodes=True,
)
for agent in results.agents:
agents.append(_library_agent_to_info(agent))
@@ -211,8 +215,17 @@ async def _search_library(
"execution results, or run_agent to execute. Let the user know we can "
"create a custom agent for them based on their needs."
)
+ if any(a.trigger_info for a in agents):
+ message += (
+ "\n\nSome agents have a webhook trigger (see their "
+ "`trigger_info`). To set up or activate "
+ "such a trigger, call setup_agent_webhook_trigger and pass the "
+ "config_schema fields as `trigger_config` — you don't need the full "
+ "graph for this, and must NOT edit the trigger node's values in the "
+ "graph (that changes the agent's global default for everyone)."
+ )
if truncation_notice:
- message = f"{message}\n\nNote: {truncation_notice}"
+ message += f"\n\nNote: {truncation_notice}"
return AgentsFoundResponse(
message=message,
@@ -331,6 +344,7 @@ def _library_agent_to_info(agent: LibraryAgent) -> AgentInfo:
graph_version=agent.graph_version,
input_schema=agent.input_schema,
output_schema=agent.output_schema,
+ trigger_info=agent.trigger_setup_info,
)
diff --git a/autogpt_platform/backend/backend/copilot/tools/agent_search_test.py b/autogpt_platform/backend/backend/copilot/tools/agent_search_test.py
index d7ba3ccc90..d2420e8774 100644
--- a/autogpt_platform/backend/backend/copilot/tools/agent_search_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/agent_search_test.py
@@ -5,6 +5,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from backend.data.graph import GraphTriggerInfo
+
from .agent_search import _enrich_agents_with_graph, search_agents
from .models import AgentInfo, AgentsFoundResponse, NoResultsResponse
@@ -151,6 +153,7 @@ class TestLibraryUUIDLookup:
mock_agent.graph_version = 1
mock_agent.input_schema = {}
mock_agent.output_schema = {}
+ mock_agent.trigger_setup_info = None
return mock_agent
@pytest.mark.asyncio(loop_scope="session")
@@ -177,6 +180,78 @@ class TestLibraryUUIDLookup:
assert response.count == 1
assert response.agents[0].name == "My Library Agent"
+ @staticmethod
+ def _github_trigger_info():
+ return GraphTriggerInfo(
+ provider="github",
+ config_schema={
+ "type": "object",
+ "properties": {"repo": {"type": "string"}},
+ "required": ["repo"],
+ },
+ credentials_input_name="payload_credentials",
+ )
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_trigger_info_surfaced_without_graph(self):
+ """A webhook-trigger agent surfaces structured trigger_info (provider +
+ config_schema) so AutoPilot need not fetch/parse the full graph, plus a
+ message steering it to setup_agent_webhook_trigger."""
+ mock_agent = self._make_mock_library_agent()
+ mock_agent.has_external_trigger = True
+ mock_agent.trigger_setup_info = self._github_trigger_info()
+
+ mock_lib_db = MagicMock()
+ mock_search_results = MagicMock()
+ mock_search_results.agents = [mock_agent]
+ mock_lib_db.list_library_agents = AsyncMock(return_value=mock_search_results)
+
+ with patch(
+ "backend.copilot.tools.agent_search.library_db",
+ return_value=mock_lib_db,
+ ):
+ response = await search_agents(
+ query="",
+ source="library",
+ session_id="s",
+ user_id=_TEST_USER_ID,
+ include_graph=False,
+ )
+
+ assert isinstance(response, AgentsFoundResponse)
+ agent = response.agents[0]
+ assert agent.graph is None
+ assert agent.trigger_info is not None
+ assert agent.trigger_info.provider == "github"
+ assert "repo" in agent.trigger_info.config_schema["properties"]
+ assert "setup_agent_webhook_trigger" in response.message
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_no_trigger_info_for_plain_agent(self):
+ """Agents without a webhook trigger have trigger_info=None and no
+ trigger guidance is appended to the message."""
+ mock_agent = self._make_mock_library_agent() # trigger_setup_info = None
+
+ mock_lib_db = MagicMock()
+ mock_search_results = MagicMock()
+ mock_search_results.agents = [mock_agent]
+ mock_lib_db.list_library_agents = AsyncMock(return_value=mock_search_results)
+
+ with patch(
+ "backend.copilot.tools.agent_search.library_db",
+ return_value=mock_lib_db,
+ ):
+ response = await search_agents(
+ query="",
+ source="library",
+ session_id="s",
+ user_id=_TEST_USER_ID,
+ )
+
+ assert isinstance(response, AgentsFoundResponse)
+ assert response.agents[0].trigger_info is None
+ assert "setup_agent_webhook_trigger" not in response.message
+
@pytest.mark.asyncio(loop_scope="session")
async def test_include_graph_fetches_graph(self):
"""include_graph=True attaches BaseGraph to agent results."""
@@ -338,6 +413,7 @@ class TestEnrichAgentsWithGraph:
mock_agent.graph_version = 1
mock_agent.input_schema = {}
mock_agent.output_schema = {}
+ mock_agent.trigger_setup_info = None
return mock_agent
@pytest.mark.asyncio(loop_scope="session")
diff --git a/autogpt_platform/backend/backend/copilot/tools/edit_agent.py b/autogpt_platform/backend/backend/copilot/tools/edit_agent.py
index c60a804ef7..7ccdbf4e04 100644
--- a/autogpt_platform/backend/backend/copilot/tools/edit_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/edit_agent.py
@@ -3,7 +3,9 @@
import logging
from typing import Any
+from backend.blocks import get_block, get_webhook_block_ids
from backend.copilot.model import ChatSession
+from backend.data.model import is_credentials_field_name
from .agent_generator import get_agent_as_json
from .agent_generator.pipeline import fetch_library_agents, fix_validate_and_save
@@ -129,6 +131,25 @@ class EditAgentTool(BaseTool):
session_id=session_id,
)
+ changed_trigger_fields = _changed_trigger_config_fields(
+ current_agent.get("nodes", []), nodes
+ )
+ if changed_trigger_fields:
+ return ErrorResponse(
+ message=(
+ "This edit changes the webhook trigger block's configuration "
+ f"({', '.join(changed_trigger_fields)}), which can't be set "
+ "by editing the graph — that would change the agent's global "
+ "default for everyone who uses it. A trigger's configuration "
+ "lives on a per-trigger preset: use the "
+ "setup_agent_webhook_trigger tool with these fields as "
+ "`trigger_config` instead. Re-run edit_agent leaving the "
+ "trigger block's config unchanged."
+ ),
+ error="trigger_config_edit_blocked",
+ session_id=session_id,
+ )
+
agent_json["id"] = current_agent.get("id", agent_id)
agent_json["version"] = current_agent.get("version", 1)
agent_json.setdefault("is_active", True)
@@ -145,3 +166,46 @@ class EditAgentTool(BaseTool):
default_name="Updated Agent",
library_agents=library_agents,
)
+
+
+def _changed_trigger_config_fields(
+ current_nodes: list[dict[str, Any]], new_nodes: list[dict[str, Any]]
+) -> list[str]:
+ """Trigger-config field names whose value this edit would change.
+
+ A webhook trigger block's config inputs (e.g. ``repo``/``events``) belong on
+ a per-trigger preset via ``setup_agent_webhook_trigger``; editing them in the
+ graph mutates the agent's global default and is the wrong path. Credentials
+ are ignored (they're not trigger config). Returns ``[]`` when there is no
+ trigger node, the node was removed wholesale (a structural edit, not a config
+ tweak), or nothing changed.
+ """
+ webhook_block_ids = set(get_webhook_block_ids())
+ current_trigger = next(
+ (n for n in current_nodes if n.get("block_id") in webhook_block_ids), None
+ )
+ if current_trigger is None:
+ return []
+
+ block = get_block(current_trigger["block_id"])
+ if block is None:
+ return []
+ config_fields = [
+ name
+ for name in block.input_schema.model_fields
+ if not is_credentials_field_name(name)
+ ]
+
+ new_trigger = next(
+ (n for n in new_nodes if n.get("id") == current_trigger.get("id")), None
+ )
+ if new_trigger is None:
+ return []
+
+ current_defaults = current_trigger.get("input_default") or {}
+ new_defaults = new_trigger.get("input_default") or {}
+ return [
+ name
+ for name in config_fields
+ if new_defaults.get(name) != current_defaults.get(name)
+ ]
diff --git a/autogpt_platform/backend/backend/copilot/tools/edit_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/edit_agent_test.py
index 8c4c0bb518..0fc57d251e 100644
--- a/autogpt_platform/backend/backend/copilot/tools/edit_agent_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/edit_agent_test.py
@@ -8,13 +8,39 @@ fix+validate+save) is exercised by the agent-generation pipeline tests.
import pytest
from backend.copilot.model import ChatSessionMetadata
-from backend.copilot.tools.edit_agent import EditAgentTool
+from backend.copilot.tools.edit_agent import (
+ EditAgentTool,
+ _changed_trigger_config_fields,
+)
from backend.copilot.tools.models import ErrorResponse
from ._test_data import make_session
_USER_ID = "test-user-edit-agent-guard"
+_EDIT_MODULE = "backend.copilot.tools.edit_agent"
+_WEBHOOK_BID = "webhook-trigger-block"
+
+
+class _FakeSchema:
+ # Mirrors a webhook trigger block: two config fields + one credentials field.
+ model_fields = {
+ "repo": object(),
+ "events": object(),
+ "payload_credentials": object(),
+ }
+
+
+class _FakeBlock:
+ input_schema = _FakeSchema
+
+
+def _patch_block_lookup(mocker) -> None:
+ """Make the trigger-config helper see ``_WEBHOOK_BID`` as a webhook block
+ with config fields ``repo``/``events`` (credentials excluded)."""
+ mocker.patch(f"{_EDIT_MODULE}.get_webhook_block_ids", return_value=[_WEBHOOK_BID])
+ mocker.patch(f"{_EDIT_MODULE}.get_block", return_value=_FakeBlock())
+
@pytest.fixture
def tool() -> EditAgentTool:
@@ -91,3 +117,142 @@ async def test_non_builder_session_keeps_missing_agent_id_error(
assert isinstance(result, ErrorResponse)
assert result.error == "missing_agent_id"
+
+
+# --- Trigger-config guard (Option A) --------------------------------------
+
+
+def _trigger_node(repo: str, events: list[str]) -> dict:
+ return {
+ "id": "trigger-1",
+ "block_id": _WEBHOOK_BID,
+ "input_default": {"repo": repo, "events": events},
+ "metadata": {},
+ }
+
+
+def test_changed_trigger_config_is_detected(mocker) -> None:
+ _patch_block_lookup(mocker)
+ current = [_trigger_node("owner/repo", ["opened"])]
+ new = [_trigger_node("owner/OTHER", ["opened"])]
+ assert _changed_trigger_config_fields(current, new) == ["repo"]
+
+
+def test_unchanged_trigger_config_is_allowed(mocker) -> None:
+ _patch_block_lookup(mocker)
+ current = [_trigger_node("owner/repo", ["opened"])]
+ new = [_trigger_node("owner/repo", ["opened"])]
+ assert _changed_trigger_config_fields(current, new) == []
+
+
+def test_removed_trigger_node_is_not_guarded(mocker) -> None:
+ """Dropping the trigger node entirely is a structural edit, not a config
+ tweak — the guard must not block it."""
+ _patch_block_lookup(mocker)
+ current = [_trigger_node("owner/repo", ["opened"])]
+ new = [{"id": "other", "block_id": "some-block", "input_default": {}}]
+ assert _changed_trigger_config_fields(current, new) == []
+
+
+def test_agent_without_trigger_is_not_guarded(mocker) -> None:
+ _patch_block_lookup(mocker)
+ nodes = [{"id": "n1", "block_id": "some-block", "input_default": {"x": 1}}]
+ assert _changed_trigger_config_fields(nodes, nodes) == []
+
+
+def test_credentials_changes_are_ignored(mocker) -> None:
+ """Changing the trigger node's credential field is not a trigger-config
+ change (credentials are handled separately)."""
+ _patch_block_lookup(mocker)
+ current = [
+ {
+ "id": "trigger-1",
+ "block_id": _WEBHOOK_BID,
+ "input_default": {
+ "repo": "owner/repo",
+ "events": ["opened"],
+ "payload_credentials": {"id": "cred-a"},
+ },
+ }
+ ]
+ new = [
+ {
+ "id": "trigger-1",
+ "block_id": _WEBHOOK_BID,
+ "input_default": {
+ "repo": "owner/repo",
+ "events": ["opened"],
+ "payload_credentials": {"id": "cred-b"},
+ },
+ }
+ ]
+ assert _changed_trigger_config_fields(current, new) == []
+
+
+async def test_execute_blocks_trigger_config_edit(tool, mocker) -> None:
+ """End-to-end: editing the trigger node's config through edit_agent is
+ rejected with an actionable pointer to setup_agent_webhook_trigger."""
+ _patch_block_lookup(mocker)
+ session = make_session(_USER_ID)
+ # builder_graph_id satisfies the guide gate; agent_id matches it so the
+ # builder guard passes too.
+ session.metadata = ChatSessionMetadata(builder_graph_id="graph-x")
+
+ mocker.patch(
+ f"{_EDIT_MODULE}.get_agent_as_json",
+ return_value={
+ "id": "graph-x",
+ "version": 3,
+ "nodes": [_trigger_node("owner/repo", ["opened"])],
+ },
+ )
+
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ agent_id="graph-x",
+ agent_json={"nodes": [_trigger_node("owner/CHANGED", ["opened"])], "links": []},
+ )
+
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "trigger_config_edit_blocked"
+ assert "setup_agent_webhook_trigger" in result.message
+
+
+async def test_execute_allows_non_trigger_edit(tool, mocker) -> None:
+ """An edit that leaves trigger config untouched flows past the guard into
+ the validate-and-save pipeline."""
+ _patch_block_lookup(mocker)
+ session = make_session(_USER_ID)
+ session.metadata = ChatSessionMetadata(builder_graph_id="graph-x")
+
+ mocker.patch(
+ f"{_EDIT_MODULE}.get_agent_as_json",
+ return_value={
+ "id": "graph-x",
+ "version": 3,
+ "nodes": [_trigger_node("owner/repo", ["opened"])],
+ },
+ )
+ mocker.patch(f"{_EDIT_MODULE}.fetch_library_agents", return_value=[])
+ sentinel = ErrorResponse(message="pipeline-reached", error="sentinel")
+ saved = mocker.patch(f"{_EDIT_MODULE}.fix_validate_and_save", return_value=sentinel)
+
+ result = await tool._execute(
+ user_id=_USER_ID,
+ session=session,
+ agent_id="graph-x",
+ # Same trigger config; only an unrelated node changes.
+ agent_json={
+ "nodes": [
+ _trigger_node("owner/repo", ["opened"]),
+ {"id": "n2", "block_id": "other", "input_default": {"x": 2}},
+ ],
+ "links": [],
+ },
+ )
+
+ assert result is sentinel
+ saved.assert_called_once()
diff --git a/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py
index d083465294..4962eafa53 100644
--- a/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/find_library_agent_test.py
@@ -44,6 +44,7 @@ def _mock_library_agent(library_id: str, name: str, description: str = ""):
agent.graph_version = 1
agent.input_schema = {}
agent.output_schema = {}
+ agent.trigger_setup_info = None
return agent
diff --git a/autogpt_platform/backend/backend/copilot/tools/list_agent_triggers.py b/autogpt_platform/backend/backend/copilot/tools/list_agent_triggers.py
index f59e4f14a5..8a6e4c2c41 100644
--- a/autogpt_platform/backend/backend/copilot/tools/list_agent_triggers.py
+++ b/autogpt_platform/backend/backend/copilot/tools/list_agent_triggers.py
@@ -6,12 +6,8 @@ from typing import Any, Literal
from pydantic import BaseModel
-from backend.api.features.library.db import (
- get_library_agent,
- list_presets,
- list_trigger_agents,
-)
from backend.copilot.model import ChatSession
+from backend.data.db_accessors import library_db
from backend.util.exceptions import NotFoundError
from .base import BaseTool
@@ -44,6 +40,11 @@ class AgentTriggerInfo(BaseModel):
# Webhook-trigger only.
is_active: bool | None = None
webhook_id: str | None = None
+ # Ingress URL for manual-setup webhooks — give this to the user verbatim
+ # so they can wire it up in their external service. None for trigger agents
+ # and for webhooks without an attached URL.
+ webhook_url: str | None = None
+ provider: str | None = None
class AgentTriggerListResponse(ToolResponseBase):
@@ -112,8 +113,9 @@ class ListAgentTriggersTool(BaseTool):
session_id=session_id,
)
+ ldb = library_db()
try:
- parent = await get_library_agent(id=library_agent_id, user_id=user_id)
+ parent = await ldb.get_library_agent(id=library_agent_id, user_id=user_id)
except NotFoundError as e:
return ErrorResponse(
message=f"Library agent not found: {e}",
@@ -126,12 +128,12 @@ class ListAgentTriggersTool(BaseTool):
# Both queries can run concurrently since they don't depend
# on each other once we have the parent's graph_id.
trigger_agents, preset_response = await asyncio.gather(
- list_trigger_agents(
+ ldb.list_trigger_agents(
user_id=user_id,
library_agent_id=library_agent_id,
parent_graph_id=parent.graph_id,
),
- list_presets(
+ ldb.list_presets(
user_id=user_id,
page=1,
page_size=100,
@@ -161,6 +163,8 @@ class ListAgentTriggersTool(BaseTool):
description=p.description or "",
is_active=p.is_active,
webhook_id=p.webhook_id,
+ webhook_url=p.webhook.url if p.webhook else None,
+ provider=p.webhook.provider if p.webhook else None,
)
for p in webhook_presets
]
diff --git a/autogpt_platform/backend/backend/copilot/tools/list_agent_triggers_test.py b/autogpt_platform/backend/backend/copilot/tools/list_agent_triggers_test.py
new file mode 100644
index 0000000000..6ec72cd4d7
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/list_agent_triggers_test.py
@@ -0,0 +1,106 @@
+"""Tests for ListAgentTriggersTool — focuses on webhook URL exposure."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.copilot.tools.list_agent_triggers import (
+ AgentTriggerListResponse,
+ ListAgentTriggersTool,
+)
+from backend.copilot.tools.models import ErrorResponse
+
+from ._test_data import make_session
+
+_USER = "test-user-triggers-list"
+_PATH = "backend.copilot.tools.list_agent_triggers"
+
+
+def tool():
+ return ListAgentTriggersTool()
+
+
+def session():
+ return make_session(_USER)
+
+
+def _make_webhook_preset():
+ preset = MagicMock()
+ preset.id = "preset-1"
+ preset.name = "Incoming webhook"
+ preset.description = "fires on HTTP event"
+ preset.is_active = True
+ preset.webhook_id = "wh-1"
+ preset.webhook.url = (
+ "https://backend.agpt.co/api/integrations/generic_webhook"
+ "/webhooks/wh-1/ingress"
+ )
+ preset.webhook.provider = "generic_webhook"
+ return preset
+
+
+async def test_list_triggers_no_auth(tool, session):
+ result = await tool._execute(user_id=None, session=session)
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "auth_required"
+
+
+async def test_list_triggers_exposes_webhook_url(tool, session):
+ preset_response = MagicMock()
+ preset_response.presets = [_make_webhook_preset()]
+
+ mock_ldb = MagicMock()
+ mock_ldb.get_library_agent = AsyncMock(return_value=MagicMock(graph_id="graph-1"))
+ mock_ldb.list_trigger_agents = AsyncMock(return_value=[])
+ mock_ldb.list_presets = AsyncMock(return_value=preset_response)
+
+ with patch(f"{_PATH}.library_db", return_value=mock_ldb):
+ result = await tool._execute(
+ user_id=_USER, session=session, library_agent_id="lib-1"
+ )
+
+ assert isinstance(result, AgentTriggerListResponse)
+ assert len(result.triggers) == 1
+ trigger = result.triggers[0]
+ assert trigger.kind == "webhook"
+ assert trigger.webhook_id == "wh-1"
+ assert trigger.webhook_url and trigger.webhook_url.endswith("/ingress")
+ assert "backend.agpt.co" in trigger.webhook_url
+ assert trigger.provider == "generic_webhook"
+
+
+async def test_list_triggers_includes_trigger_agents(tool, session):
+ """The 'agent' kind (hidden trigger agents) is surfaced alongside webhooks."""
+ trigger_agent = MagicMock()
+ trigger_agent.id = "lib-ta"
+ trigger_agent.name = "Daily Fetcher"
+ trigger_agent.description = "fetches daily"
+ trigger_agent.graph_id = "graph-ta"
+ trigger_agent.is_scheduled = True
+ trigger_agent.next_scheduled_run = "2026-06-09T00:00:00Z"
+
+ preset_response = MagicMock()
+ preset_response.presets = []
+
+ mock_ldb = MagicMock()
+ mock_ldb.get_library_agent = AsyncMock(return_value=MagicMock(graph_id="graph-1"))
+ mock_ldb.list_trigger_agents = AsyncMock(return_value=[trigger_agent])
+ mock_ldb.list_presets = AsyncMock(return_value=preset_response)
+
+ with patch(f"{_PATH}.library_db", return_value=mock_ldb):
+ result = await tool._execute(
+ user_id=_USER, session=session, library_agent_id="lib-1"
+ )
+
+ assert isinstance(result, AgentTriggerListResponse)
+ assert len(result.triggers) == 1
+ trigger = result.triggers[0]
+ assert trigger.kind == "agent"
+ assert trigger.id == "lib-ta"
+ assert trigger.is_scheduled is True
+ assert trigger.graph_id == "graph-ta"
diff --git a/autogpt_platform/backend/backend/copilot/tools/manage_presets.py b/autogpt_platform/backend/backend/copilot/tools/manage_presets.py
new file mode 100644
index 0000000000..671ebb9f16
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/manage_presets.py
@@ -0,0 +1,381 @@
+"""Tools for listing, updating, and deleting library agent presets.
+
+A preset is a saved run configuration for a library agent; a webhook trigger is a
+preset with an attached webhook. These tools mirror the ``/presets`` routes and
+work for any preset (triggered or not). Webhook re-registration + cleanup is
+delegated to the shared helpers in ``library/triggers.py`` (RPC-exposed), so the
+copilot worker reuses the exact route logic.
+"""
+
+import logging
+from typing import Any
+
+from pydantic import BaseModel
+
+from backend.copilot.model import ChatSession
+from backend.data.db_accessors import library_db, triggers_db
+from backend.util.exceptions import (
+ InvalidInputError,
+ NotFoundError,
+ WebhookRegistrationError,
+)
+
+from .base import BaseTool
+from .models import ErrorResponse, ResponseType, ToolResponseBase
+
+logger = logging.getLogger(__name__)
+
+# Presets are returned in a single page; the response carries total_count so the
+# model can tell when the list is truncated and narrow via a filter instead.
+_LIST_PAGE_SIZE = 100
+
+
+class PresetSummary(BaseModel):
+ """Summary of a single preset (saved run config / webhook trigger)."""
+
+ id: str
+ name: str
+ description: str = ""
+ graph_id: str
+ graph_version: int
+ is_active: bool
+ # Webhook-trigger presets only.
+ webhook_id: str | None = None
+ # Ingress URL for manual-setup webhooks — give to the user verbatim.
+ webhook_url: str | None = None
+ provider: str | None = None
+
+
+class PresetListResponse(ToolResponseBase):
+ """Response listing the user's presets."""
+
+ type: ResponseType = ResponseType.PRESET_LIST
+ presets: list[PresetSummary]
+ # Total presets matching the filter; > len(presets) means the list is
+ # truncated to one page — narrow with graph_id/library_agent_id.
+ total_count: int
+
+
+class PresetUpdatedResponse(ToolResponseBase):
+ """Response confirming a preset was updated."""
+
+ type: ResponseType = ResponseType.PRESET_UPDATED
+ preset_id: str
+ name: str
+ is_active: bool
+ webhook_url: str | None = None
+
+
+class PresetDeletedResponse(ToolResponseBase):
+ """Response confirming a preset was deleted."""
+
+ type: ResponseType = ResponseType.PRESET_DELETED
+ preset_id: str
+ name: str
+
+
+class ListPresetsTool(BaseTool):
+ """List the user's presets (saved run configs + webhook triggers).
+
+ Optionally filtered by library agent or graph. Use this to find a
+ ``preset_id`` before update_preset / delete_preset.
+ """
+
+ @property
+ def name(self) -> str:
+ return "list_presets"
+
+ @property
+ def description(self) -> str:
+ return (
+ "List the user's presets (saved run configurations and webhook "
+ "triggers). Optionally filter by library_agent_id or graph_id. Use "
+ "before update_preset/delete_preset to find a preset_id."
+ )
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "library_agent_id": {
+ "type": "string",
+ "description": "Filter by library agent.",
+ },
+ "graph_id": {
+ "type": "string",
+ "description": "Filter by graph.",
+ },
+ },
+ "required": [],
+ }
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id if session else None
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required.",
+ error="auth_required",
+ session_id=session_id,
+ )
+
+ library_agent_id: str | None = kwargs.get("library_agent_id")
+ graph_id: str | None = kwargs.get("graph_id")
+
+ ldb = library_db()
+ if library_agent_id:
+ try:
+ lib_agent = await ldb.get_library_agent(
+ id=library_agent_id, user_id=user_id
+ )
+ except NotFoundError as e:
+ return ErrorResponse(
+ message=f"Library agent not found: {e}",
+ error="library_agent_not_found",
+ session_id=session_id,
+ )
+ graph_id = lib_agent.graph_id
+
+ response = await ldb.list_presets(
+ user_id=user_id, page=1, page_size=_LIST_PAGE_SIZE, graph_id=graph_id
+ )
+ total_count = response.pagination.total_items
+ presets = [
+ PresetSummary(
+ id=p.id,
+ name=p.name,
+ description=p.description or "",
+ graph_id=p.graph_id,
+ graph_version=p.graph_version,
+ is_active=p.is_active,
+ webhook_id=p.webhook_id,
+ webhook_url=p.webhook.url if p.webhook else None,
+ provider=p.webhook.provider if p.webhook else None,
+ )
+ for p in response.presets
+ ]
+
+ if not presets:
+ message = "No presets found."
+ elif total_count > len(presets):
+ message = (
+ f"Showing the first {len(presets)} of {total_count} presets. "
+ "Narrow the list with graph_id or library_agent_id."
+ )
+ else:
+ message = f"Found {total_count} preset(s)."
+ return PresetListResponse(
+ message=message,
+ presets=presets,
+ total_count=total_count,
+ session_id=session_id,
+ )
+
+
+class UpdatePresetTool(BaseTool):
+ """Update a preset: rename, pause/resume, or reconfigure its inputs."""
+
+ @property
+ def name(self) -> str:
+ return "update_preset"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Update a preset by preset_id: rename, change description, pause or "
+ "resume it (is_active=false/true), or reconfigure its inputs. For a "
+ "webhook trigger, 'inputs' is the trigger block's config (e.g. repo, "
+ "events) and changing it re-registers the webhook with the preset's "
+ "existing credentials. Find preset_id via list_presets."
+ )
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "preset_id": {
+ "type": "string",
+ "description": "ID of the preset to update.",
+ },
+ "name": {"type": "string", "description": "New name."},
+ "description": {
+ "type": "string",
+ "description": "New description.",
+ },
+ "is_active": {
+ "type": "boolean",
+ "description": "Set false to pause the trigger, true to resume.",
+ },
+ "inputs": {
+ "type": "object",
+ "description": (
+ "Inputs to change, merged over the preset's current "
+ "inputs. For a webhook trigger these are the trigger "
+ "block's config (e.g. repo, events); changing them "
+ "re-registers the webhook."
+ ),
+ "additionalProperties": True,
+ },
+ },
+ "required": ["preset_id"],
+ }
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id if session else None
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required.",
+ error="auth_required",
+ session_id=session_id,
+ )
+
+ preset_id: str | None = kwargs.get("preset_id")
+ if not preset_id:
+ return ErrorResponse(
+ message="preset_id is required.",
+ error="missing_argument",
+ session_id=session_id,
+ )
+
+ merged_inputs = None
+ credentials = None
+ new_inputs = kwargs.get("inputs")
+ if new_inputs:
+ # Reconfigure: merge over current inputs and reuse the stored
+ # credentials so the webhook can be re-registered.
+ current = await library_db().get_preset(
+ user_id=user_id, preset_id=preset_id
+ )
+ if not current:
+ return ErrorResponse(
+ message=f"Preset '{preset_id}' not found.",
+ error="preset_not_found",
+ session_id=session_id,
+ )
+ merged_inputs = {**current.inputs, **new_inputs}
+ credentials = current.credentials
+
+ try:
+ updated = await triggers_db().update_triggered_preset(
+ user_id=user_id,
+ preset_id=preset_id,
+ inputs=merged_inputs,
+ credentials=credentials,
+ name=kwargs.get("name"),
+ description=kwargs.get("description"),
+ is_active=kwargs.get("is_active"),
+ )
+ except NotFoundError:
+ return ErrorResponse(
+ message=f"Preset '{preset_id}' not found.",
+ error="preset_not_found",
+ session_id=session_id,
+ )
+ except (InvalidInputError, WebhookRegistrationError) as e:
+ return ErrorResponse(
+ message=str(e),
+ error="preset_update_failed",
+ session_id=session_id,
+ )
+
+ return PresetUpdatedResponse(
+ message=f"Preset '{updated.name}' updated.",
+ preset_id=updated.id,
+ name=updated.name,
+ is_active=updated.is_active,
+ webhook_url=updated.webhook.url if updated.webhook else None,
+ session_id=session_id,
+ )
+
+
+class DeletePresetTool(BaseTool):
+ """Delete a preset, cleaning up its webhook if it's a trigger."""
+
+ @property
+ def name(self) -> str:
+ return "delete_preset"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Delete a preset by preset_id. If it's a webhook trigger, its webhook "
+ "is deregistered and cleaned up. Find preset_id via list_presets."
+ )
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "preset_id": {
+ "type": "string",
+ "description": "ID of the preset to delete.",
+ },
+ },
+ "required": ["preset_id"],
+ }
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id if session else None
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required.",
+ error="auth_required",
+ session_id=session_id,
+ )
+
+ preset_id: str | None = kwargs.get("preset_id")
+ if not preset_id:
+ return ErrorResponse(
+ message="preset_id is required.",
+ error="missing_argument",
+ session_id=session_id,
+ )
+
+ # Fetch first for the name + a clean not-found message.
+ current = await library_db().get_preset(user_id=user_id, preset_id=preset_id)
+ if not current:
+ return ErrorResponse(
+ message=f"Preset '{preset_id}' not found.",
+ error="preset_not_found",
+ session_id=session_id,
+ )
+
+ await triggers_db().delete_preset_with_webhook_cleanup(
+ user_id=user_id, preset_id=preset_id
+ )
+
+ return PresetDeletedResponse(
+ message=f"Preset '{current.name}' deleted.",
+ preset_id=preset_id,
+ name=current.name,
+ session_id=session_id,
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/manage_presets_test.py b/autogpt_platform/backend/backend/copilot/tools/manage_presets_test.py
new file mode 100644
index 0000000000..1ee7d1ce52
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/manage_presets_test.py
@@ -0,0 +1,309 @@
+"""Tests for the preset-management tools (list / update / delete)."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.copilot.tools.manage_presets import (
+ DeletePresetTool,
+ ListPresetsTool,
+ PresetDeletedResponse,
+ PresetListResponse,
+ PresetUpdatedResponse,
+ UpdatePresetTool,
+)
+from backend.copilot.tools.models import ErrorResponse
+from backend.util.exceptions import (
+ InvalidInputError,
+ NotFoundError,
+ WebhookRegistrationError,
+)
+
+from ._test_data import make_session
+
+_USER = "test-user-presets"
+_PATH = "backend.copilot.tools.manage_presets"
+
+
+def session():
+ return make_session(_USER)
+
+
+def _preset(*, id="preset-1", name="My Preset", is_active=True, webhook=True):
+ preset = MagicMock()
+ preset.id = id
+ preset.name = name
+ preset.description = "desc"
+ preset.graph_id = "graph-1"
+ preset.graph_version = 1
+ preset.is_active = is_active
+ preset.webhook_id = "wh-1" if webhook else None
+ preset.inputs = {"repo": "owner/repo"}
+ preset.credentials = {}
+ preset.webhook = (
+ MagicMock(url="https://x/ingress", provider="github") if webhook else None
+ )
+ return preset
+
+
+# ---- list_presets ----
+
+
+async def test_list_no_auth(session):
+ result = await ListPresetsTool()._execute(user_id=None, session=session)
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "auth_required"
+
+
+async def test_list_empty(session):
+ ldb = MagicMock()
+ ldb.list_presets = AsyncMock(
+ return_value=MagicMock(presets=[], pagination=MagicMock(total_items=0))
+ )
+ with patch(f"{_PATH}.library_db", return_value=ldb):
+ result = await ListPresetsTool()._execute(user_id=_USER, session=session)
+ assert isinstance(result, PresetListResponse)
+ assert result.presets == []
+
+
+async def test_list_populated_with_graph_filter(session):
+ ldb = MagicMock()
+ ldb.list_presets = AsyncMock(
+ return_value=MagicMock(presets=[_preset()], pagination=MagicMock(total_items=1))
+ )
+ with patch(f"{_PATH}.library_db", return_value=ldb):
+ result = await ListPresetsTool()._execute(
+ user_id=_USER, session=session, graph_id="graph-1"
+ )
+ assert isinstance(result, PresetListResponse)
+ assert len(result.presets) == 1
+ assert result.total_count == 1
+ assert result.presets[0].webhook_url == "https://x/ingress"
+ assert ldb.list_presets.await_args.kwargs["graph_id"] == "graph-1"
+
+
+async def test_list_truncation_hint_when_more_than_one_page(session):
+ # 1 preset returned but 247 total -> message must flag truncation + total.
+ ldb = MagicMock()
+ ldb.list_presets = AsyncMock(
+ return_value=MagicMock(
+ presets=[_preset()], pagination=MagicMock(total_items=247)
+ )
+ )
+ with patch(f"{_PATH}.library_db", return_value=ldb):
+ result = await ListPresetsTool()._execute(user_id=_USER, session=session)
+ assert isinstance(result, PresetListResponse)
+ assert result.total_count == 247
+ assert "247" in result.message and "first 1" in result.message
+
+
+async def test_list_resolves_library_agent_id(session):
+ ldb = MagicMock()
+ ldb.get_library_agent = AsyncMock(return_value=MagicMock(graph_id="graph-xyz"))
+ ldb.list_presets = AsyncMock(
+ return_value=MagicMock(presets=[], pagination=MagicMock(total_items=0))
+ )
+ with patch(f"{_PATH}.library_db", return_value=ldb):
+ await ListPresetsTool()._execute(
+ user_id=_USER, session=session, library_agent_id="lib-1"
+ )
+ assert ldb.list_presets.await_args.kwargs["graph_id"] == "graph-xyz"
+
+
+# ---- update_preset ----
+
+
+async def test_update_missing_preset_id(session):
+ result = await UpdatePresetTool()._execute(user_id=_USER, session=session)
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "missing_argument"
+
+
+async def test_update_rename_skips_preset_fetch(session):
+ tdb = MagicMock()
+ tdb.update_triggered_preset = AsyncMock(return_value=_preset(name="Renamed"))
+ ldb = MagicMock()
+ ldb.get_preset = AsyncMock()
+ with patch(f"{_PATH}.triggers_db", return_value=tdb), patch(
+ f"{_PATH}.library_db", return_value=ldb
+ ):
+ result = await UpdatePresetTool()._execute(
+ user_id=_USER, session=session, preset_id="preset-1", name="Renamed"
+ )
+ assert isinstance(result, PresetUpdatedResponse)
+ assert result.name == "Renamed"
+ ldb.get_preset.assert_not_awaited()
+ assert tdb.update_triggered_preset.await_args.kwargs["inputs"] is None
+
+
+async def test_update_pause(session):
+ tdb = MagicMock()
+ tdb.update_triggered_preset = AsyncMock(return_value=_preset(is_active=False))
+ with patch(f"{_PATH}.triggers_db", return_value=tdb), patch(
+ f"{_PATH}.library_db", return_value=MagicMock()
+ ):
+ result = await UpdatePresetTool()._execute(
+ user_id=_USER, session=session, preset_id="preset-1", is_active=False
+ )
+ assert isinstance(result, PresetUpdatedResponse)
+ assert result.is_active is False
+ assert tdb.update_triggered_preset.await_args.kwargs["is_active"] is False
+
+
+async def test_update_reconfigure_merges_and_reuses_credentials(session):
+ current = _preset()
+ current.inputs = {"repo": "owner/repo", "events": ["push"]}
+ current.credentials = {"github": MagicMock()}
+ ldb = MagicMock()
+ ldb.get_preset = AsyncMock(return_value=current)
+ tdb = MagicMock()
+ tdb.update_triggered_preset = AsyncMock(return_value=_preset())
+ with patch(f"{_PATH}.library_db", return_value=ldb), patch(
+ f"{_PATH}.triggers_db", return_value=tdb
+ ):
+ await UpdatePresetTool()._execute(
+ user_id=_USER,
+ session=session,
+ preset_id="preset-1",
+ inputs={"events": ["push", "pull_request"]},
+ )
+ kwargs = tdb.update_triggered_preset.await_args.kwargs
+ assert kwargs["inputs"] == {
+ "repo": "owner/repo",
+ "events": ["push", "pull_request"],
+ }
+ assert kwargs["credentials"] == current.credentials
+
+
+async def test_update_reconfigure_preset_not_found(session):
+ ldb = MagicMock()
+ ldb.get_preset = AsyncMock(return_value=None)
+ with patch(f"{_PATH}.library_db", return_value=ldb), patch(
+ f"{_PATH}.triggers_db", return_value=MagicMock()
+ ):
+ result = await UpdatePresetTool()._execute(
+ user_id=_USER, session=session, preset_id="missing", inputs={"x": 1}
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "preset_not_found"
+
+
+async def test_update_not_found_from_shared_fn(session):
+ tdb = MagicMock()
+ tdb.update_triggered_preset = AsyncMock(side_effect=NotFoundError("gone"))
+ with patch(f"{_PATH}.triggers_db", return_value=tdb), patch(
+ f"{_PATH}.library_db", return_value=MagicMock()
+ ):
+ result = await UpdatePresetTool()._execute(
+ user_id=_USER, session=session, preset_id="missing", name="X"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "preset_not_found"
+
+
+async def test_update_webhook_rejected(session):
+ ldb = MagicMock()
+ ldb.get_preset = AsyncMock(return_value=_preset())
+ tdb = MagicMock()
+ tdb.update_triggered_preset = AsyncMock(side_effect=InvalidInputError("no events"))
+ with patch(f"{_PATH}.library_db", return_value=ldb), patch(
+ f"{_PATH}.triggers_db", return_value=tdb
+ ):
+ result = await UpdatePresetTool()._execute(
+ user_id=_USER,
+ session=session,
+ preset_id="preset-1",
+ inputs={"events": []},
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "preset_update_failed"
+ assert "no events" in result.message
+
+
+# ---- delete_preset ----
+
+
+async def test_delete_missing_preset_id(session):
+ result = await DeletePresetTool()._execute(user_id=_USER, session=session)
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "missing_argument"
+
+
+async def test_delete_not_found(session):
+ ldb = MagicMock()
+ ldb.get_preset = AsyncMock(return_value=None)
+ with patch(f"{_PATH}.library_db", return_value=ldb), patch(
+ f"{_PATH}.triggers_db", return_value=MagicMock()
+ ):
+ result = await DeletePresetTool()._execute(
+ user_id=_USER, session=session, preset_id="missing"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "preset_not_found"
+
+
+async def test_delete_success(session):
+ ldb = MagicMock()
+ ldb.get_preset = AsyncMock(return_value=_preset(name="ToDelete"))
+ tdb = MagicMock()
+ tdb.delete_preset_with_webhook_cleanup = AsyncMock()
+ with patch(f"{_PATH}.library_db", return_value=ldb), patch(
+ f"{_PATH}.triggers_db", return_value=tdb
+ ):
+ result = await DeletePresetTool()._execute(
+ user_id=_USER, session=session, preset_id="preset-1"
+ )
+ assert isinstance(result, PresetDeletedResponse)
+ assert result.name == "ToDelete"
+ tdb.delete_preset_with_webhook_cleanup.assert_awaited_once()
+
+
+async def test_update_no_auth(session):
+ result = await UpdatePresetTool()._execute(user_id=None, session=session)
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "auth_required"
+
+
+async def test_delete_no_auth(session):
+ result = await DeletePresetTool()._execute(user_id=None, session=session)
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "auth_required"
+
+
+async def test_update_webhook_registration_error(session):
+ """A provider webhook failure during reconfigure surfaces as a clean
+ preset_update_failed, not an unhandled tool error."""
+ ldb = MagicMock()
+ ldb.get_preset = AsyncMock(return_value=_preset())
+ tdb = MagicMock()
+ tdb.update_triggered_preset = AsyncMock(
+ side_effect=WebhookRegistrationError("provider refused")
+ )
+ with patch(f"{_PATH}.library_db", return_value=ldb), patch(
+ f"{_PATH}.triggers_db", return_value=tdb
+ ):
+ result = await UpdatePresetTool()._execute(
+ user_id=_USER, session=session, preset_id="preset-1", inputs={"repo": "x"}
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "preset_update_failed"
+ assert "provider refused" in result.message
diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.py
index d28bb468f6..9b6790d0bf 100644
--- a/autogpt_platform/backend/backend/copilot/tools/models.py
+++ b/autogpt_platform/backend/backend/copilot/tools/models.py
@@ -6,7 +6,7 @@ from typing import Any, Literal
from pydantic import BaseModel, Field, model_validator
-from backend.data.graph import BaseGraph
+from backend.data.graph import BaseGraph, GraphTriggerInfo
from backend.data.model import CredentialsMetaInput
@@ -52,6 +52,13 @@ class ResponseType(str, Enum):
# Agent triggers
AGENT_TRIGGER_LIST = "agent_trigger_list"
+ TRIGGER_SETUP = "trigger_setup"
+ TRIGGER_CONFIG_REQUIRED = "trigger_config_required"
+
+ # Presets (list / update / delete)
+ PRESET_LIST = "preset_list"
+ PRESET_UPDATED = "preset_updated"
+ PRESET_DELETED = "preset_deleted"
# MCP
MCP_GUIDE = "mcp_guide"
@@ -169,6 +176,16 @@ class AgentInfo(BaseModel):
default=None,
description="Full graph structure (nodes + links) when include_graph is requested",
)
+ trigger_info: GraphTriggerInfo | None = Field(
+ default=None,
+ description=(
+ "Webhook-trigger setup info (provider, config_schema, "
+ "credentials_input_name) for agents with an external trigger. "
+ "Configure the trigger by passing config_schema fields to "
+ "setup_agent_webhook_trigger — never by editing the trigger node "
+ "in the graph. None for agents without a webhook trigger."
+ ),
+ )
class AgentsFoundResponse(ToolResponseBase):
@@ -220,7 +237,16 @@ class AgentDetails(BaseModel):
inputs: dict[str, Any] = {}
credentials: list[CredentialsMetaInput] = []
execution_options: ExecutionOptions = Field(default_factory=ExecutionOptions)
- trigger_info: dict[str, Any] | None = None
+ trigger_info: GraphTriggerInfo | None = Field(
+ default=None,
+ description=(
+ "Webhook-trigger setup info (provider, config_schema, "
+ "credentials_input_name) for agents with an external trigger. "
+ "Configure the trigger by passing config_schema fields to "
+ "setup_agent_webhook_trigger — never by editing the trigger node "
+ "in the graph. None for agents without a webhook trigger."
+ ),
+ )
class AgentDetailsResponse(ToolResponseBase):
@@ -277,6 +303,8 @@ class ExecutionStartedResponse(ToolResponseBase):
library_agent_id: str | None = None
library_agent_link: str | None = None
status: str = "QUEUED"
+ # Set when the run was started with save_as_preset=true.
+ saved_preset_id: str | None = None
# Auth/error models
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent.py b/autogpt_platform/backend/backend/copilot/tools/run_agent.py
index b5a7f1febc..06d71ccaf8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent.py
@@ -5,6 +5,7 @@ from typing import Any
from pydantic import BaseModel, Field, field_validator
+from backend.api.features.library.model import LibraryAgentPresetCreatable
from backend.copilot.config import ChatConfig
from backend.copilot.constants import MAX_TOOL_WAIT_SECONDS
from backend.copilot.model import ChatSession
@@ -98,6 +99,7 @@ class RunAgentInput(BaseModel):
username_agent_slug: str = ""
library_agent_id: str = ""
+ preset_id: str = ""
inputs: dict[str, Any] = Field(default_factory=dict)
use_defaults: bool = False
schedule_name: str = ""
@@ -105,13 +107,18 @@ class RunAgentInput(BaseModel):
timezone: str = "UTC"
wait_for_result: int = Field(default=0, ge=0, le=MAX_TOOL_WAIT_SECONDS)
dry_run: bool = Field(default=False)
+ save_as_preset: bool = False
+ preset_name: str = ""
+ preset_description: str = ""
@field_validator(
"username_agent_slug",
"library_agent_id",
+ "preset_id",
"schedule_name",
"cron",
"timezone",
+ "preset_name",
mode="before",
)
@classmethod
@@ -143,7 +150,9 @@ class RunAgentTool(BaseTool):
"and surfaces the inline credentials-setup card if anything is missing — "
"do NOT redirect to the Builder for credential setup. "
"Identify by username_agent_slug ('user/agent') or library_agent_id. "
- "For scheduling, provide schedule_name + cron."
+ "For scheduling, provide schedule_name + cron. To run a saved preset, "
+ "pass preset_id (alone). Pass save_as_preset=true (+ preset_name) to save "
+ "these inputs as a reusable preset while running."
)
@property
@@ -159,6 +168,14 @@ class RunAgentTool(BaseTool):
"type": "string",
"description": "Library agent ID.",
},
+ "preset_id": {
+ "type": "string",
+ "description": (
+ "Run a saved preset by ID (uses its stored inputs + "
+ "credentials; 'inputs' override individual fields). Use "
+ "alone — not with an agent identifier or save_as_preset."
+ ),
+ },
"inputs": {
"type": "object",
"description": "Input values for the agent.",
@@ -224,6 +241,12 @@ class RunAgentTool(BaseTool):
params.dry_run = True
session_id = session.session_id
+ # Running a saved preset is a distinct path (uses the preset's stored
+ # graph + inputs + credentials). Handle it before agent-identifier
+ # resolution below.
+ if params.preset_id:
+ return await self._handle_preset_run(user_id, session, params)
+
# Validate at least one identifier is provided
has_slug = params.username_agent_slug and "/" in params.username_agent_slug
has_library_id = bool(params.library_agent_id)
@@ -321,6 +344,30 @@ class RunAgentTool(BaseTool):
session_id=session_id,
)
+ # Webhook-trigger agents can't be run or scheduled directly — they
+ # fire on incoming HTTP events. Hand off to the trigger-setup tool,
+ # surfacing the same AgentDetails (with trigger_info) that run_agent
+ # uses elsewhere so AutoPilot has the provider + config schema ready.
+ if graph.has_external_trigger:
+ credentials = extract_credentials_from_schema(
+ graph.credentials_input_schema
+ )
+ return AgentDetailsResponse(
+ message=(
+ f"Agent '{graph.name}' runs on a webhook trigger, so it "
+ "can't be run or scheduled directly. Set it up with "
+ "setup_agent_webhook_trigger using the trigger block's "
+ "config (see trigger_info.config_schema). For provider "
+ "webhooks (e.g. GitHub), ask the user which connected "
+ "account to register the webhook under — never auto-pick."
+ ),
+ session_id=session_id,
+ agent=self._build_agent_details(graph, credentials),
+ user_authenticated=True,
+ graph_id=graph.id,
+ graph_version=graph.version,
+ )
+
# Step 2: Check credentials and inputs
graph_credentials, prereq_error = await self._check_prerequisites(
graph=graph,
@@ -333,7 +380,7 @@ class RunAgentTool(BaseTool):
# Step 3: Execute or Schedule
if is_schedule:
- return await self._schedule_agent(
+ result = await self._schedule_agent(
user_id=user_id,
session=session,
graph=graph,
@@ -344,7 +391,7 @@ class RunAgentTool(BaseTool):
timezone=params.timezone,
)
else:
- return await self._run_agent(
+ result = await self._run_agent(
user_id=user_id,
session=session,
graph=graph,
@@ -354,6 +401,20 @@ class RunAgentTool(BaseTool):
dry_run=params.dry_run,
)
+ # Step 4: persist the validated config as a reusable preset — only
+ # after the run/schedule actually started, so a failed operation
+ # (e.g. schedule validation, credential race) doesn't orphan a preset.
+ if isinstance(result, ExecutionStartedResponse):
+ saved_preset_id = await self._maybe_save_preset(
+ user_id=user_id,
+ graph=graph,
+ graph_credentials=graph_credentials,
+ params=params,
+ )
+ if saved_preset_id:
+ result.saved_preset_id = saved_preset_id
+ return result
+
except NotFoundError as e:
return ErrorResponse(
message=f"Agent '{params.username_agent_slug}' not found",
@@ -411,9 +472,7 @@ class RunAgentTool(BaseTool):
credentials: list[CredentialsMetaInput],
) -> AgentDetails:
"""Build AgentDetails from a graph."""
- trigger_info = (
- graph.trigger_setup_info.model_dump() if graph.trigger_setup_info else None
- )
+ trigger_info = graph.trigger_setup_info
return AgentDetails(
id=graph.id,
name=graph.name,
@@ -622,6 +681,133 @@ class RunAgentTool(BaseTool):
return graph_credentials, None
+ async def _handle_preset_run(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ params: RunAgentInput,
+ ) -> ToolResponseBase:
+ """Run a saved preset by id (mirrors POST /presets/{id}/execute)."""
+ session_id = session.session_id
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required. Please sign in to use this tool.",
+ session_id=session_id,
+ )
+ if params.username_agent_slug or params.library_agent_id:
+ return ErrorResponse(
+ message=(
+ "Use either preset_id or an agent identifier "
+ "(username_agent_slug / library_agent_id), not both."
+ ),
+ session_id=session_id,
+ )
+ if params.save_as_preset:
+ return ErrorResponse(
+ message=(
+ "save_as_preset can't be combined with preset_id — "
+ "the preset already exists."
+ ),
+ session_id=session_id,
+ )
+ if params.schedule_name or params.cron:
+ return ErrorResponse(
+ message=(
+ "preset_id runs the preset now; schedule it separately instead."
+ ),
+ session_id=session_id,
+ )
+
+ preset = await library_db().get_preset(
+ user_id=user_id, preset_id=params.preset_id
+ )
+ if not preset:
+ return ErrorResponse(
+ message=f"Preset '{params.preset_id}' not found.",
+ error="preset_not_found",
+ session_id=session_id,
+ )
+ graph = await graph_db().get_graph(
+ preset.graph_id, preset.graph_version, user_id=user_id
+ )
+ if not graph:
+ return ErrorResponse(
+ message=(
+ f"The agent for preset '{params.preset_id}' is not "
+ "accessible (anymore)."
+ ),
+ session_id=session_id,
+ )
+
+ # Builder-bound sessions can only run their bound agent — enforce the
+ # same guard as the regular run path so a preset for a different graph
+ # can't execute in a builder-bound chat.
+ builder_graph_id = session.metadata.builder_graph_id
+ if builder_graph_id and graph.id != builder_graph_id:
+ return ErrorResponse(
+ message=(
+ "This chat is bound to the builder's current agent. "
+ "Running a preset for a different agent is not allowed here."
+ ),
+ error="builder_session_graph_mismatch",
+ session_id=session_id,
+ )
+
+ # A webhook-triggered preset fires on its external event; it has no
+ # runnable payload here, so executing it directly would fail downstream.
+ # Reject cleanly (matching run_agent's has_external_trigger guard).
+ if graph.has_external_trigger:
+ return ErrorResponse(
+ message=(
+ f"Preset '{params.preset_id}' is a webhook trigger — it runs "
+ "automatically when its event fires, so it can't be run on "
+ "demand. Use update_preset to reconfigure or pause it "
+ "(is_active=false), or delete_preset to remove it."
+ ),
+ error="preset_is_webhook_trigger",
+ session_id=session_id,
+ )
+
+ merged_inputs = {**preset.inputs, **params.inputs}
+ return await self._run_agent(
+ user_id=user_id,
+ session=session,
+ graph=graph,
+ graph_credentials=preset.credentials,
+ inputs=merged_inputs,
+ wait_for_result=params.wait_for_result,
+ dry_run=params.dry_run,
+ preset_id=preset.id,
+ )
+
+ async def _maybe_save_preset(
+ self,
+ *,
+ user_id: str,
+ graph: GraphModel,
+ graph_credentials: dict[str, CredentialsMetaInput],
+ params: RunAgentInput,
+ ) -> str | None:
+ """Persist the validated run config as a reusable preset when requested.
+
+ Returns the new preset id, or None when save_as_preset wasn't set.
+ """
+ if not params.save_as_preset:
+ return None
+ created = await library_db().create_preset(
+ user_id=user_id,
+ preset=LibraryAgentPresetCreatable(
+ graph_id=graph.id,
+ graph_version=graph.version,
+ name=params.preset_name or graph.name,
+ description=params.preset_description,
+ inputs=params.inputs,
+ credentials=graph_credentials,
+ is_active=True,
+ ),
+ )
+ return created.id
+
async def _run_agent(
self,
user_id: str,
@@ -631,6 +817,7 @@ class RunAgentTool(BaseTool):
inputs: dict[str, Any],
dry_run: bool,
wait_for_result: int = 0,
+ preset_id: str | None = None,
) -> ToolResponseBase:
"""Execute an agent immediately, optionally waiting for completion."""
session_id = session.session_id
@@ -662,6 +849,7 @@ class RunAgentTool(BaseTool):
inputs=inputs,
graph_credentials_inputs=graph_credentials,
dry_run=dry_run,
+ preset_id=preset_id,
)
except GraphValidationError as e:
return self._handle_graph_validation_race(
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
index 3c8b89b88e..6fcb3d9e4a 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
@@ -1,5 +1,5 @@
import uuid
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
import orjson
import pytest
@@ -13,8 +13,8 @@ from ._test_data import (
setup_llm_test_data,
setup_test_data,
)
-from .models import SetupRequirementsResponse
-from .run_agent import RunAgentTool
+from .models import ErrorResponse, ExecutionStartedResponse, SetupRequirementsResponse
+from .run_agent import RunAgentInput, RunAgentTool
# This is so the formatter doesn't remove the fixture imports
setup_llm_test_data = setup_llm_test_data
@@ -819,3 +819,253 @@ async def test_run_agent_execution_structural_error_returns_error_response(
# user should see the validation error, not the credential setup card.
assert result_data.get("error") == "graph_validation_failed"
assert result_data.get("type") != "setup_requirements"
+
+
[email protected](loop_scope="session")
+async def test_run_agent_redirects_webhook_trigger_agent():
+ """A webhook-trigger agent can't be run/scheduled — run_agent returns an
+ AgentDetailsResponse (carrying trigger_info) that points AutoPilot to
+ setup_agent_webhook_trigger instead of attempting to execute it."""
+ from backend.data.graph import GraphTriggerInfo
+
+ from .models import AgentDetailsResponse
+
+ tool = RunAgentTool()
+ session = make_session(user_id="webhook-user")
+
+ lib_agent = MagicMock()
+ lib_agent.id = "lib-wh"
+ lib_agent.graph_id = "graph-wh"
+ lib_agent.graph_version = 1
+
+ graph = MagicMock()
+ graph.id = "graph-wh"
+ graph.name = "PR Notifier"
+ graph.description = "Notifies on PRs"
+ graph.version = 1
+ graph.has_external_trigger = True
+ graph.input_schema = {}
+ graph.credentials_input_schema = {}
+ graph.trigger_setup_info = GraphTriggerInfo(
+ provider="github",
+ config_schema={
+ "type": "object",
+ "properties": {"repo": {"type": "string"}},
+ "required": ["repo"],
+ },
+ credentials_input_name="payload_credentials",
+ )
+
+ mock_lib_db = MagicMock()
+ mock_lib_db.get_library_agent = AsyncMock(return_value=lib_agent)
+ mock_graph_db = MagicMock()
+ mock_graph_db.get_graph = AsyncMock(return_value=graph)
+ add_exec = AsyncMock()
+
+ with (
+ patch("backend.copilot.tools.run_agent.library_db", return_value=mock_lib_db),
+ patch("backend.copilot.tools.run_agent.graph_db", return_value=mock_graph_db),
+ patch(
+ "backend.copilot.tools.run_agent.execution_utils.add_graph_execution",
+ new=add_exec,
+ ),
+ ):
+ result = await tool._execute(
+ user_id="webhook-user",
+ session=session,
+ library_agent_id="lib-wh",
+ )
+
+ assert isinstance(result, AgentDetailsResponse)
+ assert result.agent.trigger_info is not None
+ assert result.agent.execution_options.webhook is True
+ assert result.agent.execution_options.manual is False
+ assert "setup_agent_webhook_trigger" in result.message
+ # It must NOT have attempted to execute the graph.
+ mock_graph_db.get_graph.assert_awaited_once()
+ add_exec.assert_not_awaited()
+
+
+# ---- preset_id (run on demand) + save_as_preset (create) ----
+
+
[email protected](loop_scope="session")
+async def test_run_preset_rejects_agent_identifier():
+ tool = RunAgentTool()
+ session = make_session(user_id="preset-user")
+ result = await tool._handle_preset_run(
+ "preset-user",
+ session,
+ RunAgentInput(preset_id="p1", library_agent_id="lib1"),
+ )
+ assert isinstance(result, ErrorResponse)
+ assert "not both" in result.message
+
+
[email protected](loop_scope="session")
+async def test_run_preset_rejects_save_as_preset():
+ tool = RunAgentTool()
+ session = make_session(user_id="preset-user")
+ result = await tool._handle_preset_run(
+ "preset-user",
+ session,
+ RunAgentInput(preset_id="p1", save_as_preset=True),
+ )
+ assert isinstance(result, ErrorResponse)
+ assert "already exists" in result.message
+
+
[email protected](loop_scope="session")
+async def test_run_preset_not_found():
+ tool = RunAgentTool()
+ session = make_session(user_id="preset-user")
+ mock_lib_db = MagicMock()
+ mock_lib_db.get_preset = AsyncMock(return_value=None)
+ with patch("backend.copilot.tools.run_agent.library_db", return_value=mock_lib_db):
+ result = await tool._handle_preset_run(
+ "preset-user", session, RunAgentInput(preset_id="missing")
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "preset_not_found"
+
+
[email protected](loop_scope="session")
+async def test_run_preset_executes_with_merged_inputs():
+ tool = RunAgentTool()
+ session = make_session(user_id="preset-user")
+
+ preset = MagicMock()
+ preset.id = "p1"
+ preset.graph_id = "g1"
+ preset.graph_version = 2
+ preset.inputs = {"a": 1, "b": 2}
+ preset.credentials = {}
+
+ graph = MagicMock()
+ graph.id = "g1"
+ graph.name = "My Agent"
+ graph.version = 2
+ graph.has_external_trigger = False
+
+ library_agent = MagicMock()
+ library_agent.id = "lib1"
+ library_agent.graph_id = "g1"
+ library_agent.graph_version = 2
+ library_agent.name = "My Agent"
+
+ execution = MagicMock()
+ execution.id = "exec1"
+
+ mock_lib_db = MagicMock()
+ mock_lib_db.get_preset = AsyncMock(return_value=preset)
+ mock_graph_db = MagicMock()
+ mock_graph_db.get_graph = AsyncMock(return_value=graph)
+ add_exec = AsyncMock(return_value=execution)
+
+ with (
+ patch("backend.copilot.tools.run_agent.library_db", return_value=mock_lib_db),
+ patch("backend.copilot.tools.run_agent.graph_db", return_value=mock_graph_db),
+ patch(
+ "backend.copilot.tools.run_agent.get_or_create_library_agent",
+ new=AsyncMock(return_value=library_agent),
+ ),
+ patch(
+ "backend.copilot.tools.run_agent.execution_utils.add_graph_execution",
+ new=add_exec,
+ ),
+ patch(
+ "backend.copilot.tools.run_agent._safe_link_to_chat_share",
+ new=AsyncMock(),
+ ),
+ patch("backend.copilot.tools.run_agent.track_agent_run_success"),
+ ):
+ result = await tool._handle_preset_run(
+ "preset-user", session, RunAgentInput(preset_id="p1", inputs={"b": 99})
+ )
+
+ assert isinstance(result, ExecutionStartedResponse)
+ kwargs = add_exec.await_args.kwargs
+ assert kwargs["preset_id"] == "p1"
+ assert kwargs["inputs"] == {"a": 1, "b": 99}
+
+
[email protected](loop_scope="session")
+async def test_run_preset_rejects_webhook_trigger():
+ """A webhook-triggered preset can't be run on demand (it fires on its
+ event); reject cleanly without attempting execution."""
+ tool = RunAgentTool()
+ session = make_session(user_id="preset-user")
+
+ preset = MagicMock()
+ preset.id = "p-wh"
+ preset.graph_id = "g-wh"
+ preset.graph_version = 1
+ preset.inputs = {"repo": "owner/repo"}
+ preset.credentials = {}
+
+ graph = MagicMock()
+ graph.id = "g-wh"
+ graph.has_external_trigger = True
+
+ mock_lib_db = MagicMock()
+ mock_lib_db.get_preset = AsyncMock(return_value=preset)
+ mock_graph_db = MagicMock()
+ mock_graph_db.get_graph = AsyncMock(return_value=graph)
+ add_exec = AsyncMock()
+
+ with (
+ patch("backend.copilot.tools.run_agent.library_db", return_value=mock_lib_db),
+ patch("backend.copilot.tools.run_agent.graph_db", return_value=mock_graph_db),
+ patch(
+ "backend.copilot.tools.run_agent.execution_utils.add_graph_execution",
+ new=add_exec,
+ ),
+ ):
+ result = await tool._handle_preset_run(
+ "preset-user", session, RunAgentInput(preset_id="p-wh")
+ )
+
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "preset_is_webhook_trigger"
+ add_exec.assert_not_awaited()
+
+
[email protected](loop_scope="session")
+async def test_maybe_save_preset_returns_none_when_flag_off():
+ tool = RunAgentTool()
+ graph = MagicMock()
+ graph.id = "g1"
+ graph.name = "My Agent"
+ graph.version = 1
+ result = await tool._maybe_save_preset(
+ user_id="u1", graph=graph, graph_credentials={}, params=RunAgentInput()
+ )
+ assert result is None
+
+
[email protected](loop_scope="session")
+async def test_maybe_save_preset_creates_with_default_name():
+ tool = RunAgentTool()
+ graph = MagicMock()
+ graph.id = "g1"
+ graph.name = "My Agent"
+ graph.version = 1
+
+ created = MagicMock()
+ created.id = "preset-new"
+ mock_lib_db = MagicMock()
+ mock_lib_db.create_preset = AsyncMock(return_value=created)
+
+ with patch("backend.copilot.tools.run_agent.library_db", return_value=mock_lib_db):
+ result = await tool._maybe_save_preset(
+ user_id="u1",
+ graph=graph,
+ graph_credentials={},
+ params=RunAgentInput(save_as_preset=True, inputs={"x": 1}),
+ )
+
+ assert result == "preset-new"
+ preset_arg = mock_lib_db.create_preset.await_args.kwargs["preset"]
+ assert preset_arg.name == "My Agent"
+ assert preset_arg.inputs == {"x": 1}
+ assert preset_arg.graph_id == "g1"
diff --git a/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py
new file mode 100644
index 0000000000..bb631987d5
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py
@@ -0,0 +1,472 @@
+"""Tool for setting up a webhook-triggered preset for a library agent.
+
+Wraps the same logic as the ``POST /presets/setup-trigger`` route so AutoPilot
+can set up a webhook trigger end-to-end and hand the user the correct ingress
+URL for manual-setup webhooks.
+
+Credential handling splits into two classes:
+
+- The **trigger node's own credential** (the account a provider webhook is
+ *registered under*) is surfaced for an explicit choice in the setup card and
+ used verbatim — never silently auto-picked.
+- All **other agent-body credentials** mirror ``run_agent``: auto-matched, and
+ only shown in the card when missing (to connect).
+"""
+
+import logging
+from typing import Any
+
+from backend.api.features.library.model import LibraryAgentPreset
+from backend.blocks._base import BlockType
+from backend.copilot.model import ChatSession
+from backend.data.db_accessors import graph_db, library_db, triggers_db
+from backend.data.graph import GraphModel, Node
+from backend.data.model import Credentials, CredentialsMetaInput
+from backend.util.exceptions import (
+ InvalidInputError,
+ NotFoundError,
+ WebhookRegistrationError,
+)
+
+from .base import BaseTool
+from .models import (
+ ErrorResponse,
+ ResponseType,
+ SetupInfo,
+ SetupRequirementsResponse,
+ ToolResponseBase,
+ UserReadiness,
+)
+from .utils import (
+ build_missing_credentials_from_graph,
+ create_credential_meta_from_match,
+ get_or_create_library_agent,
+ get_user_credentials,
+ match_user_credentials_to_graph,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def _is_filled(value: Any) -> bool:
+ """Whether a trigger-config value counts as provided (non-empty)."""
+ return value not in (None, "", {}, [])
+
+
+class TriggerSetupResponse(ToolResponseBase):
+ """Returned when a webhook-triggered preset has been created."""
+
+ type: ResponseType = ResponseType.TRIGGER_SETUP
+ preset_id: str
+ library_agent_id: str
+ library_agent_link: str
+ name: str
+ is_active: bool
+ provider: str
+ manual_setup_required: bool
+ webhook_url: str | None = None
+
+
+class TriggerConfigRequiredResponse(ToolResponseBase):
+ """Returned when the webhook trigger block needs configuration the LLM must
+ collect from the user (e.g. a GitHub repo + which events to subscribe to).
+
+ The config is gathered conversationally rather than via a card, because a
+ trigger block's config (event filters etc.) can be arbitrarily structured.
+ The LLM should ask the user for the fields in ``config_schema`` — never
+ guess — then re-call with ``trigger_config`` filled in.
+ """
+
+ type: ResponseType = ResponseType.TRIGGER_CONFIG_REQUIRED
+ missing_config: list[str]
+ config_schema: dict[str, Any]
+ graph_id: str
+ graph_version: int
+
+
+class SetupAgentWebhookTriggerTool(BaseTool):
+ """Set up a webhook-triggered preset for an agent that has a trigger block.
+
+ For manual-setup (generic) webhooks the response includes the ingress URL
+ to give to the user. For provider webhooks (e.g. GitHub) the user picks
+ which account the webhook is registered under via the inline setup card.
+ """
+
+ @property
+ def name(self) -> str:
+ return "setup_agent_webhook_trigger"
+
+ @property
+ def description(self) -> str:
+ return (
+ "Set up a webhook trigger for an agent with a webhook trigger block. "
+ "This is the ONLY way to configure such a trigger: pass the trigger "
+ "block's config as 'trigger_config' — never configure it by editing "
+ "the agent's graph. If credentials are needed it returns a setup card; "
+ "after the user proceeds, call again with the 'credentials' they selected. "
+ "On success the result card shows any webhook URL with a copy button — "
+ "don't reprint the URL; point the user to the card."
+ )
+
+ @property
+ def requires_auth(self) -> bool:
+ return True
+
+ @property
+ def parameters(self) -> dict[str, Any]:
+ return {
+ "type": "object",
+ "properties": {
+ "library_agent_id": {
+ "type": "string",
+ "description": "Library agent ID (preferred identifier).",
+ },
+ "graph_id": {
+ "type": "string",
+ "description": "Agent graph ID (alt to library_agent_id).",
+ },
+ "graph_version": {
+ "type": "integer",
+ "description": "Graph version (used with graph_id).",
+ },
+ "name": {
+ "type": "string",
+ "description": "Name for the trigger.",
+ },
+ "description": {
+ "type": "string",
+ "description": "Optional description for the trigger.",
+ },
+ "trigger_config": {
+ "type": "object",
+ "description": (
+ "Trigger block config inputs (from "
+ "trigger_setup_info.config_schema), e.g. repo + events; "
+ "omit credential fields. Set config HERE, not by editing "
+ "the trigger node. Usually empty for generic webhooks."
+ ),
+ "additionalProperties": True,
+ },
+ "credentials": {
+ "type": "object",
+ "description": (
+ "Credential selection {field_name: credential_id} the "
+ "user made in the setup card. Pass when re-calling after "
+ "the card; omit on the first call."
+ ),
+ "additionalProperties": {"type": "string"},
+ },
+ },
+ "required": ["name"],
+ }
+
+ async def _execute(
+ self,
+ user_id: str | None,
+ session: ChatSession,
+ **kwargs,
+ ) -> ToolResponseBase:
+ session_id = session.session_id if session else None
+ if not user_id:
+ return ErrorResponse(
+ message="Authentication required.",
+ error="auth_required",
+ session_id=session_id,
+ )
+
+ name: str = (kwargs.get("name") or "").strip()
+ if not name:
+ return ErrorResponse(
+ message="A name for the trigger is required.",
+ error="missing_argument",
+ session_id=session_id,
+ )
+
+ graph, error = await self._resolve_graph(user_id, session, kwargs)
+ if error:
+ return error
+ assert graph is not None
+
+ if not (trigger_node := graph.webhook_input_node):
+ return ErrorResponse(
+ message=(
+ f"Agent '{graph.name}' has no webhook trigger block, so it "
+ "can't have a webhook trigger. Run or schedule it instead."
+ ),
+ error="no_webhook_trigger",
+ session_id=session_id,
+ )
+
+ config_required = self._missing_trigger_config(
+ graph, kwargs.get("trigger_config") or {}, session_id
+ )
+ if config_required:
+ return config_required
+
+ agent_credentials, card = await self._resolve_credentials(
+ user_id, graph, trigger_node, kwargs.get("credentials") or {}, session_id
+ )
+ if card:
+ return card
+
+ library_agent = await get_or_create_library_agent(graph, user_id)
+ try:
+ preset = await triggers_db().setup_triggered_preset(
+ user_id=user_id,
+ graph_id=graph.id,
+ graph_version=graph.version,
+ name=name,
+ description=(kwargs.get("description") or "").strip(),
+ trigger_config=kwargs.get("trigger_config") or {},
+ agent_credentials=agent_credentials,
+ )
+ except (
+ InvalidInputError,
+ NotFoundError,
+ WebhookRegistrationError,
+ ) as e:
+ return ErrorResponse(
+ message=f"Could not set up the trigger: {e}",
+ error="trigger_setup_failed",
+ session_id=session_id,
+ )
+
+ return self._build_success_response(
+ preset, trigger_node, library_agent.id, session_id
+ )
+
+ async def _resolve_graph(
+ self,
+ user_id: str,
+ session: ChatSession,
+ kwargs: dict[str, Any],
+ ) -> tuple[GraphModel | None, ErrorResponse | None]:
+ """Resolve the target graph from library_agent_id, graph_id, or builder."""
+ session_id = session.session_id if session else None
+ library_agent_id: str = (kwargs.get("library_agent_id") or "").strip()
+ graph_id: str = (kwargs.get("graph_id") or "").strip()
+ graph_version: int | None = kwargs.get("graph_version")
+
+ if not library_agent_id and not graph_id:
+ builder_graph_id = session.metadata.builder_graph_id
+ if builder_graph_id:
+ graph_id = builder_graph_id
+ else:
+ return None, ErrorResponse(
+ message="Provide a library_agent_id or graph_id.",
+ error="missing_argument",
+ session_id=session_id,
+ )
+
+ if library_agent_id:
+ try:
+ library_agent = await library_db().get_library_agent(
+ library_agent_id, user_id
+ )
+ except NotFoundError:
+ return None, ErrorResponse(
+ message=f"Library agent '{library_agent_id}' not found.",
+ error="library_agent_not_found",
+ session_id=session_id,
+ )
+ graph_id = library_agent.graph_id
+ graph_version = library_agent.graph_version
+
+ graph = await graph_db().get_graph(graph_id, graph_version, user_id=user_id)
+ if not graph:
+ return None, ErrorResponse(
+ message=f"Agent graph '{graph_id}' not found.",
+ error="graph_not_found",
+ session_id=session_id,
+ )
+ return graph, None
+
+ def _missing_trigger_config(
+ self,
+ graph: GraphModel,
+ trigger_config: dict[str, Any],
+ session_id: str | None,
+ ) -> TriggerConfigRequiredResponse | None:
+ """Return a config-required response if the trigger block has required
+ config inputs (e.g. a repo + event filter) the caller hasn't supplied.
+
+ These are collected from the user conversationally — the LLM must ask
+ for them and never guess — rather than via the credentials card.
+ """
+ info = graph.trigger_setup_info
+ schema = info.config_schema if info else None
+ if not isinstance(schema, dict):
+ return None
+ required = schema.get("required", [])
+ missing = [
+ name for name in required if not _is_filled(trigger_config.get(name))
+ ]
+ if not missing:
+ return None
+ return TriggerConfigRequiredResponse(
+ message=(
+ "Before this trigger can be set up, ask the user for its "
+ "configuration and pass it as `trigger_config` — do NOT guess "
+ "values (e.g. don't invent a repository name). The required "
+ "fields and their schema are below; once you have the user's "
+ "answers, call setup_agent_webhook_trigger again with "
+ "`trigger_config` filled in."
+ ),
+ session_id=session_id,
+ missing_config=missing,
+ config_schema=schema,
+ graph_id=graph.id,
+ graph_version=graph.version,
+ )
+
+ async def _resolve_credentials(
+ self,
+ user_id: str,
+ graph: GraphModel,
+ trigger_node: Node,
+ selection: dict[str, str],
+ session_id: str | None,
+ ) -> tuple[dict[str, CredentialsMetaInput], SetupRequirementsResponse | None]:
+ """Resolve the agent's credentials, or return a setup card to fill them.
+
+ Body credentials are auto-matched (run_agent behaviour). The trigger
+ node's own credential is only resolved from an explicit ``selection``,
+ so it's always surfaced in the card for the user to pick the account the
+ webhook is registered under — never silently auto-picked.
+
+ Returns ``(agent_credentials, None)`` when ready to proceed, or
+ ``({}, SetupRequirementsResponse)`` when the user must act first.
+ """
+ matched, _ = await match_user_credentials_to_graph(user_id, graph)
+ trigger_cred_key = self._trigger_cred_key(graph, trigger_node)
+
+ effective = dict(matched)
+ if selection:
+ available = await get_user_credentials(user_id)
+ effective.update(self._resolve_selection(graph, selection, available))
+
+ # Force the trigger credential into the card until it's explicitly
+ # chosen, even when a candidate auto-matched.
+ matched_for_card = {
+ key: cred
+ for key, cred in effective.items()
+ if not (key == trigger_cred_key and trigger_cred_key not in selection)
+ }
+ card_missing = build_missing_credentials_from_graph(graph, matched_for_card)
+ if card_missing:
+ return {}, self._build_card(graph, card_missing, session_id)
+
+ return effective, None
+
+ @staticmethod
+ def _trigger_cred_key(graph: GraphModel, trigger_node: Node) -> str | None:
+ """Graph-level credential key that maps to the trigger node's own
+ credential field (the webhook-registration account). None for manual
+ webhooks, which have no credential."""
+ return next(
+ (
+ key
+ for key, (_, node_fields, _) in graph.regular_credentials_inputs.items()
+ if any(node_id == trigger_node.id for node_id, _ in node_fields)
+ ),
+ None,
+ )
+
+ def _resolve_selection(
+ self,
+ graph: GraphModel,
+ selection: dict[str, str],
+ available_creds: list[Credentials],
+ ) -> dict[str, CredentialsMetaInput]:
+ """Resolve {field: credential_id} the user picked into credential metas,
+ validating each against the field's provider/type. Invalid or unknown
+ selections are dropped (so the card re-surfaces them)."""
+ regular = graph.regular_credentials_inputs
+ resolved: dict[str, CredentialsMetaInput] = {}
+ for key, cred_id in selection.items():
+ if not (entry := regular.get(key)):
+ continue
+ field_info = entry[0]
+ cred = next(
+ (
+ c
+ for c in available_creds
+ if c.id == cred_id
+ and c.provider in field_info.provider
+ and c.type in field_info.supported_types
+ ),
+ None,
+ )
+ if cred:
+ resolved[key] = create_credential_meta_from_match(cred)
+ return resolved
+
+ def _build_card(
+ self,
+ graph: GraphModel,
+ missing_credentials: dict[str, Any],
+ session_id: str | None,
+ ) -> SetupRequirementsResponse:
+ """Build the inline credentials setup card (same shape as run_agent)."""
+ return SetupRequirementsResponse(
+ message=(
+ "Choose or connect the account(s) in the card below, then "
+ "proceed — connecting happens right here in this card, with no "
+ "separate connection step needed first."
+ ),
+ session_id=session_id,
+ setup_info=SetupInfo(
+ agent_id=graph.id,
+ agent_name=graph.name,
+ user_readiness=UserReadiness(
+ has_all_credentials=False,
+ missing_credentials=missing_credentials,
+ ready_to_run=False,
+ ),
+ requirements={
+ "credentials": list(missing_credentials.values()),
+ "inputs": [],
+ "execution_modes": ["webhook"],
+ },
+ ),
+ graph_id=graph.id,
+ graph_version=graph.version,
+ )
+
+ def _build_success_response(
+ self,
+ preset: LibraryAgentPreset,
+ trigger_node: Node,
+ library_agent_id: str,
+ session_id: str | None,
+ ) -> TriggerSetupResponse:
+ """Build the success response, surfacing the ingress URL when manual."""
+ manual = trigger_node.block.block_type == BlockType.WEBHOOK_MANUAL
+ webhook_url = preset.webhook.url if preset.webhook else None
+ provider = preset.webhook.provider if preset.webhook else None
+
+ if manual and webhook_url:
+ # User-facing copy only — the card renders the URL itself in a copy
+ # box; the tool description tells the model not to reprint it.
+ message = (
+ f"Trigger '{preset.name}' is set up. Copy the webhook URL below "
+ "and paste it into your external service (e.g. TypeForm) to finish."
+ )
+ else:
+ message = (
+ f"Trigger '{preset.name}' is set up and registered automatically; "
+ "no webhook URL handoff is needed."
+ )
+
+ return TriggerSetupResponse(
+ message=message,
+ session_id=session_id,
+ preset_id=preset.id,
+ library_agent_id=library_agent_id,
+ library_agent_link=f"/library/agents/{library_agent_id}",
+ name=preset.name,
+ is_active=preset.is_active,
+ provider=provider or "",
+ manual_setup_required=manual,
+ webhook_url=webhook_url,
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger_test.py b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger_test.py
new file mode 100644
index 0000000000..c12adf6725
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger_test.py
@@ -0,0 +1,443 @@
+"""Tests for SetupAgentWebhookTriggerTool."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from pydantic import SecretStr
+
+from backend.blocks._base import BlockType
+from backend.copilot.tools.models import ErrorResponse, SetupRequirementsResponse
+from backend.copilot.tools.setup_agent_webhook_trigger import (
+ SetupAgentWebhookTriggerTool,
+ TriggerConfigRequiredResponse,
+ TriggerSetupResponse,
+)
+from backend.data.model import (
+ APIKeyCredentials,
+ CredentialsFieldInfo,
+ CredentialsMetaInput,
+)
+from backend.integrations.providers import ProviderName
+from backend.util.exceptions import (
+ InvalidInputError,
+ NotFoundError,
+ WebhookRegistrationError,
+)
+
+from ._test_data import make_session
+
+_USER = "test-user-trigger"
+_PATH = "backend.copilot.tools.setup_agent_webhook_trigger"
+
+
+def tool():
+ return SetupAgentWebhookTriggerTool()
+
+
+def session():
+ return make_session(_USER)
+
+
+def _github_field_info() -> CredentialsFieldInfo:
+ return CredentialsFieldInfo(
+ credentials_provider=frozenset({ProviderName.GITHUB}),
+ credentials_types=frozenset({"api_key"}),
+ )
+
+
+def _github_credential(cred_id: str = "cred-gh-1") -> APIKeyCredentials:
+ return APIKeyCredentials(
+ id=cred_id,
+ provider="github",
+ api_key=SecretStr("secret"),
+ title="My GitHub",
+ )
+
+
+def _github_meta(cred_id: str = "cred-gh-1") -> CredentialsMetaInput:
+ return CredentialsMetaInput(
+ id=cred_id,
+ provider=ProviderName.GITHUB,
+ type="api_key",
+ title="My GitHub",
+ )
+
+
+def _make_graph(
+ *,
+ manual: bool,
+ regular_credentials: dict | None = None,
+ config_schema: dict | None = None,
+):
+ """Build a fake graph with a webhook trigger node.
+
+ ``config_schema`` defaults to an empty (no-required) schema so the trigger
+ config check passes; pass one with ``required`` to exercise that path.
+ """
+ node = MagicMock()
+ node.id = "trigger-node"
+ node.block.block_type = BlockType.WEBHOOK_MANUAL if manual else BlockType.WEBHOOK
+
+ graph = MagicMock()
+ graph.id = "graph-1"
+ graph.version = 1
+ graph.name = "My Webhook Agent"
+ graph.webhook_input_node = node
+ graph.regular_credentials_inputs = regular_credentials or {}
+ graph.trigger_setup_info = MagicMock(config_schema=config_schema or {})
+ return graph
+
+
+def _make_preset(*, provider: str, url: str):
+ preset = MagicMock()
+ preset.id = "preset-1"
+ preset.name = "My Trigger"
+ preset.is_active = True
+ preset.webhook.url = url
+ preset.webhook.provider = provider
+ return preset
+
+
+def _patches(graph, *, matched=None, available=None, preset=None):
+ """Patch graph resolution + credential matching + DB calls for the tool."""
+ mock_graph_db = MagicMock()
+ mock_graph_db.get_graph = AsyncMock(return_value=graph)
+ mock_triggers = MagicMock()
+ mock_triggers.setup_triggered_preset = AsyncMock(return_value=preset)
+ return [
+ patch(f"{_PATH}.graph_db", return_value=mock_graph_db),
+ patch(
+ f"{_PATH}.get_or_create_library_agent",
+ new=AsyncMock(return_value=MagicMock(id="lib-1")),
+ ),
+ patch(
+ f"{_PATH}.match_user_credentials_to_graph",
+ new=AsyncMock(return_value=(matched or {}, [])),
+ ),
+ patch(
+ f"{_PATH}.get_user_credentials",
+ new=AsyncMock(return_value=available or []),
+ ),
+ patch(f"{_PATH}.triggers_db", return_value=mock_triggers),
+ ], mock_triggers.setup_triggered_preset
+
+
+async def test_no_auth(tool, session):
+ result = await tool._execute(user_id=None, session=session, name="My Trigger")
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "auth_required"
+
+
+async def test_missing_name(tool, session):
+ result = await tool._execute(user_id=_USER, session=session, graph_id="graph-1")
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "missing_argument"
+
+
+async def test_no_webhook_node(tool, session):
+ graph = _make_graph(manual=True)
+ graph.webhook_input_node = None
+ ctxs, _ = _patches(graph)
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
+ result = await tool._execute(
+ user_id=_USER, session=session, name="My Trigger", graph_id="graph-1"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "no_webhook_trigger"
+
+
+async def test_manual_webhook_no_creds_proceeds(tool, session):
+ """Manual webhook with no required credentials: create the preset, return URL."""
+ graph = _make_graph(manual=True, regular_credentials={})
+ preset = _make_preset(
+ provider="generic_webhook",
+ url="https://backend.agpt.co/api/integrations/generic_webhook/webhooks/wh-1/ingress",
+ )
+ ctxs, setup_mock = _patches(graph, preset=preset)
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
+ result = await tool._execute(
+ user_id=_USER, session=session, name="My Trigger", graph_id="graph-1"
+ )
+ assert isinstance(result, TriggerSetupResponse)
+ assert result.manual_setup_required is True
+ assert result.webhook_url and "backend.agpt.co" in result.webhook_url
+ # The URL lives on webhook_url (rendered in the card's copy box) and must
+ # NOT be duplicated inline in the user-facing message.
+ assert result.webhook_url not in result.message
+ setup_mock.assert_awaited_once()
+
+
+async def test_manual_webhook_missing_body_cred_returns_card(tool, session):
+ """Manual webhook whose body needs a (missing) credential -> connect card."""
+ graph = _make_graph(
+ manual=True,
+ regular_credentials={
+ "e2b_credentials": (
+ _github_field_info(),
+ {("body-node", "credentials")},
+ True,
+ )
+ },
+ )
+ # No match + the body cred is in the graph's regular_credentials_inputs,
+ # so it surfaces as missing.
+ ctxs, setup_mock = _patches(graph, matched={})
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
+ result = await tool._execute(
+ user_id=_USER, session=session, name="My Trigger", graph_id="graph-1"
+ )
+ assert isinstance(result, SetupRequirementsResponse)
+ assert "e2b_credentials" in result.setup_info.user_readiness.missing_credentials
+ setup_mock.assert_not_called()
+
+
+async def test_provider_webhook_first_call_surfaces_trigger_cred(tool, session):
+ """Provider webhook: the trigger account is shown in the card even when a
+ candidate auto-matched, and the preset is NOT created yet."""
+ graph = _make_graph(
+ manual=False,
+ regular_credentials={
+ "github_credentials": (
+ _github_field_info(),
+ {("trigger-node", "credentials")},
+ True,
+ )
+ },
+ )
+ # Auto-match would pick the single account, but it must still be surfaced.
+ ctxs, setup_mock = _patches(graph, matched={"github_credentials": _github_meta()})
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
+ result = await tool._execute(
+ user_id=_USER, session=session, name="My Trigger", graph_id="graph-1"
+ )
+ assert isinstance(result, SetupRequirementsResponse)
+ assert "github_credentials" in result.setup_info.user_readiness.missing_credentials
+ setup_mock.assert_not_called()
+
+
+async def test_provider_webhook_explicit_selection_proceeds(tool, session):
+ """Provider webhook resumed with an explicit account -> preset created with it."""
+ graph = _make_graph(
+ manual=False,
+ regular_credentials={
+ "github_credentials": (
+ _github_field_info(),
+ {("trigger-node", "credentials")},
+ True,
+ )
+ },
+ )
+ preset = _make_preset(
+ provider="github",
+ url="https://backend.agpt.co/api/integrations/github/webhooks/wh-2/ingress",
+ )
+ ctxs, setup_mock = _patches(
+ graph,
+ matched={"github_credentials": _github_meta()},
+ available=[_github_credential()],
+ preset=preset,
+ )
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
+ result = await tool._execute(
+ user_id=_USER,
+ session=session,
+ name="My Trigger",
+ graph_id="graph-1",
+ credentials={"github_credentials": "cred-gh-1"},
+ )
+ assert isinstance(result, TriggerSetupResponse)
+ assert result.manual_setup_required is False
+ setup_mock.assert_awaited_once()
+ passed = setup_mock.await_args.kwargs["agent_credentials"]
+ assert passed["github_credentials"].id == "cred-gh-1"
+
+
+async def test_provider_webhook_missing_config_asks_user(tool, session):
+ """Required trigger config (repo/events) the LLM didn't supply -> ask the
+ user conversationally; don't attempt setup or guess values."""
+ graph = _make_graph(
+ manual=False,
+ regular_credentials={
+ "github_credentials": (
+ _github_field_info(),
+ {("trigger-node", "credentials")},
+ True,
+ )
+ },
+ config_schema={
+ "properties": {"repo": {"type": "string"}, "events": {"type": "object"}},
+ "required": ["repo", "events"],
+ },
+ )
+ ctxs, setup_mock = _patches(graph)
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
+ result = await tool._execute(
+ user_id=_USER, session=session, name="My Trigger", graph_id="graph-1"
+ )
+
+ assert isinstance(result, TriggerConfigRequiredResponse)
+ assert set(result.missing_config) == {"repo", "events"}
+ setup_mock.assert_not_called()
+
+
+async def test_provider_webhook_config_and_creds_provided_proceeds(tool, session):
+ """With required config supplied and an explicit credential, set up the
+ preset (config check is satisfied)."""
+ graph = _make_graph(
+ manual=False,
+ regular_credentials={
+ "github_credentials": (
+ _github_field_info(),
+ {("trigger-node", "credentials")},
+ True,
+ )
+ },
+ config_schema={
+ "properties": {"repo": {"type": "string"}},
+ "required": ["repo"],
+ },
+ )
+ preset = _make_preset(
+ provider="github",
+ url="https://backend.agpt.co/api/integrations/github/webhooks/wh-3/ingress",
+ )
+ ctxs, setup_mock = _patches(
+ graph,
+ matched={"github_credentials": _github_meta()},
+ available=[_github_credential()],
+ preset=preset,
+ )
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
+ result = await tool._execute(
+ user_id=_USER,
+ session=session,
+ name="My Trigger",
+ graph_id="graph-1",
+ trigger_config={"repo": "owner/repo"},
+ credentials={"github_credentials": "cred-gh-1"},
+ )
+
+ assert isinstance(result, TriggerSetupResponse)
+ setup_mock.assert_awaited_once()
+ assert setup_mock.await_args.kwargs["trigger_config"] == {"repo": "owner/repo"}
+
+
+async def test_setup_failure_surfaces_actionable_message(tool, session):
+ """A webhook-setup InvalidInputError (e.g. no enabled events) surfaces its
+ specific reason, not a generic error."""
+ graph = _make_graph(manual=True)
+ ctxs, setup_mock = _patches(graph)
+ setup_mock.side_effect = InvalidInputError(
+ "Could not set up webhook: Cannot set up github webhook without any "
+ "enabled events in event filter input 'events'"
+ )
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
+ result = await tool._execute(
+ user_id=_USER, session=session, name="My Trigger", graph_id="graph-1"
+ )
+
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "trigger_setup_failed"
+ assert "without any enabled events" in result.message
+
+
+async def test_setup_failure_webhook_registration_error(tool, session):
+ """A provider registration failure (WebhookRegistrationError, e.g. GitHub
+ refused the repo) surfaces its reason instead of the generic fallback."""
+ graph = _make_graph(manual=True)
+ ctxs, setup_mock = _patches(graph)
+ setup_mock.side_effect = WebhookRegistrationError(
+ "Failed to register webhook: repository not found"
+ )
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
+ result = await tool._execute(
+ user_id=_USER, session=session, name="My Trigger", graph_id="graph-1"
+ )
+
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "trigger_setup_failed"
+ assert "repository not found" in result.message
+
+
+async def test_setup_failure_graph_deleted_midway(tool, session):
+ """If the graph is deleted between resolve and preset creation,
+ setup_triggered_preset raises NotFoundError — caught as a clean failure."""
+ graph = _make_graph(manual=True)
+ ctxs, setup_mock = _patches(graph)
+ setup_mock.side_effect = NotFoundError("Graph #graph-1 is not accessible (anymore)")
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
+ result = await tool._execute(
+ user_id=_USER, session=session, name="My Trigger", graph_id="graph-1"
+ )
+
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "trigger_setup_failed"
+ assert "not accessible" in result.message
+
+
+async def test_library_agent_id_resolves_and_proceeds(tool, session):
+ """Passing library_agent_id resolves the graph via get_library_agent."""
+ graph = _make_graph(manual=True, regular_credentials={})
+ preset = _make_preset(
+ provider="generic_webhook",
+ url="https://backend.agpt.co/api/integrations/generic_webhook/webhooks/wh-1/ingress",
+ )
+ ctxs, setup_mock = _patches(graph, preset=preset)
+ mock_lib_db = MagicMock()
+ mock_lib_db.get_library_agent = AsyncMock(
+ return_value=MagicMock(graph_id="graph-1", graph_version=1)
+ )
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4], patch(
+ f"{_PATH}.library_db", return_value=mock_lib_db
+ ):
+ result = await tool._execute(
+ user_id=_USER, session=session, name="My Trigger", library_agent_id="lib-1"
+ )
+ assert isinstance(result, TriggerSetupResponse)
+ mock_lib_db.get_library_agent.assert_awaited_once()
+ setup_mock.assert_awaited_once()
+
+
+async def test_library_agent_not_found_returns_error(tool, session):
+ """get_library_agent raising NotFoundError -> clean library_agent_not_found."""
+ graph = _make_graph(manual=True)
+ ctxs, _ = _patches(graph)
+ mock_lib_db = MagicMock()
+ mock_lib_db.get_library_agent = AsyncMock(side_effect=NotFoundError("gone"))
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4], patch(
+ f"{_PATH}.library_db", return_value=mock_lib_db
+ ):
+ result = await tool._execute(
+ user_id=_USER, session=session, name="My Trigger", library_agent_id="lib-1"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "library_agent_not_found"
+
+
+def test_is_filled_treats_falsy_valid_values_as_filled():
+ """0/False are valid provided config values (filled); only None/empty
+ string/dict/list count as unset."""
+ from backend.copilot.tools.setup_agent_webhook_trigger import _is_filled
+
+ assert _is_filled(0) is True
+ assert _is_filled(False) is True
+ assert _is_filled(None) is False
+ assert _is_filled("") is False
+ assert _is_filled({}) is False
+ assert _is_filled([]) is False
diff --git a/autogpt_platform/backend/backend/copilot/tools/test_dry_run.py b/autogpt_platform/backend/backend/copilot/tools/test_dry_run.py
index 602229f381..61327a5ecd 100644
--- a/autogpt_platform/backend/backend/copilot/tools/test_dry_run.py
+++ b/autogpt_platform/backend/backend/copilot/tools/test_dry_run.py
@@ -735,6 +735,7 @@ def _make_graph_mock(graph_id: str = "g1") -> MagicMock:
graph.input_schema = {"type": "object", "properties": {}, "required": []}
graph.credentials_input_schema = {"type": "object", "properties": {}}
graph.trigger_setup_info = None
+ graph.has_external_trigger = False
return graph
diff --git a/autogpt_platform/backend/backend/copilot/tools/test_session_dry_run.py b/autogpt_platform/backend/backend/copilot/tools/test_session_dry_run.py
index 5f8e72a6f3..bf8bae4c1c 100644
--- a/autogpt_platform/backend/backend/copilot/tools/test_session_dry_run.py
+++ b/autogpt_platform/backend/backend/copilot/tools/test_session_dry_run.py
@@ -180,6 +180,7 @@ class TestRunAgentToolSessionDryRun:
mock_graph.description = "A test agent"
mock_graph.input_schema = {"properties": {}, "required": []}
mock_graph.trigger_setup_info = None
+ mock_graph.has_external_trigger = False
mock_library_agent = MagicMock()
mock_library_agent.id = "lib-1"
diff --git a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
index 4c89094f4a..6639e0c6e8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
@@ -74,12 +74,20 @@ from backend.copilot.tools import TOOL_REGISTRY
# a new ``agent_id`` parameter (library_agent_id / graph_id) that resolves the
# exact agent with no fuzzy name-search fallback, so the library "Chat" flow is
# reliable without a separate tool. Net smaller than a dedicated tool would add.
-# Bumped 41000 -> 43000 for the proactive chat-platform tools
-# (post_to_chat_platform + list_chat_platform_channels): one platform-enum pair
-# instead of per-platform tools. Descriptions are already trimmed to the minimum
-# viable copy (~1400 chars for both schemas); the base had reached ~40.5k of the
-# 41k cap, leaving no headroom, so the bump also restores margin for drift.
-_CHAR_BUDGET = 43_000
+# Bumped 41000 -> 42500 for the setup_agent_webhook_trigger tool (OPEN-3152). Adds
+# ~1.3k chars: identifier + trigger_config + explicit-credentials schema
+# and the "manual webhooks return an exact URL / provider webhooks need
+# an explicitly chosen account" copy the model needs to drive webhook
+# trigger setup without inventing URLs or auto-picking credentials.
+# Bumped 42500 -> 45000 for the preset-management tools (list_presets /
+# update_preset / delete_preset) that complete the /presets lifecycle for
+# AutoPilot. Adds ~1.6k chars: three tool skeletons plus the "is_active
+# pauses/resumes the trigger" + "inputs reconfigure & re-register the webhook"
+# copy the model needs to manage triggers without re-running setup.
+# Bumped 45000 -> 47000 on the dev merge: dev added the proactive chat-platform
+# tools (post_to_chat_platform + list_chat_platform_channels, ~1.4k chars) on top
+# of the trigger/preset tools above, so the merged registry needs both deltas.
+_CHAR_BUDGET = 47_000
@pytest.fixture(scope="module")
diff --git a/autogpt_platform/backend/backend/data/db_accessors.py b/autogpt_platform/backend/backend/data/db_accessors.py
index 91a7d23a5e..f5508f4b9a 100644
--- a/autogpt_platform/backend/backend/data/db_accessors.py
+++ b/autogpt_platform/backend/backend/data/db_accessors.py
@@ -53,6 +53,19 @@ def store_db():
return store_db
+def triggers_db():
+ if db.is_connected():
+ from backend.api.features.library import triggers as _triggers_db
+
+ triggers_db = _triggers_db
+ else:
+ from backend.util.clients import get_database_manager_async_client
+
+ triggers_db = get_database_manager_async_client()
+
+ return triggers_db
+
+
def search():
if db.is_connected():
from backend.api.features.search import hybrid_search as _search
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index 9c47ab6f39..ec072d9da3 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -8,19 +8,28 @@ from backend.api.features.library.db import (
create_folder,
create_graph_in_library,
create_library_agent,
+ create_preset,
delete_folder,
get_folder_agents_map,
get_folder_tree,
get_library_agent,
get_library_agent_by_graph_id,
+ get_preset,
get_root_agent_summaries,
list_folders,
list_library_agents,
+ list_presets,
+ list_trigger_agents,
move_folder,
update_folder,
update_graph_in_library,
update_library_agent,
)
+from backend.api.features.library.triggers import (
+ delete_preset_with_webhook_cleanup,
+ setup_triggered_preset,
+ update_triggered_preset,
+)
from backend.api.features.search.embeddings import (
cleanup_orphaned_embeddings,
get_embedding_stats,
@@ -306,6 +315,13 @@ class DatabaseManager(AppService):
update_library_agent = _(update_library_agent)
update_graph_in_library = _(update_graph_in_library)
validate_graph_execution_permissions = _(validate_graph_execution_permissions)
+ setup_triggered_preset = _(setup_triggered_preset)
+ update_triggered_preset = _(update_triggered_preset)
+ delete_preset_with_webhook_cleanup = _(delete_preset_with_webhook_cleanup)
+ get_preset = _(get_preset)
+ create_preset = _(create_preset)
+ list_presets = _(list_presets)
+ list_trigger_agents = _(list_trigger_agents)
create_folder = _(create_folder)
list_folders = _(list_folders)
@@ -572,6 +588,13 @@ class DatabaseManagerAsyncClient(AppServiceClient):
update_library_agent = d.update_library_agent
update_graph_in_library = d.update_graph_in_library
validate_graph_execution_permissions = d.validate_graph_execution_permissions
+ setup_triggered_preset = d.setup_triggered_preset
+ update_triggered_preset = d.update_triggered_preset
+ delete_preset_with_webhook_cleanup = d.delete_preset_with_webhook_cleanup
+ get_preset = d.get_preset
+ create_preset = d.create_preset
+ list_presets = d.list_presets
+ list_trigger_agents = d.list_trigger_agents
# ============ Library Folders ============ #
create_folder = d.create_folder
diff --git a/autogpt_platform/backend/backend/integrations/webhooks/_base.py b/autogpt_platform/backend/backend/integrations/webhooks/_base.py
index 7daf0dc6de..95981b41d5 100644
--- a/autogpt_platform/backend/backend/integrations/webhooks/_base.py
+++ b/autogpt_platform/backend/backend/integrations/webhooks/_base.py
@@ -10,7 +10,7 @@ from strenum import StrEnum
import backend.data.integrations as integrations
from backend.data.model import Credentials
from backend.integrations.providers import ProviderName
-from backend.util.exceptions import MissingConfigError
+from backend.util.exceptions import MissingConfigError, WebhookRegistrationError
from backend.util.settings import Config
from .utils import webhook_ingress_url
@@ -211,9 +211,16 @@ class BaseWebhooksManager(ABC, Generic[WT]):
if register:
if not credentials:
raise TypeError("credentials are required if register = True")
- provider_webhook_id, config = await self._register_webhook(
- credentials, webhook_type, resource, events, ingress_url, secret
- )
+ try:
+ provider_webhook_id, config = await self._register_webhook(
+ credentials, webhook_type, resource, events, ingress_url, secret
+ )
+ except Exception as e:
+ if isinstance(e, WebhookRegistrationError):
+ raise
+ raise WebhookRegistrationError(
+ f"Failed to register webhook: {e}"
+ ) from e
else:
provider_webhook_id, config = "", {}
diff --git a/autogpt_platform/backend/backend/integrations/webhooks/github.py b/autogpt_platform/backend/backend/integrations/webhooks/github.py
index a4f74249f5..ef9bd9c680 100644
--- a/autogpt_platform/backend/backend/integrations/webhooks/github.py
+++ b/autogpt_platform/backend/backend/integrations/webhooks/github.py
@@ -8,6 +8,7 @@ from strenum import StrEnum
from backend.data import integrations
from backend.data.model import Credentials
from backend.integrations.providers import ProviderName
+from backend.util.exceptions import NotAuthorizedError, NotFoundError
from backend.util.request import Requests, Response
from ._base import BaseWebhooksManager
@@ -113,7 +114,7 @@ class GithubWebhooksManager(BaseWebhooksManager):
},
}
- response = await Requests().post(
+ response = await Requests(raise_for_status=False).post(
f"{self.GITHUB_API_URL}/repos/{resource}/hooks",
headers=headers,
json=webhook_data,
@@ -121,13 +122,19 @@ class GithubWebhooksManager(BaseWebhooksManager):
if response.status != 201:
error_msg = extract_github_error_msg(response)
- if "not found" in error_msg.lower():
- error_msg = (
- f"{error_msg} "
- "(Make sure the GitHub account or API key has 'repo' or "
- f"webhook create permissions to '{resource}')"
+ if response.status == 404:
+ raise NotFoundError(
+ f"GitHub repository '{resource}' was not found, or the "
+ "selected account doesn't have access to it: "
+ f"{error_msg}"
)
- raise ValueError(f"Failed to create GitHub webhook: {error_msg}")
+ if response.status in (401, 403):
+ raise NotAuthorizedError(
+ "The selected GitHub account isn't allowed to create "
+ f"webhooks on '{resource}' — admin access to the repository "
+ f"is required: {error_msg}"
+ )
+ raise ValueError(f"GitHub returned error: {error_msg}")
resp = response.json()
webhook_id = resp["id"]
diff --git a/autogpt_platform/backend/backend/integrations/webhooks/slant3d.py b/autogpt_platform/backend/backend/integrations/webhooks/slant3d.py
index 059f0ada09..049e94f87e 100644
--- a/autogpt_platform/backend/backend/integrations/webhooks/slant3d.py
+++ b/autogpt_platform/backend/backend/integrations/webhooks/slant3d.py
@@ -39,13 +39,13 @@ class Slant3DWebhooksManager(BaseWebhooksManager):
# Slant3D's API doesn't use events list, just register for all order updates
payload = {"endPoint": ingress_url}
- response = await Requests().post(
+ response = await Requests(raise_for_status=False).post(
f"{self.BASE_URL}/customer/webhookSubscribe", headers=headers, json=payload
)
if not response.ok:
error = response.json().get("error", "Unknown error")
- raise RuntimeError(f"Failed to register webhook: {error}")
+ raise ValueError(f"Slant3D returned error: {error}")
webhook_config = {
"endpoint": ingress_url,
diff --git a/autogpt_platform/backend/backend/integrations/webhooks/telegram.py b/autogpt_platform/backend/backend/integrations/webhooks/telegram.py
index aae1a5aaa3..7a9d3fdf47 100644
--- a/autogpt_platform/backend/backend/integrations/webhooks/telegram.py
+++ b/autogpt_platform/backend/backend/integrations/webhooks/telegram.py
@@ -204,7 +204,7 @@ class TelegramWebhooksManager(BaseWebhooksManager):
if not result.get("ok"):
error_desc = result.get("description", "Unknown error")
- raise ValueError(f"Failed to set Telegram webhook: {error_desc}")
+ raise ValueError(f"Telegram returned error: {error_desc}")
# Telegram doesn't return a webhook ID, use empty string
config = {
diff --git a/autogpt_platform/backend/backend/util/exceptions.py b/autogpt_platform/backend/backend/util/exceptions.py
index c9bd0670ed..30d804b0f5 100644
--- a/autogpt_platform/backend/backend/util/exceptions.py
+++ b/autogpt_platform/backend/backend/util/exceptions.py
@@ -176,3 +176,7 @@ class LinkFlowMismatchError(ValueError):
class DuplicateChatMessageError(ValueError):
"""The same user message is already in flight for this chat session."""
+
+
+class WebhookRegistrationError(Exception):
+ """Registering a webhook with an external service failed."""
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts
index e1aefe1c68..ba211dc474 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts
@@ -4,6 +4,8 @@ import {
buildRenderSegments,
extractWorkspaceArtifacts,
filePartToArtifactRef,
+ getMessageArtifacts,
+ getMostRecentArtifact,
isCompletedToolPart,
isInteractiveToolPart,
isReasoningToolPart,
@@ -13,7 +15,7 @@ import {
splitReasoningAndResponse,
} from "../helpers";
import type { MessagePart } from "../helpers";
-import type { FileUIPart } from "ai";
+import type { FileUIPart, UIDataTypes, UIMessage, UITools } from "ai";
import type { TodoItem } from "../../ContextPanel/components/ProgressTab/helpers";
function textPart(text: string): MessagePart {
@@ -580,6 +582,26 @@ describe("splitReasoningAndResponse", () => {
expect(result.response[0]).toBe(corruptedRunBlock);
});
+ it("pins the trigger-setup card even when reasoning follows it", () => {
+ // Regression: setup_agent_webhook_trigger emits a trigger_setup card, then
+ // the model adds a trailing reasoning part before its text reply. The card
+ // must stay pinned to the response so it never gets buried in "Show steps".
+ const triggerSetup = toolPart(
+ "setup_agent_webhook_trigger",
+ "output-available",
+ JSON.stringify({ type: "trigger_setup", message: "Trigger is set up." }),
+ );
+ const parts = [
+ triggerSetup,
+ reasoningPart("The webhook trigger has been set up successfully..."),
+ textPart("The webhook trigger is live!"),
+ ];
+ const result = splitReasoningAndResponse(parts);
+ expect(result.reasoning).toEqual([parts[1]]);
+ expect(result.response).toHaveLength(2);
+ expect(result.response[0]).toBe(triggerSetup);
+ });
+
it("keeps card-capable tools with valid non-interactive output in reasoning", () => {
const okRunBlock = toolPart(
"run_block",
@@ -771,6 +793,89 @@ describe("filePartToArtifactRef with custom pattern", () => {
});
});
+type Message = UIMessage<unknown, UIDataTypes, UITools>;
+
+const FILE_A = "550e8400-e29b-41d4-a716-446655440000";
+const FILE_B = "660e8400-e29b-41d4-a716-446655440111";
+
+function message(role: Message["role"], parts: MessagePart[]): Message {
+ return { id: `m-${role}`, role, parts } as unknown as Message;
+}
+
+function filePart(fileId: string, filename: string): MessagePart {
+ return {
+ type: "file",
+ filename,
+ mediaType: "image/png",
+ url: `/api/proxy/api/workspace/files/${fileId}/download`,
+ } as unknown as MessagePart;
+}
+
+describe("getMessageArtifacts", () => {
+ it("collects file-part artifacts before text artifacts", () => {
+ const msg = message("assistant", [
+ filePart(FILE_A, "from-file.png"),
+ textPart(`Here is [doc](workspace://${FILE_B})`),
+ ]);
+ const out = getMessageArtifacts(msg);
+ expect(out.map((a) => a.id)).toEqual([FILE_A, FILE_B]);
+ expect(out[0].title).toBe("from-file.png");
+ });
+
+ it("does not double-count a file referenced as both a file part and in text", () => {
+ const msg = message("assistant", [
+ filePart(FILE_A, "rich.png"),
+ textPart(`[again](workspace://${FILE_A})`),
+ ]);
+ const out = getMessageArtifacts(msg);
+ expect(out).toHaveLength(1);
+ // File-part metadata wins over the text-derived entry.
+ expect(out[0].title).toBe("rich.png");
+ });
+
+ it("marks user-uploaded files with the user-upload origin", () => {
+ const msg = message("user", [filePart(FILE_A, "upload.png")]);
+ expect(getMessageArtifacts(msg)[0].origin).toBe("user-upload");
+ });
+});
+
+describe("getMostRecentArtifact", () => {
+ it("returns null when there are no artifacts", () => {
+ expect(
+ getMostRecentArtifact([message("assistant", [textPart("hi")])]),
+ ).toBeNull();
+ });
+
+ it("returns the last file-part artifact scanning from the end", () => {
+ const messages = [
+ message("assistant", [filePart(FILE_A, "old.png")]),
+ message("assistant", [filePart(FILE_B, "new.png")]),
+ ];
+ expect(getMostRecentArtifact(messages)?.id).toBe(FILE_B);
+ });
+
+ it("finds the most recent text-derived artifact", () => {
+ const messages = [
+ message("assistant", [textPart(`[a](workspace://${FILE_A})`)]),
+ ];
+ expect(getMostRecentArtifact(messages)?.id).toBe(FILE_A);
+ });
+
+ it("filters by origin when requested", () => {
+ const messages = [
+ message("user", [filePart(FILE_A, "upload.png")]),
+ message("assistant", [textPart(`[b](workspace://${FILE_B})`)]),
+ ];
+ // Only agent-origin artifacts are eligible; the latest such one wins.
+ expect(getMostRecentArtifact(messages, { origin: "agent" })?.id).toBe(
+ FILE_B,
+ );
+ expect(getMostRecentArtifact(messages, { origin: "user-upload" })?.id).toBe(
+ FILE_A,
+ );
+ });
+});
+
describe("shouldShowTaskListNotice", () => {
const activeTodos: TodoItem[] = [
{ content: "Step 1", status: "in_progress" },
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
index bc4ab3cfd8..3f02acc7d4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx
@@ -21,6 +21,7 @@ import { RunAgentTool } from "../../../tools/RunAgent/RunAgent";
import { RunBlockTool } from "../../../tools/RunBlock/RunBlock";
import { RunMCPToolComponent } from "../../../tools/RunMCPTool/RunMCPTool";
import { SearchDocsTool } from "../../../tools/SearchDocs/SearchDocs";
+import { SetupTriggerTool } from "../../../tools/SetupTrigger/SetupTrigger";
import { ViewAgentOutputTool } from "../../../tools/ViewAgentOutput/ViewAgentOutput";
import {
extractWorkspaceArtifacts,
@@ -217,6 +218,8 @@ export function MessagePartRenderer({
case "tool-run_agent":
case "tool-schedule_agent":
return <RunAgentTool key={key} part={part as ToolUIPart} />;
+ case "tool-setup_agent_webhook_trigger":
+ return <SetupTriggerTool key={key} part={part as ToolUIPart} />;
case "tool-decompose_goal":
return <DecomposeGoalTool key={key} part={part as ToolUIPart} />;
case "tool-create_agent":
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/MessagePartRenderer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/MessagePartRenderer.test.tsx
index fc51104bd4..150ef9666e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/MessagePartRenderer.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/MessagePartRenderer.test.tsx
@@ -11,10 +11,34 @@ vi.mock("../ReasoningCollapse", () => ({
),
}));
+// The real MessageResponse renders markdown via Streamdown, passing the custom
+// `components.img` override (WorkspaceMediaImage) down. We exercise that override
+// directly so its video/image/empty-src branches are covered.
+type ImgComponent = (
+ props: React.JSX.IntrinsicElements["img"],
+) => React.ReactNode;
vi.mock("@/components/ai-elements/message", () => ({
- MessageResponse: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="message-response">{children}</div>
- ),
+ MessageResponse: ({
+ children,
+ components,
+ }: {
+ children: React.ReactNode;
+ components?: { img?: ImgComponent };
+ }) => {
+ const Img = components?.img;
+ return (
+ <div data-testid="message-response">
+ {children}
+ {Img ? (
+ <div data-testid="custom-img-outputs">
+ {Img({ src: "/v.mp4", alt: "video:Clip" })}
+ {Img({ src: "/p.png", alt: "Pic" })}
+ {Img({ src: "", alt: "missing" })}
+ </div>
+ ) : null}
+ </div>
+ );
+ },
}));
vi.mock("@/components/molecules/ErrorCard/ErrorCard", () => ({
@@ -31,35 +55,74 @@ vi.mock("@phosphor-icons/react", async (importOriginal) => {
return { ...actual, ExclamationMarkIcon: () => null };
});
-const stub = (name: string) => ({ [name]: () => null });
-vi.mock("../../ArtifactCard/ArtifactCard", () => stub("ArtifactCard"));
-vi.mock("../../../tools/AskQuestion/AskQuestion", () =>
- stub("AskQuestionTool"),
+vi.mock("../StoppedTaskCard", () => ({
+ StoppedTaskCard: () => <div data-testid="stopped-task-card" />,
+}));
+
+function stubTool(name: string, testid: string) {
+ return { [name]: () => <div data-testid={testid} /> };
+}
+vi.mock("../../../../components/ArtifactCard/ArtifactCard", () => ({
+ ArtifactCard: () => <div data-testid="artifact-card" />,
+}));
+vi.mock("../../../../tools/AskQuestion/AskQuestion", () =>
+ stubTool("AskQuestionTool", "tool-ask-question"),
+);
+vi.mock("../../../../tools/ConnectIntegrationTool/ConnectIntegrationTool", () =>
+ stubTool("ConnectIntegrationTool", "tool-connect-integration"),
);
-vi.mock("../../../tools/ConnectIntegrationTool/ConnectIntegrationTool", () =>
- stub("ConnectIntegrationTool"),
+vi.mock("../../../../tools/CreateAgent/CreateAgent", () =>
+ stubTool("CreateAgentTool", "tool-create-agent"),
);
-vi.mock("../../../tools/CreateAgent/CreateAgent", () =>
- stub("CreateAgentTool"),
+vi.mock("../../../../tools/DecomposeGoal/DecomposeGoal", () =>
+ stubTool("DecomposeGoalTool", "tool-decompose-goal"),
);
-vi.mock("../../../tools/EditAgent/EditAgent", () => stub("EditAgentTool"));
-vi.mock("../../../tools/FeatureRequests/FeatureRequests", () => ({
- CreateFeatureRequestTool: () => null,
- SearchFeatureRequestsTool: () => null,
+vi.mock("../../../../tools/EditAgent/EditAgent", () =>
+ stubTool("EditAgentTool", "tool-edit-agent"),
+);
+vi.mock("../../../../tools/FeatureRequests/FeatureRequests", () => ({
+ CreateFeatureRequestTool: () => <div data-testid="tool-create-fr" />,
+ SearchFeatureRequestsTool: () => <div data-testid="tool-search-fr" />,
}));
-vi.mock("../../../tools/FindAgents/FindAgents", () => stub("FindAgentsTool"));
-vi.mock("../../../tools/FolderTool/FolderTool", () => stub("FolderTool"));
-vi.mock("../../../tools/FindBlocks/FindBlocks", () => stub("FindBlocksTool"));
-vi.mock("../../../tools/GenericTool/GenericTool", () => stub("GenericTool"));
-vi.mock("../../../tools/RunAgent/RunAgent", () => stub("RunAgentTool"));
-vi.mock("../../../tools/RunBlock/RunBlock", () => stub("RunBlockTool"));
-vi.mock("../../../tools/RunMCPTool/RunMCPTool", () =>
- stub("RunMCPToolComponent"),
+vi.mock("../../../../tools/FindAgents/FindAgents", () =>
+ stubTool("FindAgentsTool", "tool-find-agents"),
+);
+vi.mock("../../../../tools/FolderTool/FolderTool", () =>
+ stubTool("FolderTool", "tool-folder"),
);
-vi.mock("../../../tools/SearchDocs/SearchDocs", () => stub("SearchDocsTool"));
-vi.mock("../../../tools/ViewAgentOutput/ViewAgentOutput", () =>
- stub("ViewAgentOutputTool"),
+vi.mock("../../../../tools/FindBlocks/FindBlocks", () =>
+ stubTool("FindBlocksTool", "tool-find-blocks"),
);
+vi.mock("../../../../tools/GenericTool/GenericTool", () =>
+ stubTool("GenericTool", "tool-generic"),
+);
+vi.mock("../../../../tools/RunAgent/RunAgent", () =>
+ stubTool("RunAgentTool", "tool-run-agent"),
+);
+vi.mock("../../../../tools/RunBlock/RunBlock", () =>
+ stubTool("RunBlockTool", "tool-run-block"),
+);
+vi.mock("../../../../tools/RunMCPTool/RunMCPTool", () =>
+ stubTool("RunMCPToolComponent", "tool-run-mcp"),
+);
+vi.mock("../../../../tools/SearchDocs/SearchDocs", () =>
+ stubTool("SearchDocsTool", "tool-search-docs"),
+);
+vi.mock("../../../../tools/SetupTrigger/SetupTrigger", () =>
+ stubTool("SetupTriggerTool", "tool-setup-trigger"),
+);
+vi.mock("../../../../tools/ViewAgentOutput/ViewAgentOutput", () =>
+ stubTool("ViewAgentOutputTool", "tool-view-agent-output"),
+);
+
+function toolPart(type: string): Part {
+ return {
+ type,
+ state: "output-available",
+ toolCallId: `call-${type}`,
+ output: {},
+ } as unknown as Part;
+}
describe("MessagePartRenderer reasoning branch", () => {
afterEach(() => {
@@ -133,3 +196,132 @@ describe("MessagePartRenderer reasoning branch", () => {
expect(pre?.textContent).toBe(" reasoning-with-pad ");
});
});
+
+describe("MessagePartRenderer text branch", () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ it("renders plain text through the MessageResponse renderer", () => {
+ const part = { type: "text", text: "hello world" } as unknown as Part;
+ render(<MessagePartRenderer part={part} messageID="m1" partIndex={0} />);
+ expect(screen.getByTestId("message-response").textContent).toContain(
+ "hello world",
+ );
+ });
+
+ it("renders a <video> for video: alt, an <img> for image alt, and nothing for empty src", () => {
+ const part = { type: "text", text: "media" } as unknown as Part;
+ const { container } = render(
+ <MessagePartRenderer part={part} messageID="m1" partIndex={0} />,
+ );
+ const outputs = screen.getByTestId("custom-img-outputs");
+ // video: alt -> <video><source/></video>
+ expect(outputs.querySelector("video source")?.getAttribute("src")).toBe(
+ "/v.mp4",
+ );
+ // normal alt -> <img>
+ const img = outputs.querySelector("img");
+ expect(img?.getAttribute("src")).toBe("/p.png");
+ expect(img?.getAttribute("alt")).toBe("Pic");
+ // empty src -> render nothing extra (only the one video + one img above)
+ expect(container.querySelectorAll("img")).toHaveLength(1);
+ });
+
+ it("renders inline ArtifactCards when artifacts are forced on", () => {
+ const fileId = "550e8400-e29b-41d4-a716-446655440000";
+ const part = {
+ type: "text",
+ text: `Here is [report](workspace://${fileId}).`,
+ } as unknown as Part;
+ render(
+ <MessagePartRenderer
+ part={part}
+ messageID="m1"
+ partIndex={0}
+ forceArtifacts
+ />,
+ );
+ expect(screen.getByTestId("artifact-card")).toBeDefined();
+ });
+
+ it("renders the StoppedTaskCard for a cancellation marker", () => {
+ const part = {
+ type: "text",
+ text: "[__COPILOT_ERROR_f7a1__] Operation cancelled",
+ } as unknown as Part;
+ render(<MessagePartRenderer part={part} messageID="m1" partIndex={0} />);
+ expect(screen.getByTestId("stopped-task-card")).toBeDefined();
+ });
+
+ it("renders a system-marker note", () => {
+ const part = {
+ type: "text",
+ text: "[__COPILOT_SYSTEM_e3b0__] Reconnected to the session",
+ } as unknown as Part;
+ render(<MessagePartRenderer part={part} messageID="m1" partIndex={0} />);
+ expect(screen.getByText("Reconnected to the session")).toBeDefined();
+ });
+});
+
+describe("MessagePartRenderer tool dispatch", () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ it.each([
+ ["tool-ask_question", "tool-ask-question"],
+ ["tool-find_block", "tool-find-blocks"],
+ ["tool-find_agent", "tool-find-agents"],
+ ["tool-find_library_agent", "tool-find-agents"],
+ ["tool-search_docs", "tool-search-docs"],
+ ["tool-get_doc_page", "tool-search-docs"],
+ ["tool-connect_integration", "tool-connect-integration"],
+ ["tool-run_block", "tool-run-block"],
+ ["tool-continue_run_block", "tool-run-block"],
+ ["tool-run_mcp_tool", "tool-run-mcp"],
+ ["tool-run_agent", "tool-run-agent"],
+ ["tool-schedule_agent", "tool-run-agent"],
+ ["tool-setup_agent_webhook_trigger", "tool-setup-trigger"],
+ ["tool-decompose_goal", "tool-decompose-goal"],
+ ["tool-create_agent", "tool-create-agent"],
+ ["tool-edit_agent", "tool-edit-agent"],
+ ["tool-view_agent_output", "tool-view-agent-output"],
+ ["tool-search_feature_requests", "tool-search-fr"],
+ ["tool-create_feature_request", "tool-create-fr"],
+ ["tool-create_folder", "tool-folder"],
+ ["tool-list_folders", "tool-folder"],
+ ["tool-update_folder", "tool-folder"],
+ ["tool-move_folder", "tool-folder"],
+ ["tool-delete_folder", "tool-folder"],
+ ["tool-move_agents_to_folder", "tool-folder"],
+ ])("dispatches %s to its renderer", (type, testid) => {
+ render(
+ <MessagePartRenderer
+ part={toolPart(type)}
+ messageID="m1"
+ partIndex={0}
+ />,
+ );
+ expect(screen.getByTestId(testid)).toBeDefined();
+ });
+
+ it("renders the GenericTool for an unrecognised tool- type", () => {
+ render(
+ <MessagePartRenderer
+ part={toolPart("tool-some_builtin")}
+ messageID="m1"
+ partIndex={0}
+ />,
+ );
+ expect(screen.getByTestId("tool-generic")).toBeDefined();
+ });
+
+ it("returns null for a non-tool, non-text/reasoning part type", () => {
+ const part = { type: "step-start" } as unknown as Part;
+ const { container } = render(
+ <MessagePartRenderer part={part} messageID="m1" partIndex={0} />,
+ );
+ expect(container.firstChild).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts
index 68ce6d351d..a7e9b29958 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts
@@ -38,12 +38,14 @@ const CUSTOM_TOOL_TYPES = new Set([
"tool-find_library_agent",
"tool-search_docs",
"tool-get_doc_page",
+ "tool-connect_integration",
"tool-run_block",
"tool-continue_run_block",
"tool-connect_integration",
"tool-run_mcp_tool",
"tool-run_agent",
"tool-schedule_agent",
+ "tool-setup_agent_webhook_trigger",
"tool-create_agent",
"tool-edit_agent",
"tool-view_agent_output",
@@ -81,6 +83,7 @@ const WORKSPACE_URI_PATTERN = /workspace:\/\/([a-f0-9-]+)(?:#([^\s)\]]+))?/g;
const INTERACTIVE_RESPONSE_TYPES: ReadonlySet<string> = new Set([
ResponseType.setup_requirements,
+ ResponseType.trigger_setup,
ResponseType.agent_details,
ResponseType.block_details,
ResponseType.review_required,
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx
index 697f2cbc65..92287fa26b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/SetupRequirementsCard.tsx
@@ -22,6 +22,7 @@ import {
buildExpectedInputsSchema,
buildPreviewRunMessage,
buildRunMessage,
+ buildTriggerSetupMessage,
buildSiblingInputsFromCredentials,
checkAllCredentialsComplete,
checkAllInputsComplete,
@@ -45,12 +46,15 @@ import {
* - `inputsMode = "preview"`: renders inputs as a read-only list
* (name • type, Required/Optional badge). Used by run_agent because graph
* inputs are set in the graph definition, not from the chat.
+ * - `inputsMode = "trigger"`: like "preview", but `Proceed` carries the chosen
+ * credential IDs back so the webhook is registered under the account the user
+ * explicitly picked. Used by setup_agent_webhook_trigger.
*/
interface Props {
output: SetupRequirementsResponse;
retryInstruction?: string;
credentialsLabel?: string;
- inputsMode?: "edit" | "preview";
+ inputsMode?: "edit" | "preview" | "trigger";
onComplete?: () => void;
}
@@ -187,14 +191,17 @@ export function SetupRequirementsCard({
.markConnected({ sessionID, providers: requestedProviders });
}
onComplete?.();
- const message = isEditMode
- ? buildRunMessage(
- needsCredentials,
- needsInputs,
- inputValues,
- retryInstruction,
- )
- : buildPreviewRunMessage(needsCredentials);
+ const message =
+ inputsMode === "trigger"
+ ? buildTriggerSetupMessage(inputCredentials)
+ : isEditMode
+ ? buildRunMessage(
+ needsCredentials,
+ needsInputs,
+ inputValues,
+ retryInstruction,
+ )
+ : buildPreviewRunMessage(needsCredentials);
onSend(message);
if (isEditMode) setInputValues({});
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsx
index 9fdbc7ea1c..2b601217e3 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/__tests__/SetupRequirementsCard.test.tsx
@@ -19,8 +19,26 @@ vi.mock("../../CopilotChatActionsProvider/useCopilotChatActions", () => ({
vi.mock(
"@/components/contextual/CredentialsInput/components/CredentialsGroupedView/CredentialsGroupedView",
() => ({
- CredentialsGroupedView: () => (
- <div data-testid="credentials-grouped-view">Credentials</div>
+ CredentialsGroupedView: ({
+ requiredCredentials,
+ onCredentialChange,
+ }: {
+ requiredCredentials: Set<string>;
+ onCredentialChange: (key: string, value?: { id: string }) => void;
+ }) => (
+ <div data-testid="credentials-grouped-view">
+ Credentials
+ <button
+ data-testid="select-credential"
+ onClick={() =>
+ [...requiredCredentials].forEach((key) =>
+ onCredentialChange(key, { id: `cred-${key}` }),
+ )
+ }
+ >
+ Select
+ </button>
+ </div>
),
}),
);
@@ -603,3 +621,35 @@ describe("SetupRequirementsCard (session-scoped dismissal)", () => {
await waitFor(() => expect(mockOnSend).toHaveBeenCalledOnce());
});
});
+
+describe("SetupRequirementsCard (trigger mode)", () => {
+ it("carries the picked credential IDs back on Proceed", () => {
+ render(
+ <SetupRequirementsCard
+ inputsMode="trigger"
+ credentialsLabel="Account"
+ output={makeOutput({
+ missingCredentials: {
+ github_credentials: { provider: "github", types: ["api_key"] },
+ },
+ })}
+ />,
+ );
+
+ // Trigger mode labels the credentials section "Account".
+ expect(screen.getByText("Account")).toBeDefined();
+
+ // Proceed stays disabled until a credential is selected.
+ expect(screen.getByText("Proceed").closest("button")?.disabled).toBe(true);
+
+ fireEvent.click(screen.getByTestId("select-credential"));
+ expect(screen.getByText("Proceed").closest("button")?.disabled).toBe(false);
+
+ fireEvent.click(screen.getByText("Proceed"));
+ const sent = mockOnSend.mock.calls[0][0] as string;
+ expect(sent).toContain("setup_agent_webhook_trigger");
+ expect(sent).toContain(
+ 'credentials={"github_credentials":"cred-github_credentials"}',
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts
index 8bba692f7c..928e204e03 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/SetupRequirementsCard/helpers.ts
@@ -343,3 +343,21 @@ export function buildPreviewRunMessage(needsCredentials: boolean): string {
? "I've configured the required credentials. Please check if everything is ready and proceed with running the agent."
: "Please proceed with running the agent.";
}
+
+/**
+ * Message variant for "trigger" mode (setup_agent_webhook_trigger): the chosen
+ * credential IDs are carried back so the webhook is registered under the
+ * account the user explicitly picked, rather than auto-matched on resume.
+ */
+export function buildTriggerSetupMessage(
+ inputCredentials: Record<string, { id?: string } | undefined>,
+): string {
+ const selected: Record<string, string> = {};
+ for (const [field, cred] of Object.entries(inputCredentials)) {
+ if (cred?.id) selected[field] = cred.id;
+ }
+ return (
+ "I've selected the credentials to use. Call setup_agent_webhook_trigger " +
+ `with credentials=${JSON.stringify(selected)} to finish setting up the trigger.`
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/__tests__/helpers.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/__tests__/helpers.test.tsx
new file mode 100644
index 0000000000..5be4d17e2c
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/__tests__/helpers.test.tsx
@@ -0,0 +1,292 @@
+import { render } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import {
+ AccordionIcon,
+ formatMaybeJson,
+ getAccordionMeta,
+ getAnimationText,
+ getRunAgentToolOutput,
+ isRunAgentAgentDetailsOutput,
+ isRunAgentAgentOutputResponse,
+ isRunAgentErrorOutput,
+ isRunAgentExecutionStartedOutput,
+ isRunAgentNeedLoginOutput,
+ isRunAgentSetupRequirementsOutput,
+ type RunAgentToolOutput,
+ ToolIcon,
+} from "../helpers";
+
+const executionStarted = {
+ type: "execution_started",
+ execution_id: "exec-1",
+ graph_name: "My Graph",
+ status: "running",
+} as unknown as RunAgentToolOutput;
+
+const agentDetails = {
+ type: "agent_details",
+ message: "Inputs needed",
+ agent: { id: "g1", name: "Summariser", inputs: {} },
+} as unknown as RunAgentToolOutput;
+
+const agentDetailsWebhook = {
+ type: "agent_details",
+ message: "Webhook trigger",
+ agent: {
+ id: "g2",
+ name: "PR Notifier",
+ inputs: {},
+ trigger_info: { provider: "github" },
+ },
+} as unknown as RunAgentToolOutput;
+
+const setupRequirements = {
+ type: "setup_requirements",
+ message: "Setup needed",
+ setup_info: {
+ agent_name: "My Agent",
+ user_readiness: { missing_credentials: { gh: {}, openai: {} } },
+ },
+} as unknown as RunAgentToolOutput;
+
+const setupRequirementsNoCreds = {
+ type: "setup_requirements",
+ message: "All set, ready to run",
+ setup_info: { agent_name: "Ready Agent", user_readiness: {} },
+} as unknown as RunAgentToolOutput;
+
+const agentOutput = {
+ type: "agent_output",
+ agent_name: "Output Agent",
+} as unknown as RunAgentToolOutput;
+
+const needLogin = {
+ type: "need_login",
+ message: "Sign in",
+} as unknown as RunAgentToolOutput;
+
+const errorOut = {
+ type: "error",
+ error: "boom",
+} as unknown as RunAgentToolOutput;
+
+describe("type guards", () => {
+ it("identify each output shape", () => {
+ expect(isRunAgentExecutionStartedOutput(executionStarted)).toBe(true);
+ expect(isRunAgentAgentDetailsOutput(agentDetails)).toBe(true);
+ expect(isRunAgentAgentOutputResponse(agentOutput)).toBe(true);
+ expect(isRunAgentSetupRequirementsOutput(setupRequirements)).toBe(true);
+ expect(isRunAgentNeedLoginOutput(needLogin)).toBe(true);
+ expect(isRunAgentErrorOutput(errorOut)).toBe(true);
+ });
+
+ it("match by duck-typed keys as well as the type field", () => {
+ expect(
+ isRunAgentExecutionStartedOutput({ execution_id: "x" } as never),
+ ).toBe(true);
+ expect(isRunAgentAgentDetailsOutput({ agent: {} } as never)).toBe(true);
+ expect(isRunAgentSetupRequirementsOutput({ setup_info: {} } as never)).toBe(
+ true,
+ );
+ expect(isRunAgentErrorOutput({ error: "x" } as never)).toBe(true);
+ });
+});
+
+describe("getRunAgentToolOutput / parseOutput", () => {
+ it("returns null for non-objects and empty output", () => {
+ expect(getRunAgentToolOutput(null)).toBeNull();
+ expect(getRunAgentToolOutput("nope")).toBeNull();
+ expect(getRunAgentToolOutput({})).toBeNull();
+ expect(getRunAgentToolOutput({ output: "" })).toBeNull();
+ expect(getRunAgentToolOutput({ output: " " })).toBeNull();
+ });
+
+ it("parses JSON-string outputs", () => {
+ const parsed = getRunAgentToolOutput({
+ output: JSON.stringify(executionStarted),
+ });
+ expect(parsed && isRunAgentExecutionStartedOutput(parsed)).toBe(true);
+ });
+
+ it("returns null for invalid JSON strings", () => {
+ expect(getRunAgentToolOutput({ output: "{bad" })).toBeNull();
+ });
+
+ it("recognises objects by known type and by duck-typed keys", () => {
+ expect(getRunAgentToolOutput({ output: agentDetails })).not.toBeNull();
+ expect(getRunAgentToolOutput({ output: { details: "x" } })).not.toBeNull();
+ expect(getRunAgentToolOutput({ output: { foo: "bar" } })).toBeNull();
+ });
+});
+
+describe("getAnimationText", () => {
+ it("uses the agent slug while streaming", () => {
+ expect(
+ getAnimationText({
+ state: "input-streaming",
+ input: { username_agent_slug: "me/agent" },
+ }),
+ ).toBe('Running the agent "me/agent"');
+ });
+
+ it("uses the library agent id when no slug is present", () => {
+ expect(
+ getAnimationText({
+ state: "input-available",
+ input: { library_agent_id: "lib-9" },
+ }),
+ ).toBe('Running the agent "Library agent lib-9"');
+ });
+
+ it("uses the scheduling phrase when a schedule is requested", () => {
+ expect(
+ getAnimationText({
+ state: "input-streaming",
+ input: { schedule_name: "daily", cron: "0 0 * * *" },
+ }),
+ ).toBe("Scheduling the agent to run");
+ });
+
+ it("describes an execution_started output", () => {
+ expect(
+ getAnimationText({ state: "output-available", output: executionStarted }),
+ ).toBe('Started "My Graph"');
+ });
+
+ it("describes a webhook-trigger agent_details output", () => {
+ expect(
+ getAnimationText({
+ state: "output-available",
+ output: agentDetailsWebhook,
+ }),
+ ).toBe('Webhook trigger setup for "PR Notifier"');
+ });
+
+ it("describes a non-webhook agent_details output", () => {
+ expect(
+ getAnimationText({ state: "output-available", output: agentDetails }),
+ ).toBe('Agent inputs needed for "Summariser"');
+ });
+
+ it("describes a setup_requirements output", () => {
+ expect(
+ getAnimationText({
+ state: "output-available",
+ output: setupRequirements,
+ }),
+ ).toBe('Setup needed for "My Agent"');
+ });
+
+ it("describes a need_login output", () => {
+ expect(
+ getAnimationText({ state: "output-available", output: needLogin }),
+ ).toBe("Sign in required to run agent");
+ });
+
+ it("falls back to the action phrase when output is unparseable", () => {
+ expect(
+ getAnimationText({ state: "output-available", output: "{bad" }),
+ ).toBe("Running the agent");
+ });
+
+ it("returns the error phrase for an error output and output-error state", () => {
+ expect(
+ getAnimationText({ state: "output-available", output: errorOut }),
+ ).toBe("Something went wrong");
+ expect(getAnimationText({ state: "output-error" })).toBe(
+ "Something went wrong",
+ );
+ });
+
+ it("returns the action phrase for an unknown state", () => {
+ expect(getAnimationText({ state: "unknown" as never })).toBe(
+ "Running the agent",
+ );
+ });
+});
+
+describe("getAccordionMeta", () => {
+ it("uses the graph name and status for execution_started", () => {
+ const meta = getAccordionMeta(executionStarted);
+ expect(meta.title).toBe("My Graph");
+ expect(meta.description).toBe("Status: running");
+ });
+
+ it("defaults the status to started when blank", () => {
+ const meta = getAccordionMeta({
+ type: "execution_started",
+ execution_id: "x",
+ graph_name: "G",
+ status: " ",
+ } as unknown as RunAgentToolOutput);
+ expect(meta.description).toBe("Status: started");
+ });
+
+ it("describes the webhook-trigger agent_details branch", () => {
+ const meta = getAccordionMeta(agentDetailsWebhook);
+ expect(meta.title).toBe("PR Notifier");
+ expect(meta.description).toBe("Webhook trigger setup");
+ });
+
+ it("describes the non-webhook agent_details branch", () => {
+ const meta = getAccordionMeta(agentDetails);
+ expect(meta.description).toBe("Inputs required");
+ });
+
+ it("pluralises the missing-credentials count for setup_requirements", () => {
+ const meta = getAccordionMeta(setupRequirements);
+ expect(meta.title).toBe("My Agent");
+ expect(meta.description).toBe("Missing 2 credentials");
+ });
+
+ it("falls back to the message when no credentials are missing", () => {
+ const meta = getAccordionMeta(setupRequirementsNoCreds);
+ expect(meta.description).toBe("All set, ready to run");
+ });
+
+ it("describes agent_output", () => {
+ const meta = getAccordionMeta(agentOutput);
+ expect(meta.title).toBe("Output Agent");
+ expect(meta.description).toBe("Execution completed");
+ });
+
+ it("describes need_login", () => {
+ expect(getAccordionMeta(needLogin).title).toBe("Sign in required");
+ });
+
+ it("describes an error fallback", () => {
+ const meta = getAccordionMeta(errorOut);
+ expect(meta.title).toBe("Error");
+ expect(meta.titleClassName).toContain("text-red-500");
+ });
+});
+
+describe("formatMaybeJson", () => {
+ it("returns strings as-is", () => {
+ expect(formatMaybeJson("hello")).toBe("hello");
+ });
+
+ it("stringifies objects", () => {
+ expect(formatMaybeJson({ a: 1 })).toBe('{\n "a": 1\n}');
+ });
+
+ it("falls back to String() for non-serialisable values", () => {
+ const circular: Record<string, unknown> = {};
+ circular.self = circular;
+ expect(formatMaybeJson(circular)).toBe("[object Object]");
+ });
+});
+
+describe("icons", () => {
+ it("ToolIcon renders error, streaming and default variants", () => {
+ expect(render(<ToolIcon isError />).container.firstChild).not.toBeNull();
+ expect(
+ render(<ToolIcon isStreaming />).container.firstChild,
+ ).not.toBeNull();
+ expect(render(<ToolIcon />).container.firstChild).not.toBeNull();
+ });
+
+ it("AccordionIcon renders", () => {
+ expect(render(<AccordionIcon />).container.firstChild).not.toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/AgentDetailsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/AgentDetailsCard.tsx
index 0334160804..00f70336c7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/AgentDetailsCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/AgentDetailsCard.tsx
@@ -51,6 +51,19 @@ export function AgentDetailsCard({ output }: Props) {
);
}
+ if (output.agent.trigger_info) {
+ // Informational only — no action button. run_agent hands off to
+ // setup_agent_webhook_trigger (whose own card collects config/credentials
+ // and shows the result), so a "Set up trigger" button here would be
+ // redundant and, once setup has succeeded, a stale backward-pointing CTA.
+ return (
+ <ContentMessage>
+ This agent runs on a webhook trigger, so it can&apos;t be run or
+ scheduled directly — it&apos;s activated by setting up its trigger.
+ </ContentMessage>
+ );
+ }
+
if (!schema) {
return (
<div className="grid gap-2">
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/__tests__/AgentDetailsCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/__tests__/AgentDetailsCard.test.tsx
new file mode 100644
index 0000000000..190928c0bd
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/AgentDetailsCard/__tests__/AgentDetailsCard.test.tsx
@@ -0,0 +1,139 @@
+import type { AgentDetailsResponse } from "@/app/api/__generated__/models/agentDetailsResponse";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { AgentDetailsCard } from "../AgentDetailsCard";
+
+const onSend = vi.fn();
+
+vi.mock(
+ "@/app/(platform)/copilot/components/CopilotChatActionsProvider/useCopilotChatActions",
+ () => ({
+ useCopilotChatActions: () => ({ onSend }),
+ }),
+);
+
+vi.mock("@/components/renderers/InputRenderer/FormRenderer", () => ({
+ FormRenderer: ({
+ handleChange,
+ }: {
+ handleChange: (e: { formData?: Record<string, unknown> }) => void;
+ }) => (
+ <button
+ data-testid="form-change"
+ onClick={() => handleChange({ formData: { topic: "weather" } })}
+ >
+ Fill
+ </button>
+ ),
+}));
+
+afterEach(() => {
+ cleanup();
+ onSend.mockReset();
+});
+
+function webhookOutput(): AgentDetailsResponse {
+ return {
+ type: "agent_details",
+ message: "This agent runs on a webhook trigger.",
+ user_authenticated: true,
+ agent: {
+ id: "g-wh",
+ name: "PR Notifier",
+ description: "Notifies on PRs",
+ inputs: {},
+ execution_options: { manual: false, scheduled: false, webhook: true },
+ trigger_info: {
+ provider: "github",
+ config_schema: {
+ type: "object",
+ properties: { repo: { type: "string" } },
+ required: ["repo"],
+ },
+ credentials_input_name: null,
+ },
+ },
+ } as AgentDetailsResponse;
+}
+
+function nonWebhookOutput(): AgentDetailsResponse {
+ return {
+ type: "agent_details",
+ message: "Ready to run.",
+ user_authenticated: true,
+ agent: {
+ id: "g-run",
+ name: "Summariser",
+ description: "Summarises text",
+ // No configurable inputs -> the run path renders a Proceed button
+ // (avoids FormRenderer, which needs app-level providers).
+ inputs: {},
+ execution_options: { manual: true, scheduled: true, webhook: false },
+ },
+ } as AgentDetailsResponse;
+}
+
+function inputAgentOutput(): AgentDetailsResponse {
+ return {
+ type: "agent_details",
+ message: "Ready to run.",
+ user_authenticated: true,
+ agent: {
+ id: "g-inputs",
+ name: "Topic Agent",
+ description: "Needs a topic",
+ inputs: {
+ properties: {
+ topic: { type: "string", title: "Topic" },
+ },
+ },
+ execution_options: { manual: true, scheduled: false, webhook: false },
+ },
+ } as AgentDetailsResponse;
+}
+
+describe("AgentDetailsCard", () => {
+ it("shows an informational message and no action button for a webhook-trigger agent", () => {
+ render(<AgentDetailsCard output={webhookOutput()} />);
+
+ // Informational message about the webhook trigger is shown...
+ expect(screen.getByText(/webhook trigger/i)).toBeDefined();
+ // ...and there is NO actionable button (no Run/Proceed/Set up trigger) that
+ // could go stale after setup_agent_webhook_trigger already succeeded.
+ expect(screen.queryByRole("button")).toBeNull();
+ });
+
+ it("shows the run path (Proceed), not the webhook card, for a non-webhook agent", () => {
+ render(<AgentDetailsCard output={nonWebhookOutput()} />);
+
+ // Regular run path: the Proceed button is present and there's no
+ // webhook-trigger messaging (the webhook branch must not shadow it).
+ expect(screen.getByRole("button", { name: /proceed/i })).toBeDefined();
+ expect(screen.queryByText(/webhook trigger/i)).toBeNull();
+ });
+
+ it("sends a placeholder-values run message for an input-less agent", () => {
+ render(<AgentDetailsCard output={nonWebhookOutput()} />);
+
+ fireEvent.click(screen.getByRole("button", { name: /proceed/i }));
+ expect(onSend).toHaveBeenCalledWith(
+ 'Run the agent "Summariser" with placeholder/example values so I can test it.',
+ );
+ });
+
+ it("renders the input form and sends collected inputs on Proceed", () => {
+ render(<AgentDetailsCard output={inputAgentOutput()} />);
+
+ // The schema yields a form; Proceed starts disabled until the form is valid.
+ expect(screen.getByText(/Review the inputs below/i)).toBeDefined();
+
+ // Simulate the user filling the form, which flips validity and captures
+ // the new input values.
+ fireEvent.click(screen.getByTestId("form-change"));
+ fireEvent.click(screen.getByRole("button", { name: /proceed/i }));
+
+ expect(onSend).toHaveBeenCalledWith(
+ 'Run the agent "Topic Agent" with these inputs: {\n "topic": "weather"\n}',
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/helpers.tsx
index bdb1a28ac6..703663eac1 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/helpers.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/helpers.tsx
@@ -151,6 +151,9 @@ export function getAnimationText(part: {
return `Started "${output.graph_name}"`;
}
if (isRunAgentAgentDetailsOutput(output)) {
+ if (output.agent.trigger_info) {
+ return `Webhook trigger setup for "${output.agent.name}"`;
+ }
return `Agent inputs needed for "${output.agent.name}"`;
}
if (isRunAgentSetupRequirementsOutput(output)) {
@@ -222,7 +225,9 @@ export function getAccordionMeta(output: RunAgentToolOutput): {
return {
icon,
title: output.agent.name,
- description: "Inputs required",
+ description: output.agent.trigger_info
+ ? "Webhook trigger setup"
+ : "Inputs required",
};
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SetupTrigger/SetupTrigger.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SetupTrigger/SetupTrigger.tsx
new file mode 100644
index 0000000000..f8207d23ee
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SetupTrigger/SetupTrigger.tsx
@@ -0,0 +1,138 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { CheckIcon, CopyIcon } from "@phosphor-icons/react";
+import type { ToolUIPart } from "ai";
+import { useState } from "react";
+import { MorphingTextAnimation } from "../../components/MorphingTextAnimation/MorphingTextAnimation";
+import { SetupRequirementsCard } from "../../components/SetupRequirementsCard/SetupRequirementsCard";
+import { ContentMessage } from "../../components/ToolAccordion/AccordionContent";
+import {
+ getAnimationText,
+ getSetupTriggerToolOutput,
+ isSetupTriggerErrorOutput,
+ isSetupTriggerNeedLoginOutput,
+ isSetupTriggerSetupRequirementsOutput,
+ isTriggerConfigRequiredOutput,
+ isTriggerSetupOutput,
+ ToolIcon,
+ type TriggerSetupOutput,
+} from "./helpers";
+
+interface Props {
+ part: {
+ type: string;
+ state: ToolUIPart["state"];
+ input?: unknown;
+ output?: unknown;
+ };
+}
+
+export function SetupTriggerTool({ part }: Props) {
+ const text = getAnimationText(part);
+ const isStreaming =
+ part.state === "input-streaming" || part.state === "input-available";
+
+ const output = getSetupTriggerToolOutput(part);
+ const isOutputAvailable = part.state === "output-available" && !!output;
+
+ const setupRequirementsOutput =
+ isOutputAvailable && isSetupTriggerSetupRequirementsOutput(output)
+ ? output
+ : null;
+ const successOutput =
+ isOutputAvailable &&
+ !setupRequirementsOutput &&
+ isTriggerSetupOutput(output)
+ ? output
+ : null;
+ const configRequiredOutput =
+ isOutputAvailable && isTriggerConfigRequiredOutput(output) ? output : null;
+ const needLoginOutput =
+ isOutputAvailable && isSetupTriggerNeedLoginOutput(output) ? output : null;
+ const isError =
+ part.state === "output-error" ||
+ (isOutputAvailable && isSetupTriggerErrorOutput(output));
+
+ return (
+ <div className="py-2">
+ {!setupRequirementsOutput &&
+ !successOutput &&
+ !configRequiredOutput &&
+ !needLoginOutput && (
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
+ <ToolIcon isStreaming={isStreaming} isError={isError} />
+ <MorphingTextAnimation
+ text={text}
+ className={isError ? "text-red-500" : undefined}
+ />
+ </div>
+ )}
+
+ {setupRequirementsOutput && (
+ <div className="mt-2">
+ <SetupRequirementsCard
+ output={setupRequirementsOutput}
+ inputsMode="trigger"
+ credentialsLabel="Account"
+ />
+ </div>
+ )}
+
+ {successOutput && (
+ <div className="mt-2">
+ <TriggerSetupSuccessCard output={successOutput} />
+ </div>
+ )}
+
+ {configRequiredOutput && (
+ <div className="mt-2">
+ <ContentMessage>{configRequiredOutput.message}</ContentMessage>
+ </div>
+ )}
+
+ {needLoginOutput && (
+ <div className="mt-2">
+ <ContentMessage>{needLoginOutput.message}</ContentMessage>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function TriggerSetupSuccessCard({ output }: { output: TriggerSetupOutput }) {
+ const [copied, setCopied] = useState(false);
+
+ async function handleCopy() {
+ if (!output.webhook_url) return;
+ try {
+ await navigator.clipboard.writeText(output.webhook_url);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ } catch {
+ // Clipboard API unavailable (e.g. non-secure context) — the URL stays
+ // visible in the card for manual copy, so just skip the confirmation.
+ }
+ }
+
+ return (
+ <div className="grid gap-2 rounded-2xl border bg-background p-3">
+ <ContentMessage>{output.message}</ContentMessage>
+ {output.manual_setup_required && output.webhook_url && (
+ <div className="flex items-center gap-2 rounded-xl border bg-muted/40 p-2">
+ <code className="min-w-0 flex-1 break-all text-xs">
+ {output.webhook_url}
+ </code>
+ <Button
+ variant="ghost"
+ size="small"
+ onClick={handleCopy}
+ aria-label={copied ? "Copied" : "Copy webhook URL"}
+ >
+ {copied ? <CheckIcon size={14} /> : <CopyIcon size={14} />}
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SetupTrigger/__tests__/SetupTrigger.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SetupTrigger/__tests__/SetupTrigger.test.tsx
new file mode 100644
index 0000000000..c3c6c045c4
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SetupTrigger/__tests__/SetupTrigger.test.tsx
@@ -0,0 +1,268 @@
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { SetupTriggerTool } from "../SetupTrigger";
+import { buildTriggerSetupMessage } from "../../../components/SetupRequirementsCard/helpers";
+import { useConnectedProvidersStore } from "../../../connectedProvidersStore";
+
+vi.mock(
+ "@/app/(platform)/copilot/components/CopilotChatActionsProvider/useCopilotChatActions",
+ () => ({
+ useCopilotChatActions: () => ({ onSend: vi.fn() }),
+ }),
+);
+
+vi.mock(
+ "@/components/contextual/CredentialsInput/components/CredentialsGroupedView/CredentialsGroupedView",
+ () => ({
+ CredentialsGroupedView: () => (
+ <div data-testid="credentials-grouped-view">Credentials</div>
+ ),
+ }),
+);
+
+// The morphing animation renders text letter-by-letter across <span>s, which
+// breaks whole-string text queries. Render it as plain text in tests.
+vi.mock(
+ "../../../components/MorphingTextAnimation/MorphingTextAnimation",
+ () => ({
+ MorphingTextAnimation: ({ text }: { text: string }) => <span>{text}</span>,
+ }),
+);
+
+afterEach(() => {
+ cleanup();
+ useConnectedProvidersStore.setState({
+ connected: new Set(),
+ autoDismissedKeys: new Set(),
+ });
+});
+
+function part(output: unknown) {
+ return {
+ type: "tool-setup_agent_webhook_trigger",
+ state: "output-available" as const,
+ output,
+ };
+}
+
+describe("SetupTriggerTool", () => {
+ it("renders the credentials card for a setup_requirements output", () => {
+ render(
+ <SetupTriggerTool
+ part={part({
+ type: "setup_requirements",
+ message: "Choose an account to set up the trigger.",
+ session_id: "s1",
+ setup_info: {
+ agent_id: "g1",
+ agent_name: "My Agent",
+ user_readiness: {
+ has_all_credentials: false,
+ missing_credentials: {
+ github_credentials: { provider: "github", types: ["api_key"] },
+ },
+ ready_to_run: false,
+ },
+ requirements: {
+ credentials: [],
+ inputs: [],
+ execution_modes: ["webhook"],
+ },
+ },
+ graph_id: "g1",
+ graph_version: 1,
+ })}
+ />,
+ );
+ expect(screen.getByTestId("credentials-grouped-view")).toBeDefined();
+ // Trigger mode labels the credentials section "Account".
+ expect(screen.getByText("Account")).toBeDefined();
+ });
+
+ it("renders the webhook URL with a copy button for a trigger_setup output", () => {
+ const url =
+ "https://backend.agpt.co/api/integrations/generic_webhook/webhooks/wh-1/ingress";
+ render(
+ <SetupTriggerTool
+ part={part({
+ type: "trigger_setup",
+ message: "Webhook trigger ready.",
+ preset_id: "p1",
+ library_agent_id: "lib-1",
+ library_agent_link: "/library/agents/lib-1",
+ name: "My Trigger",
+ is_active: true,
+ provider: "generic_webhook",
+ manual_setup_required: true,
+ webhook_url: url,
+ })}
+ />,
+ );
+ expect(screen.getByText("Webhook trigger ready.")).toBeDefined();
+ expect(screen.getByText(url)).toBeDefined();
+ expect(screen.getByLabelText("Copy webhook URL")).toBeDefined();
+ });
+
+ it("renders the message for a trigger_config_required output", () => {
+ render(
+ <SetupTriggerTool
+ part={part({
+ type: "trigger_config_required",
+ message: "Ask the user which repo and events to use.",
+ missing_config: ["repo", "events"],
+ config_schema: { properties: {}, required: ["repo", "events"] },
+ graph_id: "g1",
+ graph_version: 1,
+ })}
+ />,
+ );
+ expect(
+ screen.getByText("Ask the user which repo and events to use."),
+ ).toBeDefined();
+ });
+
+ it("renders the need-login message for a need_login output", () => {
+ render(
+ <SetupTriggerTool
+ part={part({
+ type: "need_login",
+ message: "Please sign in to set up the trigger.",
+ })}
+ />,
+ );
+ expect(
+ screen.getByText("Please sign in to set up the trigger."),
+ ).toBeDefined();
+ });
+
+ it("renders the error animation text for an error output", () => {
+ render(
+ <SetupTriggerTool
+ part={part({ type: "error", error: "Something failed" })}
+ />,
+ );
+ expect(screen.getByText("Something went wrong")).toBeDefined();
+ });
+
+ it("renders the error animation text for the output-error state", () => {
+ render(
+ <SetupTriggerTool
+ part={{
+ type: "tool-setup_agent_webhook_trigger",
+ state: "output-error",
+ }}
+ />,
+ );
+ expect(screen.getByText("Something went wrong")).toBeDefined();
+ });
+
+ it("renders the streaming animation text while input is streaming", () => {
+ render(
+ <SetupTriggerTool
+ part={{
+ type: "tool-setup_agent_webhook_trigger",
+ state: "input-streaming",
+ }}
+ />,
+ );
+ expect(screen.getByText("Setting up the trigger")).toBeDefined();
+ });
+
+ it("does not render the manual webhook URL block when manual setup is not required", () => {
+ render(
+ <SetupTriggerTool
+ part={part({
+ type: "trigger_setup",
+ message: "Trigger ready (auto).",
+ preset_id: "p1",
+ library_agent_id: "lib-1",
+ library_agent_link: "/library/agents/lib-1",
+ name: "Auto Trigger",
+ is_active: true,
+ provider: "github",
+ manual_setup_required: false,
+ webhook_url: "https://example.com/wh",
+ })}
+ />,
+ );
+ expect(screen.getByText("Trigger ready (auto).")).toBeDefined();
+ expect(screen.queryByLabelText("Copy webhook URL")).toBeNull();
+ });
+});
+
+describe("SetupTriggerTool copy button", () => {
+ const url =
+ "https://backend.agpt.co/api/integrations/generic_webhook/webhooks/wh-1/ingress";
+
+ function setClipboard(writeText: (text: string) => Promise<void>) {
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: { writeText },
+ });
+ }
+
+ afterEach(() => {
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: undefined,
+ });
+ });
+
+ function renderSuccess() {
+ render(
+ <SetupTriggerTool
+ part={part({
+ type: "trigger_setup",
+ message: "Webhook trigger ready.",
+ preset_id: "p1",
+ library_agent_id: "lib-1",
+ library_agent_link: "/library/agents/lib-1",
+ name: "My Trigger",
+ is_active: true,
+ provider: "generic_webhook",
+ manual_setup_required: true,
+ webhook_url: url,
+ })}
+ />,
+ );
+ }
+
+ it("copies the webhook URL and shows the confirmation icon", async () => {
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ setClipboard(writeText);
+
+ renderSuccess();
+ fireEvent.click(screen.getByLabelText("Copy webhook URL"));
+
+ await waitFor(() => expect(writeText).toHaveBeenCalledWith(url));
+ });
+
+ it("silently ignores clipboard failures (non-secure context)", async () => {
+ const writeText = vi.fn().mockRejectedValue(new Error("blocked"));
+ setClipboard(writeText);
+
+ renderSuccess();
+ fireEvent.click(screen.getByLabelText("Copy webhook URL"));
+
+ await waitFor(() => expect(writeText).toHaveBeenCalledWith(url));
+ // The URL stays visible for manual copy.
+ expect(screen.getByText(url)).toBeDefined();
+ });
+});
+
+describe("buildTriggerSetupMessage", () => {
+ it("carries back the selected credential IDs as a credentials map", () => {
+ const msg = buildTriggerSetupMessage({
+ github_credentials: { id: "cred-1" },
+ skipped: undefined,
+ });
+ expect(msg).toContain('credentials={"github_credentials":"cred-1"}');
+ expect(msg).toContain("setup_agent_webhook_trigger");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SetupTrigger/__tests__/helpers.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SetupTrigger/__tests__/helpers.test.tsx
new file mode 100644
index 0000000000..b90c1f79ba
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SetupTrigger/__tests__/helpers.test.tsx
@@ -0,0 +1,207 @@
+import { render } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import {
+ getAnimationText,
+ getSetupTriggerToolOutput,
+ isSetupTriggerErrorOutput,
+ isSetupTriggerNeedLoginOutput,
+ isSetupTriggerSetupRequirementsOutput,
+ isTriggerConfigRequiredOutput,
+ isTriggerSetupOutput,
+ ToolIcon,
+} from "../helpers";
+
+const triggerSetup = {
+ type: "trigger_setup",
+ message: "Trigger ready.",
+ preset_id: "p1",
+ library_agent_id: "lib-1",
+ library_agent_link: "/library/agents/lib-1",
+ name: "My Trigger",
+ is_active: true,
+ provider: "generic_webhook",
+ manual_setup_required: false,
+} as const;
+
+const setupRequirements = {
+ type: "setup_requirements",
+ message: "Choose an account.",
+ setup_info: { agent_name: "My Agent" },
+} as const;
+
+const configRequired = {
+ type: "trigger_config_required",
+ message: "Which repo?",
+ missing_config: ["repo"],
+ config_schema: {},
+} as const;
+
+const needLogin = { type: "need_login", message: "Sign in." } as const;
+const errorOut = {
+ type: "error",
+ message: "Something failed",
+ error: "boom",
+} as const;
+
+describe("type guards", () => {
+ it("isSetupTriggerSetupRequirementsOutput matches by type and by setup_info", () => {
+ expect(isSetupTriggerSetupRequirementsOutput(setupRequirements)).toBe(true);
+ expect(
+ isSetupTriggerSetupRequirementsOutput({
+ setup_info: { agent_name: "x" },
+ } as never),
+ ).toBe(true);
+ expect(isSetupTriggerSetupRequirementsOutput(triggerSetup as never)).toBe(
+ false,
+ );
+ });
+
+ it("isTriggerSetupOutput matches by type and by manual_setup_required", () => {
+ expect(isTriggerSetupOutput(triggerSetup)).toBe(true);
+ expect(isTriggerSetupOutput({ manual_setup_required: true } as never)).toBe(
+ true,
+ );
+ expect(isTriggerSetupOutput(setupRequirements as never)).toBe(false);
+ });
+
+ it("isTriggerConfigRequiredOutput matches by type and by missing_config", () => {
+ expect(isTriggerConfigRequiredOutput(configRequired)).toBe(true);
+ expect(isTriggerConfigRequiredOutput({ missing_config: [] } as never)).toBe(
+ true,
+ );
+ expect(isTriggerConfigRequiredOutput(triggerSetup as never)).toBe(false);
+ });
+
+ it("isSetupTriggerNeedLoginOutput matches only need_login type", () => {
+ expect(isSetupTriggerNeedLoginOutput(needLogin)).toBe(true);
+ expect(isSetupTriggerNeedLoginOutput(errorOut as never)).toBe(false);
+ });
+
+ it("isSetupTriggerErrorOutput matches by type and by error key", () => {
+ expect(isSetupTriggerErrorOutput(errorOut)).toBe(true);
+ expect(isSetupTriggerErrorOutput({ error: "x" } as never)).toBe(true);
+ expect(isSetupTriggerErrorOutput(needLogin as never)).toBe(false);
+ });
+});
+
+describe("getSetupTriggerToolOutput / parseOutput", () => {
+ it("returns null for a non-object part", () => {
+ expect(getSetupTriggerToolOutput(null)).toBeNull();
+ expect(getSetupTriggerToolOutput("nope")).toBeNull();
+ });
+
+ it("returns null when there is no output", () => {
+ expect(getSetupTriggerToolOutput({})).toBeNull();
+ expect(getSetupTriggerToolOutput({ output: null })).toBeNull();
+ expect(getSetupTriggerToolOutput({ output: "" })).toBeNull();
+ expect(getSetupTriggerToolOutput({ output: " " })).toBeNull();
+ });
+
+ it("parses a JSON string output", () => {
+ const parsed = getSetupTriggerToolOutput({
+ output: JSON.stringify(triggerSetup),
+ });
+ expect(parsed && isTriggerSetupOutput(parsed)).toBe(true);
+ });
+
+ it("returns null for an invalid JSON string", () => {
+ expect(getSetupTriggerToolOutput({ output: "{not json" })).toBeNull();
+ });
+
+ it("recognises each object shape", () => {
+ expect(
+ getSetupTriggerToolOutput({ output: setupRequirements }),
+ ).not.toBeNull();
+ expect(getSetupTriggerToolOutput({ output: triggerSetup })).not.toBeNull();
+ expect(
+ getSetupTriggerToolOutput({ output: configRequired }),
+ ).not.toBeNull();
+ expect(
+ getSetupTriggerToolOutput({ output: { details: "x" } }),
+ ).not.toBeNull();
+ expect(getSetupTriggerToolOutput({ output: needLogin })).not.toBeNull();
+ });
+
+ it("returns null for an unrecognised object type", () => {
+ expect(getSetupTriggerToolOutput({ output: { foo: "bar" } })).toBeNull();
+ });
+});
+
+describe("getAnimationText", () => {
+ it("returns the setup phrase while streaming", () => {
+ expect(getAnimationText({ state: "input-streaming" })).toBe(
+ "Setting up the trigger",
+ );
+ expect(getAnimationText({ state: "input-available" })).toBe(
+ "Setting up the trigger",
+ );
+ });
+
+ it("falls back to the setup phrase when output is unparseable", () => {
+ expect(
+ getAnimationText({ state: "output-available", output: "{bad" }),
+ ).toBe("Setting up the trigger");
+ });
+
+ it("describes a trigger_setup output by name", () => {
+ expect(
+ getAnimationText({ state: "output-available", output: triggerSetup }),
+ ).toBe('Trigger "My Trigger" set up');
+ });
+
+ it("describes a setup_requirements output by agent name", () => {
+ expect(
+ getAnimationText({
+ state: "output-available",
+ output: setupRequirements,
+ }),
+ ).toBe('Setup needed for "My Agent"');
+ });
+
+ it("describes a trigger_config_required output", () => {
+ expect(
+ getAnimationText({ state: "output-available", output: configRequired }),
+ ).toBe("Trigger configuration needed");
+ });
+
+ it("describes a need_login output", () => {
+ expect(
+ getAnimationText({ state: "output-available", output: needLogin }),
+ ).toBe("Sign in required to set up the trigger");
+ });
+
+ it("returns the error phrase for an error output", () => {
+ expect(
+ getAnimationText({ state: "output-available", output: errorOut }),
+ ).toBe("Something went wrong");
+ });
+
+ it("returns the error phrase for output-error state", () => {
+ expect(getAnimationText({ state: "output-error" })).toBe(
+ "Something went wrong",
+ );
+ });
+
+ it("returns the setup phrase for an unknown state", () => {
+ expect(getAnimationText({ state: "unknown" as never })).toBe(
+ "Setting up the trigger",
+ );
+ });
+});
+
+describe("ToolIcon", () => {
+ it("renders the error icon when isError", () => {
+ const { container } = render(<ToolIcon isError />);
+ expect(container.querySelector("svg")).not.toBeNull();
+ });
+
+ it("renders the loader while streaming", () => {
+ const { container } = render(<ToolIcon isStreaming />);
+ expect(container.firstChild).not.toBeNull();
+ });
+
+ it("renders the default webhook icon otherwise", () => {
+ const { container } = render(<ToolIcon />);
+ expect(container.querySelector("svg")).not.toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SetupTrigger/helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SetupTrigger/helpers.tsx
new file mode 100644
index 0000000000..eb60069df2
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/SetupTrigger/helpers.tsx
@@ -0,0 +1,157 @@
+import type { ErrorResponse } from "@/app/api/__generated__/models/errorResponse";
+import type { NeedLoginResponse } from "@/app/api/__generated__/models/needLoginResponse";
+import { ResponseType } from "@/app/api/__generated__/models/responseType";
+import type { SetupRequirementsResponse } from "@/app/api/__generated__/models/setupRequirementsResponse";
+import { WarningDiamondIcon, WebhooksLogoIcon } from "@phosphor-icons/react";
+import type { ToolUIPart } from "ai";
+import { ScaleLoader } from "../../components/ScaleLoader/ScaleLoader";
+
+/** Success output of the `setup_agent_webhook_trigger` tool. Duck-typed: it's a
+ * copilot tool result, not a REST response model. */
+export interface TriggerSetupOutput {
+ type?: string;
+ message: string;
+ preset_id: string;
+ library_agent_id: string;
+ library_agent_link: string;
+ name: string;
+ is_active: boolean;
+ provider: string;
+ manual_setup_required: boolean;
+ webhook_url?: string | null;
+}
+
+/** Returned when the trigger block needs config the user must provide (e.g. a
+ * GitHub repo + event filter). The LLM asks the user and re-calls; this is
+ * duck-typed since it's a copilot tool result, not a REST response model. */
+export interface TriggerConfigRequiredOutput {
+ type?: string;
+ message: string;
+ missing_config: string[];
+ config_schema: Record<string, unknown>;
+}
+
+export type SetupTriggerToolOutput =
+ | SetupRequirementsResponse
+ | TriggerSetupOutput
+ | TriggerConfigRequiredOutput
+ | NeedLoginResponse
+ | ErrorResponse;
+
+export function isSetupTriggerSetupRequirementsOutput(
+ output: SetupTriggerToolOutput,
+): output is SetupRequirementsResponse {
+ return (
+ output.type === ResponseType.setup_requirements ||
+ ("setup_info" in output && typeof output.setup_info === "object")
+ );
+}
+
+export function isTriggerSetupOutput(
+ output: SetupTriggerToolOutput,
+): output is TriggerSetupOutput {
+ return (
+ output.type === ResponseType.trigger_setup ||
+ "manual_setup_required" in output
+ );
+}
+
+export function isTriggerConfigRequiredOutput(
+ output: SetupTriggerToolOutput,
+): output is TriggerConfigRequiredOutput {
+ return (
+ output.type === ResponseType.trigger_config_required ||
+ "missing_config" in output
+ );
+}
+
+export function isSetupTriggerNeedLoginOutput(
+ output: SetupTriggerToolOutput,
+): output is NeedLoginResponse {
+ return output.type === ResponseType.need_login;
+}
+
+export function isSetupTriggerErrorOutput(
+ output: SetupTriggerToolOutput,
+): output is ErrorResponse {
+ return output.type === ResponseType.error || "error" in output;
+}
+
+function parseOutput(output: unknown): SetupTriggerToolOutput | null {
+ if (!output) return null;
+ if (typeof output === "string") {
+ const trimmed = output.trim();
+ if (!trimmed) return null;
+ try {
+ return parseOutput(JSON.parse(trimmed) as unknown);
+ } catch {
+ return null;
+ }
+ }
+ if (typeof output === "object") {
+ if ("setup_info" in output) return output as SetupRequirementsResponse;
+ if ("manual_setup_required" in output) return output as TriggerSetupOutput;
+ if ("missing_config" in output)
+ return output as TriggerConfigRequiredOutput;
+ if ("error" in output || "details" in output)
+ return output as ErrorResponse;
+ if ((output as { type?: unknown }).type === ResponseType.need_login)
+ return output as NeedLoginResponse;
+ }
+ return null;
+}
+
+export function getSetupTriggerToolOutput(
+ part: unknown,
+): SetupTriggerToolOutput | null {
+ if (!part || typeof part !== "object") return null;
+ return parseOutput((part as { output?: unknown }).output);
+}
+
+export function getAnimationText(part: {
+ state: ToolUIPart["state"];
+ output?: unknown;
+}): string {
+ switch (part.state) {
+ case "input-streaming":
+ case "input-available":
+ return "Setting up the trigger";
+ case "output-available": {
+ const output = parseOutput(part.output);
+ if (!output) return "Setting up the trigger";
+ if (isTriggerSetupOutput(output))
+ return `Trigger "${output.name}" set up`;
+ if (isSetupTriggerSetupRequirementsOutput(output))
+ return `Setup needed for "${output.setup_info.agent_name}"`;
+ if (isTriggerConfigRequiredOutput(output))
+ return "Trigger configuration needed";
+ if (isSetupTriggerNeedLoginOutput(output))
+ return "Sign in required to set up the trigger";
+ return "Something went wrong";
+ }
+ case "output-error":
+ return "Something went wrong";
+ default:
+ return "Setting up the trigger";
+ }
+}
+
+export function ToolIcon({
+ isStreaming,
+ isError,
+}: {
+ isStreaming?: boolean;
+ isError?: boolean;
+}) {
+ if (isError) {
+ return (
+ <WarningDiamondIcon size={14} weight="regular" className="text-red-500" />
+ );
+ }
+ if (isStreaming) {
+ return <ScaleLoader size={14} />;
+ }
+ return (
+ <WebhooksLogoIcon size={14} weight="regular" className="text-neutral-400" />
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index d25f5a29d3..48650db67a 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -3269,6 +3269,9 @@
},
{ "$ref": "#/components/schemas/ScheduleListResponse" },
{ "$ref": "#/components/schemas/ScheduleDeletedResponse" },
+ { "$ref": "#/components/schemas/PresetListResponse" },
+ { "$ref": "#/components/schemas/PresetUpdatedResponse" },
+ { "$ref": "#/components/schemas/PresetDeletedResponse" },
{ "$ref": "#/components/schemas/MemoryStoreResponse" },
{ "$ref": "#/components/schemas/MemorySearchResponse" },
{
@@ -11486,10 +11489,10 @@
},
"trigger_info": {
"anyOf": [
- { "additionalProperties": true, "type": "object" },
+ { "$ref": "#/components/schemas/GraphTriggerInfo" },
{ "type": "null" }
],
- "title": "Trigger Info"
+ "description": "Webhook-trigger setup info (provider, config_schema, credentials_input_name) for agents with an external trigger. Configure the trigger by passing config_schema fields to setup_agent_webhook_trigger — never by editing the trigger node in the graph. None for agents without a webhook trigger."
}
},
"type": "object",
@@ -11648,6 +11651,13 @@
{ "type": "null" }
],
"description": "Full graph structure (nodes + links) when include_graph is requested"
+ },
+ "trigger_info": {
+ "anyOf": [
+ { "$ref": "#/components/schemas/GraphTriggerInfo" },
+ { "type": "null" }
+ ],
+ "description": "Webhook-trigger setup info (provider, config_schema, credentials_input_name) for agents with an external trigger. Configure the trigger by passing config_schema fields to setup_agent_webhook_trigger — never by editing the trigger node in the graph. None for agents without a webhook trigger."
}
},
"type": "object",
@@ -14484,7 +14494,15 @@
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Library Agent Link"
},
- "status": { "type": "string", "title": "Status", "default": "QUEUED" }
+ "status": {
+ "type": "string",
+ "title": "Status",
+ "default": "QUEUED"
+ },
+ "saved_preset_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Saved Preset Id"
+ }
},
"type": "object",
"required": ["message", "execution_id", "graph_id", "graph_name"],
@@ -17935,6 +17953,102 @@
],
"title": "PostmarkSubscriptionChangeWebhook"
},
+ "PresetDeletedResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "preset_deleted"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "preset_id": { "type": "string", "title": "Preset Id" },
+ "name": { "type": "string", "title": "Name" }
+ },
+ "type": "object",
+ "required": ["message", "preset_id", "name"],
+ "title": "PresetDeletedResponse",
+ "description": "Response confirming a preset was deleted."
+ },
+ "PresetListResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "preset_list"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "presets": {
+ "items": { "$ref": "#/components/schemas/PresetSummary" },
+ "type": "array",
+ "title": "Presets"
+ },
+ "total_count": { "type": "integer", "title": "Total Count" }
+ },
+ "type": "object",
+ "required": ["message", "presets", "total_count"],
+ "title": "PresetListResponse",
+ "description": "Response listing the user's presets."
+ },
+ "PresetSummary": {
+ "properties": {
+ "id": { "type": "string", "title": "Id" },
+ "name": { "type": "string", "title": "Name" },
+ "description": {
+ "type": "string",
+ "title": "Description",
+ "default": ""
+ },
+ "graph_id": { "type": "string", "title": "Graph Id" },
+ "graph_version": { "type": "integer", "title": "Graph Version" },
+ "is_active": { "type": "boolean", "title": "Is Active" },
+ "webhook_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Webhook Id"
+ },
+ "webhook_url": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Webhook Url"
+ },
+ "provider": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Provider"
+ }
+ },
+ "type": "object",
+ "required": ["id", "name", "graph_id", "graph_version", "is_active"],
+ "title": "PresetSummary",
+ "description": "Summary of a single preset (saved run config / webhook trigger)."
+ },
+ "PresetUpdatedResponse": {
+ "properties": {
+ "type": {
+ "$ref": "#/components/schemas/ResponseType",
+ "default": "preset_updated"
+ },
+ "message": { "type": "string", "title": "Message" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "preset_id": { "type": "string", "title": "Preset Id" },
+ "name": { "type": "string", "title": "Name" },
+ "is_active": { "type": "boolean", "title": "Is Active" },
+ "webhook_url": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Webhook Url"
+ }
+ },
+ "type": "object",
+ "required": ["message", "preset_id", "name", "is_active"],
+ "title": "PresetUpdatedResponse",
+ "description": "Response confirming a preset was updated."
+ },
"Profile": {
"properties": {
"username": { "type": "string", "title": "Username" },
@@ -18474,6 +18588,11 @@
"schedule_deleted",
"schedule_created",
"agent_trigger_list",
+ "trigger_setup",
+ "trigger_config_required",
+ "preset_list",
+ "preset_updated",
+ "preset_deleted",
"mcp_guide",
"mcp_tools_discovered",
"mcp_tool_output",
diff --git a/docs/integrations/block-integrations/misc.md b/docs/integrations/block-integrations/misc.md
index 3b308e1282..65a995269e 100644
--- a/docs/integrations/block-integrations/misc.md
+++ b/docs/integrations/block-integrations/misc.md
@@ -58,7 +58,7 @@ Tool and block identifiers provided in `tools` and `blocks` are validated at run
| system_context | Optional additional context prepended to the prompt. Use this to constrain autopilot behavior, provide domain context, or set output format requirements. | str | No |
| session_id | Session ID to continue an existing autopilot conversation. Leave empty to start a new session. Use the session_id output from a previous run to continue. | str | No |
| max_recursion_depth | Maximum nesting depth when the autopilot calls this block recursively (sub-agent pattern). Prevents infinite loops. | int | No |
-| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delete_folder" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "edit_agent" \| "find_agent" \| "find_block" \| "find_library_agent" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "get_platform_info" \| "get_sub_session_result" \| "list_agent_triggers" \| "list_folders" \| "list_schedules" \| "list_skills" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "move_agents_to_folder" \| "move_folder" \| "read_skill" \| "read_workspace_file" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "store_skill" \| "update_folder" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |
+| tools | Tool names to filter. Works with tools_exclude to form an allow-list or deny-list. Leave empty to apply no tool filter. | List["add_understanding" \| "bash_exec" \| "browser_act" \| "browser_navigate" \| "browser_screenshot" \| "connect_integration" \| "continue_run_block" \| "create_agent" \| "create_feature_request" \| "create_folder" \| "customize_agent" \| "decompose_goal" \| "delete_folder" \| "delete_preset" \| "delete_schedule" \| "delete_skill" \| "delete_workspace_file" \| "edit_agent" \| "find_agent" \| "find_block" \| "find_library_agent" \| "fix_agent_graph" \| "get_agent_building_guide" \| "get_doc_page" \| "get_mcp_guide" \| "get_platform_info" \| "get_sub_session_result" \| "list_agent_triggers" \| "list_chat_platform_channels" \| "list_folders" \| "list_presets" \| "list_schedules" \| "list_skills" \| "list_workspace_files" \| "memory_forget_confirm" \| "memory_forget_search" \| "memory_search" \| "memory_store" \| "move_agents_to_folder" \| "move_folder" \| "post_to_chat_platform" \| "read_skill" \| "read_workspace_file" \| "run_agent" \| "run_block" \| "run_mcp_tool" \| "run_sub_session" \| "schedule_followup" \| "search_docs" \| "search_feature_requests" \| "setup_agent_webhook_trigger" \| "store_skill" \| "update_folder" \| "update_preset" \| "validate_agent_graph" \| "view_agent_output" \| "web_fetch" \| "web_search" \| "write_workspace_file" \| "Agent" \| "Edit" \| "Glob" \| "Grep" \| "Read" \| "Task" \| "TodoWrite" \| "WebSearch" \| "Write"] | No |
| tools_exclude | Controls how the 'tools' list is interpreted. True (default): 'tools' is a deny-list — listed tools are blocked, all others are allowed. An empty 'tools' list means allow everything. False: 'tools' is an allow-list — only listed tools are permitted. | bool | No |
| blocks | Block identifiers to filter when the copilot uses run_block. Each entry can be: a block name (e.g. 'HTTP Request'), a full block UUID, or the first 8 hex characters of the UUID (e.g. 'c069dc6b'). Works with blocks_exclude. Leave empty to apply no block filter. | List[str] | No |
| blocks_exclude | Controls how the 'blocks' list is interpreted. True (default): 'blocks' is a deny-list — listed blocks are blocked, all others are allowed. An empty 'blocks' list means allow everything. False: 'blocks' is an allow-list — only listed blocks are permitted. | bool | No |