Skip to content

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

fix(backend/executions): show static Agent Output values on public share links (#15654)

Nicholas Tindle4c50510662c6
diff --git a/autogpt_platform/backend/backend/api/features/graph_executions/deleted_share_test.py b/autogpt_platform/backend/backend/api/features/graph_executions/deleted_share_test.py
index 8f4c183eee..358ff6d782 100644
--- a/autogpt_platform/backend/backend/api/features/graph_executions/deleted_share_test.py
+++ b/autogpt_platform/backend/backend/api/features/graph_executions/deleted_share_test.py
@@ -60,7 +60,10 @@ class _FakeShareDb:
) -> None:
self.executions[execution_id] = {
"id": execution_id,
+ "agentGraphId": "graph-1",
+ "agentGraphVersion": 1,
"userId": user_id,
+ "visibility": "PRIVATE",
"isDeleted": False,
"isShared": True,
"shareToken": token,
@@ -114,8 +117,11 @@ class _FakeShareDb:
async def _find_execution(self, where: dict, include: Any = None) -> Any:
for row in self.executions.values():
if _matches(self._execution_view(row), where):
- graph = SimpleNamespace(name="Shared agent", description=None)
- return SimpleNamespace(**row, AgentGraph=graph, NodeExecutions=[])
+ # The real model, so code reading the run (e.g.
+ # GraphExecution.from_db) sees every field Prisma returns.
+ return AgentGraphExecution.model_validate(
+ {**row, "AgentGraph": _graph(row), "NodeExecutions": []}
+ )
return None
async def _update_executions(self, where: dict, data: dict) -> int:
@@ -155,6 +161,19 @@ class _FakeShareDb:
return removed
+def _graph(row: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "id": row["agentGraphId"],
+ "version": row["agentGraphVersion"],
+ "name": "Shared agent",
+ "description": None,
+ "userId": row["userId"],
+ "createdAt": row["createdAt"],
+ "isActive": True,
+ "visibility": "PRIVATE",
+ }
+
+
def _matches(row: dict[str, Any] | None, where: dict[str, Any]) -> bool:
if row is None:
return False
diff --git a/autogpt_platform/backend/backend/data/execution.py b/autogpt_platform/backend/backend/data/execution.py
index ebcc97b819..f616b5fa8f 100644
--- a/autogpt_platform/backend/backend/data/execution.py
+++ b/autogpt_platform/backend/backend/data/execution.py
@@ -1893,59 +1893,24 @@ async def update_graph_execution_share_status(
async def get_graph_execution_by_share_token(
share_token: str,
) -> SharedExecutionResponse | None:
- """Get a shared execution with limited public-safe data."""
+ """Get a shared execution with limited public-safe data.
+
+ Outputs are built exactly as the owner sees them (``GraphExecution.from_db``):
+ moderation-cleared values, no INCOMPLETE node executions, queue-time order,
+ and Output blocks whose value only lives in their ``Input`` rows.
+ """
execution = await AgentGraphExecution.prisma().find_first(
where=live_execution_share(share_token),
include={
"AgentGraph": True,
- "NodeExecutions": {
- "include": {
- "Output": True,
- "Node": {
- "include": {
- "AgentBlock": True,
- }
- },
- },
- },
+ **GRAPH_EXECUTION_INCLUDE_WITH_NODES,
},
)
if not execution:
return None
- # Extract outputs from OUTPUT blocks only (consistent with GraphExecution.from_db)
- outputs: CompletedBlockOutput = defaultdict(list)
- if execution.NodeExecutions:
- for node_exec in execution.NodeExecutions:
- if node_exec.Node and node_exec.Node.agentBlockId:
- # Get the block definition to check its type
- block = get_block(node_exec.Node.agentBlockId)
-
- if block and block.block_type == BlockType.OUTPUT:
- # For OUTPUT blocks, the data is stored in executionData or Input
- # The executionData contains the structured input with 'name' and 'value' fields
- if hasattr(node_exec, "executionData") and node_exec.executionData:
- exec_data = type_utils.convert(
- node_exec.executionData, BlockInput
- )
- if "name" in exec_data:
- name = exec_data["name"]
- value = exec_data.get("value")
- outputs[name].append(value)
- elif node_exec.Input:
- # Build input_data from Input relation
- input_data = {}
- for data in node_exec.Input:
- if data.name and data.data is not None:
- input_data[data.name] = type_utils.convert(
- data.data, JsonValue
- )
-
- if "name" in input_data:
- name = input_data["name"]
- value = input_data.get("value")
- outputs[name].append(value)
+ outputs = GraphExecution.from_db(execution).outputs
return SharedExecutionResponse(
id=execution.id,
diff --git a/autogpt_platform/backend/backend/data/execution_share_outputs_db_test.py b/autogpt_platform/backend/backend/data/execution_share_outputs_db_test.py
new file mode 100644
index 0000000000..a3853d2549
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/execution_share_outputs_db_test.py
@@ -0,0 +1,204 @@
+"""DB-backed: a shared run's outputs equal the owner's (#15652).
+
+Static Agent Output blocks (value typed in the builder, no inbound link) are
+starting nodes: ``create_graph_execution`` gives them ``Input`` rows and no
+``executionData``. The share query didn't load ``Input``, so they vanished
+from the public page.
+"""
+
+import logging
+import uuid
+from datetime import datetime, timedelta, timezone
+
+import prisma.models
+import pytest
+from prisma import Json
+from prisma.enums import AgentExecutionStatus
+
+from backend.blocks.io import AgentInputBlock, AgentOutputBlock
+from backend.data.execution import (
+ create_graph_execution,
+ get_graph_execution,
+ get_graph_execution_by_share_token,
+ update_graph_execution_share_status,
+)
+from backend.data.includes import MAX_NODE_EXECUTIONS_FETCH
+
+logger = logging.getLogger(__name__)
+OUTPUT_BLOCK_ID = AgentOutputBlock().id
+MODERATED = "Failed due to content moderation"
+
+
+async def _setup() -> tuple[str, str, dict[str, str]]:
+ user_id = str(uuid.uuid4())
+ graph_id = str(uuid.uuid4())
+ await prisma.models.User.prisma().create(
+ data={
+ "id": user_id,
+ "email": f"share-outputs-{user_id}@example.com",
+ "name": "Share Outputs Test",
+ }
+ )
+ await prisma.models.AgentGraph.prisma().create(
+ data={
+ "id": graph_id,
+ "version": 1,
+ "name": "share-outputs-test",
+ "description": "share-outputs-test",
+ "userId": user_id,
+ "isActive": True,
+ }
+ )
+ nodes = {}
+ for key in ("static_note", "static_number", "linked_note", "moderated"):
+ node = await prisma.models.AgentNode.prisma().create(
+ data={
+ "agentBlockId": OUTPUT_BLOCK_ID,
+ "agentGraphId": graph_id,
+ "agentGraphVersion": 1,
+ }
+ )
+ nodes[key] = node.id
+ return user_id, graph_id, nodes
+
+
+async def _cleanup(user_id: str, graph_id: str) -> None:
+ try:
+ await prisma.models.AgentGraphExecution.prisma().delete_many(
+ where={"userId": user_id}
+ )
+ await prisma.models.AgentGraph.prisma().delete_many(where={"id": graph_id})
+ await prisma.models.User.prisma().delete_many(where={"id": user_id})
+ except Exception as exc:
+ logger.warning("cleanup for %s failed: %s", user_id, exc)
+
+
[email protected](loop_scope="session")
+async def test_shared_outputs_include_static_outputs_and_match_owner(server):
+ user_id, graph_id, nodes = await _setup()
+ try:
+ # Static outputs: starting nodes, Input rows only.
+ execution = await create_graph_execution(
+ graph_id=graph_id,
+ graph_version=1,
+ starting_nodes_input=[
+ (nodes["static_note"], {"name": "static_note", "value": "typed"}),
+ (nodes["static_number"], {"name": "static_number", "value": 42}),
+ ],
+ inputs={},
+ user_id=user_id,
+ )
+ # Linked output: executionData written when it was enqueued.
+ await prisma.models.AgentNodeExecution.prisma().create(
+ data={
+ "agentNodeId": nodes["linked_note"],
+ "agentGraphExecutionId": execution.id,
+ "executionStatus": AgentExecutionStatus.COMPLETED,
+ "queuedTime": datetime.now(timezone.utc),
+ "executionData": Json({"name": "linked_note", "value": "linked"}),
+ }
+ )
+ # Moderated output: original executionData stays on the row.
+ await prisma.models.AgentNodeExecution.prisma().create(
+ data={
+ "agentNodeId": nodes["moderated"],
+ "agentGraphExecutionId": execution.id,
+ "executionStatus": AgentExecutionStatus.FAILED,
+ "queuedTime": datetime.now(timezone.utc),
+ "executionData": Json({"name": "secret", "value": "original"}),
+ "stats": Json(
+ {
+ "error": MODERATED,
+ "cleared_inputs": {
+ "name": [MODERATED],
+ "value": [MODERATED],
+ },
+ "cleared_outputs": {},
+ }
+ ),
+ }
+ )
+ token = str(uuid.uuid4())
+ await update_graph_execution_share_status(
+ execution_id=execution.id,
+ user_id=user_id,
+ is_shared=True,
+ share_token=token,
+ shared_at=datetime.now(timezone.utc),
+ )
+
+ owner = await get_graph_execution(
+ user_id, execution.id, include_node_executions=True
+ )
+ shared = await get_graph_execution_by_share_token(token)
+
+ assert owner is not None and shared is not None
+ assert dict(shared.outputs) == dict(owner.outputs)
+ assert shared.outputs["static_note"] == ["typed"]
+ assert shared.outputs["static_number"] == [42]
+ assert shared.outputs["linked_note"] == ["linked"]
+ assert "secret" not in shared.outputs
+ assert "original" not in shared.model_dump_json()
+ finally:
+ await _cleanup(user_id, graph_id)
+
+
[email protected](loop_scope="session")
+ "newer_count", [MAX_NODE_EXECUTIONS_FETCH - 1, MAX_NODE_EXECUTIONS_FETCH]
+)
+async def test_shared_outputs_match_owner_at_node_execution_limit(server, newer_count):
+ user_id, graph_id, nodes = await _setup()
+ try:
+ execution = await create_graph_execution(
+ graph_id=graph_id,
+ graph_version=1,
+ starting_nodes_input=[
+ (nodes["static_note"], {"name": "static_note", "value": "typed"})
+ ],
+ inputs={},
+ user_id=user_id,
+ )
+ input_node = await prisma.models.AgentNode.prisma().create(
+ data={
+ "agentBlockId": AgentInputBlock().id,
+ "agentGraphId": graph_id,
+ "agentGraphVersion": 1,
+ }
+ )
+ now = datetime.now(timezone.utc)
+ await prisma.models.AgentNodeExecution.prisma().create_many(
+ data=[
+ {
+ "agentNodeId": input_node.id,
+ "agentGraphExecutionId": execution.id,
+ "executionStatus": AgentExecutionStatus.COMPLETED,
+ "queuedTime": now + timedelta(seconds=i + 1),
+ "executionData": Json({"name": "input", "value": i}),
+ }
+ for i in range(newer_count)
+ ]
+ )
+ token = str(uuid.uuid4())
+ await update_graph_execution_share_status(
+ execution_id=execution.id,
+ user_id=user_id,
+ is_shared=True,
+ share_token=token,
+ shared_at=now,
+ )
+
+ owner = await get_graph_execution(
+ user_id, execution.id, include_node_executions=True
+ )
+ shared = await get_graph_execution_by_share_token(token)
+
+ assert owner is not None and shared is not None
+ assert dict(owner.outputs) == (
+ {"static_note": ["typed"]}
+ if newer_count < MAX_NODE_EXECUTIONS_FETCH
+ else {}
+ )
+ assert dict(shared.outputs) == dict(owner.outputs)
+ finally:
+ await _cleanup(user_id, graph_id)
diff --git a/autogpt_platform/backend/backend/data/execution_share_outputs_test.py b/autogpt_platform/backend/backend/data/execution_share_outputs_test.py
new file mode 100644
index 0000000000..c1151012e1
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/execution_share_outputs_test.py
@@ -0,0 +1,204 @@
+"""Shared-run outputs match the owner's view (#15652).
+
+``get_graph_execution_by_share_token`` used to hand-roll output extraction
+from ``executionData`` without loading ``Input`` rows, so an Agent Output
+block whose value was typed in the builder (a starting node: ``Input`` rows,
+no ``executionData``) never reached the public page, and moderation-cleared
+values weren't applied.
+"""
+
+import json
+from datetime import datetime, timedelta, timezone
+from typing import Any
+
+import prisma.models
+import pytest
+from prisma.enums import AgentExecutionStatus
+
+from backend.blocks.io import AgentInputBlock, AgentOutputBlock
+from backend.data.execution import (
+ get_graph_execution,
+ get_graph_execution_by_share_token,
+)
+
+OUTPUT_BLOCK_ID = AgentOutputBlock().id
+INPUT_BLOCK_ID = AgentInputBlock().id
+MODERATED = "Failed due to content moderation (Moderation ID: mod-1)"
+_T0 = datetime(2026, 10, 1, 12, 0, tzinfo=timezone.utc)
+
+
+def _io(name: str, value: Any, n: int) -> dict:
+ return {
+ "id": f"io-{name}-{n}",
+ "name": name,
+ "data": json.dumps(value),
+ "time": _T0,
+ }
+
+
+def _node_exec(
+ exec_id: str,
+ *,
+ block_id: str = OUTPUT_BLOCK_ID,
+ status: AgentExecutionStatus = AgentExecutionStatus.COMPLETED,
+ queued_s: int,
+ execution_data: dict | None = None,
+ inputs: dict | None = None,
+ stats: dict | None = None,
+) -> dict:
+ return {
+ "id": exec_id,
+ "agentGraphExecutionId": "ge-1",
+ "agentNodeId": f"node-{exec_id}",
+ "executionStatus": status,
+ "addedTime": _T0,
+ "queuedTime": _T0 + timedelta(seconds=queued_s),
+ "executionData": (
+ json.dumps(execution_data) if execution_data is not None else None
+ ),
+ "stats": json.dumps(stats) if stats is not None else None,
+ "Input": [
+ _io(name, value, i)
+ for i, (name, value) in enumerate((inputs or {}).items())
+ ],
+ "Output": [],
+ "Node": {
+ "id": f"node-{exec_id}",
+ "agentBlockId": block_id,
+ "agentGraphId": "g-1",
+ "agentGraphVersion": 1,
+ "constantInput": "{}",
+ "metadata": "{}",
+ },
+ }
+
+
+def _execution() -> prisma.models.AgentGraphExecution:
+ return prisma.models.AgentGraphExecution.model_validate(
+ {
+ "id": "ge-1",
+ "agentGraphId": "g-1",
+ "agentGraphVersion": 1,
+ "userId": "owner-1",
+ "createdAt": _T0,
+ "executionStatus": AgentExecutionStatus.COMPLETED,
+ "isDeleted": False,
+ "isShared": True,
+ "shareToken": "tok-1",
+ "visibility": "PRIVATE",
+ "AgentGraph": {
+ "id": "g-1",
+ "version": 1,
+ "name": "Shared graph",
+ "userId": "owner-1",
+ "createdAt": _T0,
+ "isActive": True,
+ "visibility": "PRIVATE",
+ },
+ "NodeExecutions": [
+ # Linked Agent Output: executionData written when enqueued.
+ _node_exec(
+ "linked",
+ queued_s=5,
+ execution_data={"name": "linked_note", "value": "from input"},
+ ),
+ # Static Agent Outputs typed in the builder: Input rows only.
+ _node_exec(
+ "static-str",
+ queued_s=1,
+ inputs={"name": "static_note", "value": "typed in builder"},
+ ),
+ _node_exec(
+ "static-num",
+ queued_s=2,
+ inputs={"name": "static_number", "value": 42},
+ ),
+ # Two values for one output name: queue-time order, not row order.
+ _node_exec(
+ "multi-late",
+ queued_s=9,
+ execution_data={"name": "multi", "value": "second"},
+ ),
+ _node_exec(
+ "multi-early",
+ queued_s=3,
+ execution_data={"name": "multi", "value": "first"},
+ ),
+ # Moderated output: original executionData is still on the row.
+ _node_exec(
+ "moderated",
+ status=AgentExecutionStatus.FAILED,
+ queued_s=4,
+ execution_data={"name": "secret", "value": "original content"},
+ stats={
+ "error": MODERATED,
+ "cleared_inputs": {"name": [MODERATED], "value": [MODERATED]},
+ "cleared_outputs": {},
+ },
+ ),
+ # Not yet queued: owner view drops it.
+ _node_exec(
+ "incomplete",
+ status=AgentExecutionStatus.INCOMPLETE,
+ queued_s=6,
+ execution_data={"name": "pending", "value": "not run"},
+ ),
+ ],
+ }
+ )
+
+
+def exec_client(mocker):
+ client = mocker.AsyncMock()
+ client.find_first.return_value = _execution()
+ mocker.patch.object(
+ prisma.models.AgentGraphExecution, "prisma", return_value=client
+ )
+ return client
+
+
+async def test_shared_outputs_equal_owner_outputs(exec_client):
+ owner = await get_graph_execution("owner-1", "ge-1", include_node_executions=True)
+ shared = await get_graph_execution_by_share_token("tok-1")
+
+ assert owner is not None and shared is not None
+ assert dict(shared.outputs) == dict(owner.outputs)
+ assert dict(shared.outputs) == {
+ "static_note": ["typed in builder"],
+ "static_number": [42],
+ "multi": ["first", "second"],
+ MODERATED: [MODERATED],
+ "linked_note": ["from input"],
+ }
+ assert shared.graph_name == "Shared graph"
+
+
+async def test_shared_outputs_hide_moderated_original_value(exec_client):
+ shared = await get_graph_execution_by_share_token("tok-1")
+
+ assert shared is not None
+ assert "secret" not in shared.outputs
+ assert "original content" not in json.dumps(shared.model_dump(mode="json"))
+
+
+async def test_share_query_uses_owner_node_execution_window(exec_client):
+ await get_graph_execution("owner-1", "ge-1", include_node_executions=True)
+ owner_nodes = exec_client.find_first.call_args.kwargs["include"]["NodeExecutions"]
+ await get_graph_execution_by_share_token("tok-1")
+
+ include = exec_client.find_first.call_args.kwargs["include"]
+ node_execs = include["NodeExecutions"]
+ assert include["AgentGraph"] is True
+ assert "Input" in node_execs["include"]
+ assert node_execs == owner_nodes
+
+
+async def test_unknown_share_token_returns_none(exec_client):
+ exec_client.find_first.return_value = None
+
+ assert await get_graph_execution_by_share_token("nope") is None