Skip to content

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

feat(platform): Add public share links for agent run results (#10938)

Nicholas Tindledd84fb5c6688
diff --git a/autogpt_platform/backend/backend/data/execution.py b/autogpt_platform/backend/backend/data/execution.py
index f1d2607563..873ae6e314 100644
--- a/autogpt_platform/backend/backend/data/execution.py
+++ b/autogpt_platform/backend/backend/data/execution.py
@@ -130,6 +130,8 @@ class GraphExecutionMeta(BaseDbModel):
status: ExecutionStatus
started_at: datetime
ended_at: datetime
+ is_shared: bool = False
+ share_token: Optional[str] = None
class Stats(BaseModel):
model_config = ConfigDict(
@@ -246,6 +248,8 @@ class GraphExecutionMeta(BaseDbModel):
if stats
else None
),
+ is_shared=_graph_exec.isShared,
+ share_token=_graph_exec.shareToken,
)
@@ -1021,6 +1025,18 @@ class NodeExecutionEvent(NodeExecutionResult):
)
+class SharedExecutionResponse(BaseModel):
+ """Public-safe response for shared executions"""
+
+ id: str
+ graph_name: str
+ graph_description: Optional[str]
+ status: ExecutionStatus
+ created_at: datetime
+ outputs: CompletedBlockOutput # Only the final outputs, no intermediate data
+ # Deliberately exclude: user_id, inputs, credentials, node details
+
+
ExecutionEvent = Annotated[
GraphExecutionEvent | NodeExecutionEvent, Field(discriminator="event_type")
]
@@ -1198,3 +1214,98 @@ async def get_block_error_stats(
)
for row in result
]
+
+
+async def update_graph_execution_share_status(
+ execution_id: str,
+ user_id: str,
+ is_shared: bool,
+ share_token: str | None,
+ shared_at: datetime | None,
+) -> None:
+ """Update the sharing status of a graph execution."""
+ await AgentGraphExecution.prisma().update(
+ where={"id": execution_id},
+ data={
+ "isShared": is_shared,
+ "shareToken": share_token,
+ "sharedAt": shared_at,
+ },
+ )
+
+
+async def get_graph_execution_by_share_token(
+ share_token: str,
+) -> SharedExecutionResponse | None:
+ """Get a shared execution with limited public-safe data."""
+ execution = await AgentGraphExecution.prisma().find_first(
+ where={
+ "shareToken": share_token,
+ "isShared": True,
+ "isDeleted": False,
+ },
+ include={
+ "AgentGraph": True,
+ "NodeExecutions": {
+ "include": {
+ "Output": True,
+ "Node": {
+ "include": {
+ "AgentBlock": True,
+ }
+ },
+ },
+ },
+ },
+ )
+
+ 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, dict[str, Any]
+ )
+ 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)
+
+ return SharedExecutionResponse(
+ id=execution.id,
+ graph_name=(
+ execution.AgentGraph.name
+ if (execution.AgentGraph and execution.AgentGraph.name)
+ else "Untitled Agent"
+ ),
+ graph_description=(
+ execution.AgentGraph.description if execution.AgentGraph else None
+ ),
+ status=ExecutionStatus(execution.executionStatus),
+ created_at=execution.createdAt,
+ outputs=outputs,
+ )
diff --git a/autogpt_platform/backend/backend/server/middleware/security.py b/autogpt_platform/backend/backend/server/middleware/security.py
index e6e23467ca..ad551c55c2 100644
--- a/autogpt_platform/backend/backend/server/middleware/security.py
+++ b/autogpt_platform/backend/backend/server/middleware/security.py
@@ -81,6 +81,10 @@ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
+ # Add noindex header for shared execution pages
+ if "/public/shared" in request.url.path:
+ response.headers["X-Robots-Tag"] = "noindex, nofollow"
+
# Default: Disable caching for all endpoints
# Only allow caching for explicitly permitted paths
if not self.is_cacheable_path(request.url.path):
diff --git a/autogpt_platform/backend/backend/server/routers/v1.py b/autogpt_platform/backend/backend/server/routers/v1.py
index d512b8601c..170eb18c0e 100644
--- a/autogpt_platform/backend/backend/server/routers/v1.py
+++ b/autogpt_platform/backend/backend/server/routers/v1.py
@@ -2,8 +2,9 @@ import asyncio
import base64
import logging
import time
+import uuid
from collections import defaultdict
-from datetime import datetime
+from datetime import datetime, timezone
from typing import Annotated, Any, Sequence
import pydantic
@@ -958,6 +959,99 @@ async def delete_graph_execution(
)
+class ShareRequest(pydantic.BaseModel):
+ """Optional request body for share endpoint."""
+
+ pass # Empty body is fine
+
+
+class ShareResponse(pydantic.BaseModel):
+ """Response from share endpoints."""
+
+ share_url: str
+ share_token: str
+
+
+@v1_router.post(
+ "/graphs/{graph_id}/executions/{graph_exec_id}/share",
+ dependencies=[Security(requires_user)],
+)
+async def enable_execution_sharing(
+ graph_id: Annotated[str, Path],
+ graph_exec_id: Annotated[str, Path],
+ user_id: Annotated[str, Security(get_user_id)],
+ _body: ShareRequest = Body(default=ShareRequest()),
+) -> ShareResponse:
+ """Enable sharing for a graph execution."""
+ # Verify the execution belongs to the user
+ execution = await execution_db.get_graph_execution(
+ user_id=user_id, execution_id=graph_exec_id
+ )
+ if not execution:
+ raise HTTPException(status_code=404, detail="Execution not found")
+
+ # Generate a unique share token
+ share_token = str(uuid.uuid4())
+
+ # Update the execution with share info
+ await execution_db.update_graph_execution_share_status(
+ execution_id=graph_exec_id,
+ user_id=user_id,
+ is_shared=True,
+ share_token=share_token,
+ shared_at=datetime.now(timezone.utc),
+ )
+
+ # Return the share URL
+ frontend_url = Settings().config.frontend_base_url or "http://localhost:3000"
+ share_url = f"{frontend_url}/share/{share_token}"
+
+ return ShareResponse(share_url=share_url, share_token=share_token)
+
+
+@v1_router.delete(
+ "/graphs/{graph_id}/executions/{graph_exec_id}/share",
+ status_code=HTTP_204_NO_CONTENT,
+ dependencies=[Security(requires_user)],
+)
+async def disable_execution_sharing(
+ graph_id: Annotated[str, Path],
+ graph_exec_id: Annotated[str, Path],
+ user_id: Annotated[str, Security(get_user_id)],
+) -> None:
+ """Disable sharing for a graph execution."""
+ # Verify the execution belongs to the user
+ execution = await execution_db.get_graph_execution(
+ user_id=user_id, execution_id=graph_exec_id
+ )
+ if not execution:
+ raise HTTPException(status_code=404, detail="Execution not found")
+
+ # Remove share info
+ await execution_db.update_graph_execution_share_status(
+ execution_id=graph_exec_id,
+ user_id=user_id,
+ is_shared=False,
+ share_token=None,
+ shared_at=None,
+ )
+
+
+@v1_router.get("/public/shared/{share_token}")
+async def get_shared_execution(
+ share_token: Annotated[
+ str,
+ Path(regex=r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"),
+ ],
+) -> execution_db.SharedExecutionResponse:
+ """Get a shared graph execution by share token (no auth required)."""
+ execution = await execution_db.get_graph_execution_by_share_token(share_token)
+ if not execution:
+ raise HTTPException(status_code=404, detail="Shared execution not found")
+
+ return execution
+
+
########################################################
##################### Schedules ########################
########################################################
diff --git a/autogpt_platform/backend/migrations/20250916191832_add_share_page/migration.sql b/autogpt_platform/backend/migrations/20250916191832_add_share_page/migration.sql
new file mode 100644
index 0000000000..c63c9201d7
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20250916191832_add_share_page/migration.sql
@@ -0,0 +1,22 @@
+/*
+ Warnings:
+
+ - A unique constraint covering the columns `[shareToken]` on the table `AgentGraphExecution` will be added. If there are existing duplicate values, this will fail.
+
+*/
+-- AlterTable
+ALTER TABLE "AgentGraphExecution" ADD COLUMN "isShared" BOOLEAN NOT NULL DEFAULT false,
+ADD COLUMN "shareToken" TEXT,
+ADD COLUMN "sharedAt" TIMESTAMP(3);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "AgentGraphExecution_shareToken_key" ON "AgentGraphExecution"("shareToken");
+
+-- CreateIndex
+CREATE INDEX "AgentGraphExecution_shareToken_idx" ON "AgentGraphExecution"("shareToken");
+
+-- RenameIndex
+ALTER INDEX "APIKey_key_key" RENAME TO "APIKey_hash_key";
+
+-- RenameIndex
+ALTER INDEX "APIKey_prefix_name_idx" RENAME TO "APIKey_head_name_idx";
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index f48cf62ed1..7da9293cf7 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -371,10 +371,16 @@ model AgentGraphExecution {
stats Json?
+ // Sharing fields
+ isShared Boolean @default(false)
+ shareToken String? @unique
+ sharedAt DateTime?
+
@@index([agentGraphId, agentGraphVersion])
@@index([userId])
@@index([createdAt])
@@index([agentPresetId])
+ @@index([shareToken])
}
// This model describes the execution of an AgentNode.
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/[token]/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/[token]/page.tsx
new file mode 100644
index 0000000000..61ecb85c59
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/[token]/page.tsx
@@ -0,0 +1,127 @@
+"use client";
+
+import React from "react";
+import { useParams } from "next/navigation";
+import { RunOutputs } from "@/app/(platform)/library/agents/[id]/components/AgentRunsView/components/SelectedRunView/components/RunOutputs";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Alert, AlertDescription } from "@/components/ui/alert";
+import { InfoIcon } from "lucide-react";
+import { useGetV1GetSharedExecution } from "@/app/api/__generated__/endpoints/default/default";
+
+export default function SharePage() {
+ const params = useParams();
+ const token = params.token as string;
+
+ const {
+ data: response,
+ isLoading: loading,
+ error,
+ } = useGetV1GetSharedExecution(token);
+
+ const executionData = response?.status === 200 ? response.data : undefined;
+ const is404 = !loading && !executionData;
+
+ if (loading) {
+ return (
+ <div className="flex min-h-screen items-center justify-center">
+ <div className="text-center">
+ <div className="mx-auto mb-4 h-12 w-12 animate-spin rounded-full border-b-2 border-primary"></div>
+ <p className="text-muted-foreground">Loading shared execution...</p>
+ </div>
+ </div>
+ );
+ }
+
+ if (error || is404 || !executionData) {
+ return (
+ <div className="flex min-h-screen items-center justify-center">
+ <div className="mx-auto w-full max-w-md p-6">
+ <Card className="border-dashed">
+ <CardContent className="pt-6">
+ <div className="space-y-4 text-center">
+ <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-muted">
+ <InfoIcon className="h-6 w-6 text-muted-foreground" />
+ </div>
+ <div className="space-y-2">
+ <h3 className="text-lg font-semibold">
+ {is404 ? "Share Link Not Found" : "Unable to Load"}
+ </h3>
+ <p className="text-sm text-muted-foreground">
+ {is404
+ ? "This shared link is invalid or has been disabled by the owner. Please check with the person who shared this link."
+ : "There was an error loading this shared execution. Please try refreshing the page."}
+ </p>
+ </div>
+ <div className="pt-2">
+ <button
+ onClick={() => window.location.reload()}
+ className="text-sm text-primary hover:underline"
+ >
+ Try again
+ </button>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+ <div className="mt-8 text-center text-xs text-muted-foreground">
+ <p>Powered by AutoGPT Platform</p>
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="mx-auto max-w-6xl">
+ <div className="mb-6">
+ <Alert>
+ <InfoIcon className="h-4 w-4" />
+ <AlertDescription>
+ This is a publicly shared agent run result. The person who shared
+ this link can disable access at any time.
+ </AlertDescription>
+ </Alert>
+ </div>
+
+ <Card className="mb-6">
+ <CardHeader>
+ <CardTitle className="text-2xl">{executionData.graph_name}</CardTitle>
+ {executionData.graph_description && (
+ <p className="mt-2 text-muted-foreground">
+ {executionData.graph_description}
+ </p>
+ )}
+ </CardHeader>
+ <CardContent>
+ <div className="grid grid-cols-2 gap-4 text-sm">
+ <div>
+ <span className="font-medium">Status:</span>
+ <span className="ml-2 capitalize">
+ {executionData.status.toLowerCase()}
+ </span>
+ </div>
+ <div>
+ <span className="font-medium">Created:</span>
+ <span className="ml-2">
+ {new Date(executionData.created_at).toLocaleString()}
+ </span>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Output</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <RunOutputs outputs={executionData.outputs} />
+ </CardContent>
+ </Card>
+
+ <div className="mt-8 text-center text-sm text-muted-foreground">
+ <p>Powered by AutoGPT Platform</p>
+ </div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/layout.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/layout.tsx
new file mode 100644
index 0000000000..3b79d323c0
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/layout.tsx
@@ -0,0 +1,19 @@
+import type { Metadata } from "next";
+
+export const metadata: Metadata = {
+ title: "Shared Agent Run - AutoGPT",
+ description: "View shared agent run results",
+ robots: "noindex, nofollow",
+};
+
+export default function ShareLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="min-h-screen bg-background">
+ <div className="container mx-auto px-4 py-8">{children}</div>
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/AgentRunsView/components/RunDetailHeader/RunDetailHeader.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/AgentRunsView/components/RunDetailHeader/RunDetailHeader.tsx
index f6a31ff69c..3283b38b72 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/AgentRunsView/components/RunDetailHeader/RunDetailHeader.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/AgentRunsView/components/RunDetailHeader/RunDetailHeader.tsx
@@ -14,6 +14,8 @@ import { GraphExecution } from "@/app/api/__generated__/models/graphExecution";
import { useRunDetailHeader } from "./useRunDetailHeader";
import { AgentActionsDropdown } from "../AgentActionsDropdown";
import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { ShareButton } from "@/components/ShareButton";
+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
type Props = {
agent: LibraryAgent;
@@ -30,6 +32,8 @@ export function RunDetailHeader({
onSelectRun,
onClearSelectedRun,
}: Props) {
+ const shareExecutionResultsEnabled = useGetFlag(Flag.SHARE_EXECUTION_RESULTS);
+
const {
canStop,
isStopping,
@@ -68,6 +72,14 @@ export function RunDetailHeader({
>
<PlayIcon size={16} /> Run again
</Button>
+ {shareExecutionResultsEnabled && (
+ <ShareButton
+ graphId={agent.graph_id}
+ executionId={run.id}
+ isShared={run.is_shared}
+ shareToken={run.share_token}
+ />
+ )}
{!isRunning ? (
<Button
variant="secondary"
diff --git a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
index c73955090f..347ab30636 100644
--- a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
+++ b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
@@ -57,7 +57,13 @@ export const customMutator = async <
const contentType = isFormData ? "multipart/form-data" : "application/json";
// Currently, only two content types are handled here: application/json and multipart/form-data
- if (!isFormData && data && !headers["Content-Type"]) {
+ // For POST/PUT/PATCH requests, always set Content-Type to application/json if not FormData
+ // This is required by the proxy even for requests without a body
+ if (
+ !isFormData &&
+ !headers["Content-Type"] &&
+ ["POST", "PUT", "PATCH"].includes(method)
+ ) {
headers["Content-Type"] = "application/json";
}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 770a5890d3..c55be2345d 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -1968,6 +1968,135 @@
}
}
},
+ "/api/graphs/{graph_id}/executions/{graph_exec_id}/share": {
+ "post": {
+ "tags": ["v1"],
+ "summary": "Enable Execution Sharing",
+ "description": "Enable sharing for a graph execution.",
+ "operationId": "postV1EnableExecutionSharing",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "graph_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Graph Id" }
+ },
+ {
+ "name": "graph_exec_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Graph Exec Id" }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ShareRequest",
+ "default": {}
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/ShareResponse" }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ }
+ }
+ },
+ "delete": {
+ "tags": ["v1"],
+ "summary": "Disable Execution Sharing",
+ "description": "Disable sharing for a graph execution.",
+ "operationId": "deleteV1DisableExecutionSharing",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "graph_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Graph Id" }
+ },
+ {
+ "name": "graph_exec_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Graph Exec Id" }
+ }
+ ],
+ "responses": {
+ "204": { "description": "Successful Response" },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ }
+ }
+ }
+ },
+ "/api/public/shared/{share_token}": {
+ "get": {
+ "tags": ["v1"],
+ "summary": "Get Shared Execution",
+ "description": "Get a shared graph execution by share token (no auth required).",
+ "operationId": "getV1GetSharedExecution",
+ "parameters": [
+ {
+ "name": "share_token",
+ "in": "path",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
+ "title": "Share Token"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SharedExecutionResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/graphs/{graph_id}/schedules": {
"post": {
"tags": ["v1", "schedules"],
@@ -5390,6 +5519,15 @@
"format": "date-time",
"title": "Ended At"
},
+ "is_shared": {
+ "type": "boolean",
+ "title": "Is Shared",
+ "default": false
+ },
+ "share_token": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Share Token"
+ },
"stats": {
"anyOf": [
{ "$ref": "#/components/schemas/Stats" },
@@ -5514,6 +5652,15 @@
"format": "date-time",
"title": "Ended At"
},
+ "is_shared": {
+ "type": "boolean",
+ "title": "Is Shared",
+ "default": false
+ },
+ "share_token": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Share Token"
+ },
"stats": {
"anyOf": [
{ "$ref": "#/components/schemas/Stats" },
@@ -5589,6 +5736,15 @@
"format": "date-time",
"title": "Ended At"
},
+ "is_shared": {
+ "type": "boolean",
+ "title": "Is Shared",
+ "default": false
+ },
+ "share_token": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Share Token"
+ },
"stats": {
"anyOf": [
{ "$ref": "#/components/schemas/Stats" },
@@ -7256,6 +7412,54 @@
"required": ["active_graph_version"],
"title": "SetGraphActiveVersion"
},
+ "ShareRequest": {
+ "properties": {},
+ "type": "object",
+ "title": "ShareRequest",
+ "description": "Optional request body for share endpoint."
+ },
+ "ShareResponse": {
+ "properties": {
+ "share_url": { "type": "string", "title": "Share Url" },
+ "share_token": { "type": "string", "title": "Share Token" }
+ },
+ "type": "object",
+ "required": ["share_url", "share_token"],
+ "title": "ShareResponse",
+ "description": "Response from share endpoints."
+ },
+ "SharedExecutionResponse": {
+ "properties": {
+ "id": { "type": "string", "title": "Id" },
+ "graph_name": { "type": "string", "title": "Graph Name" },
+ "graph_description": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Graph Description"
+ },
+ "status": { "$ref": "#/components/schemas/AgentExecutionStatus" },
+ "created_at": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Created At"
+ },
+ "outputs": {
+ "additionalProperties": { "items": {}, "type": "array" },
+ "type": "object",
+ "title": "Outputs"
+ }
+ },
+ "type": "object",
+ "required": [
+ "id",
+ "graph_name",
+ "graph_description",
+ "status",
+ "created_at",
+ "outputs"
+ ],
+ "title": "SharedExecutionResponse",
+ "description": "Public-safe response for shared executions"
+ },
"Stats": {
"properties": {
"cost": {
diff --git a/autogpt_platform/frontend/src/components/ShareButton.tsx b/autogpt_platform/frontend/src/components/ShareButton.tsx
new file mode 100644
index 0000000000..95b7beafa8
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/ShareButton.tsx
@@ -0,0 +1,223 @@
+"use client";
+
+import React, { useState, useEffect } from "react";
+import { Button } from "@/components/atoms/Button/Button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Alert, AlertDescription } from "@/components/ui/alert";
+import {
+ ShareFatIcon,
+ CopyIcon,
+ CheckIcon,
+ WarningIcon,
+} from "@phosphor-icons/react";
+import { useToast } from "./molecules/Toast/use-toast";
+import {
+ usePostV1EnableExecutionSharing,
+ useDeleteV1DisableExecutionSharing,
+} from "@/app/api/__generated__/endpoints/default/default";
+
+interface ShareButtonProps {
+ graphId: string;
+ executionId: string;
+ isShared?: boolean;
+ shareToken?: string | null;
+}
+
+export function ShareButton({
+ graphId,
+ executionId,
+ isShared: initialIsShared = false,
+ shareToken: initialShareToken,
+}: ShareButtonProps) {
+ const [isOpen, setIsOpen] = useState(false);
+ const [isShared, setIsShared] = useState(initialIsShared);
+ const [shareToken, setShareToken] = useState(initialShareToken || null);
+ const [copied, setCopied] = useState(false);
+ const { toast } = useToast();
+
+ // Sync state when props change (e.g., after re-fetching run data)
+ useEffect(() => {
+ setIsShared(initialIsShared);
+ setShareToken(initialShareToken || null);
+ }, [initialIsShared, initialShareToken]);
+
+ // Generate the share URL from the token
+ const baseUrl =
+ process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || window.location.origin;
+ const shareUrl = shareToken ? `${baseUrl}/share/${shareToken}` : "";
+
+ const { mutate: enableSharing, isPending: isEnabling } =
+ usePostV1EnableExecutionSharing();
+ const { mutate: disableSharing, isPending: isDisabling } =
+ useDeleteV1DisableExecutionSharing();
+
+ const loading = isEnabling || isDisabling;
+
+ const handleShare = () => {
+ enableSharing(
+ {
+ graphId,
+ graphExecId: executionId,
+ data: {}, // Empty ShareRequest
+ },
+ {
+ onSuccess: (response) => {
+ if (response.status === 200) {
+ setShareToken(response.data.share_token);
+ setIsShared(true);
+ toast({
+ title: "Sharing enabled",
+ description:
+ "Your agent run is now publicly accessible via the share link.",
+ });
+ } else {
+ toast({
+ title: "Error",
+ description: "Failed to enable sharing. Please try again.",
+ variant: "destructive",
+ });
+ }
+ },
+ onError: () => {
+ toast({
+ title: "Error",
+ description: "Failed to enable sharing. Please try again.",
+ variant: "destructive",
+ });
+ },
+ },
+ );
+ };
+
+ const handleStopSharing = () => {
+ disableSharing(
+ {
+ graphId,
+ graphExecId: executionId,
+ },
+ {
+ onSuccess: () => {
+ setIsShared(false);
+ setShareToken(null);
+ toast({
+ title: "Sharing disabled",
+ description: "The share link is no longer accessible.",
+ });
+ },
+ onError: () => {
+ toast({
+ title: "Error",
+ description: "Failed to disable sharing. Please try again.",
+ variant: "destructive",
+ });
+ },
+ },
+ );
+ };
+
+ const handleCopy = async () => {
+ try {
+ await navigator.clipboard.writeText(shareUrl);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ toast({
+ title: "Copied!",
+ description: "Share link copied to clipboard.",
+ });
+ } catch {
+ toast({
+ title: "Error",
+ description: "Failed to copy link. Please try again.",
+ variant: "destructive",
+ });
+ }
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={setIsOpen}>
+ <DialogTrigger asChild>
+ <Button
+ variant={isShared ? "primary" : "secondary"}
+ size="small"
+ className={isShared ? "relative" : ""}
+ >
+ <ShareFatIcon size={16} />
+ {isShared ? "Shared" : "Share"}
+ {isShared && (
+ <span className="absolute -right-1 -top-1 h-2 w-2 rounded-full bg-green-500" />
+ )}
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Share Agent Run</DialogTitle>
+ <DialogDescription>
+ {isShared
+ ? "Your agent run is currently shared. Anyone with the link can view the output."
+ : "Generate a public link to share this agent run output with others."}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4">
+ {!isShared ? (
+ <>
+ <Alert>
+ <WarningIcon className="h-4 w-4" />
+ <AlertDescription>
+ When you enable sharing, the output of this agent run will be
+ publicly accessible to anyone with the link. The page will
+ include a noindex directive to discourage search engine
+ crawling, but this cannot be guaranteed.
+ </AlertDescription>
+ </Alert>
+ <Button
+ onClick={handleShare}
+ loading={loading}
+ className="w-full"
+ >
+ Enable Sharing
+ </Button>
+ </>
+ ) : (
+ <>
+ <div className="flex items-center space-x-2">
+ <Input value={shareUrl} readOnly className="flex-1" />
+ <button
+ onClick={handleCopy}
+ className="inline-flex h-10 w-10 items-center justify-center rounded-md border border-input bg-background text-sm font-medium ring-offset-background transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
+ type="button"
+ >
+ {copied ? <CheckIcon size={16} /> : <CopyIcon size={16} />}
+ </button>
+ </div>
+ <Alert>
+ <WarningIcon className="h-4 w-4" />
+ <AlertDescription>
+ This link is publicly accessible. Only share it with people
+ you trust. The shared page includes noindex directives to
+ discourage search engines.
+ </AlertDescription>
+ </Alert>
+ <Button
+ onClick={handleStopSharing}
+ loading={loading}
+ variant="destructive"
+ className="w-full"
+ >
+ Stop Sharing
+ </Button>
+ </>
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
index 253b94cde0..c8f4036e36 100644
--- a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
+++ b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts
@@ -10,6 +10,7 @@ export enum Flag {
NEW_AGENT_RUNS = "new-agent-runs",
GRAPH_SEARCH = "graph-search",
ENABLE_ENHANCED_OUTPUT_HANDLING = "enable-enhanced-output-handling",
+ SHARE_EXECUTION_RESULTS = "share-execution-results",
AGENT_FAVORITING = "agent-favoriting",
}
@@ -20,6 +21,7 @@ export type FlagValues = {
[Flag.NEW_AGENT_RUNS]: boolean;
[Flag.GRAPH_SEARCH]: boolean;
[Flag.ENABLE_ENHANCED_OUTPUT_HANDLING]: boolean;
+ [Flag.SHARE_EXECUTION_RESULTS]: boolean;
[Flag.AGENT_FAVORITING]: boolean;
};
@@ -32,6 +34,7 @@ const mockFlags = {
[Flag.NEW_AGENT_RUNS]: false,
[Flag.GRAPH_SEARCH]: true,
[Flag.ENABLE_ENHANCED_OUTPUT_HANDLING]: false,
+ [Flag.SHARE_EXECUTION_RESULTS]: false,
[Flag.AGENT_FAVORITING]: false,
};