Skip to content

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

fix(backend): store marketplace media locally when GCS is unset (#14524)

Nicholas Tindlefe350b73265a
diff --git a/.secrets.baseline b/.secrets.baseline
index bb24923f75..17dab85c38 100644
--- a/.secrets.baseline
+++ b/.secrets.baseline
@@ -417,6 +417,26 @@
"line_number": 449
}
],
+ "autogpt_platform/docker-compose.platform.yml": [
+ {
+ "type": "Basic Auth Credentials",
+ "filename": "autogpt_platform/docker-compose.platform.yml",
+ "hashed_secret": "de6b16a1aa2c97b8963a4f966774ae09fbe47300",
+ "is_verified": false,
+ "line_number": 37,
+ "is_secret": false
+ }
+ ],
+ "autogpt_platform/docker-compose.yml": [
+ {
+ "type": "Secret Keyword",
+ "filename": "autogpt_platform/docker-compose.yml",
+ "hashed_secret": "de6b16a1aa2c97b8963a4f966774ae09fbe47300",
+ "is_verified": false,
+ "line_number": 155,
+ "is_secret": false
+ }
+ ],
"autogpt_platform/frontend/src/app/(platform)/build/components/FlowEditor/nodes/helpers.ts": [
{
"type": "Secret Keyword",
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.default
index 0fb6eb855a..57510daf19 100644
--- a/autogpt_platform/backend/.env.default
+++ b/autogpt_platform/backend/.env.default
@@ -73,14 +73,15 @@ VAPID_CLAIM_EMAIL=mailto:[email protected]
## ===== IMPORTANT OPTIONAL CONFIGURATION ===== ##
# Platform URLs (set these for webhooks and OAuth to work)
-PLATFORM_BASE_URL=http://localhost:8000
+PLATFORM_BASE_URL=http://localhost:8006
FRONTEND_BASE_URL=http://localhost:3000
# Extra frontend origins (beyond FRONTEND_BASE_URL) that auth-email action
# links may target — JSON list of full origins or "regex:"-prefixed patterns,
# same format as BACKEND_CORS_ALLOW_ORIGINS. Self-hosting needs nothing here.
# TRUSTED_FRONTEND_ORIGINS=["regex:https://autogpt-pr-\\d+\\.vercel\\.app"]
-# Media Storage (required for marketplace and library functionality)
+# Optional GCS media bucket. When empty, marketplace media uses local store-media/
+# beside WORKSPACE_STORAGE_DIR (or the backend data directory when unset).
MEDIA_GCS_BUCKET_NAME=
## ===== API KEYS AND OAUTH CREDENTIALS ===== ##
diff --git a/autogpt_platform/backend/.gitignore b/autogpt_platform/backend/.gitignore
index 6e688311a6..a979805bee 100644
--- a/autogpt_platform/backend/.gitignore
+++ b/autogpt_platform/backend/.gitignore
@@ -22,3 +22,4 @@ migrations/*/rollback*.sql
# Workspace files
workspaces/
+store-media/
diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.py
index 4a1e2d120d..a5926ef91d 100644
--- a/autogpt_platform/backend/backend/api/features/library/db.py
+++ b/autogpt_platform/backend/backend/api/features/library/db.py
@@ -7,6 +7,7 @@ import fastapi
import prisma.errors
import prisma.models
import prisma.types
+from starlette.datastructures import Headers
import backend.api.features.store.image_gen as store_image_gen
import backend.api.features.store.media as store_media
@@ -542,7 +543,11 @@ async def add_generated_agent_image(
image = await store_image_gen.generate_agent_image(graph)
# Create UploadFile with the correct filename and content_type
- image_file = fastapi.UploadFile(file=image, filename=filename)
+ image_file = fastapi.UploadFile(
+ file=image,
+ filename=filename,
+ headers=Headers({"content-type": "image/jpeg"}),
+ )
image_url = await store_media.upload_media(
user_id=user_id, file=image_file, use_file_name=True
diff --git a/autogpt_platform/backend/backend/api/features/store/generated_media_test.py b/autogpt_platform/backend/backend/api/features/store/generated_media_test.py
new file mode 100644
index 0000000000..33c5732987
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/store/generated_media_test.py
@@ -0,0 +1,167 @@
+import io
+from unittest.mock import AsyncMock, Mock
+
+import httpx
+import pytest
+from PIL import Image, UnidentifiedImageError
+
+from backend.api.features.library import db as library_db
+from backend.api.features.store import image_gen, local_media, media, routes
+from backend.blocks.ideogram import TEST_CREDENTIALS, IdeogramModelBlock
+from backend.data.graph import GraphBaseMeta
+from backend.util.settings import Settings
+
+
+def generated_media_io(monkeypatch, tmp_path):
+ settings = Settings()
+ settings.config.use_agent_image_generation_v2 = True
+ settings.config.workspace_storage_dir = str(tmp_path / "workspaces")
+ settings.config.platform_base_url = ""
+ monkeypatch.setattr(image_gen, "settings", settings)
+ monkeypatch.setattr(image_gen, "ideogram_credentials", TEST_CREDENTIALS)
+ monkeypatch.setattr(media, "Settings", lambda: settings)
+ monkeypatch.setattr(local_media, "Settings", lambda: settings)
+
+ objects = {}
+
+ async def upload(bucket, path, content, *, content_type):
+ objects[path] = (content, content_type)
+
+ async def metadata(bucket, path):
+ if path not in objects:
+ raise FileNotFoundError(path)
+ return {"contentType": objects[path][1]}
+
+ storage = AsyncMock()
+ storage.__aenter__.return_value = storage
+ storage.upload.side_effect = upload
+ storage.download_metadata.side_effect = metadata
+ monkeypatch.setattr(media.async_storage, "Storage", Mock(return_value=storage))
+ scanner = AsyncMock()
+ monkeypatch.setattr(media, "scan_content_safe", scanner)
+ return settings, objects, scanner
+
+
+def graph_and_library_update(monkeypatch):
+ graph = GraphBaseMeta(id="graph-1", name="Agent", description="An agent")
+ monkeypatch.setattr(
+ routes.backend.data.graph, "get_graph", AsyncMock(return_value=graph)
+ )
+ update = AsyncMock(return_value=Mock())
+ monkeypatch.setattr(
+ library_db.prisma.models.LibraryAgent,
+ "prisma",
+ Mock(return_value=Mock(update=update)),
+ )
+ return graph, update
+
+
+def ideogram_response(monkeypatch, provider_format, mode):
+ source = io.BytesIO()
+ color = (255, 0, 0, 0) if mode == "RGBA" else "red"
+ Image.new(mode, (16, 12), color).save(source, format=provider_format)
+ source_bytes = source.getvalue()
+ generate = AsyncMock(return_value="https://ideogram.example/generated.png")
+ monkeypatch.setattr(IdeogramModelBlock, "run_once", generate)
+ download = AsyncMock(return_value=httpx.Response(200, content=source_bytes))
+ monkeypatch.setattr(image_gen, "Requests", Mock(return_value=Mock(get=download)))
+ return source_bytes, generate, download
+
+
[email protected]("caller", ["marketplace", "library"])
[email protected]("bucket", ["", "test-bucket"])
+ "provider_format,mode", [("PNG", "RGB"), ("PNG", "RGBA"), ("JPEG", "RGB")]
+)
+async def test_generated_thumbnail_upload_and_reuse(
+ generated_media_io,
+ graph_and_library_update,
+ ideogram_response,
+ caller,
+ bucket,
+ provider_format,
+ mode,
+):
+ settings, objects, scanner = generated_media_io
+ settings.config.media_gcs_bucket_name = bucket
+ graph, update = graph_and_library_update
+ source_bytes, generate, download = ideogram_response
+ expected_path = "users/test-user/images/agent_graph-1.jpeg"
+ expected_url = (
+ f"https://storage.googleapis.com/{bucket}/{expected_path}"
+ if bucket
+ else "/api/store/media/test-user/images/agent_graph-1.jpeg"
+ )
+ for _ in range(2):
+ if caller == "marketplace":
+ result = await routes.generate_image(graph.id, user_id="test-user")
+ assert result.image_url == expected_url
+ else:
+ result = await library_db.add_generated_agent_image(
+ graph, "test-user", "library-agent-1"
+ )
+ assert result is not None
+ update.assert_awaited_with(
+ where={"id": "library-agent-1"}, data={"imageUrl": expected_url}
+ )
+
+ generate.assert_awaited_once()
+ download.assert_awaited_once()
+ if bucket:
+ uploaded, content_type = objects[expected_path]
+ assert content_type == "image/jpeg"
+ else:
+ uploaded = local_media.get_media_path(
+ "test-user", "images", "agent_graph-1.jpeg"
+ ).read_bytes()
+ scanner.assert_awaited_once_with(uploaded, filename="agent_graph-1.jpeg")
+ with Image.open(io.BytesIO(uploaded)) as thumbnail:
+ assert thumbnail.format == "JPEG"
+ assert thumbnail.size == (16, 12)
+ if mode == "RGBA":
+ assert thumbnail.getpixel((0, 0)) == (255, 255, 255)
+ if provider_format == "JPEG":
+ assert uploaded == source_bytes
+
+
[email protected]("payload", [b"not an image", b"\x89PNG\r\n\x1a\n"])
+async def test_invalid_generated_image_is_not_uploaded(
+ generated_media_io, graph_and_library_update, monkeypatch, payload
+):
+ _, objects, scanner = generated_media_io
+ graph, _ = graph_and_library_update
+ monkeypatch.setattr(
+ IdeogramModelBlock,
+ "run_once",
+ AsyncMock(return_value="https://ideogram.example/image.png"),
+ )
+ download = AsyncMock(return_value=httpx.Response(200, content=payload))
+ monkeypatch.setattr(image_gen, "Requests", Mock(return_value=Mock(get=download)))
+
+ with pytest.raises(UnidentifiedImageError):
+ await routes.generate_image(graph.id, user_id="test-user")
+ scanner.assert_not_awaited()
+ assert not objects
+ assert not local_media.media_root().exists()
+
+
+async def test_flux_still_requests_and_preserves_jpeg(
+ generated_media_io, graph_and_library_update, monkeypatch
+):
+ settings, _, _ = generated_media_io
+ settings.config.use_agent_image_generation_v2 = False
+ monkeypatch.setattr(image_gen.settings.secrets, "replicate_api_key", "test-key")
+ graph, _ = graph_and_library_update
+ source = io.BytesIO()
+ Image.new("RGB", (16, 12), "red").save(source, format="JPEG")
+ run = Mock(return_value="https://replicate.example/image.jpg")
+ monkeypatch.setattr(image_gen, "ReplicateClient", Mock(return_value=Mock(run=run)))
+ download = AsyncMock(return_value=httpx.Response(200, content=source.getvalue()))
+ monkeypatch.setattr(image_gen, "Requests", Mock(return_value=Mock(get=download)))
+
+ result = await image_gen.generate_agent_image(graph)
+ assert result.read() == source.getvalue()
+ assert run.call_args.kwargs["input"]["output_format"] == "jpg"
diff --git a/autogpt_platform/backend/backend/api/features/store/image_gen.py b/autogpt_platform/backend/backend/api/features/store/image_gen.py
index 64ac203182..15fc37c8b9 100644
--- a/autogpt_platform/backend/backend/api/features/store/image_gen.py
+++ b/autogpt_platform/backend/backend/api/features/store/image_gen.py
@@ -1,7 +1,9 @@
+import asyncio
import io
import logging
from enum import Enum
+from PIL import Image
from prisma.models import AgentGraph
from replicate.client import Client as ReplicateClient
from replicate.exceptions import ReplicateError
@@ -26,17 +28,33 @@ class ImageStyle(str, Enum):
async def generate_agent_image(agent: GraphBaseMeta | AgentGraph) -> io.BytesIO:
+ """Generate a JPEG thumbnail, independent of the provider's image format."""
if settings.config.use_agent_image_generation_v2:
- return await generate_agent_image_v2(graph=agent)
+ image = await generate_agent_image_v2(graph=agent)
else:
- return await generate_agent_image_v1(agent=agent)
+ image = await generate_agent_image_v1(agent=agent)
+ return await asyncio.to_thread(_as_jpeg, image)
+
+
+def _as_jpeg(image: io.BytesIO) -> io.BytesIO:
+ content = image.getvalue()
+ with Image.open(io.BytesIO(content)) as generated:
+ if generated.format == "JPEG":
+ return io.BytesIO(content)
+ rgba = generated.convert("RGBA")
+ background = Image.new("RGB", generated.size, "white")
+ background.paste(rgba, mask=rgba.getchannel("A"))
+ output = io.BytesIO()
+ background.save(output, format="JPEG", quality=90)
+ output.seek(0)
+ return output
async def generate_agent_image_v2(graph: GraphBaseMeta | AgentGraph) -> io.BytesIO:
"""
Generate an image for an agent using Ideogram model.
Returns:
- str: The URL of the generated image
+ io.BytesIO: The image bytes in the provider's original format.
"""
if not ideogram_credentials.api_key:
raise ValueError("Missing Ideogram API key")
diff --git a/autogpt_platform/backend/backend/api/features/store/local_media.py b/autogpt_platform/backend/backend/api/features/store/local_media.py
new file mode 100644
index 0000000000..50a8b1a9b7
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/store/local_media.py
@@ -0,0 +1,122 @@
+import asyncio
+import os
+import re
+import tempfile
+import uuid
+from pathlib import Path
+
+from backend.util.data import get_data_path
+from backend.util.settings import Settings
+
+MEDIA_TYPES = frozenset({"images", "videos"})
+CONTENT_TYPE_EXTENSIONS = {
+ "image/jpeg": ".jpeg",
+ "image/png": ".png",
+ "image/gif": ".gif",
+ "image/webp": ".webp",
+ "video/mp4": ".mp4",
+ "video/webm": ".webm",
+}
+EXTENSION_CONTENT_TYPES = {
+ extension: content_type
+ for content_type, extension in CONTENT_TYPE_EXTENSIONS.items()
+} | {".jpg": "image/jpeg"}
+_SAFE_PATH_COMPONENT = re.compile(r"^[A-Za-z0-9_.-]+$")
+
+
+async def store_media(
+ user_id: str, media_type: str, filename: str, content: bytes
+) -> str:
+ """Publish fully validated media atomically so readers never see partial writes."""
+ await asyncio.to_thread(_write_media, user_id, media_type, filename, content)
+ return media_url(user_id, media_type, filename)
+
+
+async def check_media_exists(user_id: str, filename: str) -> str | None:
+ """Find named uploads using the same extension normalization as storage."""
+ return await asyncio.to_thread(_check_media_exists, user_id, filename)
+
+
+def get_media_path(user_id: str, media_type: str, filename: str) -> Path:
+ """Resolve a file inside the media root, rejecting traversal and escaping symlinks."""
+ if media_type not in MEDIA_TYPES:
+ raise ValueError("Invalid media type")
+
+ base_dir = os.path.realpath(media_root())
+ candidate = os.path.realpath(
+ os.path.join(
+ base_dir,
+ "users",
+ _validate_path_component(user_id),
+ media_type,
+ _validate_path_component(filename),
+ )
+ )
+ if not candidate.startswith(base_dir + os.sep):
+ raise ValueError("Invalid media path")
+ return Path(candidate)
+
+
+def content_type_for_filename(filename: str) -> str | None:
+ """Only serve the image and video formats accepted by marketplace uploads."""
+ return EXTENSION_CONTENT_TYPES.get(Path(filename).suffix.lower())
+
+
+def stored_filename(filename: str, content_type: str, use_file_name: bool) -> str:
+ """Derive the extension from validated content rather than a client-supplied name."""
+ extension = CONTENT_TYPE_EXTENSIONS[content_type]
+ if use_file_name:
+ return f"{Path(_validate_path_component(filename)).stem}{extension}"
+ return f"{uuid.uuid4()}{extension}"
+
+
+def media_root() -> Path:
+ """Keep marketplace files beside workspaces, including persistent /data installs."""
+ storage_dir = Settings().config.workspace_storage_dir
+ if storage_dir:
+ return Path(storage_dir).resolve().parent / "store-media"
+ return get_data_path() / "store-media"
+
+
+def media_url(user_id: str, media_type: str, filename: str) -> str:
+ """Return a public backend URL or a same-origin path for local installations."""
+ path = (
+ f"/api/store/media/{_validate_path_component(user_id)}"
+ f"/{media_type}/{_validate_path_component(filename)}"
+ )
+ return f"{Settings().config.platform_base_url.rstrip('/')}{path}"
+
+
+def _validate_path_component(value: str) -> str:
+ if value in {".", ".."} or not _SAFE_PATH_COMPONENT.fullmatch(value):
+ raise ValueError("Invalid media path component")
+ return value
+
+
+def _check_media_exists(user_id: str, filename: str) -> str | None:
+ try:
+ _validate_path_component(user_id)
+ _validate_path_component(filename)
+ content_type = content_type_for_filename(filename)
+ if content_type is None:
+ return None
+ canonical_filename = stored_filename(filename, content_type, True)
+ for media_type in ("images", "videos"):
+ if get_media_path(user_id, media_type, canonical_filename).is_file():
+ return media_url(user_id, media_type, canonical_filename)
+ except ValueError:
+ return None
+ return None
+
+
+def _write_media(user_id: str, media_type: str, filename: str, content: bytes) -> None:
+ file_path = get_media_path(user_id, media_type, filename)
+ file_path.parent.mkdir(parents=True, exist_ok=True)
+ temporary = tempfile.NamedTemporaryFile(dir=file_path.parent, delete=False)
+ temporary_path = Path(temporary.name)
+ try:
+ with temporary:
+ temporary.write(content)
+ os.replace(temporary_path, file_path)
+ finally:
+ temporary_path.unlink(missing_ok=True)
diff --git a/autogpt_platform/backend/backend/api/features/store/local_media_test.py b/autogpt_platform/backend/backend/api/features/store/local_media_test.py
new file mode 100644
index 0000000000..582e2f94cd
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/store/local_media_test.py
@@ -0,0 +1,226 @@
+import io
+from pathlib import Path
+from unittest.mock import AsyncMock
+
+import fastapi
+import fastapi.testclient
+import pytest
+from starlette.datastructures import Headers
+
+from backend.api.features.store import local_media, media, routes
+from backend.util.exceptions import NotFoundError
+from backend.util.settings import Settings
+
+
+def local_settings(monkeypatch, tmp_path):
+ settings = Settings()
+ settings.config.media_gcs_bucket_name = ""
+ settings.config.workspace_storage_dir = str(tmp_path / "workspaces")
+ settings.config.platform_base_url = ""
+ monkeypatch.setattr(local_media, "Settings", lambda: settings)
+ monkeypatch.setattr(media, "Settings", lambda: settings)
+ return settings
+
+
+def client():
+ app = fastapi.FastAPI()
+ app.add_exception_handler(NotFoundError, _handle_not_found)
+ app.include_router(routes.router, prefix="/api/store")
+ return fastapi.testclient.TestClient(app)
+
+
+def _handle_not_found(request: fastapi.Request, exc: Exception):
+ return fastapi.responses.JSONResponse({"detail": str(exc)}, status_code=404)
+
+
+ "content_type,content,extension,media_type",
+ [
+ ("image/jpeg", b"\xff\xd8\xffimage", ".jpeg", "images"),
+ ("image/png", b"\x89PNG\r\n\x1a\nimage", ".png", "images"),
+ ("image/gif", b"GIF89aimage", ".gif", "images"),
+ ("image/webp", b"RIFF\x00\x00\x00\x00WEBPimage", ".webp", "images"),
+ ("video/mp4", b"\x00\x00\x00\x18ftypmp42video", ".mp4", "videos"),
+ ("video/webm", b"\x1a\x45\xdf\xa3video", ".webm", "videos"),
+ ],
+)
[email protected]("use_file_name", [False, True])
+async def test_upload_and_public_download(
+ local_settings,
+ client,
+ monkeypatch,
+ content_type,
+ content,
+ extension,
+ media_type,
+ use_file_name,
+):
+ scanner = AsyncMock()
+ monkeypatch.setattr(media, "scan_content_safe", scanner)
+ upload = fastapi.UploadFile(
+ filename="picture.html",
+ file=io.BytesIO(content),
+ headers=Headers({"content-type": content_type}),
+ )
+ url = await media.upload_media("user-id", upload, use_file_name=use_file_name)
+ assert url.startswith(f"/api/store/media/user-id/{media_type}/")
+ assert url.endswith(extension)
+ assert ".html" not in url
+ scanner.assert_awaited_once_with(content, filename=url.rsplit("/", 1)[1])
+ response = client.get(url)
+ assert response.status_code == 200
+ assert response.content == content
+ assert response.headers["content-type"] == content_type
+ assert response.headers["x-content-type-options"] == "nosniff"
+
+
[email protected]("workspace", ["", "/data/workspaces"])
+def test_media_root_uses_persistent_location(
+ local_settings, monkeypatch, tmp_path, workspace
+):
+ local_settings.config.workspace_storage_dir = workspace
+ monkeypatch.setattr(local_media, "get_data_path", lambda: tmp_path)
+ expected = Path("/data") if workspace else tmp_path
+ assert local_media.media_root() == expected / "store-media"
+
+
+ "base_url",
+ [
+ "http://localhost:8006",
+ "https://backend.example.test/",
+ "https://autogpt.example.test/_agpt",
+ ],
+)
+def test_media_url_uses_backend_origin(local_settings, client, base_url):
+ local_settings.config.platform_base_url = base_url
+ destination = local_media.get_media_path("u", "images", "image.png")
+ destination.parent.mkdir(parents=True)
+ destination.write_bytes(b"image")
+ url = local_media.media_url("u", "images", "image.png")
+ assert url == f"{base_url.rstrip('/')}/api/store/media/u/images/image.png"
+ if not base_url.endswith("/_agpt"):
+ assert client.get(url).content == b"image"
+
+
+ "component", [".", "..", "../secret", "a/b", "a\\b", "", "a%2fb"]
+)
+def test_media_path_rejects_invalid_components(local_settings, component):
+ with pytest.raises(ValueError):
+ local_media.get_media_path(component, "images", "file.png")
+ with pytest.raises(ValueError):
+ local_media.get_media_path("user", "images", component)
+
+
+def test_media_path_rejects_symlink_escape(local_settings, tmp_path):
+ images = local_media.media_root() / "users/user/images"
+ images.mkdir(parents=True)
+ secret = tmp_path / "private.png"
+ secret.write_bytes(b"private")
+ (images / "image.png").symlink_to(secret)
+ with pytest.raises(ValueError):
+ local_media.get_media_path("user", "images", "image.png")
+
+
+ "path", ["images/missing.png", "documents/file.png", "images/file.html"]
+)
+def test_public_download_rejects_missing_or_unsupported_media(
+ local_settings, client, path
+):
+ response = client.get(f"/api/store/media/user/{path}")
+ assert response.status_code == 404
+ assert response.json() == {"detail": "Media not found"}
+ assert not local_media.media_root().exists()
+
+
+def test_public_download_rejects_symlink_escape(local_settings, client, tmp_path):
+ images = local_media.media_root() / "users/user/images"
+ images.mkdir(parents=True)
+ secret = tmp_path / "private.png"
+ secret.write_bytes(b"private")
+ (images / "image.png").symlink_to(secret)
+ response = client.get("/api/store/media/user/images/image.png")
+ assert response.status_code == 404
+ assert b"private" not in response.content
+
+
+ "link_directory,private_relative_path",
+ [("users/user", "images/image.png"), ("users/user/images", "image.png")],
+)
+async def test_media_rejects_symlink_to_sibling_with_shared_root_prefix(
+ local_settings, client, link_directory, private_relative_path
+):
+ root = local_media.media_root()
+ outside = root.with_name(f"{root.name}-private")
+ private_file = outside / private_relative_path
+ private_file.parent.mkdir(parents=True)
+ private_file.write_bytes(b"private")
+ link = root / link_directory
+ link.parent.mkdir(parents=True)
+ link.symlink_to(outside, target_is_directory=True)
+
+ response = client.get("/api/store/media/user/images/image.png")
+ assert response.status_code == 404
+ assert b"private" not in response.content
+ with pytest.raises(ValueError, match="Invalid media path"):
+ await local_media.store_media("user", "images", "image.png", b"replacement")
+ assert private_file.read_bytes() == b"private"
+
+
+async def test_media_allows_symlink_to_file_within_root(local_settings, client):
+ await local_media.store_media("user", "images", "original.png", b"image")
+ original = local_media.get_media_path("user", "images", "original.png")
+ original.with_name("alias.png").symlink_to(original)
+ response = client.get("/api/store/media/user/images/alias.png")
+ assert response.status_code == 200
+ assert response.content == b"image"
+
+
+async def test_rejected_virus_scan_never_writes_media(local_settings, monkeypatch):
+ monkeypatch.setattr(
+ media, "scan_content_safe", AsyncMock(side_effect=RuntimeError("virus"))
+ )
+ upload = fastapi.UploadFile(
+ filename="image.png",
+ file=io.BytesIO(b"\x89PNG\r\n\x1a\n"),
+ headers=Headers({"content-type": "image/png"}),
+ )
+ with pytest.raises(media.store_exceptions.MediaUploadError):
+ await media.upload_media("user", upload)
+ assert not local_media.media_root().exists()
+
+
+async def test_failed_replacement_preserves_existing_media(local_settings, monkeypatch):
+ await local_media.store_media("user", "images", "image.png", b"old")
+ destination = local_media.get_media_path("user", "images", "image.png")
+
+ def failed_replace(source, target):
+ assert Path(source).read_bytes() == b"new"
+ assert Path(target).read_bytes() == b"old"
+ raise OSError("disk error")
+
+ monkeypatch.setattr(local_media.os, "replace", failed_replace)
+ with pytest.raises(OSError, match="disk error"):
+ await local_media.store_media("user", "images", "image.png", b"new")
+ assert destination.read_bytes() == b"old"
+ assert list(destination.parent.iterdir()) == [destination]
+
+
+ "filename", ["image.jpg", "image.JPG", "image.JPEG", "image.jpeg"]
+)
+async def test_named_jpeg_aliases_reuse_upload(local_settings, filename):
+ await local_media.store_media("user", "images", "image.jpeg", b"image")
+ assert await local_media.check_media_exists("user", filename) == (
+ "/api/store/media/user/images/image.jpeg"
+ )
+
+
[email protected]("filename", ["../image.png", "image.html", "missing.png"])
+async def test_invalid_or_missing_lookup_returns_none(local_settings, filename):
+ assert await local_media.check_media_exists("user", filename) is None
diff --git a/autogpt_platform/backend/backend/api/features/store/media.py b/autogpt_platform/backend/backend/api/features/store/media.py
index cfdc71567a..91c5ae3151 100644
--- a/autogpt_platform/backend/backend/api/features/store/media.py
+++ b/autogpt_platform/backend/backend/api/features/store/media.py
@@ -5,11 +5,11 @@ import uuid
import fastapi
from gcloud.aio import storage as async_storage
-from backend.util.exceptions import MissingConfigError
from backend.util.settings import Settings
from backend.util.virus_scanner import scan_content_safe
from . import exceptions as store_exceptions
+from . import local_media
logger = logging.getLogger(__name__)
@@ -32,7 +32,7 @@ async def check_media_exists(user_id: str, filename: str) -> str | None:
"""
settings = Settings()
if not settings.config.media_gcs_bucket_name:
- raise MissingConfigError("GCS media bucket is not configured")
+ return await local_media.check_media_exists(user_id, filename)
async with async_storage.Storage() as async_client:
bucket_name = settings.config.media_gcs_bucket_name
@@ -71,41 +71,45 @@ async def upload_media(
logger.error(f"Error reading file content: {str(e)}")
raise store_exceptions.FileReadError("Failed to read file content") from e
+ content_type = file.content_type
+ if content_type is None:
+ content_type = "image/jpeg"
+
# Validate file signature/magic bytes
- if file.content_type in ALLOWED_IMAGE_TYPES:
+ if content_type in ALLOWED_IMAGE_TYPES:
# Check image file signatures
if content.startswith(b"\xff\xd8\xff"): # JPEG
- if file.content_type != "image/jpeg":
+ if content_type != "image/jpeg":
raise store_exceptions.InvalidFileTypeError(
"File signature does not match content type"
)
elif content.startswith(b"\x89PNG\r\n\x1a\n"): # PNG
- if file.content_type != "image/png":
+ if content_type != "image/png":
raise store_exceptions.InvalidFileTypeError(
"File signature does not match content type"
)
elif content.startswith(b"GIF87a") or content.startswith(b"GIF89a"): # GIF
- if file.content_type != "image/gif":
+ if content_type != "image/gif":
raise store_exceptions.InvalidFileTypeError(
"File signature does not match content type"
)
elif content.startswith(b"RIFF") and content[8:12] == b"WEBP": # WebP
- if file.content_type != "image/webp":
+ if content_type != "image/webp":
raise store_exceptions.InvalidFileTypeError(
"File signature does not match content type"
)
else:
raise store_exceptions.InvalidFileTypeError("Invalid image file signature")
- elif file.content_type in ALLOWED_VIDEO_TYPES:
+ elif content_type in ALLOWED_VIDEO_TYPES:
# Check video file signatures
if content.startswith(b"\x00\x00\x00") and (content[4:8] == b"ftyp"): # MP4
- if file.content_type != "video/mp4":
+ if content_type != "video/mp4":
raise store_exceptions.InvalidFileTypeError(
"File signature does not match content type"
)
elif content.startswith(b"\x1a\x45\xdf\xa3"): # WebM
- if file.content_type != "video/webm":
+ if content_type != "video/webm":
raise store_exceptions.InvalidFileTypeError(
"File signature does not match content type"
)
@@ -113,20 +117,10 @@ async def upload_media(
raise store_exceptions.InvalidFileTypeError("Invalid video file signature")
settings = Settings()
-
- # Check required settings first before doing any file processing
- if not settings.config.media_gcs_bucket_name:
- logger.error("Missing GCS bucket name setting")
- raise store_exceptions.StorageConfigError(
- "Missing storage bucket configuration"
- )
+ use_local_storage = not settings.config.media_gcs_bucket_name
try:
# Validate file type
- content_type = file.content_type
- if content_type is None:
- content_type = "image/jpeg"
-
if (
content_type not in ALLOWED_IMAGE_TYPES
and content_type not in ALLOWED_VIDEO_TYPES
@@ -167,6 +161,17 @@ async def upload_media(
# Construct storage path
media_type = "images" if content_type in ALLOWED_IMAGE_TYPES else "videos"
+
+ if use_local_storage:
+ unique_filename = local_media.stored_filename(
+ unique_filename, content_type, use_file_name
+ )
+ file_bytes = await file.read()
+ await scan_content_safe(file_bytes, filename=unique_filename)
+ return await local_media.store_media(
+ user_id, media_type, unique_filename, file_bytes
+ )
+
storage_path = f"users/{user_id}/{media_type}/{unique_filename}"
try:
diff --git a/autogpt_platform/backend/backend/api/features/store/media_test.py b/autogpt_platform/backend/backend/api/features/store/media_test.py
index 264fc30774..10224760b3 100644
--- a/autogpt_platform/backend/backend/api/features/store/media_test.py
+++ b/autogpt_platform/backend/backend/api/features/store/media_test.py
@@ -9,6 +9,7 @@ import starlette.datastructures
from backend.util.settings import Settings
from . import exceptions as store_exceptions
+from . import local_media
from . import media as store_media
@@ -77,20 +78,97 @@ async def test_upload_media_invalid_type(mock_settings, mock_storage_client):
mock_storage_client.upload.assert_not_called()
-async def test_upload_media_missing_credentials(monkeypatch):
+async def test_upload_media_missing_content_type_still_validates_signature(
+ mock_settings,
+ mock_storage_client,
+):
+ upload = fastapi.UploadFile(filename="image.jpeg", file=io.BytesIO(b"not an image"))
+ with pytest.raises(store_exceptions.InvalidFileTypeError):
+ await store_media.upload_media("test-user", upload)
+ mock_storage_client.upload.assert_not_called()
+
+
+async def test_upload_media_missing_content_type_accepts_valid_jpeg(
+ mock_settings,
+ mock_storage_client,
+):
+ upload = fastapi.UploadFile(
+ filename="image.jpeg", file=io.BytesIO(b"\xff\xd8\xffimage")
+ )
+ result = await store_media.upload_media("test-user", upload)
+ assert result.startswith("https://storage.googleapis.com/test-bucket/")
+ assert mock_storage_client.upload.call_args.kwargs["content_type"] == "image/jpeg"
+
+
+def local_storage_settings(monkeypatch, tmp_path):
settings = Settings()
settings.config.media_gcs_bucket_name = ""
settings.config.google_application_credentials = ""
+ settings.config.workspace_storage_dir = str(tmp_path / "workspaces")
+ settings.config.platform_base_url = ""
monkeypatch.setattr("backend.api.features.store.media.Settings", lambda: settings)
+ monkeypatch.setattr(
+ "backend.api.features.store.local_media.Settings", lambda: settings
+ )
+ monkeypatch.setattr(
+ "backend.api.features.store.media.scan_content_safe",
+ unittest.mock.AsyncMock(),
+ )
+ return settings
+
+async def test_upload_media_missing_credentials(local_storage_settings, tmp_path):
+ test_data = b"\xff\xd8\xff" + b"test data"
test_file = fastapi.UploadFile(
filename="laptop.jpeg",
- file=io.BytesIO(b"\xff\xd8\xff" + b"test data"), # Valid JPEG signature
+ file=io.BytesIO(test_data),
headers=starlette.datastructures.Headers({"content-type": "image/jpeg"}),
)
- with pytest.raises(store_exceptions.StorageConfigError):
- await store_media.upload_media("test-user", test_file)
+ result = await store_media.upload_media("test-user", test_file)
+
+ assert result.startswith("/api/store/media/test-user/images/")
+ assert result.endswith(".jpeg")
+
+ stored = tmp_path / "store-media" / "users" / "test-user" / "images"
+ files = list(stored.iterdir())
+ assert len(files) == 1
+ assert files[0].read_bytes() == test_data
+
+
[email protected]("filename", ["agent_graph-1.jpeg", "agent_graph-1.jpg"])
+async def test_check_media_exists_without_gcs(
+ local_storage_settings, tmp_path, filename
+):
+ missing = await store_media.check_media_exists("test-user", filename)
+ assert missing is None
+
+ test_file = fastapi.UploadFile(
+ filename=filename,
+ file=io.BytesIO(b"\xff\xd8\xff" + b"existing"),
+ headers=starlette.datastructures.Headers({"content-type": "image/jpeg"}),
+ )
+ uploaded = await store_media.upload_media(
+ "test-user", test_file, use_file_name=True
+ )
+ stored_filename = "agent_graph-1.jpeg"
+ assert uploaded == f"/api/store/media/test-user/images/{stored_filename}"
+ assert (
+ tmp_path / "store-media" / "users" / "test-user" / "images" / stored_filename
+ ).is_file()
+
+ found = await store_media.check_media_exists("test-user", filename)
+ assert found == uploaded
+
+ assert await store_media.check_media_exists("test-user", "../secret.jpeg") is None
+
+
+def test_get_local_media_path_rejects_traversal(local_storage_settings):
+ with pytest.raises(ValueError):
+ local_media.get_media_path("test-user", "images", "../secret.jpeg")
+ with pytest.raises(ValueError):
+ local_media.get_media_path("test-user", "other", "file.jpeg")
async def test_upload_media_video_type(mock_settings, mock_storage_client):
diff --git a/autogpt_platform/backend/backend/api/features/store/routes.py b/autogpt_platform/backend/backend/api/features/store/routes.py
index b55ce42479..c5cb5361f8 100644
--- a/autogpt_platform/backend/backend/api/features/store/routes.py
+++ b/autogpt_platform/backend/backend/api/features/store/routes.py
@@ -8,6 +8,7 @@ import fastapi.responses
import prisma.enums
from fastapi import Query, Security
from pydantic import BaseModel
+from starlette.datastructures import Headers
import backend.data.graph
import backend.util.json
@@ -19,6 +20,7 @@ from . import cache as store_cache
from . import categories as store_categories
from . import db as store_db
from . import image_gen as store_image_gen
+from . import local_media
from . import media as store_media
from . import model as store_model
@@ -518,6 +520,39 @@ async def edit_submission(
return result
+ "/media/{user_id}/{media_type}/{filename}",
+ summary="Get stored marketplace media",
+ response_class=fastapi.responses.FileResponse,
+ responses={
+ 200: {
+ "content": {
+ content_type: {"schema": {"type": "string", "format": "binary"}}
+ for content_type in local_media.CONTENT_TYPE_EXTENSIONS
+ }
+ }
+ },
+ tags=["store", "public"],
+)
+def get_store_media(
+ user_id: str,
+ media_type: str,
+ filename: str,
+) -> fastapi.responses.FileResponse:
+ content_type = local_media.content_type_for_filename(filename)
+ if content_type is None or media_type not in local_media.MEDIA_TYPES:
+ raise NotFoundError("Media not found")
+ try:
+ path = local_media.get_media_path(user_id, media_type, filename)
+ except ValueError:
+ raise NotFoundError("Media not found")
+ if not path.is_file():
+ raise NotFoundError("Media not found")
+ return fastapi.responses.FileResponse(
+ path, media_type=content_type, headers={"X-Content-Type-Options": "nosniff"}
+ )
+
+
@router.post(
"/submissions/media",
summary="Upload submission media",
@@ -571,6 +606,7 @@ async def generate_image(
image_file = fastapi.UploadFile(
file=image,
filename=filename,
+ headers=Headers({"content-type": "image/jpeg"}),
)
image_url = await store_media.upload_media(
user_id=user_id, file=image_file, use_file_name=True
diff --git a/autogpt_platform/docker-compose.platform.yml b/autogpt_platform/docker-compose.platform.yml
index 5eb6f587bf..299a076e72 100644
--- a/autogpt_platform/docker-compose.platform.yml
+++ b/autogpt_platform/docker-compose.platform.yml
@@ -216,6 +216,7 @@ services:
- "8006:8006"
volumes:
- workspace-data:/app/autogpt_platform/backend/workspaces
+ - store-media-data:/app/autogpt_platform/backend/store-media
networks:
- app-network
logging:
@@ -355,6 +356,8 @@ services:
<<: *backend-env
ports:
- "8005:8005"
+ volumes:
+ - store-media-data:/app/autogpt_platform/backend/store-media
networks:
- app-network
logging:
@@ -502,6 +505,7 @@ services:
AUTH_DB_SCHEMA: platform
volumes:
workspace-data:
+ store-media-data:
falkordb_data:
networks:
diff --git a/autogpt_platform/docker-compose.yml b/autogpt_platform/docker-compose.yml
index 48d2baa80d..5bfdaf24f2 100644
--- a/autogpt_platform/docker-compose.yml
+++ b/autogpt_platform/docker-compose.yml
@@ -7,6 +7,7 @@ networks:
volumes:
clamav-data:
workspace-data:
+ store-media-data:
falkordb_data:
x-agpt-services:
diff --git a/autogpt_platform/frontend/next.config.mjs b/autogpt_platform/frontend/next.config.mjs
index 18ed83c5d4..ba0fa89131 100644
--- a/autogpt_platform/frontend/next.config.mjs
+++ b/autogpt_platform/frontend/next.config.mjs
@@ -13,6 +13,14 @@ const nextConfig = {
},
// Suppress the "X-Powered-By: Next.js" header (framework fingerprinting).
poweredByHeader: false,
+ async rewrites() {
+ return [
+ {
+ source: "/api/store/media/:path*",
+ destination: "/api/proxy/api/store/media/:path*",
+ },
+ ];
+ },
productionBrowserSourceMaps: enableSourceMaps,
// Externalize OpenTelemetry packages to fix Turbopack HMR issues
serverExternalPackages: [
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/MarketplaceAgentBlock.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/MarketplaceAgentBlock.tsx
index 4f4016737c..6542e5479d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/MarketplaceAgentBlock.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/MarketplaceAgentBlock.tsx
@@ -2,6 +2,7 @@ import { Button } from "@/components/__legacy__/ui/button";
import { Skeleton } from "@/components/__legacy__/ui/skeleton";
import { cn } from "@/lib/utils";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import React, { ButtonHTMLAttributes } from "react";
import Link from "next/link";
import { highlightText } from "./helpers";
@@ -50,6 +51,7 @@ export const MarketplaceAgentBlock: MarketplaceAgentBlockComponent = ({
{image_url && (
<Image
src={image_url}
+ unoptimized={isLocalStoreMediaUrl(image_url)}
alt="integration-icon"
fill
sizes="5.625rem"
diff --git a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/UGCAgentBlock.tsx b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/UGCAgentBlock.tsx
index b8723a63da..e2e9605407 100644
--- a/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/UGCAgentBlock.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/build/components/NewControlPanel/NewBlockMenu/UGCAgentBlock.tsx
@@ -2,6 +2,7 @@ import { Button } from "@/components/__legacy__/ui/button";
import { Skeleton } from "@/components/__legacy__/ui/skeleton";
import { cn } from "@/lib/utils";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import React, { ButtonHTMLAttributes } from "react";
import { highlightText } from "./helpers";
import { formatTimeAgo } from "@/lib/utils/time";
@@ -44,6 +45,7 @@ export const UGCAgentBlock: UGCAgentBlockComponent = ({
<div className="relative h-[3.125rem] w-[5.625rem] overflow-hidden rounded-[0.375rem] bg-white">
<Image
src={image_url}
+ unoptimized={isLocalStoreMediaUrl(image_url)}
alt="integration-icon"
fill
sizes="5.625rem"
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx
index 65a1259956..2864f5a7b7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/components/LibraryAgentCard/LibraryAgentCard.tsx
@@ -2,6 +2,7 @@
import { Text } from "@/components/atoms/Text/Text";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import NextLink from "next/link";
import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
@@ -118,6 +119,7 @@ export function LibraryAgentCard({
) : (
<Image
src={image_url}
+ unoptimized={isLocalStoreMediaUrl(image_url)}
alt={`${name} preview image`}
width={107}
height={58}
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/AgentImageItem.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/AgentImageItem.tsx
index 3ca880ca48..de7fb19268 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/AgentImageItem.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/AgentImageItem/AgentImageItem.tsx
@@ -1,6 +1,7 @@
import { Button } from "@/components/atoms/Button/Button";
import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import { useEffect, useState } from "react";
import {
getYouTubeVideoId,
@@ -73,6 +74,7 @@ export function AgentImageItem({
)}
<Image
src={image}
+ unoptimized={isLocalStoreMediaUrl(image)}
alt="Image"
fill
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/FeaturedAgentCard/FeaturedAgentCard.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/FeaturedAgentCard/FeaturedAgentCard.tsx
index a4c4c540a0..c171d67fb2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/FeaturedAgentCard/FeaturedAgentCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/FeaturedAgentCard/FeaturedAgentCard.tsx
@@ -14,6 +14,7 @@ import {
import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
import { cn } from "@/lib/utils";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import { useRef, useState } from "react";
import { AddToLibraryButton } from "../AddToLibraryButton/AddToLibraryButton";
@@ -69,6 +70,7 @@ export function FeaturedAgentCard({ agent, backgroundColor }: Props) {
)}
<Image
src={agent.agent_image}
+ unoptimized={isLocalStoreMediaUrl(agent.agent_image)}
alt={`${agent.agent_name} preview image`}
fill
className="object-cover"
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/StoreCard/StoreCard.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/StoreCard/StoreCard.tsx
index 85cadb1298..0bc26bf55d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/StoreCard/StoreCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/StoreCard/StoreCard.tsx
@@ -7,6 +7,7 @@ import Avatar, {
} from "@/components/atoms/Avatar/Avatar";
import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import { useState } from "react";
import { AddToLibraryButton } from "../AddToLibraryButton/AddToLibraryButton";
import { isKey } from "@/lib/keyboard";
@@ -70,6 +71,7 @@ export function StoreCard({
)}
<Image
src={agentImage}
+ unoptimized={isLocalStoreMediaUrl(agentImage)}
alt={`${agentName} preview image`}
fill
className="object-cover"
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/components/ExpertWorkflowCard/ExpertWorkflowCard.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/components/ExpertWorkflowCard/ExpertWorkflowCard.tsx
index 7b119cb8d1..b60f499cb6 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/components/ExpertWorkflowCard/ExpertWorkflowCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/components/ExpertWorkflowCard/ExpertWorkflowCard.tsx
@@ -6,6 +6,7 @@ import { Icon } from "@/components/atoms/Icon/Icon";
import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
import { Calendar03Icon, FlashIcon } from "@hugeicons/core-free-icons";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import { getCadenceLabel } from "./helpers";
import { useExpertWorkflowCard } from "./useExpertWorkflowCard";
@@ -26,6 +27,7 @@ export function ExpertWorkflowCard({ workflow, accent }: Props) {
{imageUrl ? (
<Image
src={imageUrl}
+ unoptimized={isLocalStoreMediaUrl(imageUrl)}
alt={`${name} preview image`}
fill
sizes="(min-width: 640px) 360px, 100vw"
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableCard/AgentTableCard.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableCard/AgentTableCard.tsx
index 4595405a80..296e6987fd 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableCard/AgentTableCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableCard/AgentTableCard.tsx
@@ -1,6 +1,7 @@
"use client";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import { IconStarFilled, IconMore } from "@/components/__legacy__/ui/icons";
import { StoreSubmission } from "@/app/api/__generated__/models/storeSubmission";
import { Status } from "@/components/__legacy__/Status";
@@ -35,6 +36,7 @@ export const AgentTableCard = ({
<div className="relative aspect-video w-24 shrink-0 overflow-hidden rounded-lg bg-[#d9d9d9] dark:bg-neutral-800">
<Image
src={image_urls?.[0] ?? "/nada.png"}
+ unoptimized={isLocalStoreMediaUrl(image_urls?.[0] ?? "/nada.png")}
alt={agentName}
fill
style={{ objectFit: "cover" }}
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableRow/AgentTableRow.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableRow/AgentTableRow.tsx
index 830d581649..e204eed5df 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableRow/AgentTableRow.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/dashboard/components/AgentTableRow/AgentTableRow.tsx
@@ -1,6 +1,7 @@
"use client";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import { Text } from "@/components/atoms/Text/Text";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
@@ -73,6 +74,7 @@ export const AgentTableRow = ({
<div className="relative aspect-video w-32 shrink-0 overflow-hidden rounded-[10px] bg-zinc-100">
<Image
src={image_urls?.[0] ?? ""}
+ unoptimized={isLocalStoreMediaUrl(image_urls?.[0] ?? "")}
alt={agentName}
fill
style={{ objectFit: "cover" }}
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/page.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/page.tsx
index 21834e0dc6..bf2ccb71d3 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/page.tsx
@@ -1,7 +1,7 @@
"use client";
import { useGetV2GetUserProfile } from "@/app/api/__generated__/endpoints/store/store";
-import { ProfileInfoForm } from "@/components/__legacy__/ProfileInfoForm";
+import { ProfileInfoForm } from "@/components/contextual/ProfileInfoForm/ProfileInfoForm";
import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
import { isLogoutInProgress } from "@/lib/autogpt-server-api/helpers";
import type { ProfileDetails } from "@/app/api/__generated__/models/profileDetails";
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/creator-dashboard/components/MobileSubmissionItem/MobileSubmissionItem.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/creator-dashboard/components/MobileSubmissionItem/MobileSubmissionItem.tsx
index 1b728dd32b..96c10fe189 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/creator-dashboard/components/MobileSubmissionItem/MobileSubmissionItem.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/creator-dashboard/components/MobileSubmissionItem/MobileSubmissionItem.tsx
@@ -1,6 +1,7 @@
"use client";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import Link from "next/link";
import { motion, useReducedMotion } from "framer-motion";
import type { StoreSubmission } from "@/app/api/__generated__/models/storeSubmission";
@@ -97,6 +98,7 @@ export function MobileSubmissionItem({
{thumbnail ? (
<Image
src={thumbnail}
+ unoptimized={isLocalStoreMediaUrl(thumbnail)}
alt={submission.name}
fill
sizes="64px"
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/creator-dashboard/components/SubmissionItem/SubmissionItem.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/creator-dashboard/components/SubmissionItem/SubmissionItem.tsx
index cca9cd867e..22044ead59 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/creator-dashboard/components/SubmissionItem/SubmissionItem.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/creator-dashboard/components/SubmissionItem/SubmissionItem.tsx
@@ -1,6 +1,7 @@
"use client";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import Link from "next/link";
import { motion, useReducedMotion } from "framer-motion";
import type { StoreSubmission } from "@/app/api/__generated__/models/storeSubmission";
@@ -100,6 +101,7 @@ export function SubmissionItem({
{thumbnail ? (
<Image
src={thumbnail}
+ unoptimized={isLocalStoreMediaUrl(thumbnail)}
alt={submission.name}
fill
sizes="80px"
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertWorkflowCard.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertWorkflowCard.tsx
index e7708b42bd..f824253fca 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertWorkflowCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertWorkflowCard.tsx
@@ -8,6 +8,7 @@ import { cn } from "@/lib/utils";
import { Activity01Icon } from "@hugeicons/core-free-icons";
import { isRenderableImageUrl } from "@/lib/next-image";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import NextLink from "next/link";
import { useState } from "react";
import { ExpertCover } from "../../components/ExpertTeamCard/components/ExpertCover";
@@ -63,6 +64,7 @@ export function ExpertWorkflowCard({
{isRenderableImageUrl(libraryAgent?.image_url) && !hasImageError ? (
<Image
src={libraryAgent.image_url}
+ unoptimized={isLocalStoreMediaUrl(libraryAgent.image_url)}
alt=""
fill
sizes="(min-width: 1024px) 33vw, (min-width: 640px) 50vw, 100vw"
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertWorkflowListItem.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertWorkflowListItem.tsx
index ec05165633..fb2fb91752 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertWorkflowListItem.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertWorkflowListItem.tsx
@@ -11,6 +11,7 @@ import {
} from "@hugeicons/core-free-icons";
import { isRenderableImageUrl } from "@/lib/next-image";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import NextLink from "next/link";
import { useState } from "react";
import { ExpertWorkflowActions } from "./ExpertWorkflowActions";
@@ -73,6 +74,7 @@ export function ExpertWorkflowListItem({
<div className="pointer-events-none relative aspect-square shrink-0 self-stretch overflow-hidden rounded-lg bg-zinc-100">
<Image
src={libraryAgent.image_url}
+ unoptimized={isLocalStoreMediaUrl(libraryAgent.image_url)}
alt=""
fill
sizes="96px"
diff --git a/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts b/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts
index cd37453607..cb1578476c 100644
--- a/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts
+++ b/autogpt_platform/frontend/src/app/api/mutators/__tests__/custom-mutator.test.ts
@@ -190,7 +190,7 @@ describe("customMutator — Sentry trace propagation", () => {
});
});
-describe("customMutator — empty body handling", () => {
+describe("customMutator — response body handling", () => {
beforeEach(() => {
vi.clearAllMocks();
mockIsClientSide.mockReturnValue(true);
@@ -268,6 +268,36 @@ describe("customMutator — empty body handling", () => {
expect(result.data).toEqual({ ok: true });
});
+
+ it.each([
+ "image/jpeg",
+ "image/png",
+ "image/gif",
+ "image/webp",
+ "video/mp4",
+ "video/webm",
+ "application/pdf",
+ ])("preserves %s bytes as a Blob", async (contentType) => {
+ const bytes = new Uint8Array([0, 255, 128, 10, 42]);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue(
+ new Response(bytes, {
+ headers: { "content-type": contentType },
+ }),
+ ),
+ );
+
+ const result = await customMutator<{
+ data: Blob;
+ status: number;
+ headers: Headers;
+ }>("/api/store/media/user/images/image.png", { method: "GET" });
+
+ expect(result.data).toBeInstanceOf(Blob);
+ expect(new Uint8Array(await result.data.arrayBuffer())).toEqual(bytes);
+ expect(result.data.type).toBe(contentType);
+ });
});
describe("customMutator validation errors", () => {
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 67014e53ac..f3e60f6457 100644
--- a/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
+++ b/autogpt_platform/frontend/src/app/api/mutators/custom-mutator.ts
@@ -36,7 +36,12 @@ const getBody = async <T>(c: Response | Request): Promise<T> => {
return c.json();
}
- if (contentType && contentType.includes("application/pdf")) {
+ if (
+ contentType &&
+ (contentType.includes("application/pdf") ||
+ contentType.startsWith("image/") ||
+ contentType.startsWith("video/"))
+ ) {
return c.blob() as Promise<T>;
}
@@ -166,10 +171,11 @@ export const customMutator = async <
throw new ApiError(errorMessage, response.status, responseData);
}
- const responseData = await getBody<T["data"]>(response);
+ const responseData = await getBody<unknown>(response);
// Transform ISO date strings to Date objects in the response data
- const transformedData = transformDates(responseData);
+ const transformedData =
+ responseData instanceof Blob ? responseData : transformDates(responseData);
return {
status: response.status,
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 9a3903eefe..2a50fcf1cd 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -14664,6 +14664,66 @@
}
}
},
+ "/api/store/media/{user_id}/{media_type}/{filename}": {
+ "get": {
+ "tags": ["v2", "store", "public"],
+ "summary": "Get stored marketplace media",
+ "operationId": "getV2Get stored marketplace media",
+ "parameters": [
+ {
+ "name": "user_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "User Id" }
+ },
+ {
+ "name": "media_type",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Media Type" }
+ },
+ {
+ "name": "filename",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Filename" }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "image/jpeg": {
+ "schema": { "type": "string", "format": "binary" }
+ },
+ "image/png": {
+ "schema": { "type": "string", "format": "binary" }
+ },
+ "image/gif": {
+ "schema": { "type": "string", "format": "binary" }
+ },
+ "image/webp": {
+ "schema": { "type": "string", "format": "binary" }
+ },
+ "video/mp4": {
+ "schema": { "type": "string", "format": "binary" }
+ },
+ "video/webm": {
+ "schema": { "type": "string", "format": "binary" }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/store/metrics/cache": {
"get": {
"tags": ["v2", "store", "metrics"],
diff --git a/autogpt_platform/frontend/src/components/atoms/Avatar/Avatar.tsx b/autogpt_platform/frontend/src/components/atoms/Avatar/Avatar.tsx
index 8456caede8..d44d4850b1 100644
--- a/autogpt_platform/frontend/src/components/atoms/Avatar/Avatar.tsx
+++ b/autogpt_platform/frontend/src/components/atoms/Avatar/Avatar.tsx
@@ -10,6 +10,7 @@ import React, {
import BoringAvatar from "boring-avatars";
import Image, { ImageProps } from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import { cn } from "@/lib/utils";
type AvatarContextValue = {
@@ -156,7 +157,7 @@ export function AvatarImage({
fill={Boolean(fill)}
sizes={sizes}
priority={priority}
- unoptimized={unoptimized}
+ unoptimized={unoptimized || isLocalStoreMediaUrl(normalizedSrc)}
onLoad={handleLoadingComplete}
onError={handleErrorNext as ImageProps["onError"]}
/>
diff --git a/autogpt_platform/frontend/src/components/__legacy__/ProfileInfoForm.tsx b/autogpt_platform/frontend/src/components/contextual/ProfileInfoForm/ProfileInfoForm.tsx
similarity index 72%
rename from autogpt_platform/frontend/src/components/__legacy__/ProfileInfoForm.tsx
rename to autogpt_platform/frontend/src/components/contextual/ProfileInfoForm/ProfileInfoForm.tsx
index d96a79224d..598c7b3df2 100644
--- a/autogpt_platform/frontend/src/components/__legacy__/ProfileInfoForm.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/ProfileInfoForm/ProfileInfoForm.tsx
@@ -1,78 +1,25 @@
"use client";
-import { useState } from "react";
-
import Image from "next/image";
-
-import { IconPersonFill } from "@/components/__legacy__/ui/icons";
-import { Separator } from "@/components/__legacy__/ui/separator";
-import { postV2UpdateUserProfile } from "@/app/api/__generated__/endpoints/store/store";
-import { resolveResponse } from "@/app/api/helpers";
+import { UserIcon } from "@phosphor-icons/react";
import type { ProfileDetails } from "@/app/api/__generated__/models/profileDetails";
-import { useToast } from "@/components/molecules/Toast/use-toast";
-import {
- isFileTooLarge,
- SUBMISSION_MEDIA_MAX_SIZE_MB,
- uploadSubmissionMediaDirect,
-} from "@/lib/direct-upload";
-import { Button } from "./Button";
-
-export function ProfileInfoForm({ profile }: { profile: ProfileDetails }) {
- const { toast } = useToast();
- const [isSubmitting, setIsSubmitting] = useState(false);
- const [profileData, setProfileData] = useState<ProfileDetails>(profile);
-
- async function submitForm() {
- try {
- setIsSubmitting(true);
-
- const updatedProfile = {
- name: profileData.name,
- username: profileData.username,
- description: profileData.description,
- links: profileData.links.filter((link) => link), // Filter out empty links
- avatar_url: profileData.avatar_url,
- };
-
- if (!isSubmitting) {
- const returnedProfile = await resolveResponse(
- postV2UpdateUserProfile(updatedProfile),
- );
- if (returnedProfile) setProfileData(returnedProfile);
- }
- } catch (error) {
- console.error("Error updating profile:", error);
- } finally {
- setIsSubmitting(false);
- }
- }
+import { Button } from "@/components/atoms/Button/Button";
+import { Separator } from "@/components/ui/separator";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
+import { useProfileInfoForm } from "./useProfileInfoForm";
- async function handleImageUpload(file: File) {
- if (
- isFileTooLarge({ file, maxSizeMB: SUBMISSION_MEDIA_MAX_SIZE_MB, toast })
- )
- return;
-
- try {
- const mediaUrl = await uploadSubmissionMediaDirect(file);
-
- const updatedProfile = {
- ...profileData,
- avatar_url: mediaUrl,
- };
+interface Props {
+ profile: ProfileDetails;
+}
- const returnedProfile = await resolveResponse(
- postV2UpdateUserProfile(updatedProfile),
- );
- if (returnedProfile) setProfileData(returnedProfile);
- } catch (error) {
- toast({
- title: "Failed to upload photo",
- description: error instanceof Error ? error.message : undefined,
- variant: "destructive",
- });
- }
- }
+export function ProfileInfoForm({ profile }: Props) {
+ const {
+ profileData,
+ setProfileData,
+ isSubmitting,
+ submitForm,
+ handleImageUpload,
+ } = useProfileInfoForm(profile);
return (
<div className="w-full min-w-[800px] px-4 sm:px-8">
@@ -89,12 +36,17 @@ export function ProfileInfoForm({ profile }: { profile: ProfileDetails }) {
{profileData.avatar_url ? (
<Image
src={profileData.avatar_url}
+ unoptimized={isLocalStoreMediaUrl(profileData.avatar_url)}
alt="Profile"
fill
className="rounded-full"
/>
) : (
- <IconPersonFill className="absolute left-[30px] top-[24px] h-[77.80px] w-[70.63px] text-[#7e7e7e] dark:text-[#999999]" />
+ <UserIcon
+ weight="fill"
+ aria-label="Person Fill Icon"
+ className="absolute left-[30px] top-[24px] h-[77.80px] w-[70.63px] text-[#7e7e7e] dark:text-[#999999]"
+ />
)}
</div>
<label className="font-circular mt-11 inline-flex h-[43px] items-center justify-center rounded-[22px] bg-[#15171A] px-6 py-2 text-sm font-normal text-white transition-colors hover:bg-[#2D2F34] dark:bg-white dark:text-[#15171A] dark:hover:bg-[#E5E5E5]">
@@ -239,22 +191,11 @@ export function ProfileInfoForm({ profile }: { profile: ProfileDetails }) {
<Separator />
<div className="flex h-[50px] items-center justify-end gap-3 py-8">
- {/* FRONTEND-TODO: Need to fix it */}
- {/* <Button
- type="button"
- variant="secondary"
- className="font-circular h-[50px] rounded-[35px] bg-neutral-200 px-6 py-3 text-base font-medium text-neutral-800 transition-colors hover:bg-neutral-300 dark:border-neutral-700 dark:bg-neutral-700 dark:text-neutral-200 dark:hover:border-neutral-600 dark:hover:bg-neutral-600"
- onClick={() => {
- setProfileData(profile);
- }}
- >
- Cancel
- </Button> */}
<Button
type="submit"
disabled={isSubmitting}
+ loading={isSubmitting}
className="font-circular h-[50px] rounded-[35px] bg-neutral-800 px-6 py-3 text-base font-medium text-white transition-colors hover:bg-neutral-900 dark:bg-neutral-200 dark:text-neutral-900 dark:hover:bg-neutral-100"
- onClick={submitForm}
>
{isSubmitting ? "Saving..." : "Save changes"}
</Button>
diff --git a/autogpt_platform/frontend/src/components/contextual/ProfileInfoForm/__tests__/ProfileInfoForm.local-media.test.tsx b/autogpt_platform/frontend/src/components/contextual/ProfileInfoForm/__tests__/ProfileInfoForm.local-media.test.tsx
new file mode 100644
index 0000000000..dbe064cf6a
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/ProfileInfoForm/__tests__/ProfileInfoForm.local-media.test.tsx
@@ -0,0 +1,88 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+import { getPostV2UpdateUserProfileMockHandler200 } from "@/app/api/__generated__/endpoints/store/store.msw";
+import type { ProfileDetails } from "@/app/api/__generated__/models/profileDetails";
+import { server } from "@/mocks/mock-server";
+import { ProfileInfoForm } from "../ProfileInfoForm";
+
+vi.mock("next/image", async () =>
+ vi.importActual<typeof import("next/image")>("next/image"),
+);
+const uploadSpy = vi.hoisted(() => vi.fn());
+vi.mock("@/lib/direct-upload", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/direct-upload")>();
+ return { ...actual, uploadSubmissionMediaDirect: uploadSpy };
+});
+
+function profile(avatar_url: string): ProfileDetails {
+ return {
+ name: "Local user",
+ username: "local-user",
+ description: "Profile",
+ links: [],
+ avatar_url,
+ is_featured: false,
+ };
+}
+
+afterEach(() => vi.unstubAllEnvs());
+beforeEach(() => uploadSpy.mockReset());
+
+it.each([
+ [
+ "http://localhost:8006/api",
+ "http://localhost:8006/api/store/media/user/images/avatar.png",
+ ],
+ [
+ "https://appliance.example/_agpt/api",
+ "https://appliance.example/_agpt/api/store/media/user/images/avatar.png",
+ ],
+ ["http://localhost:8006/api", "/api/store/media/user/images/avatar.png"],
+])(
+ "renders saved and newly uploaded local avatars from %s",
+ async (backend, url) => {
+ vi.stubEnv("NEXT_PUBLIC_AGPT_SERVER_URL", backend);
+ const uploadedURL = url.replace("avatar.png", "uploaded.png");
+ uploadSpy.mockResolvedValueOnce(uploadedURL);
+ let persistedProfile: unknown;
+ server.use(
+ getPostV2UpdateUserProfileMockHandler200(async ({ request }) => {
+ persistedProfile = await request.json();
+ return profile(uploadedURL);
+ }),
+ );
+ render(<ProfileInfoForm profile={profile(url)} />);
+
+ const image = screen.getByRole("img", { name: "Profile" });
+ expect(image.getAttribute("src")).toBe(url);
+ expect(image.hasAttribute("srcset")).toBe(false);
+
+ const input = document.querySelector(
+ 'input[type="file"]',
+ ) as HTMLInputElement;
+ fireEvent.change(input, {
+ target: {
+ files: [new File(["image"], "avatar.png", { type: "image/png" })],
+ },
+ });
+ await vi.waitFor(() =>
+ expect(
+ screen.getByRole("img", { name: "Profile" }).getAttribute("src"),
+ ).toBe(uploadedURL),
+ );
+ const uploaded = screen.getByRole("img", { name: "Profile" });
+ expect(persistedProfile).toEqual(profile(uploadedURL));
+ expect(uploaded.hasAttribute("srcset")).toBe(false);
+ },
+);
+
+it.each([
+ "https://storage.googleapis.com/media/avatar.png",
+ "https://untrusted.example/api/store/media/user/images/avatar.png",
+])("preserves existing optimization for %s", (url) => {
+ vi.stubEnv("NEXT_PUBLIC_AGPT_SERVER_URL", "http://localhost:8006/api");
+ render(<ProfileInfoForm profile={profile(url)} />);
+ const image = screen.getByRole("img", { name: "Profile" });
+ expect(image.getAttribute("src")).toMatch(/^\/_next\/image\?/);
+ expect(image.getAttribute("srcset")).toContain("/_next/image?");
+});
diff --git a/autogpt_platform/frontend/src/components/__legacy__/__tests__/ProfileInfoForm.test.tsx b/autogpt_platform/frontend/src/components/contextual/ProfileInfoForm/__tests__/ProfileInfoForm.test.tsx
similarity index 65%
rename from autogpt_platform/frontend/src/components/__legacy__/__tests__/ProfileInfoForm.test.tsx
rename to autogpt_platform/frontend/src/components/contextual/ProfileInfoForm/__tests__/ProfileInfoForm.test.tsx
index 49b0a3a37e..6de5ab664f 100644
--- a/autogpt_platform/frontend/src/components/__legacy__/__tests__/ProfileInfoForm.test.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/ProfileInfoForm/__tests__/ProfileInfoForm.test.tsx
@@ -154,4 +154,84 @@ describe("ProfileInfoForm", () => {
});
expect(uploadSpy).not.toHaveBeenCalled();
});
+
+ it.each(["button", "form"])(
+ "submits once through %s and keeps the pending state until the response",
+ async (trigger) => {
+ let calls = 0;
+ let finishSave: () => void = () => {};
+ const pending = new Promise<void>((resolve) => {
+ finishSave = resolve;
+ });
+ server.use(
+ getPostV2UpdateUserProfileMockHandler200(async ({ request }) => {
+ calls += 1;
+ const body = await request.json();
+ expect(body).toMatchObject({
+ name: "Updated name",
+ links: ["https://example.com"],
+ });
+ await pending;
+ return makeProfile({ name: "Updated name" });
+ }),
+ );
+ render(
+ <ProfileInfoForm
+ profile={makeProfile({ links: ["https://example.com", ""] })}
+ />,
+ );
+ fireEvent.change(screen.getByTestId("profile-info-form-display-name"), {
+ target: { value: "Updated name" },
+ });
+ try {
+ if (trigger === "button") {
+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
+ } else {
+ const form = screen
+ .getByRole("button", { name: "Save changes" })
+ .closest("form");
+ expect(form).not.toBeNull();
+ expect(fireEvent.submit(form!)).toBe(false);
+ }
+ await waitFor(() => {
+ expect(calls).toBe(1);
+ expect(
+ screen
+ .getByRole("button", { name: "Saving..." })
+ .hasAttribute("disabled"),
+ ).toBe(true);
+ });
+ } finally {
+ finishSave();
+ }
+ await waitFor(() => {
+ const button = screen.getByRole("button", { name: "Save changes" });
+ expect(button.hasAttribute("disabled")).toBe(false);
+ });
+ expect(calls).toBe(1);
+ },
+ );
+
+ it("keeps the saved avatar and explains an upload failure", async () => {
+ toastSpy.mockClear();
+ uploadSpy.mockReset();
+ uploadSpy.mockRejectedValueOnce(new Error("Upload unavailable"));
+ const avatar = "https://storage.googleapis.com/media/avatar.png";
+ render(<ProfileInfoForm profile={makeProfile({ avatar_url: avatar })} />);
+ fireEvent.change(fileInput(), {
+ target: {
+ files: [new File(["image"], "avatar.png", { type: "image/png" })],
+ },
+ });
+ await waitFor(() =>
+ expect(toastSpy).toHaveBeenCalledWith({
+ title: "Failed to upload photo",
+ description: "Upload unavailable",
+ variant: "destructive",
+ }),
+ );
+ expect(
+ screen.getByRole("img", { name: "Profile" }).getAttribute("src"),
+ ).toBe(avatar);
+ });
});
diff --git a/autogpt_platform/frontend/src/components/contextual/ProfileInfoForm/useProfileInfoForm.ts b/autogpt_platform/frontend/src/components/contextual/ProfileInfoForm/useProfileInfoForm.ts
new file mode 100644
index 0000000000..72554a3b85
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/ProfileInfoForm/useProfileInfoForm.ts
@@ -0,0 +1,76 @@
+import { useState, type FormEvent } from "react";
+import { postV2UpdateUserProfile } from "@/app/api/__generated__/endpoints/store/store";
+import { resolveResponse } from "@/app/api/helpers";
+import type { ProfileDetails } from "@/app/api/__generated__/models/profileDetails";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import {
+ isFileTooLarge,
+ SUBMISSION_MEDIA_MAX_SIZE_MB,
+ uploadSubmissionMediaDirect,
+} from "@/lib/direct-upload";
+
+export function useProfileInfoForm(profile: ProfileDetails) {
+ const { toast } = useToast();
+ const [isSubmitting, setIsSubmitting] = useState(false);
+ const [profileData, setProfileData] = useState<ProfileDetails>(profile);
+
+ async function submitForm(event: FormEvent<HTMLFormElement>) {
+ event.preventDefault();
+ if (isSubmitting) return;
+ try {
+ setIsSubmitting(true);
+
+ const updatedProfile = {
+ name: profileData.name,
+ username: profileData.username,
+ description: profileData.description,
+ links: profileData.links.filter((link) => link), // Filter out empty links
+ avatar_url: profileData.avatar_url,
+ };
+
+ const returnedProfile = await resolveResponse(
+ postV2UpdateUserProfile(updatedProfile),
+ );
+ if (returnedProfile) setProfileData(returnedProfile);
+ } catch (error) {
+ console.error("Error updating profile:", error);
+ } finally {
+ setIsSubmitting(false);
+ }
+ }
+
+ async function handleImageUpload(file: File) {
+ if (
+ isFileTooLarge({ file, maxSizeMB: SUBMISSION_MEDIA_MAX_SIZE_MB, toast })
+ )
+ return;
+
+ try {
+ const mediaUrl = await uploadSubmissionMediaDirect(file);
+
+ const updatedProfile = {
+ ...profileData,
+ avatar_url: mediaUrl,
+ };
+
+ const returnedProfile = await resolveResponse(
+ postV2UpdateUserProfile(updatedProfile),
+ );
+ if (returnedProfile) setProfileData(returnedProfile);
+ } catch (error) {
+ toast({
+ title: "Failed to upload photo",
+ description: error instanceof Error ? error.message : undefined,
+ variant: "destructive",
+ });
+ }
+ }
+
+ return {
+ profileData,
+ setProfileData,
+ isSubmitting,
+ submitForm,
+ handleImageUpload,
+ };
+}
diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/ThumbnailImages.tsx b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/ThumbnailImages.tsx
index 044671d595..e9698d69ee 100644
--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/ThumbnailImages.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/ThumbnailImages.tsx
@@ -3,6 +3,7 @@
import { Button } from "@/components/atoms/Button/Button";
import { Text } from "@/components/atoms/Text/Text";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import { useThumbnailImages } from "./useThumbnailImages";
import { cn } from "@/lib/utils";
import {
@@ -125,6 +126,7 @@ export function ThumbnailImages({
>
<Image
src={src}
+ unoptimized={isLocalStoreMediaUrl(src)}
alt={`Thumbnail ${index + 1}`}
fill
style={{ objectFit: "cover" }}
diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/__tests__/ThumbnailImages.local-media.test.tsx b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/__tests__/ThumbnailImages.local-media.test.tsx
new file mode 100644
index 0000000000..9924cbb84c
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/AgentInfoStep/components/__tests__/ThumbnailImages.local-media.test.tsx
@@ -0,0 +1,75 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+import { ThumbnailImages } from "../ThumbnailImages";
+
+vi.mock("next/image", async () => {
+ return vi.importActual<typeof import("next/image")>("next/image");
+});
+
+const uploadSpy = vi.hoisted(() => vi.fn());
+vi.mock("@/lib/direct-upload", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@/lib/direct-upload")>();
+ return { ...actual, uploadSubmissionMediaDirect: uploadSpy };
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe("local marketplace image previews", () => {
+ it.each([
+ "http://localhost:8006/api/store/media/user-1/images/thumbnail.png",
+ "https://appliance.example/_agpt/api/store/media/user-1/images/thumbnail.png",
+ ])("shows the uploaded image directly from %s", async (url) => {
+ vi.stubEnv("NEXT_PUBLIC_AGPT_SERVER_URL", url.split("/store/media/")[0]);
+ uploadSpy.mockResolvedValueOnce(url);
+ const onImagesChange = vi.fn();
+ render(
+ <ThumbnailImages agentId="agent-1" onImagesChange={onImagesChange} />,
+ );
+
+ const input = document.getElementById("image-upload") as HTMLInputElement;
+ fireEvent.change(input, {
+ target: {
+ files: [new File(["image"], "thumbnail.png", { type: "image/png" })],
+ },
+ });
+
+ const image = await screen.findByRole("img", { name: "Thumbnail 1" });
+ expect(image.getAttribute("src")).toBe(url);
+ expect(image.hasAttribute("srcset")).toBe(false);
+ expect(onImagesChange).toHaveBeenCalledWith([url]);
+ });
+
+ it("keeps GCS thumbnails optimized", () => {
+ const url = "https://storage.googleapis.com/media/thumbnail.png";
+ render(
+ <ThumbnailImages
+ agentId="agent-1"
+ onImagesChange={() => {}}
+ initialImages={[url]}
+ />,
+ );
+
+ const image = screen.getByRole("img", { name: "Thumbnail 1" });
+ expect(image.getAttribute("src")).toMatch(/^\/_next\/image\?/);
+ expect(image.getAttribute("srcset")).toContain("/_next/image?");
+ });
+
+ it("does not bypass the optimizer for an external host using the media path", () => {
+ vi.stubEnv("NEXT_PUBLIC_AGPT_SERVER_URL", "http://localhost:8006/api");
+ render(
+ <ThumbnailImages
+ agentId="agent-1"
+ onImagesChange={() => {}}
+ initialImages={[
+ "https://untrusted.example/api/store/media/user-1/images/thumbnail.png",
+ ]}
+ />,
+ );
+
+ const image = screen.getByRole("img", { name: "Thumbnail 1" });
+ expect(image.getAttribute("src")).toMatch(/^\/_next\/image\?/);
+ expect(image.getAttribute("srcset")).toContain("/_next/image?");
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/SubmissionSummaryCard.tsx b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/SubmissionSummaryCard.tsx
index 109eb8a76d..c82b716d0c 100644
--- a/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/SubmissionSummaryCard.tsx
+++ b/autogpt_platform/frontend/src/components/contextual/PublishAgentModal/components/SubmissionSummaryCard.tsx
@@ -1,6 +1,7 @@
"use client";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import { motion } from "framer-motion";
import { Text } from "@/components/atoms/Text/Text";
import { Clock01Icon, ImageNotFound01Icon } from "@hugeicons/core-free-icons";
@@ -32,6 +33,7 @@ export function SubmissionSummaryCard({
{thumbnailSrc ? (
<Image
src={thumbnailSrc}
+ unoptimized={isLocalStoreMediaUrl(thumbnailSrc)}
alt=""
fill
sizes="86px"
diff --git a/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/components/WorkflowTile.tsx b/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/components/WorkflowTile.tsx
index 9b4f413fb6..244ed9b9fd 100644
--- a/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/components/WorkflowTile.tsx
+++ b/autogpt_platform/frontend/src/components/molecules/InstallWorkflowPicker/components/WorkflowTile.tsx
@@ -2,6 +2,7 @@
import { isRenderableImageUrl } from "@/lib/next-image";
import Image from "next/image";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
import { useState } from "react";
interface Props {
@@ -24,6 +25,7 @@ export function WorkflowTile({ imageUrl }: Props) {
return (
<Image
src={imageUrl}
+ unoptimized={isLocalStoreMediaUrl(imageUrl)}
alt=""
width={36}
height={36}
diff --git a/autogpt_platform/frontend/src/lib/__tests__/store-media-routing.test.ts b/autogpt_platform/frontend/src/lib/__tests__/store-media-routing.test.ts
new file mode 100644
index 0000000000..95f21b33e1
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/__tests__/store-media-routing.test.ts
@@ -0,0 +1,114 @@
+import { join } from "node:path";
+import type { NextConfig } from "next";
+import { NextRequest } from "next/server";
+import {
+ getRewrittenUrl,
+ unstable_getResponseFromNextConfig,
+} from "next/experimental/testing/server";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
+
+vi.mock("@sentry/nextjs", () => ({
+ withSentryConfig: (config: NextConfig) => config,
+}));
+vi.mock("@/lib/auth/server/getServerAuthToken", () => ({
+ getServerAuthToken: vi.fn().mockResolvedValue(null),
+}));
+vi.mock("@/services/environment", () => ({
+ environment: {
+ getAGPTServerBaseUrl: () => "http://internal-backend:8006",
+ },
+}));
+
+import { GET } from "@/app/api/proxy/[...path]/route";
+
+beforeEach(() => {
+ vi.stubEnv("NEXT_PUBLIC_AGPT_SERVER_URL", "http://localhost:8006/api");
+ vi.stubGlobal("fetch", vi.fn());
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+});
+
+it.each([
+ ["images/thumbnail.png", "image/png"],
+ ["videos/preview.webm", "video/webm"],
+])(
+ "serves backend-relative %s through the anonymous frontend proxy",
+ async (file, mime) => {
+ const { default: nextConfig } = await vi.importActual<{
+ default: NextConfig;
+ }>(join(process.cwd(), "next.config.mjs"));
+ const relativeURL = `/api/store/media/user-123/${file}`;
+ const browserURL = `http://localhost:3000${relativeURL}?v=2`;
+ const routing = await unstable_getResponseFromNextConfig({
+ url: browserURL,
+ nextConfig,
+ });
+ const proxyURL = getRewrittenUrl(routing);
+ expect(proxyURL).toBe(`http://localhost:3000/api/proxy${relativeURL}?v=2`);
+
+ const bytes = Uint8Array.from(
+ { length: 256 * 1024 },
+ (_, index) => index % 251,
+ );
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ for (let index = 0; index < bytes.length; index += 8191) {
+ controller.enqueue(bytes.slice(index, index + 8191));
+ }
+ controller.close();
+ },
+ });
+ vi.mocked(fetch).mockResolvedValue(
+ new Response(body, {
+ headers: { "content-type": mime, "x-content-type-options": "nosniff" },
+ }),
+ );
+ const response = await GET(new NextRequest(proxyURL!), {
+ params: Promise.resolve({
+ path: ["api", "store", "media", "user-123", ...file.split("/")],
+ }),
+ });
+ expect(fetch).toHaveBeenCalledWith(
+ `http://internal-backend:8006${relativeURL}?v=2`,
+ expect.anything(),
+ );
+ expect(
+ (vi.mocked(fetch).mock.calls[0][1]?.headers as Headers).has(
+ "authorization",
+ ),
+ ).toBe(false);
+ expect(response.headers.get("content-type")).toBe(mime);
+ expect(response.headers.get("x-content-type-options")).toBe("nosniff");
+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(bytes);
+
+ if (mime === "image/png") {
+ const { getImageProps } =
+ await vi.importActual<typeof import("next/image")>("next/image");
+ expect(isLocalStoreMediaUrl(relativeURL)).toBe(true);
+ const { props } = getImageProps({
+ src: relativeURL,
+ alt: "Thumbnail",
+ width: 320,
+ height: 180,
+ unoptimized: isLocalStoreMediaUrl(relativeURL),
+ });
+ expect(props.src).toBe(relativeURL);
+ expect(props.srcSet).toBeUndefined();
+ }
+ },
+);
+
+it("does not rewrite unrelated frontend API routes", async () => {
+ const { default: nextConfig } = await vi.importActual<{
+ default: NextConfig;
+ }>(join(process.cwd(), "next.config.mjs"));
+ const response = await unstable_getResponseFromNextConfig({
+ url: "http://localhost:3000/api/store/submissions",
+ nextConfig,
+ });
+ expect(getRewrittenUrl(response)).toBeNull();
+});
diff --git a/autogpt_platform/frontend/src/lib/__tests__/store-media.test.ts b/autogpt_platform/frontend/src/lib/__tests__/store-media.test.ts
new file mode 100644
index 0000000000..6724f5821c
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/__tests__/store-media.test.ts
@@ -0,0 +1,228 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { isLocalStoreMediaUrl } from "@/lib/store-media";
+import { isRenderableImageUrl } from "@/lib/next-image";
+
+const mediaPath = "/store/media/user-123/images/thumbnail.png";
+const defaultImageURLs = [
+ `http://localhost:8006/api${mediaPath}`,
+ `http://localhost:8006/api${mediaPath}?version=2#preview`,
+ "http://localhost:8006/api/store/media/user.name_1-2/images/preview.v2_1-thumb.webp",
+ `/api${mediaPath}`,
+ `http://localhost:3000/api${mediaPath}`,
+ `/api/proxy/api${mediaPath}`,
+ `http://localhost:3000/api/proxy/api${mediaPath}`,
+];
+
+beforeEach(() => {
+ vi.stubEnv("NEXT_PUBLIC_AGPT_SERVER_URL", undefined);
+ vi.stubEnv("BETTER_AUTH_URL", undefined);
+ vi.stubEnv("NEXT_PUBLIC_FRONTEND_BASE_URL", undefined);
+ vi.stubEnv("AGPT_SERVER_URL", "http://internal-backend:8006/api");
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+});
+
+describe("configured local store media", () => {
+ it.each(defaultImageURLs)(
+ "recognizes the default backend or proxy: %s",
+ (src) => {
+ expect(isLocalStoreMediaUrl(src)).toBe(true);
+ expect(isRenderableImageUrl(src)).toBe(true);
+ },
+ );
+
+ it.each([
+ `https://unknown.example/api${mediaPath}`,
+ `http://localhost:8007/api${mediaPath}`,
+ `http://localhost:8006/wrong/api${mediaPath}`,
+ `http://internal-backend:8006/api${mediaPath}`,
+ `https://unknown.example/api/proxy/api${mediaPath}`,
+ `http://localhost:8006/api/proxy/api${mediaPath}`,
+ `/unrelated/api/proxy/api${mediaPath}`,
+ `//localhost:8006/api${mediaPath}`,
+ `http://user@localhost:8006/api${mediaPath}`,
+ `http://:test@localhost:8006/api${mediaPath}`,
+ ])("rejects an unconfigured origin or prefix: %s", (src) => {
+ expect(isLocalStoreMediaUrl(src)).toBe(false);
+ });
+
+ it.each(["browser", "SSR"])(
+ "uses the public absolute API URL in %s",
+ (mode) => {
+ vi.stubEnv(
+ "NEXT_PUBLIC_AGPT_SERVER_URL",
+ "https://media.appliance.example/team/backend/api",
+ );
+ if (mode === "SSR") vi.stubGlobal("window", undefined);
+
+ expect(
+ isLocalStoreMediaUrl(
+ `https://media.appliance.example/team/backend/api${mediaPath}`,
+ ),
+ ).toBe(true);
+ expect(
+ isLocalStoreMediaUrl(`https://media.appliance.example/api${mediaPath}`),
+ ).toBe(false);
+ expect(
+ isLocalStoreMediaUrl(
+ `https://other.example/team/backend/api${mediaPath}`,
+ ),
+ ).toBe(false);
+ expect(isLocalStoreMediaUrl(`/team/backend/api${mediaPath}`)).toBe(false);
+ },
+ );
+
+ it("resolves an appliance API prefix against the browser origin", () => {
+ vi.stubEnv("NEXT_PUBLIC_AGPT_SERVER_URL", "/_agpt/api");
+ vi.stubEnv("BETTER_AUTH_URL", "https://wrong.example");
+ vi.stubGlobal("window", {
+ location: { origin: "https://appliance.example" },
+ });
+
+ expect(isLocalStoreMediaUrl(`/_agpt/api${mediaPath}`)).toBe(true);
+ expect(
+ isLocalStoreMediaUrl(`https://appliance.example/_agpt/api${mediaPath}`),
+ ).toBe(true);
+ expect(
+ isLocalStoreMediaUrl(`https://wrong.example/_agpt/api${mediaPath}`),
+ ).toBe(false);
+ expect(isLocalStoreMediaUrl(`/api${mediaPath}`)).toBe(true);
+ expect(
+ isLocalStoreMediaUrl(
+ `https://appliance.example/api/proxy/api${mediaPath}`,
+ ),
+ ).toBe(true);
+ });
+
+ it.each(["BETTER_AUTH_URL", "NEXT_PUBLIC_FRONTEND_BASE_URL"])(
+ "resolves the appliance API prefix using %s during SSR",
+ (frontendEnv) => {
+ vi.stubGlobal("window", undefined);
+ vi.stubEnv("NEXT_PUBLIC_AGPT_SERVER_URL", "/_agpt/api");
+ vi.stubEnv(frontendEnv, "https://appliance.example");
+ if (frontendEnv === "BETTER_AUTH_URL") {
+ vi.stubEnv("NEXT_PUBLIC_FRONTEND_BASE_URL", "https://wrong.example");
+ }
+
+ expect(isLocalStoreMediaUrl(`/_agpt/api${mediaPath}`)).toBe(true);
+ expect(
+ isLocalStoreMediaUrl(`https://appliance.example/_agpt/api${mediaPath}`),
+ ).toBe(true);
+ expect(
+ isLocalStoreMediaUrl(`https://wrong.example/_agpt/api${mediaPath}`),
+ ).toBe(false);
+ expect(isLocalStoreMediaUrl(`/api${mediaPath}`)).toBe(true);
+ expect(isLocalStoreMediaUrl(`/api/proxy/api${mediaPath}`)).toBe(true);
+ expect(
+ isLocalStoreMediaUrl(
+ `https://appliance.example/api/proxy/api${mediaPath}`,
+ ),
+ ).toBe(true);
+ },
+ );
+
+ it("uses the default frontend origin during SSR", () => {
+ vi.stubGlobal("window", undefined);
+ vi.stubEnv("NEXT_PUBLIC_AGPT_SERVER_URL", "/_agpt/api");
+
+ expect(
+ isLocalStoreMediaUrl(`http://localhost:3000/_agpt/api${mediaPath}`),
+ ).toBe(true);
+ expect(
+ isLocalStoreMediaUrl(`http://localhost:3001/_agpt/api${mediaPath}`),
+ ).toBe(false);
+ });
+});
+
+describe("malformed and ordinary URLs", () => {
+ beforeEach(() => vi.stubEnv("NEXT_PUBLIC_AGPT_SERVER_URL", "/api"));
+
+ it.each([
+ null,
+ undefined,
+ "",
+ "not a URL",
+ "/images/thumbnail.png",
+ "https://cdn.example.com/images/thumbnail.png",
+ "/api/store/media/user-123/videos/preview.mp4",
+ "/api/store/media/user-123/images/thumbnail.png/extra",
+ "/api/store/media/user-123/images/thumbnail.png/",
+ "/api/store/media/user-123/images/",
+ "/api/store/media//images/thumbnail.png",
+ "/api/store/media/user 123/images/thumbnail.png",
+ "/api/store/media/user%20123/images/thumbnail.png",
+ "/api/store/media/user-123/images/thumbnail%20image.png",
+ "/api/store/media/user-123/images/[email protected]",
+ "/api/store/media/./images/thumbnail.png",
+ "/api/store/media/../images/thumbnail.png",
+ "/api/store/media/user-123/images/.",
+ "/api/store/media/user-123/images/..",
+ "/api/store/media/user-123/images/%2e%2e",
+ "/api/store/media/user-123/images/%2Fthumbnail.png",
+ "/api/store/media/user-123/images/nested/../thumbnail.png",
+ "http://localhost:3000/api/store/media/user-123/images/nested/../thumbnail.png",
+ "http://localhost:3000/api/store/media/user-123/images/%2e%2e/images/thumbnail.png",
+ "/api/store/media/user-123/images/thumbnail\\image.png",
+ "api/store/media/user-123/images/thumbnail.png",
+ "//localhost:3000/api/store/media/user-123/images/thumbnail.png",
+ "ftp://localhost:3000/api/store/media/user-123/images/thumbnail.png",
+ "file:///api/store/media/user-123/images/thumbnail.png",
+ "javascript:/api/store/media/user-123/images/thumbnail.png",
+ "data:image/png;base64,abc",
+ "blob:http://localhost:3000/api/store/media/user-123/images/thumbnail.png",
+ `https://cdn.example.com/image.png?src=/api${mediaPath}`,
+ ])("rejects %s", (src) => {
+ expect(isLocalStoreMediaUrl(src)).toBe(false);
+ });
+});
+
+describe("local store images with Next.js", () => {
+ it.each(defaultImageURLs)("loads %s directly without srcSet", async (src) => {
+ const { getImageProps } =
+ await vi.importActual<typeof import("next/image")>("next/image");
+ const { props } = getImageProps({
+ src,
+ alt: "Agent thumbnail",
+ width: 320,
+ height: 180,
+ unoptimized: isLocalStoreMediaUrl(src),
+ });
+
+ expect(props.src).toBe(src);
+ expect(props.srcSet).toBeUndefined();
+ });
+
+ it.each([
+ "https://storage.googleapis.com/agent-uploads/user-123/images/thumbnail.png",
+ `https://storage.googleapis.com/api${mediaPath}`,
+ "/images/thumbnail.png",
+ ])("keeps ordinary and GCS images optimized: %s", async (src) => {
+ const { getImageProps } =
+ await vi.importActual<typeof import("next/image")>("next/image");
+ const { props } = getImageProps({
+ src,
+ alt: "Agent thumbnail",
+ width: 320,
+ height: 180,
+ unoptimized: isLocalStoreMediaUrl(src),
+ });
+
+ expect(props.src).toMatch(/^\/_next\/image\?/);
+ expect(new URL(props.src, "http://localhost").searchParams.get("url")).toBe(
+ src,
+ );
+ expect(props.srcSet).toContain("/_next/image?");
+ });
+
+ it("keeps unconfigured URLs outside the render gate", () => {
+ expect(isRenderableImageUrl("https://unknown.example/thumbnail.png")).toBe(
+ false,
+ );
+ expect(
+ isRenderableImageUrl(`https://unknown.example/api${mediaPath}`),
+ ).toBe(false);
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/next-image.ts b/autogpt_platform/frontend/src/lib/next-image.ts
index 05ecef988d..ecd634a422 100644
--- a/autogpt_platform/frontend/src/lib/next-image.ts
+++ b/autogpt_platform/frontend/src/lib/next-image.ts
@@ -1,3 +1,5 @@
+import { isLocalStoreMediaUrl } from "./store-media";
+
/** The hosts `next.config.mjs` lets `next/image` load from.
*
* `next/image` throws while rendering — it never reaches `onError` — when
@@ -20,6 +22,7 @@ export function isRenderableImageUrl(
url: string | null | undefined,
): url is string {
if (!url) return false;
+ if (isLocalStoreMediaUrl(url)) return true;
if (url.startsWith("/")) return true;
try {
return ALLOWED_IMAGE_HOSTS.includes(new URL(url).hostname);
diff --git a/autogpt_platform/frontend/src/lib/store-media.ts b/autogpt_platform/frontend/src/lib/store-media.ts
new file mode 100644
index 0000000000..421e2e94f1
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/store-media.ts
@@ -0,0 +1,54 @@
+const LOCAL_STORE_IMAGE_PATH =
+ /\/api\/store\/media\/(?!\.{1,2}\/)[A-Za-z0-9_.-]+\/images\/(?!\.{1,2}$)[A-Za-z0-9_.-]+$/;
+
+export function isLocalStoreMediaUrl(src: string | null | undefined): boolean {
+ if (!src || src.startsWith("//")) return false;
+
+ const match = /^(?:https?:\/\/[^/?#]+)?(\/[^?#]*)(?:[?#].*)?$/i.exec(src);
+ if (!match) return false;
+
+ try {
+ const frontendURL = new URL(getFrontendOrigin());
+ const url = new URL(src, frontendURL);
+ if (
+ url.username ||
+ url.password ||
+ url.pathname !== match[1] ||
+ !LOCAL_STORE_IMAGE_PATH.test(url.pathname)
+ ) {
+ return false;
+ }
+
+ const apiPath = url.pathname.slice(
+ 0,
+ url.pathname.lastIndexOf("/store/media/"),
+ );
+ if (
+ url.origin === frontendURL.origin &&
+ (apiPath === "/api" || apiPath === "/api/proxy/api")
+ ) {
+ return true;
+ }
+
+ const backendURL = new URL(
+ process.env.NEXT_PUBLIC_AGPT_SERVER_URL || "http://localhost:8006/api",
+ frontendURL,
+ );
+ return (
+ url.origin === backendURL.origin &&
+ apiPath === backendURL.pathname.replace(/\/$/, "")
+ );
+ } catch {
+ return false;
+ }
+}
+
+function getFrontendOrigin(): string {
+ if (typeof window !== "undefined") return window.location.origin;
+
+ return (
+ process.env.BETTER_AUTH_URL ||
+ process.env.NEXT_PUBLIC_FRONTEND_BASE_URL ||
+ "http://localhost:3000"
+ );
+}
diff --git a/autogpt_platform/single-container/entrypoint.sh b/autogpt_platform/single-container/entrypoint.sh
index 5137a7ec4a..c4563aa76e 100755
--- a/autogpt_platform/single-container/entrypoint.sh
+++ b/autogpt_platform/single-container/entrypoint.sh
@@ -40,7 +40,7 @@ prepare_directories() {
for managed_path in \
/data/config /data/postgres /data/rabbitmq /data/valkey \
/data/valkey/17000 /data/valkey/17001 /data/valkey/17002 /data/falkordb \
- /data/workspaces /data/home /data/frontend-home \
+ /data/workspaces /data/store-media /data/home /data/frontend-home \
/data/cache /data/cache/backend /data/cache/next \
"${CODEX_TEMP_ROOT}"; do
[[ ! -L "${managed_path}" ]] || fatal "refusing symlink at managed data path: ${managed_path}"
@@ -54,6 +54,7 @@ prepare_directories() {
install -d -m 0750 -o autogpt-valkey -g autogpt-valkey /data/valkey/17002
install -d -m 0750 -o autogpt-falkor -g autogpt-falkor /data/falkordb
install -d -m 0750 -o autogpt -g autogpt /data/workspaces
+ install -d -m 0750 -o autogpt -g autogpt /data/store-media
install -d -m 0750 -o autogpt -g autogpt /data/home
install -d -m 0700 -o autogpt_frontend -g autogpt_frontend /data/frontend-home
install -d -m 0711 -o root -g root /data/cache
diff --git a/autogpt_platform/single-container/tests/test_documented_operations.py b/autogpt_platform/single-container/tests/test_documented_operations.py
index 4be730b6ba..630aacd0d1 100644
--- a/autogpt_platform/single-container/tests/test_documented_operations.py
+++ b/autogpt_platform/single-container/tests/test_documented_operations.py
@@ -181,6 +181,7 @@ class DocumentedOperationsTest(unittest.TestCase):
self.assertNotIn("cache", archived_paths)
self.assertIn("config", archived_paths)
self.assertIn("workspaces", archived_paths)
+ self.assertIn("store-media", archived_paths)
restore = self._run(
RESTORE_BLOCK,
@@ -223,6 +224,12 @@ class DocumentedOperationsTest(unittest.TestCase):
(restored_data / "workspaces" / "example.txt").read_text(encoding="utf-8"),
"durable workspace\n",
)
+ self.assertEqual(
+ (restored_data / "store-media/users/example/images/example.png").read_text(
+ encoding="utf-8"
+ ),
+ "durable marketplace media\n",
+ )
validation = self._run(
STRUCTURAL_VALIDATION_BLOCK,
@@ -816,6 +823,7 @@ class DocumentedOperationsTest(unittest.TestCase):
"postgres/postgresql.conf": POSTGRESQL_CONF,
"postgres/pg_hba.conf": PG_HBA_CONF,
"workspaces/example.txt": "durable workspace\n",
+ "store-media/users/example/images/example.png": "durable marketplace media\n",
"cache/regenerable.txt": "do not archive\n",
}
for relative_path, content in files.items():
diff --git a/autogpt_platform/single-container/tests/test_entrypoint.py b/autogpt_platform/single-container/tests/test_entrypoint.py
index 79747b4308..a125d3c4d5 100644
--- a/autogpt_platform/single-container/tests/test_entrypoint.py
+++ b/autogpt_platform/single-container/tests/test_entrypoint.py
@@ -19,6 +19,31 @@ BACKEND_SERVICE_PATH = ASSET_DIR.parent / "backend" / "backend" / "util" / "serv
class InternalServiceTopologyTest(unittest.TestCase):
+ def test_prepares_marketplace_media_for_unprivileged_backend(self) -> None:
+ result = subprocess.run(
+ [
+ "bash",
+ "-Eeuo",
+ "pipefail",
+ "-c",
+ 'source "$1"; install() { printf "%s\\n" "$*"; }; prepare_directories',
+ "bash",
+ str(ENTRYPOINT_PATH),
+ ],
+ check=False,
+ capture_output=True,
+ encoding="utf-8",
+ env={
+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"),
+ "AUTOGPT_ASSET_DIR": str(ASSET_DIR),
+ },
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn(
+ "-d -m 0750 -o autogpt -g autogpt /data/store-media",
+ result.stdout.splitlines(),
+ )
+
def test_rpc_health_path_matches_backend(self) -> None:
module = ast.parse(BACKEND_SERVICE_PATH.read_text(encoding="utf-8"))
route_paths = {
diff --git a/docs/platform/single-container.md b/docs/platform/single-container.md
index 8bb96cec15..171c09faf9 100644
--- a/docs/platform/single-container.md
+++ b/docs/platform/single-container.md
@@ -562,6 +562,7 @@ The named volume mounted at `/data` contains all durable appliance state:
| `/data/valkey` | Three-node Valkey state |
| `/data/falkordb` | Graphiti memory data |
| `/data/workspaces` | User workspaces |
+| `/data/store-media` | Marketplace images and videos when GCS is not configured |
| `/data/home` and `/data/frontend-home` | Application home directories |
| `/data/cache` | Regenerable backend and Next.js caches (excluded from backups) |
@@ -944,6 +945,7 @@ same `RESTORE_IMAGE`:
test -d /data/valkey/17002
test -d /data/falkordb
test -d /data/workspaces
+ test -d /data/store-media
test -d /data/home
test -d /data/frontend-home
quote="$(printf "\047")"