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(frontend): add AutoGPT logo to share page and zip download for outputs (#11741)

Nicholas Tindlee4f291e54b2f
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index 3559071043..12a31e6bd1 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -30,6 +30,7 @@ from pydantic import BaseModel, Field
from starlette.status import HTTP_204_NO_CONTENT, HTTP_404_NOT_FOUND
from typing_extensions import Optional, TypedDict
+from backend.api.features.workspace.routes import create_file_download_response
from backend.api.model import (
CreateAPIKeyRequest,
CreateAPIKeyResponse,
@@ -96,6 +97,7 @@ from backend.data.user import (
update_user_notification_preference,
update_user_timezone,
)
+from backend.data.workspace import get_workspace_file_by_id
from backend.executor import scheduler
from backend.executor import utils as execution_utils
from backend.integrations.webhooks.graph_lifecycle_hooks import (
@@ -1703,6 +1705,10 @@ async def enable_execution_sharing(
# Generate a unique share token
share_token = str(uuid.uuid4())
+ # Remove stale allowlist records before updating the token — prevents a
+ # window where old records + new token could coexist.
+ await execution_db.delete_shared_execution_files(execution_id=graph_exec_id)
+
# Update the execution with share info
await execution_db.update_graph_execution_share_status(
execution_id=graph_exec_id,
@@ -1712,6 +1718,14 @@ async def enable_execution_sharing(
shared_at=datetime.now(timezone.utc),
)
+ # Create allowlist of workspace files referenced in outputs
+ await execution_db.create_shared_execution_files(
+ execution_id=graph_exec_id,
+ share_token=share_token,
+ user_id=user_id,
+ outputs=execution.outputs,
+ )
+
# Return the share URL
frontend_url = settings.config.frontend_base_url or "http://localhost:3000"
share_url = f"{frontend_url}/share/{share_token}"
@@ -1737,6 +1751,9 @@ async def disable_execution_sharing(
if not execution:
raise HTTPException(status_code=404, detail="Execution not found")
+ # Remove shared file allowlist records
+ await execution_db.delete_shared_execution_files(execution_id=graph_exec_id)
+
# Remove share info
await execution_db.update_graph_execution_share_status(
execution_id=graph_exec_id,
@@ -1762,6 +1779,43 @@ async def get_shared_execution(
return execution
+@v1_router.get(
+ "/public/shared/{share_token}/files/{file_id}/download",
+ summary="Download a file from a shared execution",
+ operation_id="download_shared_file",
+ tags=["graphs"],
+)
+async def download_shared_file(
+ share_token: Annotated[
+ str,
+ Path(pattern=r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"),
+ ],
+ file_id: Annotated[
+ str,
+ Path(pattern=r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"),
+ ],
+) -> Response:
+ """Download a workspace file from a shared execution (no auth required).
+
+ Validates that the file was explicitly exposed when sharing was enabled.
+ Returns a uniform 404 for all failure modes to prevent enumeration attacks.
+ """
+ # Single-query validation against the allowlist
+ execution_id = await execution_db.get_shared_execution_file(
+ share_token=share_token, file_id=file_id
+ )
+ if not execution_id:
+ raise HTTPException(status_code=404, detail="Not found")
+
+ # Look up the actual file (no workspace scoping needed — the allowlist
+ # already validated that this file belongs to the shared execution)
+ file = await get_workspace_file_by_id(file_id)
+ if not file:
+ raise HTTPException(status_code=404, detail="Not found")
+
+ return await create_file_download_response(file, inline=True)
+
+
########################################################
##################### Schedules ########################
########################################################
diff --git a/autogpt_platform/backend/backend/api/features/v1_share_test.py b/autogpt_platform/backend/backend/api/features/v1_share_test.py
new file mode 100644
index 0000000000..de5d14ad80
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/v1_share_test.py
@@ -0,0 +1,157 @@
+"""Tests for the public shared file download endpoint."""
+
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from starlette.responses import Response
+
+from backend.api.features.v1 import v1_router
+from backend.data.workspace import WorkspaceFile
+
+app = FastAPI()
+app.include_router(v1_router, prefix="/api")
+
+VALID_TOKEN = "550e8400-e29b-41d4-a716-446655440000"
+VALID_FILE_ID = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
+
+
+def _make_workspace_file(**overrides) -> WorkspaceFile:
+ defaults = {
+ "id": VALID_FILE_ID,
+ "workspace_id": "ws-001",
+ "created_at": datetime(2026, 1, 1, tzinfo=timezone.utc),
+ "updated_at": datetime(2026, 1, 1, tzinfo=timezone.utc),
+ "name": "image.png",
+ "path": "/image.png",
+ "storage_path": "local://uploads/image.png",
+ "mime_type": "image/png",
+ "size_bytes": 4,
+ "checksum": None,
+ "is_deleted": False,
+ "deleted_at": None,
+ "metadata": {},
+ }
+ defaults.update(overrides)
+ return WorkspaceFile(**defaults)
+
+
+def _mock_download_response(**kwargs):
+ """Return an AsyncMock that resolves to a Response with inline disposition."""
+
+ async def _handler(file, *, inline=False):
+ return Response(
+ content=b"\x89PNG",
+ media_type="image/png",
+ headers={
+ "Content-Disposition": (
+ 'inline; filename="image.png"'
+ if inline
+ else 'attachment; filename="image.png"'
+ ),
+ "Content-Length": "4",
+ },
+ )
+
+ return _handler
+
+
+class TestDownloadSharedFile:
+ """Tests for GET /api/public/shared/{token}/files/{id}/download."""
+
+ @pytest.fixture(autouse=True)
+ def _client(self):
+ self.client = TestClient(app, raise_server_exceptions=False)
+
+ def test_valid_token_and_file_returns_inline_content(self):
+ with (
+ patch(
+ "backend.api.features.v1.execution_db.get_shared_execution_file",
+ new_callable=AsyncMock,
+ return_value="exec-123",
+ ),
+ patch(
+ "backend.api.features.v1.get_workspace_file_by_id",
+ new_callable=AsyncMock,
+ return_value=_make_workspace_file(),
+ ),
+ patch(
+ "backend.api.features.v1.create_file_download_response",
+ side_effect=_mock_download_response(),
+ ),
+ ):
+ response = self.client.get(
+ f"/api/public/shared/{VALID_TOKEN}/files/{VALID_FILE_ID}/download"
+ )
+
+ assert response.status_code == 200
+ assert response.content == b"\x89PNG"
+ assert "inline" in response.headers["Content-Disposition"]
+
+ def test_invalid_token_format_returns_422(self):
+ response = self.client.get(
+ f"/api/public/shared/not-a-uuid/files/{VALID_FILE_ID}/download"
+ )
+ assert response.status_code == 422
+
+ def test_token_not_in_allowlist_returns_404(self):
+ with patch(
+ "backend.api.features.v1.execution_db.get_shared_execution_file",
+ new_callable=AsyncMock,
+ return_value=None,
+ ):
+ response = self.client.get(
+ f"/api/public/shared/{VALID_TOKEN}/files/{VALID_FILE_ID}/download"
+ )
+ assert response.status_code == 404
+
+ def test_file_missing_from_workspace_returns_404(self):
+ with (
+ patch(
+ "backend.api.features.v1.execution_db.get_shared_execution_file",
+ new_callable=AsyncMock,
+ return_value="exec-123",
+ ),
+ patch(
+ "backend.api.features.v1.get_workspace_file_by_id",
+ new_callable=AsyncMock,
+ return_value=None,
+ ),
+ ):
+ response = self.client.get(
+ f"/api/public/shared/{VALID_TOKEN}/files/{VALID_FILE_ID}/download"
+ )
+ assert response.status_code == 404
+
+ def test_uniform_404_prevents_enumeration(self):
+ """Both failure modes produce identical 404 — no information leak."""
+ with patch(
+ "backend.api.features.v1.execution_db.get_shared_execution_file",
+ new_callable=AsyncMock,
+ return_value=None,
+ ):
+ resp_no_allow = self.client.get(
+ f"/api/public/shared/{VALID_TOKEN}/files/{VALID_FILE_ID}/download"
+ )
+
+ with (
+ patch(
+ "backend.api.features.v1.execution_db.get_shared_execution_file",
+ new_callable=AsyncMock,
+ return_value="exec-123",
+ ),
+ patch(
+ "backend.api.features.v1.get_workspace_file_by_id",
+ new_callable=AsyncMock,
+ return_value=None,
+ ),
+ ):
+ resp_no_file = self.client.get(
+ f"/api/public/shared/{VALID_TOKEN}/files/{VALID_FILE_ID}/download"
+ )
+
+ assert resp_no_allow.status_code == 404
+ assert resp_no_file.status_code == 404
+ assert resp_no_allow.json() == resp_no_file.json()
diff --git a/autogpt_platform/backend/backend/api/features/workspace/routes.py b/autogpt_platform/backend/backend/api/features/workspace/routes.py
index 39bcc6c7c4..c22cc445c4 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/routes.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/routes.py
@@ -29,7 +29,9 @@ from backend.util.workspace import WorkspaceManager
from backend.util.workspace_storage import get_workspace_storage
-def _sanitize_filename_for_header(filename: str) -> str:
+def _sanitize_filename_for_header(
+ filename: str, disposition: str = "attachment"
+) -> str:
"""
Sanitize filename for Content-Disposition header to prevent header injection.
@@ -44,11 +46,11 @@ def _sanitize_filename_for_header(filename: str) -> str:
# Check if filename has non-ASCII characters
try:
sanitized.encode("ascii")
- return f'attachment; filename="{sanitized}"'
+ return f'{disposition}; filename="{sanitized}"'
except UnicodeEncodeError:
# Use RFC5987 encoding for UTF-8 filenames
encoded = quote(sanitized, safe="")
- return f"attachment; filename*=UTF-8''{encoded}"
+ return f"{disposition}; filename*=UTF-8''{encoded}"
logger = logging.getLogger(__name__)
@@ -58,19 +60,26 @@ router = fastapi.APIRouter(
)
-def _create_streaming_response(content: bytes, file: WorkspaceFile) -> Response:
+def _create_streaming_response(
+ content: bytes, file: WorkspaceFile, *, inline: bool = False
+) -> Response:
"""Create a streaming response for file content."""
+ disposition = _sanitize_filename_for_header(
+ file.name, disposition="inline" if inline else "attachment"
+ )
return Response(
content=content,
media_type=file.mime_type,
headers={
- "Content-Disposition": _sanitize_filename_for_header(file.name),
+ "Content-Disposition": disposition,
"Content-Length": str(len(content)),
},
)
-async def _create_file_download_response(file: WorkspaceFile) -> Response:
+async def create_file_download_response(
+ file: WorkspaceFile, *, inline: bool = False
+) -> Response:
"""
Create a download response for a workspace file.
@@ -82,7 +91,7 @@ async def _create_file_download_response(file: WorkspaceFile) -> Response:
# For local storage, stream the file directly
if file.storage_path.startswith("local://"):
content = await storage.retrieve(file.storage_path)
- return _create_streaming_response(content, file)
+ return _create_streaming_response(content, file, inline=inline)
# For GCS, try to redirect to signed URL, fall back to streaming
try:
@@ -90,7 +99,7 @@ async def _create_file_download_response(file: WorkspaceFile) -> Response:
# If we got back an API path (fallback), stream directly instead
if url.startswith("/api/"):
content = await storage.retrieve(file.storage_path)
- return _create_streaming_response(content, file)
+ return _create_streaming_response(content, file, inline=inline)
return fastapi.responses.RedirectResponse(url=url, status_code=302)
except Exception as e:
# Log the signed URL failure with context
@@ -102,7 +111,7 @@ async def _create_file_download_response(file: WorkspaceFile) -> Response:
# Fall back to streaming directly from GCS
try:
content = await storage.retrieve(file.storage_path)
- return _create_streaming_response(content, file)
+ return _create_streaming_response(content, file, inline=inline)
except Exception as fallback_error:
logger.error(
f"Fallback streaming also failed for file {file.id} "
@@ -169,7 +178,7 @@ async def download_file(
if file is None:
raise fastapi.HTTPException(status_code=404, detail="File not found")
- return await _create_file_download_response(file)
+ return await create_file_download_response(file)
@router.delete(
diff --git a/autogpt_platform/backend/backend/api/features/workspace/routes_test.py b/autogpt_platform/backend/backend/api/features/workspace/routes_test.py
index 42726ba051..ffc712014f 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/routes_test.py
@@ -600,3 +600,221 @@ def test_list_files_offset_is_echoed_back(mock_manager_cls, mock_get_workspace):
mock_instance.list_files.assert_called_once_with(
limit=11, offset=50, include_all_sessions=True
)
+
+
+# -- _sanitize_filename_for_header tests --
+
+
+class TestSanitizeFilenameForHeader:
+ def test_simple_ascii_attachment(self):
+ from backend.api.features.workspace.routes import _sanitize_filename_for_header
+
+ assert _sanitize_filename_for_header("report.pdf") == (
+ 'attachment; filename="report.pdf"'
+ )
+
+ def test_inline_disposition(self):
+ from backend.api.features.workspace.routes import _sanitize_filename_for_header
+
+ assert _sanitize_filename_for_header("image.png", disposition="inline") == (
+ 'inline; filename="image.png"'
+ )
+
+ def test_strips_cr_lf_null(self):
+ from backend.api.features.workspace.routes import _sanitize_filename_for_header
+
+ result = _sanitize_filename_for_header("a\rb\nc\x00d.txt")
+ assert "\r" not in result
+ assert "\n" not in result
+ assert "\x00" not in result
+ assert 'filename="abcd.txt"' in result
+
+ def test_escapes_quotes(self):
+ from backend.api.features.workspace.routes import _sanitize_filename_for_header
+
+ result = _sanitize_filename_for_header('file"name.txt')
+ assert 'filename="file\\"name.txt"' in result
+
+ def test_header_injection_blocked(self):
+ from backend.api.features.workspace.routes import _sanitize_filename_for_header
+
+ result = _sanitize_filename_for_header("evil.txt\r\nX-Injected: true")
+ # CR/LF stripped — the remaining text is safely inside the quoted value
+ assert "\r" not in result
+ assert "\n" not in result
+ assert result == 'attachment; filename="evil.txtX-Injected: true"'
+
+ def test_unicode_uses_rfc5987(self):
+ from backend.api.features.workspace.routes import _sanitize_filename_for_header
+
+ result = _sanitize_filename_for_header("日本語.pdf")
+ assert "filename*=UTF-8''" in result
+ assert "attachment" in result
+
+ def test_unicode_inline(self):
+ from backend.api.features.workspace.routes import _sanitize_filename_for_header
+
+ result = _sanitize_filename_for_header("图片.png", disposition="inline")
+ assert result.startswith("inline; filename*=UTF-8''")
+
+ def test_empty_filename(self):
+ from backend.api.features.workspace.routes import _sanitize_filename_for_header
+
+ result = _sanitize_filename_for_header("")
+ assert result == 'attachment; filename=""'
+
+
+# -- _create_streaming_response tests --
+
+
+class TestCreateStreamingResponse:
+ def test_attachment_disposition_by_default(self):
+ from backend.api.features.workspace.routes import _create_streaming_response
+
+ file = _make_file(name="data.bin", mime_type="application/octet-stream")
+ response = _create_streaming_response(b"binary-data", file)
+ assert (
+ response.headers["Content-Disposition"] == 'attachment; filename="data.bin"'
+ )
+ assert response.headers["Content-Type"] == "application/octet-stream"
+ assert response.headers["Content-Length"] == "11"
+ assert response.body == b"binary-data"
+
+ def test_inline_disposition(self):
+ from backend.api.features.workspace.routes import _create_streaming_response
+
+ file = _make_file(name="photo.png", mime_type="image/png")
+ response = _create_streaming_response(b"\x89PNG", file, inline=True)
+ assert response.headers["Content-Disposition"] == 'inline; filename="photo.png"'
+ assert response.headers["Content-Type"] == "image/png"
+
+ def test_inline_sanitizes_filename(self):
+ from backend.api.features.workspace.routes import _create_streaming_response
+
+ file = _make_file(name='evil"\r\n.txt', mime_type="text/plain")
+ response = _create_streaming_response(b"data", file, inline=True)
+ assert "\r" not in response.headers["Content-Disposition"]
+ assert "\n" not in response.headers["Content-Disposition"]
+ assert "inline" in response.headers["Content-Disposition"]
+
+ def test_content_length_matches_body(self):
+ from backend.api.features.workspace.routes import _create_streaming_response
+
+ content = b"x" * 1000
+ file = _make_file(name="big.bin", mime_type="application/octet-stream")
+ response = _create_streaming_response(content, file)
+ assert response.headers["Content-Length"] == "1000"
+
+
+# -- create_file_download_response tests --
+
+
+class TestCreateFileDownloadResponse:
+ @pytest.mark.asyncio
+ async def test_local_storage_returns_streaming_response(self, mocker):
+ from backend.api.features.workspace.routes import create_file_download_response
+
+ mock_storage = AsyncMock()
+ mock_storage.retrieve.return_value = b"file contents"
+ mocker.patch(
+ "backend.api.features.workspace.routes.get_workspace_storage",
+ return_value=mock_storage,
+ )
+
+ file = _make_file(
+ storage_path="local://uploads/test.txt",
+ mime_type="text/plain",
+ )
+ response = await create_file_download_response(file)
+ assert response.status_code == 200
+ assert response.body == b"file contents"
+ assert "attachment" in response.headers["Content-Disposition"]
+
+ @pytest.mark.asyncio
+ async def test_local_storage_inline(self, mocker):
+ from backend.api.features.workspace.routes import create_file_download_response
+
+ mock_storage = AsyncMock()
+ mock_storage.retrieve.return_value = b"\x89PNG"
+ mocker.patch(
+ "backend.api.features.workspace.routes.get_workspace_storage",
+ return_value=mock_storage,
+ )
+
+ file = _make_file(
+ storage_path="local://uploads/photo.png",
+ mime_type="image/png",
+ name="photo.png",
+ )
+ response = await create_file_download_response(file, inline=True)
+ assert "inline" in response.headers["Content-Disposition"]
+
+ @pytest.mark.asyncio
+ async def test_gcs_redirect(self, mocker):
+ from backend.api.features.workspace.routes import create_file_download_response
+
+ mock_storage = AsyncMock()
+ mock_storage.get_download_url.return_value = (
+ "https://storage.googleapis.com/signed-url"
+ )
+ mocker.patch(
+ "backend.api.features.workspace.routes.get_workspace_storage",
+ return_value=mock_storage,
+ )
+
+ file = _make_file(storage_path="gcs://bucket/file.pdf")
+ response = await create_file_download_response(file)
+ assert response.status_code == 302
+ assert (
+ response.headers["location"] == "https://storage.googleapis.com/signed-url"
+ )
+
+ @pytest.mark.asyncio
+ async def test_gcs_api_fallback_streams_directly(self, mocker):
+ from backend.api.features.workspace.routes import create_file_download_response
+
+ mock_storage = AsyncMock()
+ mock_storage.get_download_url.return_value = "/api/fallback"
+ mock_storage.retrieve.return_value = b"fallback content"
+ mocker.patch(
+ "backend.api.features.workspace.routes.get_workspace_storage",
+ return_value=mock_storage,
+ )
+
+ file = _make_file(storage_path="gcs://bucket/file.txt")
+ response = await create_file_download_response(file)
+ assert response.status_code == 200
+ assert response.body == b"fallback content"
+
+ @pytest.mark.asyncio
+ async def test_gcs_signed_url_failure_falls_back_to_streaming(self, mocker):
+ from backend.api.features.workspace.routes import create_file_download_response
+
+ mock_storage = AsyncMock()
+ mock_storage.get_download_url.side_effect = RuntimeError("GCS error")
+ mock_storage.retrieve.return_value = b"streamed"
+ mocker.patch(
+ "backend.api.features.workspace.routes.get_workspace_storage",
+ return_value=mock_storage,
+ )
+
+ file = _make_file(storage_path="gcs://bucket/file.txt")
+ response = await create_file_download_response(file)
+ assert response.status_code == 200
+ assert response.body == b"streamed"
+
+ @pytest.mark.asyncio
+ async def test_gcs_total_failure_raises(self, mocker):
+ from backend.api.features.workspace.routes import create_file_download_response
+
+ mock_storage = AsyncMock()
+ mock_storage.get_download_url.side_effect = RuntimeError("GCS error")
+ mock_storage.retrieve.side_effect = RuntimeError("Also failed")
+ mocker.patch(
+ "backend.api.features.workspace.routes.get_workspace_storage",
+ return_value=mock_storage,
+ )
+
+ file = _make_file(storage_path="gcs://bucket/file.txt")
+ with pytest.raises(RuntimeError, match="Also failed"):
+ await create_file_download_response(file)
diff --git a/autogpt_platform/backend/backend/data/execution.py b/autogpt_platform/backend/backend/data/execution.py
index 4403a59080..cd50d7df3c 100644
--- a/autogpt_platform/backend/backend/data/execution.py
+++ b/autogpt_platform/backend/backend/data/execution.py
@@ -19,11 +19,15 @@ from typing import (
from prisma import Json
from prisma.enums import AgentExecutionStatus
+from prisma.errors import ForeignKeyViolationError, UniqueViolationError
from prisma.models import (
AgentGraphExecution,
AgentNodeExecution,
AgentNodeExecutionInputOutput,
AgentNodeExecutionKeyValueData,
+ SharedExecutionFile,
+ UserWorkspace,
+ UserWorkspaceFile,
)
from prisma.types import (
AgentGraphExecutionOrderByInput,
@@ -1602,6 +1606,121 @@ async def get_graph_execution_by_share_token(
)
+def _extract_workspace_file_ids(outputs: CompletedBlockOutput) -> set[str]:
+ """Extract workspace file IDs from execution outputs.
+
+ Scans all output values for workspace:// URI strings and extracts
+ the file IDs. Only matches values that are plain strings starting
+ with workspace://, not substrings within larger text.
+ """
+ file_ids: set[str] = set()
+
+ def _scan(value: Any) -> None:
+ if isinstance(value, str) and value.startswith("workspace://"):
+ raw = value.removeprefix("workspace://")
+ file_ref = raw.split("#", 1)[0] if "#" in raw else raw
+ if file_ref and not file_ref.startswith("/"):
+ file_ids.add(file_ref)
+ elif isinstance(value, list):
+ for item in value:
+ _scan(item)
+ elif isinstance(value, dict):
+ for v in value.values():
+ _scan(v)
+
+ for output_values in outputs.values():
+ if isinstance(output_values, list):
+ for val in output_values:
+ _scan(val)
+ else:
+ _scan(output_values)
+
+ return file_ids
+
+
+async def create_shared_execution_files(
+ execution_id: str,
+ share_token: str,
+ user_id: str,
+ outputs: CompletedBlockOutput,
+) -> int:
+ """Scan execution outputs for workspace files and create allowlist records.
+
+ Only files belonging to the user's workspace are allowlisted — prevents
+ cross-workspace file exposure via crafted outputs.
+
+ Returns the number of records created.
+ """
+ file_ids = _extract_workspace_file_ids(outputs)
+ if not file_ids:
+ return 0
+
+ # Validate file IDs belong to the user's workspace
+ workspace = await UserWorkspace.prisma().find_unique(where={"userId": user_id})
+ if not workspace:
+ return 0
+
+ owned_files = await UserWorkspaceFile.prisma().find_many(
+ where={
+ "id": {"in": list(file_ids)},
+ "workspaceId": workspace.id,
+ "isDeleted": False,
+ }
+ )
+ owned_ids = {f.id for f in owned_files}
+
+ created = 0
+ for file_id in owned_ids:
+ try:
+ await SharedExecutionFile.prisma().create(
+ data={
+ "executionId": execution_id,
+ "fileId": file_id,
+ "shareToken": share_token,
+ }
+ )
+ created += 1
+ except UniqueViolationError:
+ logger.debug(
+ f"Skipping shared file record for {file_id}: " f"record already exists"
+ )
+ except ForeignKeyViolationError:
+ logger.debug(
+ f"Skipping shared file record for {file_id}: " f"file does not exist"
+ )
+ return created
+
+
+async def delete_shared_execution_files(execution_id: str) -> int:
+ """Delete all shared file records for an execution.
+
+ Returns the number of records deleted.
+ """
+ result = await SharedExecutionFile.prisma().delete_many(
+ where={"executionId": execution_id}
+ )
+ return result
+
+
+async def get_shared_execution_file(
+ share_token: str,
+ file_id: str,
+) -> str | None:
+ """Look up a file ID in the shared execution file allowlist.
+
+ Returns the execution ID if the file is in the allowlist, None otherwise.
+ Uses a single query and returns a uniform None for all failure modes
+ to prevent timing-based enumeration attacks.
+ """
+ record = await SharedExecutionFile.prisma().find_first(
+ where={
+ "shareToken": share_token,
+ "fileId": file_id,
+ }
+ )
+ return record.executionId if record else None
+
+
async def get_frequently_executed_graphs(
days_back: int = 30,
min_executions: int = 10,
diff --git a/autogpt_platform/backend/backend/data/shared_execution_file_test.py b/autogpt_platform/backend/backend/data/shared_execution_file_test.py
new file mode 100644
index 0000000000..e9beed280c
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/shared_execution_file_test.py
@@ -0,0 +1,72 @@
+"""Tests for SharedExecutionFile workspace URI extraction logic."""
+
+from backend.data.execution import _extract_workspace_file_ids
+
+
+class TestExtractWorkspaceFileIds:
+ def test_extracts_simple_workspace_uri(self):
+ outputs = {"image": ["workspace://abc123"]}
+ assert _extract_workspace_file_ids(outputs) == {"abc123"}
+
+ def test_extracts_workspace_uri_with_mime_fragment(self):
+ outputs = {"image": ["workspace://abc123#image/png"]}
+ assert _extract_workspace_file_ids(outputs) == {"abc123"}
+
+ def test_extracts_multiple_files_from_multiple_outputs(self):
+ outputs = {
+ "images": ["workspace://file1#image/png", "workspace://file2#image/jpeg"],
+ "video": ["workspace://file3#video/mp4"],
+ }
+ assert _extract_workspace_file_ids(outputs) == {"file1", "file2", "file3"}
+
+ def test_ignores_non_workspace_strings(self):
+ outputs = {
+ "text": ["hello world"],
+ "url": ["https://example.com/image.png"],
+ "data": ["data:image/png;base64,abc"],
+ }
+ assert _extract_workspace_file_ids(outputs) == set()
+
+ def test_ignores_path_references(self):
+ """workspace:///path/to/file is a path reference, not a file ID."""
+ outputs = {"file": ["workspace:///path/to/file.txt"]}
+ assert _extract_workspace_file_ids(outputs) == set()
+
+ def test_handles_nested_dicts_in_output_values(self):
+ outputs = {
+ "result": [{"url": "workspace://nested-file#image/png", "label": "test"}]
+ }
+ assert _extract_workspace_file_ids(outputs) == {"nested-file"}
+
+ def test_handles_nested_lists_in_output_values(self):
+ outputs = {"result": [["workspace://inner-file"]]}
+ assert _extract_workspace_file_ids(outputs) == {"inner-file"}
+
+ def test_handles_empty_outputs(self):
+ assert _extract_workspace_file_ids({}) == set()
+
+ def test_handles_non_string_values(self):
+ outputs = {"count": [42], "flag": [True], "empty": [None]}
+ assert _extract_workspace_file_ids(outputs) == set()
+
+ def test_deduplicates_repeated_file_ids(self):
+ outputs = {
+ "a": ["workspace://same-file#image/png"],
+ "b": ["workspace://same-file#image/jpeg"],
+ }
+ assert _extract_workspace_file_ids(outputs) == {"same-file"}
+
+ def test_does_not_match_workspace_substring_in_text(self):
+ """Plain text that contains workspace:// as a substring should NOT be extracted
+ because the value itself must start with workspace://."""
+ outputs = {"text": ["check out workspace://fake-id for details"]}
+ # The string starts with "check out", not "workspace://", so no match
+ assert _extract_workspace_file_ids(outputs) == set()
+
+ def test_mixed_workspace_and_non_workspace_outputs(self):
+ outputs = {
+ "image": ["workspace://real-file#image/png"],
+ "text": ["just some text"],
+ "url": ["https://example.com"],
+ }
+ assert _extract_workspace_file_ids(outputs) == {"real-file"}
diff --git a/autogpt_platform/backend/backend/data/workspace.py b/autogpt_platform/backend/backend/data/workspace.py
index 43e328813b..62220b45fe 100644
--- a/autogpt_platform/backend/backend/data/workspace.py
+++ b/autogpt_platform/backend/backend/data/workspace.py
@@ -204,6 +204,22 @@ async def get_workspace_file(
return WorkspaceFile.from_db(file) if file else None
+async def get_workspace_file_by_id(
+ file_id: str,
+) -> Optional[WorkspaceFile]:
+ """
+ Get a workspace file by ID without workspace scoping.
+
+ Only use this when access has already been validated through another
+ mechanism (e.g. SharedExecutionFile allowlist). For user-facing
+ endpoints, use get_workspace_file() which enforces workspace scoping.
+ """
+ file = await UserWorkspaceFile.prisma().find_first(
+ where={"id": file_id, "isDeleted": False}
+ )
+ return WorkspaceFile.from_db(file) if file else None
+
+
async def get_workspace_file_by_path(
workspace_id: str,
path: str,
diff --git a/autogpt_platform/backend/migrations/20260417000000_add_shared_execution_file/migration.sql b/autogpt_platform/backend/migrations/20260417000000_add_shared_execution_file/migration.sql
new file mode 100644
index 0000000000..ad8b67647e
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260417000000_add_shared_execution_file/migration.sql
@@ -0,0 +1,25 @@
+-- CreateTable
+CREATE TABLE "SharedExecutionFile" (
+ "id" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "executionId" TEXT NOT NULL,
+ "fileId" TEXT NOT NULL,
+ "shareToken" TEXT NOT NULL,
+
+ CONSTRAINT "SharedExecutionFile_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "SharedExecutionFile_shareToken_fileId_key" ON "SharedExecutionFile"("shareToken", "fileId");
+
+-- CreateIndex
+CREATE INDEX "SharedExecutionFile_shareToken_idx" ON "SharedExecutionFile"("shareToken");
+
+-- CreateIndex
+CREATE INDEX "SharedExecutionFile_executionId_idx" ON "SharedExecutionFile"("executionId");
+
+-- AddForeignKey
+ALTER TABLE "SharedExecutionFile" ADD CONSTRAINT "SharedExecutionFile_executionId_fkey" FOREIGN KEY ("executionId") REFERENCES "AgentGraphExecution"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "SharedExecutionFile" ADD CONSTRAINT "SharedExecutionFile_fileId_fkey" FOREIGN KEY ("fileId") REFERENCES "UserWorkspaceFile"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 7774873829..b6ddc7cad0 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -204,10 +204,32 @@ model UserWorkspaceFile {
metadata Json @default("{}")
+ SharedExecutionFiles SharedExecutionFile[]
+
@@unique([workspaceId, path])
@@index([workspaceId, isDeleted])
}
+// Tracks which workspace files are exposed via a shared execution.
+// Created when sharing is enabled, deleted when sharing is disabled.
+// The public file download endpoint validates against this table.
+model SharedExecutionFile {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+
+ executionId String
+ Execution AgentGraphExecution @relation(fields: [executionId], references: [id], onDelete: Cascade)
+
+ fileId String
+ File UserWorkspaceFile @relation(fields: [fileId], references: [id], onDelete: Cascade)
+
+ shareToken String
+
+ @@unique([shareToken, fileId])
+ @@index([shareToken])
+ @@index([executionId])
+}
+
model BuilderSearchHistory {
id String @id @default(uuid())
createdAt DateTime @default(now())
@@ -589,9 +611,10 @@ model AgentGraphExecution {
ChildExecutions AgentGraphExecution[] @relation("ParentChildExecution")
// Sharing fields
- isShared Boolean @default(false)
- shareToken String? @unique
- sharedAt DateTime?
+ isShared Boolean @default(false)
+ shareToken String? @unique
+ sharedAt DateTime?
+ SharedExecutionFiles SharedExecutionFile[]
@@index([agentGraphId, agentGraphVersion])
@@index([userId, isDeleted, createdAt])
diff --git a/autogpt_platform/frontend/package.json b/autogpt_platform/frontend/package.json
index 9fa590c04e..68815bcf79 100644
--- a/autogpt_platform/frontend/package.json
+++ b/autogpt_platform/frontend/package.json
@@ -92,6 +92,7 @@
"geist": "1.5.1",
"highlight.js": "11.11.1",
"jaro-winkler": "0.2.8",
+ "jszip": "3.10.1",
"katex": "0.16.25",
"launchdarkly-react-client-sdk": "3.9.0",
"lodash": "4.17.21",
diff --git a/autogpt_platform/frontend/pnpm-lock.yaml b/autogpt_platform/frontend/pnpm-lock.yaml
index a6ef21282c..82a76350af 100644
--- a/autogpt_platform/frontend/pnpm-lock.yaml
+++ b/autogpt_platform/frontend/pnpm-lock.yaml
@@ -192,6 +192,9 @@ importers:
jaro-winkler:
specifier: 0.2.8
version: 0.2.8
+ jszip:
+ specifier: 3.10.1
+ version: 3.10.1
katex:
specifier: 0.16.25
version: 0.16.25
@@ -5919,6 +5922,9 @@ packages:
engines: {node: '>=16.x'}
hasBin: true
+ resolution: {integrity: sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==}
+
resolution: {integrity: sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw==}
@@ -6279,6 +6285,9 @@ packages:
resolution: {integrity: sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==}
engines: {node: '>=4.0'}
+ resolution: {integrity: sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==}
+
resolution: {integrity: sha512-ZNOIIGMzqCGcHQEA2Q4rIQQ3Df6gSIfne+X9Rly9Bc2y55KxAZu8iGv+n2pP0bLf0XAOctJZgeloC54hWzCahQ==}
engines: {node: '>=16'}
@@ -6348,6 +6357,9 @@ packages:
resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==}
engines: {node: '>= 0.8.0'}
+ resolution: {integrity: sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==}
+
resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==}
engines: {node: '>=14'}
@@ -15290,6 +15302,8 @@ snapshots:
+
@@ -15646,6 +15660,13 @@ snapshots:
object.assign: 4.1.7
object.values: 1.2.1
+ dependencies:
+ lie: 3.3.0
+ pako: 1.0.11
+ readable-stream: 2.3.8
+ setimmediate: 1.0.5
+
dependencies:
lodash: 4.17.21
@@ -15739,6 +15760,10 @@ snapshots:
prelude-ls: 1.2.1
type-check: 0.4.0
+ dependencies:
+ immediate: 3.0.6
+
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
index 1c37c6c72f..3db91f411b 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/share/[token]/page.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/[token]/page.tsx
@@ -119,7 +119,7 @@ export default function SharePage() {
<CardTitle>Output</CardTitle>
</CardHeader>
<CardContent>
- <RunOutputs outputs={executionData.outputs} />
+ <RunOutputs outputs={executionData.outputs} shareToken={token} />
</CardContent>
</Card>
diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/layout.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/layout.tsx
index 3b79d323c0..a0d4654ff8 100644
--- a/autogpt_platform/frontend/src/app/(no-navbar)/share/layout.tsx
+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/layout.tsx
@@ -1,4 +1,6 @@
import type { Metadata } from "next";
+import Image from "next/image";
+import Link from "next/link";
export const metadata: Metadata = {
title: "Shared Agent Run - AutoGPT",
@@ -13,6 +15,27 @@ export default function ShareLayout({
}) {
return (
<div className="min-h-screen bg-background">
+ <header className="border-b border-border bg-background">
+ <div className="container mx-auto flex justify-center px-4 py-4">
+ <Link href="/" className="inline-block">
+ <Image
+ src="/autogpt-logo-dark-bg.png"
+ alt="AutoGPT"
+ width={120}
+ height={54}
+ className="hidden h-8 w-auto dark:block"
+ />
+ <Image
+ src="/autogpt-logo-light-bg.png"
+ alt="AutoGPT"
+ width={120}
+ height={54}
+ className="block h-8 w-auto dark:hidden"
+ priority
+ />
+ </Link>
+ </div>
+ </header>
<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/NewAgentLibraryView/components/selected-views/OutputRenderers/utils/download.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/OutputRenderers/utils/download.ts
index 78adda8029..5111d4aeb2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/OutputRenderers/utils/download.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/OutputRenderers/utils/download.ts
@@ -1,74 +1,2 @@
-import { OutputRenderer, OutputMetadata } from "../types";
-
-export interface DownloadItem {
- value: any;
- metadata?: OutputMetadata;
- renderer: OutputRenderer;
-}
-
-export async function downloadOutputs(items: DownloadItem[]) {
- const concatenableTexts: string[] = [];
- const nonConcatenableDownloads: Array<{ blob: Blob; filename: string }> = [];
-
- for (const item of items) {
- if (item.renderer.isConcatenable(item.value, item.metadata)) {
- const copyContent = item.renderer.getCopyContent(
- item.value,
- item.metadata,
- );
- if (copyContent) {
- // Extract text from CopyContent
- let text: string;
- if (typeof copyContent.data === "string") {
- text = copyContent.data;
- } else if (copyContent.fallbackText) {
- text = copyContent.fallbackText;
- } else {
- continue;
- }
- concatenableTexts.push(text);
- }
- } else {
- const downloadContent = item.renderer.getDownloadContent(
- item.value,
- item.metadata,
- );
- if (downloadContent) {
- if (typeof downloadContent.data === "string") {
- if (downloadContent.data.startsWith("http")) {
- const link = document.createElement("a");
- link.href = downloadContent.data;
- link.download = downloadContent.filename;
- link.click();
- }
- } else {
- nonConcatenableDownloads.push({
- blob: downloadContent.data as Blob,
- filename: downloadContent.filename,
- });
- }
- }
- }
- }
-
- if (concatenableTexts.length > 0) {
- const combinedText = concatenableTexts.join("\n\n---\n\n");
- const blob = new Blob([combinedText], { type: "text/plain" });
- downloadBlob(blob, "combined_output.txt");
- }
-
- for (const download of nonConcatenableDownloads) {
- downloadBlob(download.blob, download.filename);
- }
-}
-
-function downloadBlob(blob: Blob, filename: string) {
- const url = URL.createObjectURL(blob);
- const link = document.createElement("a");
- link.href = url;
- link.download = filename;
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- URL.revokeObjectURL(url);
-}
+export { downloadOutputs } from "@/lib/utils/download-outputs";
+export type { DownloadItem } from "@/lib/utils/download-outputs";
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedRunView/components/RunOutputs.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedRunView/components/RunOutputs.tsx
index 9824283c40..deff4a3c03 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedRunView/components/RunOutputs.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedRunView/components/RunOutputs.tsx
@@ -15,9 +15,10 @@ type OutputsRecord = Record<string, Array<unknown>>;
interface RunOutputsProps {
outputs: OutputsRecord;
+ shareToken?: string;
}
-export function RunOutputs({ outputs }: RunOutputsProps) {
+export function RunOutputs({ outputs, shareToken }: RunOutputsProps) {
const items = useMemo(() => {
const list: Array<{
key: string;
@@ -30,6 +31,7 @@ export function RunOutputs({ outputs }: RunOutputsProps) {
Object.entries(outputs || {}).forEach(([key, values]) => {
(values || []).forEach((value, index) => {
const metadata: OutputMetadata = {};
+ if (shareToken) metadata.shareToken = shareToken;
if (
typeof value === "object" &&
value !== null &&
@@ -76,7 +78,7 @@ export function RunOutputs({ outputs }: RunOutputsProps) {
});
return list;
- }, [outputs]);
+ }, [outputs, shareToken]);
if (!items.length) {
return <div className="text-neutral-600">No output from this run.</div>;
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 3a9d8be33c..5997921c26 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -7227,6 +7227,50 @@
}
}
},
+ "/api/public/shared/{share_token}/files/{file_id}/download": {
+ "get": {
+ "tags": ["v1", "graphs"],
+ "summary": "Download a file from a shared execution",
+ "description": "Download a workspace file from a shared execution (no auth required).\n\nValidates that the file was explicitly exposed when sharing was enabled.\nReturns a uniform 404 for all failure modes to prevent enumeration attacks.",
+ "operationId": "download_shared_file",
+ "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"
+ }
+ },
+ {
+ "name": "file_id",
+ "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": "File Id"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": { "application/json": { "schema": {} } }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/review/action": {
"post": {
"tags": ["v2", "executions", "review", "v2", "executions", "review"],
diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.test.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.test.ts
index c5f8f6d9f9..0801e35936 100644
--- a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.test.ts
@@ -9,13 +9,16 @@ import {
} from "./route.helpers";
describe("isWorkspaceDownloadRequest", () => {
- it("matches api/workspace/files/{id}/download pattern", () => {
+ const VALID_UUID = "550e8400-e29b-41d4-a716-446655440000";
+ const VALID_UUID_2 = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
+
+ it("matches api/workspace/files/{uuid}/download pattern", () => {
expect(
isWorkspaceDownloadRequest([
"api",
"workspace",
"files",
- "abc-123",
+ VALID_UUID,
"download",
]),
).toBe(true);
@@ -30,7 +33,7 @@ describe("isWorkspaceDownloadRequest", () => {
"api",
"workspace",
"files",
- "id",
+ VALID_UUID,
"download",
"extra",
]),
@@ -43,7 +46,7 @@ describe("isWorkspaceDownloadRequest", () => {
"v1",
"workspace",
"files",
- "id",
+ VALID_UUID,
"download",
]),
).toBe(false);
@@ -55,11 +58,622 @@ describe("isWorkspaceDownloadRequest", () => {
"api",
"workspace",
"files",
- "id",
+ VALID_UUID,
+ "metadata",
+ ]),
+ ).toBe(false);
+ });
+
+ it("matches api/public/shared/{uuid}/files/{uuid}/download pattern", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "public",
+ "shared",
+ VALID_UUID,
+ "files",
+ VALID_UUID_2,
+ "download",
+ ]),
+ ).toBe(true);
+ });
+
+ it("rejects public shared paths not ending with download", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "public",
+ "shared",
+ VALID_UUID,
+ "files",
+ VALID_UUID_2,
"metadata",
]),
).toBe(false);
});
+
+ it("rejects non-UUID file ID in workspace path", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "not-a-uuid",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects non-UUID token in public share path", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "public",
+ "shared",
+ "not-a-uuid",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects non-UUID file ID in public share path", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "public",
+ "shared",
+ VALID_UUID,
+ "files",
+ "not-a-uuid",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("accepts uppercase hex in UUIDs", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "550E8400-E29B-41D4-A716-446655440000",
+ "download",
+ ]),
+ ).toBe(true);
+ });
+
+ describe("adversarial inputs", () => {
+ it("rejects empty path", () => {
+ expect(isWorkspaceDownloadRequest([])).toBe(false);
+ });
+
+ it("rejects single-segment path", () => {
+ expect(isWorkspaceDownloadRequest(["download"])).toBe(false);
+ });
+
+ it("rejects path traversal in file ID segment", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "../../etc/passwd",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects path traversal in token segment", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "public",
+ "shared",
+ "../../etc/passwd",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects path traversal replacing fixed segments", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "..",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "..",
+ "workspace",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects swapped workspace/public segments to confuse routing", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "public",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "shared",
+ VALID_UUID,
+ "files",
+ VALID_UUID_2,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects case variations on fixed segments", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "API",
+ "workspace",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "Workspace",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ VALID_UUID,
+ "DOWNLOAD",
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "PUBLIC",
+ "shared",
+ VALID_UUID,
+ "files",
+ VALID_UUID_2,
+ "download",
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "public",
+ "SHARED",
+ VALID_UUID,
+ "files",
+ VALID_UUID_2,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects empty string in fixed segments", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects empty token in public share path", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "public",
+ "shared",
+ "",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects empty file ID in public share path", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "public",
+ "shared",
+ VALID_UUID,
+ "files",
+ "",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects empty file ID in workspace path", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects UUID with null bytes injected", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ VALID_UUID + "\x00.jpg",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects UUID with trailing garbage", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ VALID_UUID + "-extra",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects UUID with leading garbage", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "prefix-" + VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects truncated UUIDs", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "550e8400-e29b-41d4",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects UUID-length strings with wrong format", () => {
+ // Right length (36 chars) but missing hyphens
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "550e8400e29b41d4a716446655440000xxxx",
+ "download",
+ ]),
+ ).toBe(false);
+ // Hyphens in wrong positions
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "550e-8400e29b-41d4a716-44665544-0000",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects UUID with non-hex characters", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "550e8400-e29b-41d4-a716-44665544000g",
+ "download",
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "550e8400-e29b-41d4-a716-44665544000!",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects SQL injection via ID segment", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "'; DROP TABLE files;--",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects padded segments with whitespace", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ " workspace",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace ",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ " " + VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects extra trailing segments after download", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ VALID_UUID,
+ "download",
+ "",
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "public",
+ "shared",
+ VALID_UUID,
+ "files",
+ VALID_UUID_2,
+ "download",
+ "extra",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects extra leading segments before api", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "prefix",
+ "api",
+ "workspace",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "",
+ "api",
+ "public",
+ "shared",
+ VALID_UUID,
+ "files",
+ VALID_UUID_2,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects URL-encoded segment lookalikes", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace%2Ffiles",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "public%2Fshared",
+ VALID_UUID,
+ "files",
+ VALID_UUID_2,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects unicode homoglyph substitutions in fixed segments", () => {
+ // Cyrillic 'а' (U+0430) instead of Latin 'a'
+ expect(
+ isWorkspaceDownloadRequest([
+ "\u0430pi",
+ "workspace",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ // Fullwidth 'a' (U+FF41)
+ expect(
+ isWorkspaceDownloadRequest([
+ "\uff41pi",
+ "workspace",
+ "files",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects hybrid path mixing workspace and public patterns", () => {
+ // 5-segment but with public prefix
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "public",
+ "shared",
+ VALID_UUID,
+ "download",
+ ]),
+ ).toBe(false);
+ // 7-segment but with workspace prefix
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ VALID_UUID,
+ "files",
+ VALID_UUID_2,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects download appearing in non-terminal position", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "download",
+ "files",
+ VALID_UUID,
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "public",
+ "shared",
+ "download",
+ "files",
+ VALID_UUID,
+ "extra",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects prototype pollution segment names as IDs", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "__proto__",
+ "download",
+ ]),
+ ).toBe(false);
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "constructor",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects very long path segments (DoS vector)", () => {
+ const longId = "a".repeat(10000);
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ longId,
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects UUID with embedded path separators", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "550e8400/e29b-41d4-a716-446655440000",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects UUID-shaped strings with unicode hyphens", () => {
+ // EN DASH (U+2013) instead of HYPHEN-MINUS
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "550e8400\u2013e29b\u201341d4\u2013a716\u2013446655440000",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects SSRF-style payloads in ID position", () => {
+ expect(
+ isWorkspaceDownloadRequest([
+ "api",
+ "workspace",
+ "files",
+ "http://169.254.169.254",
+ "download",
+ ]),
+ ).toBe(false);
+ });
+ });
});
describe("isRedirectStatus", () => {
diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.ts
index cd83c7274d..3e258f5a57 100644
--- a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.ts
+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.ts
@@ -1,11 +1,34 @@
+const UUID_RE =
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
export function isWorkspaceDownloadRequest(path: string[]): boolean {
- return (
- path.length == 5 &&
+ // api/workspace/files/{id}/download
+ if (
+ path.length === 5 &&
path[0] === "api" &&
path[1] === "workspace" &&
path[2] === "files" &&
- path[path.length - 1] === "download"
- );
+ UUID_RE.test(path[3]) &&
+ path[4] === "download"
+ ) {
+ return true;
+ }
+
+ // api/public/shared/{token}/files/{id}/download
+ if (
+ path.length === 7 &&
+ path[0] === "api" &&
+ path[1] === "public" &&
+ path[2] === "shared" &&
+ UUID_RE.test(path[3]) &&
+ path[4] === "files" &&
+ UUID_RE.test(path[5]) &&
+ path[6] === "download"
+ ) {
+ return true;
+ }
+
+ return false;
}
export function isRedirectStatus(status: number): boolean {
diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/WorkspaceFileRenderer.test.ts b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/WorkspaceFileRenderer.test.ts
index 13f58a6cb9..2def8d7268 100644
--- a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/WorkspaceFileRenderer.test.ts
+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/WorkspaceFileRenderer.test.ts
@@ -5,6 +5,7 @@ import {
isWorkspaceURI,
buildWorkspaceURI,
} from "@/lib/workspace-uri";
+import { workspaceFileRenderer } from "./WorkspaceFileRenderer";
describe("parseWorkspaceURI", () => {
it("parses a full workspace URI with mime type", () => {
@@ -113,3 +114,26 @@ describe("buildWorkspaceURI", () => {
expect(parsed).toEqual({ fileID: "file-abc", mimeType: "text/plain" });
});
});
+
+describe("workspaceFileRenderer.getDownloadContent", () => {
+ it("returns auth-proxied URL without share token", () => {
+ const result = workspaceFileRenderer.getDownloadContent(
+ "workspace://file-123#image/png",
+ );
+ expect(result).not.toBeNull();
+ expect(result!.data).toBe(
+ "/api/proxy/api/workspace/files/file-123/download",
+ );
+ });
+
+ it("returns public share URL when share token is in metadata", () => {
+ const result = workspaceFileRenderer.getDownloadContent(
+ "workspace://file-123#image/png",
+ { shareToken: "abc-token-123" },
+ );
+ expect(result).not.toBeNull();
+ expect(result!.data).toBe(
+ "/api/proxy/api/public/shared/abc-token-123/files/file-123/download",
+ );
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/WorkspaceFileRenderer.tsx b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/WorkspaceFileRenderer.tsx
index 50aeba47c0..26fe75f54a 100644
--- a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/WorkspaceFileRenderer.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/renderers/WorkspaceFileRenderer.tsx
@@ -37,7 +37,10 @@ const audioMimeTypes = [
"audio/flac",
];
-function buildDownloadURL(fileID: string): string {
+function buildDownloadURL(fileID: string, shareToken?: string): string {
+ if (shareToken) {
+ return `/api/proxy/api/public/shared/${shareToken}/files/${fileID}/download`;
+ }
return `/api/proxy/api/workspace/files/${fileID}/download`;
}
@@ -124,7 +127,7 @@ function renderWorkspaceFile(
const uri = parseWorkspaceURI(String(value));
if (!uri) return null;
- const downloadURL = buildDownloadURL(uri.fileID);
+ const downloadURL = buildDownloadURL(uri.fileID, metadata?.shareToken);
const mimeType = uri.mimeType || metadata?.mimeType || null;
if (mimeType && imageMimeTypes.includes(mimeType)) {
@@ -174,7 +177,7 @@ function getCopyContentWorkspaceFile(
const uri = parseWorkspaceURI(String(value));
if (!uri) return null;
- const downloadURL = buildDownloadURL(uri.fileID);
+ const downloadURL = buildDownloadURL(uri.fileID, metadata?.shareToken);
const mimeType =
uri.mimeType || metadata?.mimeType || "application/octet-stream";
@@ -205,7 +208,7 @@ function getDownloadContentWorkspaceFile(
const filename = metadata?.filename || `file.${ext}`;
return {
- data: buildDownloadURL(uri.fileID),
+ data: buildDownloadURL(uri.fileID, metadata?.shareToken),
filename,
mimeType,
};
diff --git a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/utils/download.ts b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/utils/download.ts
index 78adda8029..5111d4aeb2 100644
--- a/autogpt_platform/frontend/src/components/contextual/OutputRenderers/utils/download.ts
+++ b/autogpt_platform/frontend/src/components/contextual/OutputRenderers/utils/download.ts
@@ -1,74 +1,2 @@
-import { OutputRenderer, OutputMetadata } from "../types";
-
-export interface DownloadItem {
- value: any;
- metadata?: OutputMetadata;
- renderer: OutputRenderer;
-}
-
-export async function downloadOutputs(items: DownloadItem[]) {
- const concatenableTexts: string[] = [];
- const nonConcatenableDownloads: Array<{ blob: Blob; filename: string }> = [];
-
- for (const item of items) {
- if (item.renderer.isConcatenable(item.value, item.metadata)) {
- const copyContent = item.renderer.getCopyContent(
- item.value,
- item.metadata,
- );
- if (copyContent) {
- // Extract text from CopyContent
- let text: string;
- if (typeof copyContent.data === "string") {
- text = copyContent.data;
- } else if (copyContent.fallbackText) {
- text = copyContent.fallbackText;
- } else {
- continue;
- }
- concatenableTexts.push(text);
- }
- } else {
- const downloadContent = item.renderer.getDownloadContent(
- item.value,
- item.metadata,
- );
- if (downloadContent) {
- if (typeof downloadContent.data === "string") {
- if (downloadContent.data.startsWith("http")) {
- const link = document.createElement("a");
- link.href = downloadContent.data;
- link.download = downloadContent.filename;
- link.click();
- }
- } else {
- nonConcatenableDownloads.push({
- blob: downloadContent.data as Blob,
- filename: downloadContent.filename,
- });
- }
- }
- }
- }
-
- if (concatenableTexts.length > 0) {
- const combinedText = concatenableTexts.join("\n\n---\n\n");
- const blob = new Blob([combinedText], { type: "text/plain" });
- downloadBlob(blob, "combined_output.txt");
- }
-
- for (const download of nonConcatenableDownloads) {
- downloadBlob(download.blob, download.filename);
- }
-}
-
-function downloadBlob(blob: Blob, filename: string) {
- const url = URL.createObjectURL(blob);
- const link = document.createElement("a");
- link.href = url;
- link.download = filename;
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- URL.revokeObjectURL(url);
-}
+export { downloadOutputs } from "@/lib/utils/download-outputs";
+export type { DownloadItem } from "@/lib/utils/download-outputs";
diff --git a/autogpt_platform/frontend/src/lib/utils/__tests__/download-outputs.test.ts b/autogpt_platform/frontend/src/lib/utils/__tests__/download-outputs.test.ts
new file mode 100644
index 0000000000..f85cff71e8
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/utils/__tests__/download-outputs.test.ts
@@ -0,0 +1,423 @@
+import { describe, expect, it, vi, beforeEach } from "vitest";
+import {
+ sanitizeFilename,
+ getUniqueFilename,
+ downloadOutputs,
+} from "../download-outputs";
+import type { DownloadItem } from "../download-outputs";
+
+describe("sanitizeFilename", () => {
+ it("strips forward slashes", () => {
+ expect(sanitizeFilename("path/to/file.txt")).toBe("path_to_file.txt");
+ });
+
+ it("strips backslashes", () => {
+ expect(sanitizeFilename("path\\to\\file.txt")).toBe("path_to_file.txt");
+ });
+
+ it("replaces parent directory traversal", () => {
+ const result = sanitizeFilename("../../etc/passwd");
+ expect(result).not.toContain("/");
+ expect(result).not.toContain("\\");
+ expect(result).not.toContain("..");
+ expect(result).not.toMatch(/^\./);
+ });
+
+ it("strips leading dots", () => {
+ expect(sanitizeFilename(".gitignore")).toBe("gitignore");
+ expect(sanitizeFilename("..hidden")).toBe("hidden");
+ expect(sanitizeFilename("...triple")).toBe("triple");
+ });
+
+ it("returns 'file' for empty results", () => {
+ expect(sanitizeFilename("")).toBe("file");
+ expect(sanitizeFilename("...")).toBe("file");
+ expect(sanitizeFilename(".")).toBe("file");
+ });
+
+ it("leaves safe filenames unchanged", () => {
+ expect(sanitizeFilename("report.pdf")).toBe("report.pdf");
+ expect(sanitizeFilename("image_001.png")).toBe("image_001.png");
+ });
+});
+
+describe("getUniqueFilename", () => {
+ it("returns the filename when not already used", () => {
+ const used = new Set<string>();
+ expect(getUniqueFilename("file.txt", used)).toBe("file.txt");
+ expect(used.has("file.txt")).toBe(true);
+ });
+
+ it("appends a counter on collision", () => {
+ const used = new Set<string>(["file.txt"]);
+ expect(getUniqueFilename("file.txt", used)).toBe("file_1.txt");
+ expect(used.has("file_1.txt")).toBe(true);
+ });
+
+ it("increments counter until unique", () => {
+ const used = new Set<string>(["file.txt", "file_1.txt", "file_2.txt"]);
+ expect(getUniqueFilename("file.txt", used)).toBe("file_3.txt");
+ });
+
+ it("handles filenames without extensions", () => {
+ const used = new Set<string>(["README"]);
+ expect(getUniqueFilename("README", used)).toBe("README_1");
+ });
+
+ it("sanitizes the filename before deduplication", () => {
+ const used = new Set<string>();
+ expect(getUniqueFilename("../evil.txt", used)).toBe("_evil.txt");
+ });
+
+ it("handles dotfiles by stripping leading dots first", () => {
+ const used = new Set<string>();
+ expect(getUniqueFilename(".gitignore", used)).toBe("gitignore");
+ });
+});
+
+const mockZipFile = vi.fn();
+const mockGenerateAsync = vi.fn();
+let mockZipFiles: Record<string, { async: () => Promise<Blob> }> = {};
+
+vi.mock("jszip", () => ({
+ default: class MockJSZip {
+ files = mockZipFiles;
+ file = (...args: unknown[]) => {
+ if (typeof args[0] === "string" && args[1] !== undefined) {
+ const content = args[1];
+ mockZipFiles[args[0] as string] = {
+ async: () =>
+ Promise.resolve(
+ content instanceof Blob ? content : new Blob([String(content)]),
+ ),
+ };
+ }
+ mockZipFile(...args);
+ };
+ generateAsync = mockGenerateAsync;
+ },
+}));
+
+function makeRenderer(overrides: {
+ isConcatenable?: boolean;
+ copyData?: string;
+ downloadData?: Blob | string;
+ downloadFilename?: string;
+}) {
+ return {
+ value: "test",
+ metadata: undefined,
+ renderer: {
+ name: "test",
+ priority: 1,
+ canRender: () => true,
+ render: () => null,
+ isConcatenable: () => overrides.isConcatenable ?? false,
+ getCopyContent: () =>
+ overrides.copyData
+ ? { mimeType: "text/plain", data: overrides.copyData }
+ : null,
+ getDownloadContent: () =>
+ overrides.downloadData
+ ? {
+ data: overrides.downloadData,
+ filename: overrides.downloadFilename ?? "file.bin",
+ mimeType: "application/octet-stream",
+ }
+ : null,
+ },
+ } satisfies DownloadItem;
+}
+
+describe("downloadOutputs", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockZipFiles = {};
+ mockGenerateAsync.mockResolvedValue(new Blob(["zip-content"]));
+ vi.stubGlobal(
+ "URL",
+ Object.assign(URL, {
+ createObjectURL: vi.fn(() => "blob:mock-url"),
+ revokeObjectURL: vi.fn(),
+ }),
+ );
+ });
+
+ it("creates a zip with concatenable text outputs", async () => {
+ const items = [
+ makeRenderer({ isConcatenable: true, copyData: "Hello" }),
+ makeRenderer({ isConcatenable: true, copyData: "World" }),
+ ];
+
+ await downloadOutputs(items);
+
+ expect(mockZipFile).toHaveBeenCalledWith(
+ "combined_output.txt",
+ "Hello\n\n---\n\nWorld",
+ );
+ // Single file in zip → downloaded directly, no zip generation
+ expect(mockGenerateAsync).not.toHaveBeenCalled();
+ });
+
+ it("includes direct blob data in the zip", async () => {
+ const blob = new Blob(["binary data"]);
+ const items = [
+ makeRenderer({ downloadData: blob, downloadFilename: "image.png" }),
+ ];
+
+ await downloadOutputs(items);
+
+ expect(mockZipFile).toHaveBeenCalledWith("image.png", blob);
+ });
+
+ it("skips blobs exceeding size limit", async () => {
+ const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const bigBlob = new Blob(["x".repeat(100)]);
+ Object.defineProperty(bigBlob, "size", { value: 60 * 1024 * 1024 });
+
+ const items = [
+ makeRenderer({ downloadData: bigBlob, downloadFilename: "huge.bin" }),
+ ];
+
+ await downloadOutputs(items);
+
+ expect(consoleSpy).toHaveBeenCalledWith(
+ expect.stringContaining("blob too large"),
+ );
+ expect(mockZipFile).not.toHaveBeenCalledWith("huge.bin", expect.anything());
+ consoleSpy.mockRestore();
+ });
+
+ it("fetches http URLs and adds to zip", async () => {
+ const mockBlob = new Blob(["fetched"]);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ headers: new Headers({ "content-length": "7" }),
+ blob: () => Promise.resolve(mockBlob),
+ }),
+ );
+
+ const items = [
+ makeRenderer({
+ downloadData: "https://example.com/file.pdf",
+ downloadFilename: "report.pdf",
+ }),
+ ];
+
+ await downloadOutputs(items);
+
+ expect(fetch).toHaveBeenCalledWith("https://example.com/file.pdf", {
+ mode: "cors",
+ });
+ expect(mockZipFile).toHaveBeenCalledWith("report.pdf", mockBlob);
+ });
+
+ it("handles fetch failures gracefully and records unfetchable URLs", async () => {
+ const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("CORS error")));
+
+ const items = [
+ makeRenderer({ isConcatenable: true, copyData: "some text" }),
+ makeRenderer({
+ downloadData: "https://cors-blocked.com/file.bin",
+ downloadFilename: "blocked.bin",
+ }),
+ ];
+
+ await downloadOutputs(items);
+
+ expect(mockZipFile).toHaveBeenCalledWith(
+ "unfetched_files.txt",
+ expect.stringContaining("cors-blocked.com"),
+ );
+ consoleSpy.mockRestore();
+ });
+
+ it("handles malformed data URLs with try-catch", async () => {
+ const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockRejectedValue(new Error("Invalid data URL")),
+ );
+
+ const items = [
+ makeRenderer({
+ downloadData: "data:invalid",
+ downloadFilename: "broken.bin",
+ }),
+ ];
+
+ await downloadOutputs(items);
+
+ expect(consoleSpy).toHaveBeenCalledWith(
+ expect.stringContaining("malformed or unsupported format"),
+ );
+ consoleSpy.mockRestore();
+ });
+
+ it("skips unsupported URL formats with a warning", async () => {
+ const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+
+ const items = [
+ makeRenderer({
+ downloadData: "ftp://server/file.dat",
+ downloadFilename: "file.dat",
+ }),
+ ];
+
+ await downloadOutputs(items);
+
+ expect(consoleSpy).toHaveBeenCalledWith(
+ expect.stringContaining("unsupported URL format"),
+ );
+ consoleSpy.mockRestore();
+ });
+
+ it("does nothing when items array is empty", async () => {
+ await downloadOutputs([]);
+
+ expect(mockZipFile).not.toHaveBeenCalled();
+ expect(mockGenerateAsync).not.toHaveBeenCalled();
+ });
+
+ it("fetches relative URLs (workspace files) and adds to zip", async () => {
+ const mockBlob = new Blob(["image-data"]);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ headers: new Headers({ "content-length": "10" }),
+ blob: () => Promise.resolve(mockBlob),
+ }),
+ );
+
+ const items = [
+ makeRenderer({
+ downloadData: "/api/proxy/api/workspace/files/abc-123/download",
+ downloadFilename: "photo.png",
+ }),
+ ];
+
+ await downloadOutputs(items);
+
+ expect(fetch).toHaveBeenCalledWith(
+ "/api/proxy/api/workspace/files/abc-123/download",
+ { mode: "cors" },
+ );
+ expect(mockZipFile).toHaveBeenCalledWith("photo.png", mockBlob);
+ });
+
+ it("includes workspace images that renderers return as relative URLs", async () => {
+ const mockBlob = new Blob(["img"]);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ headers: new Headers({ "content-length": "3" }),
+ blob: () => Promise.resolve(mockBlob),
+ }),
+ );
+
+ const items = [
+ makeRenderer({
+ downloadData: "/api/proxy/api/workspace/files/file-1/download",
+ downloadFilename: "image1.png",
+ }),
+ makeRenderer({
+ downloadData: "/api/proxy/api/workspace/files/file-2/download",
+ downloadFilename: "image2.jpg",
+ }),
+ ];
+
+ await downloadOutputs(items);
+
+ expect(mockZipFile).toHaveBeenCalledWith("image1.png", mockBlob);
+ expect(mockZipFile).toHaveBeenCalledWith("image2.jpg", mockBlob);
+ });
+
+ it("fetches public share endpoint URLs for workspace files", async () => {
+ const mockBlob = new Blob(["shared-image-data"]);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ headers: new Headers({ "content-length": "17" }),
+ blob: () => Promise.resolve(mockBlob),
+ }),
+ );
+
+ const items = [
+ makeRenderer({
+ downloadData:
+ "/api/proxy/api/public/shared/abc-token/files/file-123/download",
+ downloadFilename: "shared-image.png",
+ }),
+ ];
+
+ await downloadOutputs(items);
+
+ expect(fetch).toHaveBeenCalledWith(
+ "/api/proxy/api/public/shared/abc-token/files/file-123/download",
+ { mode: "cors" },
+ );
+ expect(mockZipFile).toHaveBeenCalledWith("shared-image.png", mockBlob);
+ });
+
+ it("rejects files over content-length before buffering", async () => {
+ const consoleSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const blobFn = vi.fn();
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ headers: new Headers({
+ "content-length": String(60 * 1024 * 1024),
+ }),
+ blob: blobFn,
+ }),
+ );
+
+ const items = [
+ makeRenderer({
+ downloadData: "https://example.com/huge.zip",
+ downloadFilename: "huge.zip",
+ }),
+ ];
+
+ await downloadOutputs(items);
+
+ expect(blobFn).not.toHaveBeenCalled();
+ expect(consoleSpy).toHaveBeenCalledWith(
+ expect.stringContaining("file too large"),
+ );
+ consoleSpy.mockRestore();
+ });
+
+ it("downloads single file directly without zip wrapping", async () => {
+ const blob = new Blob(["single file"]);
+ const items = [
+ makeRenderer({ downloadData: blob, downloadFilename: "photo.png" }),
+ ];
+
+ await downloadOutputs(items);
+
+ expect(mockZipFile).toHaveBeenCalledWith("photo.png", blob);
+ expect(mockGenerateAsync).not.toHaveBeenCalled();
+ expect(URL.createObjectURL).toHaveBeenCalled();
+ });
+
+ it("uses zip when multiple files are present", async () => {
+ const blob1 = new Blob(["file1"]);
+ const blob2 = new Blob(["file2"]);
+ const items = [
+ makeRenderer({ downloadData: blob1, downloadFilename: "a.png" }),
+ makeRenderer({ downloadData: blob2, downloadFilename: "b.png" }),
+ ];
+
+ await downloadOutputs(items);
+
+ expect(mockGenerateAsync).toHaveBeenCalledWith({ type: "blob" });
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/utils/download-outputs.ts b/autogpt_platform/frontend/src/lib/utils/download-outputs.ts
new file mode 100644
index 0000000000..8dbf51ef67
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/utils/download-outputs.ts
@@ -0,0 +1,282 @@
+import type {
+ OutputRenderer,
+ OutputMetadata,
+} from "@/components/contextual/OutputRenderers/types";
+
+export interface DownloadItem {
+ value: unknown;
+ metadata?: OutputMetadata;
+ renderer: OutputRenderer;
+}
+
+/** Maximum individual file size for zip inclusion (50 MB) */
+const MAX_FILE_SIZE_BYTES = 50 * 1024 * 1024;
+
+/** Maximum total zip content size before generation (200 MB) */
+const MAX_TOTAL_SIZE_BYTES = 200 * 1024 * 1024;
+
+/** Maximum concurrent file fetches */
+const FETCH_CONCURRENCY = 5;
+
+async function fetchFileAsBlob(url: string): Promise<Blob | null> {
+ try {
+ const response = await fetch(url, { mode: "cors" });
+ if (!response.ok) {
+ console.error(`Failed to fetch ${url}: ${response.status}`);
+ return null;
+ }
+ const contentLength = Number(response.headers.get("content-length") ?? "0");
+ if (contentLength > MAX_FILE_SIZE_BYTES) {
+ console.warn(
+ `Skipping ${url}: file too large (${(contentLength / 1024 / 1024).toFixed(1)} MB, limit ${MAX_FILE_SIZE_BYTES / 1024 / 1024} MB)`,
+ );
+ return null;
+ }
+ const blob = await response.blob();
+ if (blob.size > MAX_FILE_SIZE_BYTES) {
+ console.warn(
+ `Skipping ${url}: file too large (${(blob.size / 1024 / 1024).toFixed(1)} MB, limit ${MAX_FILE_SIZE_BYTES / 1024 / 1024} MB)`,
+ );
+ return null;
+ }
+ return blob;
+ } catch (_error) {
+ console.warn(
+ `Could not fetch ${url} (likely CORS). Adding as link reference.`,
+ );
+ return null;
+ }
+}
+
+/** Strip path traversal components and unsafe characters from a filename. */
+export function sanitizeFilename(filename: string): string {
+ const sanitized = filename
+ .replace(/[/\\]/g, "_")
+ .replace(/^\.+/, "")
+ .replace(/\.\./g, "_");
+ return sanitized || "file";
+}
+
+export function getUniqueFilename(
+ filename: string,
+ usedNames: Set<string>,
+): string {
+ const safe = sanitizeFilename(filename);
+ if (!usedNames.has(safe)) {
+ usedNames.add(safe);
+ return safe;
+ }
+
+ const dotIndex = safe.lastIndexOf(".");
+ const baseName = dotIndex > 0 ? safe.slice(0, dotIndex) : safe;
+ const extension = dotIndex > 0 ? safe.slice(dotIndex) : "";
+
+ let counter = 1;
+ let newName = `${baseName}_${counter}${extension}`;
+ while (usedNames.has(newName)) {
+ counter++;
+ newName = `${baseName}_${counter}${extension}`;
+ }
+ usedNames.add(newName);
+ return newName;
+}
+
+async function fetchInParallel<T>(
+ tasks: (() => Promise<T>)[],
+ concurrency: number,
+): Promise<T[]> {
+ const results: T[] = [];
+ let index = 0;
+
+ async function worker() {
+ while (index < tasks.length) {
+ const i = index++;
+ results[i] = await tasks[i]();
+ }
+ }
+
+ await Promise.all(
+ Array.from({ length: Math.min(concurrency, tasks.length) }, () => worker()),
+ );
+ return results;
+}
+
+type FetchResult = {
+ blob: Blob | null;
+ filename: string;
+ sourceUrl: string | null;
+};
+
+export async function downloadOutputs(items: DownloadItem[]) {
+ if (items.length === 0) return;
+
+ const { default: JSZip } = await import("jszip");
+ const zip = new JSZip();
+ const usedFilenames = new Set<string>();
+ let hasFiles = false;
+ let totalSize = 0;
+
+ const concatenableTexts: string[] = [];
+ const unfetchableUrls: string[] = [];
+
+ const fileItems: Array<{
+ downloadContent: { data: unknown; filename: string };
+ }> = [];
+
+ for (const item of items) {
+ if (item.renderer.isConcatenable(item.value, item.metadata)) {
+ const copyContent = item.renderer.getCopyContent(
+ item.value,
+ item.metadata,
+ );
+ if (copyContent) {
+ let text: string;
+ if (typeof copyContent.data === "string") {
+ text = copyContent.data;
+ } else if (copyContent.fallbackText) {
+ text = copyContent.fallbackText;
+ } else {
+ continue;
+ }
+ concatenableTexts.push(text);
+ }
+ } else {
+ const downloadContent = item.renderer.getDownloadContent(
+ item.value,
+ item.metadata,
+ );
+ if (downloadContent) {
+ fileItems.push({ downloadContent });
+ }
+ }
+ }
+
+ const fetchTasks = fileItems.map(
+ ({ downloadContent }) =>
+ async (): Promise<FetchResult> => {
+ let blob: Blob | null = null;
+ const filename = downloadContent.filename;
+ let sourceUrl: string | null = null;
+
+ if (typeof downloadContent.data === "string") {
+ if (
+ downloadContent.data.startsWith("http://") ||
+ downloadContent.data.startsWith("https://") ||
+ downloadContent.data.startsWith("/")
+ ) {
+ sourceUrl = downloadContent.data;
+ blob = await fetchFileAsBlob(downloadContent.data);
+ } else if (downloadContent.data.startsWith("data:")) {
+ try {
+ const dataBlob = await fetch(downloadContent.data).then((r) =>
+ r.blob(),
+ );
+ if (dataBlob.size <= MAX_FILE_SIZE_BYTES) {
+ blob = dataBlob;
+ } else {
+ console.warn(
+ `Skipping data URL: too large (${(dataBlob.size / 1024 / 1024).toFixed(1)} MB)`,
+ );
+ }
+ } catch (_error) {
+ console.warn(
+ `Failed to process data URL for ${filename}: malformed or unsupported format`,
+ );
+ }
+ } else {
+ console.warn(
+ `Skipping unsupported URL format: ${downloadContent.data.slice(0, 50)}...`,
+ );
+ }
+ } else {
+ const rawBlob = downloadContent.data as Blob;
+ if (rawBlob.size <= MAX_FILE_SIZE_BYTES) {
+ blob = rawBlob;
+ } else {
+ console.warn(
+ `Skipping ${filename}: blob too large (${(rawBlob.size / 1024 / 1024).toFixed(1)} MB)`,
+ );
+ }
+ }
+
+ return { blob, filename, sourceUrl };
+ },
+ );
+
+ const results = await fetchInParallel(fetchTasks, FETCH_CONCURRENCY);
+
+ for (const { blob, filename, sourceUrl } of results) {
+ if (blob) {
+ if (totalSize + blob.size > MAX_TOTAL_SIZE_BYTES) {
+ console.warn(
+ `Skipping ${filename}: would exceed total zip size limit (${MAX_TOTAL_SIZE_BYTES / 1024 / 1024} MB)`,
+ );
+ if (sourceUrl) unfetchableUrls.push(sourceUrl);
+ continue;
+ }
+ const uniqueFilename = getUniqueFilename(filename, usedFilenames);
+ zip.file(uniqueFilename, blob);
+ totalSize += blob.size;
+ hasFiles = true;
+ } else if (sourceUrl) {
+ unfetchableUrls.push(sourceUrl);
+ }
+ }
+
+ if (concatenableTexts.length > 0) {
+ const combinedText = concatenableTexts.join("\n\n---\n\n");
+ const textSize = new Blob([combinedText]).size;
+ if (totalSize + textSize <= MAX_TOTAL_SIZE_BYTES) {
+ const filename = getUniqueFilename("combined_output.txt", usedFilenames);
+ zip.file(filename, combinedText);
+ totalSize += textSize;
+ hasFiles = true;
+ }
+ }
+
+ if (unfetchableUrls.length > 0) {
+ const linksContent = unfetchableUrls
+ .map((url, i) => `${i + 1}. ${url}`)
+ .join("\n");
+ const manifest = `The following files could not be included in the zip (CORS restriction or size limit).\nYou can download them directly from these URLs:\n\n${linksContent}\n`;
+ const manifestSize = new Blob([manifest]).size;
+ if (totalSize + manifestSize <= MAX_TOTAL_SIZE_BYTES) {
+ const manifestFilename = getUniqueFilename(
+ "unfetched_files.txt",
+ usedFilenames,
+ );
+ zip.file(manifestFilename, manifest);
+ totalSize += manifestSize;
+ hasFiles = true;
+ }
+ }
+
+ if (!hasFiles) return;
+
+ // Single-file shortcut: download directly instead of wrapping in a zip
+ if (
+ zip.files &&
+ Object.keys(zip.files).length === 1 &&
+ unfetchableUrls.length === 0
+ ) {
+ const onlyFilename = Object.keys(zip.files)[0];
+ const entry = zip.files[onlyFilename];
+ const content = await entry.async("blob");
+ downloadBlob(content, onlyFilename);
+ return;
+ }
+
+ const zipBlob = await zip.generateAsync({ type: "blob" });
+ downloadBlob(zipBlob, "outputs.zip");
+}
+
+function downloadBlob(blob: Blob, filename: string) {
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = filename;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+}