AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): optimized file preview endpoint + rich artifact cards (#13281)
Abhimanyu Yadavadcfae9b153d
diff --git a/autogpt_platform/backend/backend/api/features/workspace/preview.py b/autogpt_platform/backend/backend/api/features/workspace/preview.pynew file mode 100644index 0000000000..2895d94bc6--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/workspace/preview.py@@ -0,0 +1,255 @@+"""+Preview generation for workspace files.++Produces small, cheap previews for the Artifacts page instead of shipping the+whole file to the browser:++* raster images -> resized WebP thumbnail (Pillow)+* PDFs -> first page rasterised to WebP (pypdfium2)+* Office openxml docs -> embedded ``docProps/thumbnail`` re-encoded to WebP+* text-like files -> first N bytes (partial read, no full download)++Image/PDF/Office thumbnails are cached in Redis keyed by file checksum so+repeat views and re-renders are free. All CPU-bound work runs in a thread so+the event loop is never blocked.+"""++import asyncio+import base64+import io+import logging+import zipfile+from typing import Awaitable, Callable, Optional++import fastapi+import pypdfium2+from fastapi.responses import Response+from PIL import Image++from backend.data.redis_client import get_redis_async+from backend.data.workspace import WorkspaceFile+from backend.util.workspace_storage import get_workspace_storage++logger = logging.getLogger(__name__)++PREVIEW_CACHE_TTL = 86_400 # 1 day+WEBP_QUALITY = 80+MAX_IMAGE_PIXELS = 50_000_000 # decompression-bomb guard (~50 MP)+CACHE_HEADERS = {"Cache-Control": "private, max-age=86400"}++# Per-kind size ceilings. The frontend mirrors these exactly so it never+# requests a preview for a file this big (it shows an illustration instead);+# these server-side checks are defence-in-depth against direct calls.+PREVIEW_MAX_IMAGE_BYTES = 10_000_000+PREVIEW_MAX_DOC_BYTES = 50_000_000+PREVIEW_MAX_TEXT_BYTES = 50_000_000++OFFICE_MIMES = frozenset(+ {+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ }+)+_TEXT_HINTS = (+ "json",+ "xml",+ "csv",+ "yaml",+ "javascript",+ "typescript",+ "markdown",+ "svg",+)+_EMBEDDED_THUMBNAILS = (+ "docprops/thumbnail.jpeg",+ "docprops/thumbnail.jpg",+ "docprops/thumbnail.png",+)+++async def build_preview_response(+ file: WorkspaceFile, *, width: int, max_bytes: int+) -> Response:+ """Dispatch on MIME type and return the smallest useful preview."""+ try:+ return await _dispatch_preview(file, width=width, max_bytes=max_bytes)+ except FileNotFoundError as e:+ # File row exists but its bytes are gone from storage.+ raise fastapi.HTTPException(status_code=404, detail="File not found") from e+++async def _dispatch_preview(+ file: WorkspaceFile, *, width: int, max_bytes: int+) -> Response:+ mime = (file.mime_type or "").lower()++ if mime.startswith("image/") and "svg" not in mime:+ _ensure_size(file, PREVIEW_MAX_IMAGE_BYTES)+ return _webp_response(await _image_thumbnail(file, width))+ if mime == "application/pdf":+ _ensure_size(file, PREVIEW_MAX_DOC_BYTES)+ return _webp_response(await _pdf_thumbnail(file, width))+ if mime in OFFICE_MIMES:+ _ensure_size(file, PREVIEW_MAX_DOC_BYTES)+ return _webp_response(await _office_thumbnail(file, width))+ if _is_text_like(mime):+ _ensure_size(file, PREVIEW_MAX_TEXT_BYTES)+ content = await _text_preview(file, max_bytes)+ return Response(+ content=content,+ media_type=file.mime_type or "text/plain",+ headers=CACHE_HEADERS,+ )++ raise fastapi.HTTPException(+ status_code=415, detail="Preview not available for this file type"+ )+++def _is_text_like(mime: str) -> bool:+ return mime.startswith("text/") or any(hint in mime for hint in _TEXT_HINTS)+++def _ensure_size(file: WorkspaceFile, limit: int) -> None:+ if file.size_bytes > limit:+ raise fastapi.HTTPException(status_code=413, detail="File too large to preview")+++def _webp_response(content: bytes) -> Response:+ return Response(content=content, media_type="image/webp", headers=CACHE_HEADERS)+++# ---------------------------------------------------------------------------+# Renderers (cached)+# ---------------------------------------------------------------------------+++async def _image_thumbnail(file: WorkspaceFile, width: int) -> bytes:+ async def render() -> bytes:+ content = await _retrieve(file)+ return await _to_thread_webp(_resize_webp, content, width)++ return await _cached(file, "img", width, render)+++async def _pdf_thumbnail(file: WorkspaceFile, width: int) -> bytes:+ async def render() -> bytes:+ content = await _retrieve(file)+ return await _to_thread_webp(_pdfium_first_page, content, width)++ return await _cached(file, "pdf", width, render)+++async def _office_thumbnail(file: WorkspaceFile, width: int) -> bytes:+ async def render() -> bytes:+ content = await _retrieve(file)+ try:+ raw = await asyncio.to_thread(_extract_zip_thumbnail, content)+ except Exception as e:+ raise fastapi.HTTPException(+ status_code=415, detail="Cannot render preview"+ ) from e+ if raw is None:+ raise fastapi.HTTPException(status_code=415, detail="No embedded thumbnail")+ return await _to_thread_webp(_resize_webp, raw, width)++ return await _cached(file, "office", width, render)+++async def _text_preview(file: WorkspaceFile, max_bytes: int) -> bytes:+ storage = await get_workspace_storage()+ return await storage.retrieve_partial(file.storage_path, max_bytes)+++async def _retrieve(file: WorkspaceFile) -> bytes:+ storage = await get_workspace_storage()+ return await storage.retrieve(file.storage_path)+++async def _to_thread_webp(fn: Callable[..., bytes], *args) -> bytes:+ """Run a sync renderer in a thread, mapping any failure to a 415."""+ try:+ return await asyncio.to_thread(fn, *args)+ except fastapi.HTTPException:+ raise+ except Exception as e:+ raise fastapi.HTTPException(+ status_code=415, detail="Cannot render preview"+ ) from e+++async def _cached(+ file: WorkspaceFile,+ kind: str,+ width: int,+ render: Callable[[], Awaitable[bytes]],+) -> bytes:+ key = f"wsfile:preview:{file.id}:{kind}:{width}:{(file.checksum or '')[:12]}"+ redis = None+ try:+ redis = await get_redis_async()+ cached = await redis.get(key)+ if cached:+ return base64.b64decode(cached)+ except Exception as e:+ logger.warning(f"Preview cache read failed for {file.id}: {e}")++ content = await render()++ if redis is not None:+ try:+ await redis.set(+ key, base64.b64encode(content).decode(), ex=PREVIEW_CACHE_TTL+ )+ except Exception as e:+ logger.warning(f"Preview cache write failed for {file.id}: {e}")+ return content+++# ---------------------------------------------------------------------------+# Sync helpers (run in a thread)+# ---------------------------------------------------------------------------+++def _resize_webp(content: bytes, width: int) -> bytes:+ Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS+ with Image.open(io.BytesIO(content)) as img:+ # Image.open positions at the first frame, so animated GIFs/WebP already+ # render their frame 0 without an explicit seek.+ if img.mode not in ("RGB", "RGBA", "L"):+ img = img.convert("RGB")+ img.thumbnail((width, width * 4), Image.Resampling.LANCZOS)+ out = io.BytesIO()+ img.save(out, format="WEBP", quality=WEBP_QUALITY, method=4)+ return out.getvalue()+++def _pdfium_first_page(content: bytes, width: int) -> bytes:+ pdf = pypdfium2.PdfDocument(content)+ try:+ page = pdf[0]+ page_width = page.get_width() or width+ # Integer render scale (pypdfium2's scale defaults to int); PIL downscales+ # to the exact target width afterwards.+ scale = max(1, min(3, round(width / page_width)))+ bitmap = page.render(scale=scale)+ image = bitmap.to_pil()+ out = io.BytesIO()+ if image.mode not in ("RGB", "L"):+ image = image.convert("RGB")+ image.thumbnail((width, width * 4), Image.Resampling.LANCZOS)+ image.save(out, format="WEBP", quality=WEBP_QUALITY, method=4)+ return out.getvalue()+ finally:+ pdf.close()+++def _extract_zip_thumbnail(content: bytes) -> Optional[bytes]:+ """Return the embedded ``docProps/thumbnail.*`` image from an openxml file."""+ with zipfile.ZipFile(io.BytesIO(content)) as archive:+ names = {name.lower(): name for name in archive.namelist()}+ for candidate in _EMBEDDED_THUMBNAILS:+ if candidate in names:+ return archive.read(names[candidate])+ return Nonediff --git a/autogpt_platform/backend/backend/api/features/workspace/preview_test.py b/autogpt_platform/backend/backend/api/features/workspace/preview_test.pynew file mode 100644index 0000000000..4a8584d0ee--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/workspace/preview_test.py@@ -0,0 +1,252 @@+import base64+import io+import zipfile+from datetime import datetime, timezone+from unittest.mock import AsyncMock++import fastapi+import fastapi.testclient+import pytest+from fpdf import FPDF+from PIL import Image++from backend.api.features.workspace.routes import router+from backend.data.workspace import Workspace, WorkspaceFile++app = fastapi.FastAPI()+app.include_router(router)+client = fastapi.testclient.TestClient(app)++PPTX_MIME = "application/vnd.openxmlformats-officedocument.presentationml.presentation"++[email protected](autouse=True)+def setup_app_auth(mock_jwt_user):+ from autogpt_libs.auth.jwt_utils import get_jwt_payload++ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]+ yield+ app.dependency_overrides.clear()+++def _make_workspace() -> Workspace:+ return Workspace(+ id="ws-001",+ user_id="test-user-id",+ created_at=datetime(2026, 1, 1, tzinfo=timezone.utc),+ updated_at=datetime(2026, 1, 1, tzinfo=timezone.utc),+ )+++def _make_file(**overrides) -> WorkspaceFile:+ defaults = {+ "id": "file-001",+ "workspace_id": "ws-001",+ "created_at": datetime(2026, 1, 1, tzinfo=timezone.utc),+ "updated_at": datetime(2026, 1, 1, tzinfo=timezone.utc),+ "name": "test.bin",+ "path": "/test.bin",+ "storage_path": "local://test.bin",+ "mime_type": "application/octet-stream",+ "size_bytes": 100,+ "checksum": "abc123",+ "is_deleted": False,+ "deleted_at": None,+ "metadata": {},+ }+ defaults.update(overrides)+ return WorkspaceFile(**defaults)+++def _png_bytes(width: int = 200, height: int = 200) -> bytes:+ out = io.BytesIO()+ Image.new("RGB", (width, height), (10, 20, 30)).save(out, format="PNG")+ return out.getvalue()+++def _pdf_bytes() -> bytes:+ pdf = FPDF()+ pdf.add_page()+ pdf.set_font("helvetica", size=24)+ pdf.cell(40, 10, "Hello preview")+ return bytes(pdf.output())+++def _zip_bytes(*, with_thumbnail: bool) -> bytes:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as archive:+ if with_thumbnail:+ archive.writestr("docProps/thumbnail.png", _png_bytes(120, 90))+ archive.writestr("ppt/presentation.xml", "<p/>")+ return buf.getvalue()+++def _mock_lookups(mocker, file: WorkspaceFile) -> None:+ mocker.patch(+ "backend.api.features.workspace.routes.get_workspace",+ AsyncMock(return_value=_make_workspace()),+ )+ mocker.patch(+ "backend.api.features.workspace.routes.get_workspace_file",+ AsyncMock(return_value=file),+ )+++def _mock_storage(mocker, content: bytes):+ storage = mocker.MagicMock()+ storage.retrieve = AsyncMock(return_value=content)+ storage.retrieve_partial = AsyncMock(side_effect=lambda _path, n: content[:n])+ mocker.patch(+ "backend.api.features.workspace.preview.get_workspace_storage",+ AsyncMock(return_value=storage),+ )+ return storage+++def _mock_redis(mocker, *, cached: bytes | None = None):+ redis = mocker.MagicMock()+ redis.get = AsyncMock(+ return_value=base64.b64encode(cached).decode() if cached else None+ )+ redis.set = AsyncMock(return_value=None)+ mocker.patch(+ "backend.api.features.workspace.preview.get_redis_async",+ AsyncMock(return_value=redis),+ )+ return redis+++def test_image_preview_returns_smaller_webp(mocker):+ png = _png_bytes(800, 600)+ _mock_lookups(mocker, _make_file(mime_type="image/png"))+ _mock_storage(mocker, png)+ _mock_redis(mocker)++ response = client.get("/files/file-001/preview?w=100")++ assert response.status_code == 200+ assert response.headers["content-type"] == "image/webp"+ assert response.headers["cache-control"] == "private, max-age=86400"+ assert 0 < len(response.content) < len(png)+++def test_pdf_preview_returns_webp(mocker):+ _mock_lookups(mocker, _make_file(mime_type="application/pdf"))+ _mock_storage(mocker, _pdf_bytes())+ _mock_redis(mocker)++ response = client.get("/files/file-001/preview?w=200")++ assert response.status_code == 200+ assert response.headers["content-type"] == "image/webp"+ assert response.content[:4] == b"RIFF"+++def test_office_preview_extracts_embedded_thumbnail(mocker):+ _mock_lookups(mocker, _make_file(mime_type=PPTX_MIME))+ _mock_storage(mocker, _zip_bytes(with_thumbnail=True))+ _mock_redis(mocker)++ response = client.get("/files/file-001/preview")++ assert response.status_code == 200+ assert response.headers["content-type"] == "image/webp"+++def test_office_preview_without_thumbnail_returns_415(mocker):+ _mock_lookups(mocker, _make_file(mime_type=PPTX_MIME))+ _mock_storage(mocker, _zip_bytes(with_thumbnail=False))+ _mock_redis(mocker)++ response = client.get("/files/file-001/preview")++ assert response.status_code == 415+++def test_office_preview_corrupt_zip_returns_415(mocker):+ _mock_lookups(mocker, _make_file(mime_type=PPTX_MIME))+ _mock_storage(mocker, b"not-a-zip-file")+ _mock_redis(mocker)++ response = client.get("/files/file-001/preview")++ assert response.status_code == 415+ assert response.json()["detail"] == "Cannot render preview"+++def test_preview_404_when_bytes_missing_from_storage(mocker):+ _mock_lookups(mocker, _make_file(mime_type="text/plain"))+ storage = mocker.MagicMock()+ storage.retrieve_partial = AsyncMock(side_effect=FileNotFoundError("gone"))+ storage.retrieve = AsyncMock(side_effect=FileNotFoundError("gone"))+ mocker.patch(+ "backend.api.features.workspace.preview.get_workspace_storage",+ AsyncMock(return_value=storage),+ )+ _mock_redis(mocker)++ response = client.get("/files/file-001/preview")++ assert response.status_code == 404+++def test_text_preview_caps_bytes(mocker):+ _mock_lookups(mocker, _make_file(mime_type="text/plain"))+ storage = _mock_storage(mocker, b"x" * 10_000)+ _mock_redis(mocker)++ response = client.get("/files/file-001/preview?bytes=512")++ assert response.status_code == 200+ assert len(response.content) == 512+ storage.retrieve_partial.assert_awaited_once_with("local://test.bin", 512)+++def test_preview_404_when_file_missing(mocker):+ mocker.patch(+ "backend.api.features.workspace.routes.get_workspace",+ AsyncMock(return_value=_make_workspace()),+ )+ mocker.patch(+ "backend.api.features.workspace.routes.get_workspace_file",+ AsyncMock(return_value=None),+ )++ response = client.get("/files/missing/preview")++ assert response.status_code == 404+++def test_preview_415_for_unsupported_type(mocker):+ _mock_lookups(mocker, _make_file(mime_type="application/octet-stream"))+ _mock_storage(mocker, b"\x00\x01\x02")+ _mock_redis(mocker)++ response = client.get("/files/file-001/preview")++ assert response.status_code == 415+++def test_preview_413_when_file_too_large(mocker):+ huge = _make_file(mime_type="image/png", size_bytes=20_000_000)+ _mock_lookups(mocker, huge)+ storage = _mock_storage(mocker, _png_bytes())+ _mock_redis(mocker)++ response = client.get("/files/file-001/preview?w=100")++ assert response.status_code == 413+ storage.retrieve.assert_not_called()+++def test_image_preview_cache_hit_skips_retrieve(mocker):+ cached = b"RIFF-cached-webp-bytes"+ _mock_lookups(mocker, _make_file(mime_type="image/png"))+ storage = _mock_storage(mocker, _png_bytes())+ _mock_redis(mocker, cached=cached)++ response = client.get("/files/file-001/preview?w=100")++ assert response.status_code == 200+ assert response.content == cached+ storage.retrieve.assert_not_called()diff --git a/autogpt_platform/backend/backend/api/features/workspace/routes.py b/autogpt_platform/backend/backend/api/features/workspace/routes.pyindex e172c167cd..bcdf87b24e 100644--- a/autogpt_platform/backend/backend/api/features/workspace/routes.py+++ b/autogpt_platform/backend/backend/api/features/workspace/routes.py@@ -16,6 +16,7 @@ from fastapi.responses import Responsefrom pydantic import BaseModel, Fieldfrom backend.api.features.store.exceptions import VirusDetectedError, VirusScanError+from backend.api.features.workspace.preview import build_preview_responsefrom backend.copilot.rate_limit import get_workspace_storage_limit_bytesfrom backend.data.workspace import (WorkspaceFile,@@ -182,6 +183,35 @@ async def download_file(return await create_file_download_response(file)+ "/files/{file_id}/preview",+ summary="Preview file by ID",+ operation_id="getWorkspaceFilePreview",+)+async def preview_file(+ user_id: Annotated[str, fastapi.Security(get_user_id)],+ file_id: str,+ w: int = Query(default=400, ge=16, le=1024),+ bytes_: int = Query(default=4096, ge=256, le=131072, alias="bytes"),+) -> Response:+ """+ Return a cheap preview of a file.++ Images/PDFs/Office docs are returned as a small WebP thumbnail; text-like+ files return only their first ``bytes`` bytes. Used by the Artifacts page so+ a grid of files no longer downloads every file in full.+ """+ workspace = await get_workspace(user_id)+ if workspace is None:+ raise fastapi.HTTPException(status_code=404, detail="Workspace not found")++ file = await get_workspace_file(file_id, workspace.id)+ if file is None:+ raise fastapi.HTTPException(status_code=404, detail="File not found")++ return await build_preview_response(file, width=w, max_bytes=bytes_)++@router.delete("/files/{file_id}",summary="Delete a workspace file",diff --git a/autogpt_platform/backend/backend/api/middleware/security.py b/autogpt_platform/backend/backend/api/middleware/security.pyindex 1a3b3715aa..ac18b623e5 100644--- a/autogpt_platform/backend/backend/api/middleware/security.py+++ b/autogpt_platform/backend/backend/api/middleware/security.py@@ -25,6 +25,8 @@ class SecurityHeadersMiddleware:"/api/status","/api/blocks","/api/v1/blocks",+ # Workspace file previews (user-private; response sets Cache-Control: private)+ "/api/workspace/files/*/preview",# Public store/marketplace pages (read-only)"/api/store/agents","/api/v1/store/agents",diff --git a/autogpt_platform/backend/backend/api/middleware/security_test.py b/autogpt_platform/backend/backend/api/middleware/security_test.pyindex 57137afc9a..16fb665f58 100644--- a/autogpt_platform/backend/backend/api/middleware/security_test.py+++ b/autogpt_platform/backend/backend/api/middleware/security_test.py@@ -118,6 +118,7 @@ def test_is_cacheable_path_detection():assert middleware.is_cacheable_path("/api/store/agents")assert middleware.is_cacheable_path("/docs")assert middleware.is_cacheable_path("/favicon.ico")+ assert middleware.is_cacheable_path("/api/workspace/files/abc-123/preview")# Test non-cacheable paths (everything else)assert not middleware.is_cacheable_path("/api/auth/user")@@ -125,6 +126,8 @@ def test_is_cacheable_path_detection():assert not middleware.is_cacheable_path("/api/integrations/credentials/123")assert not middleware.is_cacheable_path("/api/graphs/abc123/execute")assert not middleware.is_cacheable_path("/api/store/xyz/submissions")+ # The wildcard only covers /preview, not the full file download.+ assert not middleware.is_cacheable_path("/api/workspace/files/abc-123/download")def test_path_prefix_matching():diff --git a/autogpt_platform/backend/backend/util/gcs_utils.py b/autogpt_platform/backend/backend/util/gcs_utils.pyindex 3f91f21897..10bb58d75c 100644--- a/autogpt_platform/backend/backend/util/gcs_utils.py+++ b/autogpt_platform/backend/backend/util/gcs_utils.py@@ -78,6 +78,52 @@ async def download_with_fresh_session(bucket: str, blob: str) -> bytes:await session.close()+async def download_range(bucket: str, blob: str, max_bytes: int) -> bytes:+ """+ Download only the first ``max_bytes`` of a GCS object using a Range request.++ Falls back to a full download when the installed ``gcloud-aio`` build does+ not accept a ``headers`` kwarg; the result is sliced to ``max_bytes`` either+ way so callers always get at most ``max_bytes``.++ Args:+ bucket: GCS bucket name+ blob: Blob path within the bucket+ max_bytes: Maximum number of leading bytes to fetch++ Returns:+ Up to ``max_bytes`` of file content as bytes++ Raises:+ FileNotFoundError: If the file doesn't exist+ """+ session = aiohttp.ClientSession(+ connector=aiohttp.TCPConnector(limit=10, force_close=True)+ )+ client: async_gcs_storage.Storage | None = None+ try:+ client = async_gcs_storage.Storage(session=session)+ try:+ content = await client.download(+ bucket, blob, headers={"Range": f"bytes=0-{max(0, max_bytes - 1)}"}+ )+ except TypeError:+ # Older gcloud-aio without a headers kwarg: full download, then slice.+ content = await client.download(bucket, blob)+ return content[:max_bytes]+ except Exception as e:+ if "404" in str(e) or "Not Found" in str(e):+ raise FileNotFoundError(f"File not found: gcs://{bucket}/{blob}")+ raise+ finally:+ if client:+ try:+ await client.close()+ except Exception:+ pass # Best-effort cleanup+ await session.close()++async def generate_signed_url(sync_client: gcs_storage.Client,bucket_name: str,diff --git a/autogpt_platform/backend/backend/util/gcs_utils_test.py b/autogpt_platform/backend/backend/util/gcs_utils_test.pynew file mode 100644index 0000000000..2be64a06fb--- /dev/null+++ b/autogpt_platform/backend/backend/util/gcs_utils_test.py@@ -0,0 +1,72 @@+from unittest.mock import AsyncMock, MagicMock++import pytest++from backend.util.gcs_utils import download_range, parse_gcs_path+++def _mock_client(mocker, *, download: AsyncMock) -> MagicMock:+ """Patch the async GCS Storage client and session used by gcs_utils."""+ client = MagicMock()+ client.download = download+ client.close = AsyncMock(return_value=None)+ mocker.patch(+ "backend.util.gcs_utils.async_gcs_storage.Storage",+ return_value=client,+ )+ session = MagicMock()+ session.close = AsyncMock(return_value=None)+ mocker.patch(+ "backend.util.gcs_utils.aiohttp.ClientSession",+ return_value=session,+ )+ mocker.patch(+ "backend.util.gcs_utils.aiohttp.TCPConnector", return_value=MagicMock()+ )+ return client+++def test_parse_gcs_path_splits_bucket_and_blob():+ assert parse_gcs_path("gcs://my-bucket/path/to/file") == (+ "my-bucket",+ "path/to/file",+ )+++def test_parse_gcs_path_rejects_invalid_prefix():+ with pytest.raises(ValueError):+ parse_gcs_path("s3://my-bucket/file")+++async def test_download_range_sends_range_header_and_slices(mocker):+ download = AsyncMock(return_value=b"0123456789ABCDEF")+ client = _mock_client(mocker, download=download)++ result = await download_range("bucket", "blob", 8)++ assert result == b"01234567"+ download.assert_awaited_once_with("bucket", "blob", headers={"Range": "bytes=0-7"})+ client.close.assert_awaited_once()+++async def test_download_range_falls_back_when_headers_unsupported(mocker):+ download = AsyncMock(+ side_effect=[TypeError("unexpected kwarg 'headers'"), b"full-content-here"]+ )+ _mock_client(mocker, download=download)++ result = await download_range("bucket", "blob", 4)++ assert result == b"full"+ assert download.await_count == 2+++async def test_download_range_maps_404_to_file_not_found(mocker):+ download = AsyncMock(side_effect=Exception("404 Not Found"))+ _mock_client(mocker, download=download)++ with pytest.raises(FileNotFoundError):+ await download_range("bucket", "missing", 16)diff --git a/autogpt_platform/backend/backend/util/workspace_storage.py b/autogpt_platform/backend/backend/util/workspace_storage.pyindex eca41b6616..b0462253eb 100644--- a/autogpt_platform/backend/backend/util/workspace_storage.py+++ b/autogpt_platform/backend/backend/util/workspace_storage.py@@ -20,6 +20,7 @@ from google.cloud import storage as gcs_storagefrom backend.util.data import get_data_pathfrom backend.util.gcs_utils import (+ download_range,download_with_fresh_session,generate_signed_url,parse_gcs_path,@@ -67,6 +68,22 @@ class WorkspaceStorageBackend(ABC):"""pass+ @abstractmethod+ async def retrieve_partial(self, storage_path: str, max_bytes: int) -> bytes:+ """+ Retrieve up to ``max_bytes`` from the start of the file.++ Used for cheap text previews so large files are not loaded in full.++ Args:+ storage_path: The storage path returned from store()+ max_bytes: Maximum number of leading bytes to return++ Returns:+ At most ``max_bytes`` of file content as bytes+ """+ pass+@abstractmethodasync def delete(self, storage_path: str) -> None:"""@@ -174,6 +191,11 @@ class GCSWorkspaceStorage(WorkspaceStorageBackend):bucket_name, blob_name = parse_gcs_path(storage_path)return await download_with_fresh_session(bucket_name, blob_name)+ async def retrieve_partial(self, storage_path: str, max_bytes: int) -> bytes:+ """Retrieve the first ``max_bytes`` of a GCS file via a Range request."""+ bucket_name, blob_name = parse_gcs_path(storage_path)+ return await download_range(bucket_name, blob_name, max_bytes)+async def delete(self, storage_path: str) -> None:"""Delete file from GCS."""bucket_name, blob_name = parse_gcs_path(storage_path)@@ -301,6 +323,16 @@ class LocalWorkspaceStorage(WorkspaceStorageBackend):async with aiofiles.open(file_path, "rb") as f:return await f.read()+ async def retrieve_partial(self, storage_path: str, max_bytes: int) -> bytes:+ """Retrieve the first ``max_bytes`` of a local file."""+ file_path = self._parse_storage_path(storage_path)++ try:+ async with aiofiles.open(file_path, "rb") as f:+ return await f.read(max_bytes)+ except FileNotFoundError as e:+ raise FileNotFoundError(f"File not found: {storage_path}") from e+async def delete(self, storage_path: str) -> None:"""Delete file from local storage."""file_path = self._parse_storage_path(storage_path)diff --git a/autogpt_platform/backend/backend/util/workspace_storage_test.py b/autogpt_platform/backend/backend/util/workspace_storage_test.pynew file mode 100644index 0000000000..b88e2332e7--- /dev/null+++ b/autogpt_platform/backend/backend/util/workspace_storage_test.py@@ -0,0 +1,47 @@+from unittest.mock import AsyncMock++import pytest++from backend.util.workspace_storage import GCSWorkspaceStorage, LocalWorkspaceStorage+++async def test_retrieve_partial_returns_only_leading_bytes(tmp_path):+ storage = LocalWorkspaceStorage(base_dir=str(tmp_path))+ storage_path = await storage.store("ws", "file", "data.txt", b"x" * 10_000)++ partial = await storage.retrieve_partial(storage_path, 512)++ assert partial == b"x" * 512+++async def test_retrieve_partial_returns_whole_file_when_smaller_than_cap(tmp_path):+ storage = LocalWorkspaceStorage(base_dir=str(tmp_path))+ storage_path = await storage.store("ws", "file", "data.txt", b"hello")++ partial = await storage.retrieve_partial(storage_path, 4096)++ assert partial == b"hello"+++async def test_retrieve_partial_raises_when_missing(tmp_path):+ storage = LocalWorkspaceStorage(base_dir=str(tmp_path))++ with pytest.raises(FileNotFoundError):+ await storage.retrieve_partial("local://ws/file/missing.txt", 256)+++async def test_gcs_retrieve_partial_delegates_to_download_range(mocker):+ download_range = mocker.patch(+ "backend.util.workspace_storage.download_range",+ AsyncMock(return_value=b"head"),+ )+ storage = GCSWorkspaceStorage(bucket_name="my-bucket")++ result = await storage.retrieve_partial("gcs://my-bucket/path/file.txt", 4)++ assert result == b"head"+ download_range.assert_awaited_once_with("my-bucket", "path/file.txt", 4)diff --git a/autogpt_platform/backend/poetry.lock b/autogpt_platform/backend/poetry.lockindex 6cb3533df8..7eb4b4969a 100644--- a/autogpt_platform/backend/poetry.lock+++ b/autogpt_platform/backend/poetry.lock@@ -6032,6 +6032,38 @@ files = [[package.extras]diagrams = ["jinja2", "railroad-diagrams"]+[[package]]+name = "pypdfium2"+version = "5.8.0"+description = "Python bindings to PDFium"+optional = false+python-versions = ">=3.6"+groups = ["main"]+files = [+ {file = "pypdfium2-5.8.0-py3-none-android_23_arm64_v8a.whl", hash = "sha256:f67b6c74b716d9ac725ad1af49ae786ad813ac20823d45606d59f1fc06caa8af"},+ {file = "pypdfium2-5.8.0-py3-none-android_23_armeabi_v7a.whl", hash = "sha256:53e82bf3e6a2da170b1bda83f93b7eec57cb6efe3cacd05cba78823879a85203"},+ {file = "pypdfium2-5.8.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:085e633dcc89b65ff4035a4787e98ce7ae636836eb39c83dd0db26113d9774bc"},+ {file = "pypdfium2-5.8.0-py3-none-macosx_11_0_x86_64.whl", hash = "sha256:bc84b7c6efede88fcfb9467f81daf416f26b973a54fc1cf4d3410d622fda6d7a"},+ {file = "pypdfium2-5.8.0-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a63bf09b2e13ba8545c930d243f0650c664a1b51314daa3b5f38df6d1a17b4bc"},+ {file = "pypdfium2-5.8.0-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:937881c1698456749ed203a58db1895baa5eb7178cdb837ef84867790638da28"},+ {file = "pypdfium2-5.8.0-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6be9dc2b84a8694ad7e626bab133244e8241014d5ed1930d865a9bdf90df1e24"},+ {file = "pypdfium2-5.8.0-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7f27bd82891ae302dd02d736b14809661f6d1220ee1e96dbed9b23e2811922a3"},+ {file = "pypdfium2-5.8.0-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:26c1089cdbbdc7fe1248f6d17fe3f30214be4f287dd0196b31aaee18a1564240"},+ {file = "pypdfium2-5.8.0-py3-none-manylinux_2_27_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1c038a9290864aaa4862dd32e591993d82551ca4d152b4e8ce6d43ba37dc04a8"},+ {file = "pypdfium2-5.8.0-py3-none-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:f104bc1a6d8bfc1ff088aa50db13b9729cfdb3722b44975c3c457e9a7b9c7318"},+ {file = "pypdfium2-5.8.0-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:04ca7c57a553facf8d46c6ea8ba6fa557e698670cfa4a58e0e01fdae2f6be87d"},+ {file = "pypdfium2-5.8.0-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:ad42b9c22477b32dbedcbc8232833f385d92fd0cf92822547b02383cf9a476d7"},+ {file = "pypdfium2-5.8.0-py3-none-musllinux_1_2_i686.whl", hash = "sha256:388e3119cf5ca0979b7d5f6d40b7fcd5ab49e17ed4e6de6af89ba116061acfda"},+ {file = "pypdfium2-5.8.0-py3-none-musllinux_1_2_ppc64le.whl", hash = "sha256:aa05bbfa485ce7916217aa78d856c9f9cd86b08b20846c650392a67975ee72e9"},+ {file = "pypdfium2-5.8.0-py3-none-musllinux_1_2_riscv64.whl", hash = "sha256:f0813a16bb39d5ebd173ea5484430bb67a89b4b181db0a636c73b64ad063c3ea"},+ {file = "pypdfium2-5.8.0-py3-none-musllinux_1_2_s390x.whl", hash = "sha256:a3c78f7d20dd821bec6c072efdb21a1370b9efe10fdeeb68c969e67608e25385"},+ {file = "pypdfium2-5.8.0-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:86d302e207c138c827b885a72784f7b306d840646ebeae07e8efdbc39321c629"},+ {file = "pypdfium2-5.8.0-py3-none-win32.whl", hash = "sha256:3f25fd436920a907291462b41bdc0ab9f8235c3944b4c9c15398da595ffd1fed"},+ {file = "pypdfium2-5.8.0-py3-none-win_amd64.whl", hash = "sha256:55592af0bddd2d62bed18e0053c546c9b72041430c5115e54870f7f6163125b0"},+ {file = "pypdfium2-5.8.0-py3-none-win_arm64.whl", hash = "sha256:3f17ed97ae8a5a1705301ca93af256a5b02f9009dee4e99c5e175831d46ebd7c"},+ {file = "pypdfium2-5.8.0.tar.gz", hash = "sha256:049397c647e50f83115ee951c49394dab9e9ba52ebdd5a11ab1109390eb3d34e"},+]+[[package]]name = "pyproject-hooks"version = "1.2.0"@@ -8985,4 +9017,4 @@ cffi = ["cffi (>=1.17,<2.0) ; platform_python_implementation != \"PyPy\" and pyt[metadata]lock-version = "2.1"python-versions = ">=3.10,<3.14"-content-hash = "8b33b42305e8168e4427c57daba0ea91f96809a08f428ec491a47bd11e80b1a8"+content-hash = "eb1905be6dc5c0b6db5f42d1168cd112ea486a55b61bcac89d4cc45b85b655c9"diff --git a/autogpt_platform/backend/pyproject.toml b/autogpt_platform/backend/pyproject.tomlindex 834724b92b..acef4cdc6a 100644--- a/autogpt_platform/backend/pyproject.toml+++ b/autogpt_platform/backend/pyproject.toml@@ -102,6 +102,8 @@ pymssql = "^2.3.2"pymysql = "^1.1.1"pyarrow = "^23.0.0"sqlparse = "^0.5.5"+pillow = ">=9.1.0,<12"+pypdfium2 = "^5.8.0"[tool.poetry.group.dev.dependencies]aiohappyeyeballs = "^2.6.1"diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/main.test.tsxindex 8e71cd630a..299d0e257c 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/main.test.tsx@@ -2,6 +2,7 @@ import { describe, expect, test, vi } from "vitest";import { fireEvent, render, screen } from "@/tests/integrations/test-utils";import { server } from "@/mocks/mock-server";+import { http, HttpResponse } from "msw";import {getGetWorkspaceStorageUsageMockHandler,getListWorkspaceFilesMockHandler,@@ -92,7 +93,7 @@ describe("ArtifactsPage - basic rendering", () => {render(<ArtifactsPage />);expect(- await screen.findByRole("heading", { name: /artifacts/i }),+ await screen.findByRole("heading", { name: /files/i }),).toBeDefined();});@@ -109,7 +110,7 @@ describe("ArtifactsPage - basic rendering", () => {render(<ArtifactsPage />);expect(await screen.findByTestId("artifacts-empty")).toBeDefined();- expect(screen.getByText(/no artifacts yet/i)).toBeDefined();+ expect(screen.getByText(/no files yet/i)).toBeDefined();});test("renders one card per file with name + type label", async () => {@@ -231,3 +232,122 @@ describe("ArtifactsPage - card menu", () => {expect(screen.getByTestId("artifacts-card-menu")).toBeDefined();});});++describe("ArtifactsPage - rich previews", () => {+ test("image cards request the resized preview endpoint", async () => {+ useStorageHandler();+ server.use(+ getListWorkspaceFilesMockHandler({+ files: [+ makeFile({ id: "img1", name: "pic.png", mime_type: "image/png" }),+ ],+ offset: 0,+ has_more: false,+ }),+ );++ render(<ArtifactsPage />);++ const img = (await screen.findByAltText("pic.png")) as HTMLImageElement;+ expect(img.getAttribute("src")).toContain(+ "/api/proxy/api/workspace/files/img1/preview?w=400",+ );+ });++ test("pdf cards render an image from the preview endpoint", async () => {+ useStorageHandler();+ server.use(+ getListWorkspaceFilesMockHandler({+ files: [+ makeFile({+ id: "pdf1",+ name: "report.pdf",+ mime_type: "application/pdf",+ }),+ ],+ offset: 0,+ has_more: false,+ }),+ );++ render(<ArtifactsPage />);++ const img = (await screen.findByAltText("report.pdf")) as HTMLImageElement;+ expect(img.getAttribute("src")).toContain("/preview?w=400");+ });++ test("csv cards render a table from the byte-capped preview", async () => {+ useStorageHandler();+ server.use(+ getListWorkspaceFilesMockHandler({+ files: [+ makeFile({ id: "csv1", name: "data.csv", mime_type: "text/csv" }),+ ],+ offset: 0,+ has_more: false,+ }),+ http.get("/api/proxy/api/workspace/files/csv1/preview", () =>+ HttpResponse.text("name,age\nAda,36\nBob,40\n"),+ ),+ );++ render(<ArtifactsPage />);++ expect(await screen.findByText("name")).toBeDefined();+ expect(await screen.findByText("Ada")).toBeDefined();+ });++ test("ics cards render the event summary", async () => {+ useStorageHandler();+ server.use(+ getListWorkspaceFilesMockHandler({+ files: [+ makeFile({+ id: "ics1",+ name: "meeting.ics",+ mime_type: "text/calendar",+ size_bytes: 400,+ }),+ ],+ offset: 0,+ has_more: false,+ }),+ http.get("/api/proxy/api/workspace/files/ics1/preview", () =>+ HttpResponse.text(+ "BEGIN:VCALENDAR\nBEGIN:VEVENT\nSUMMARY:Launch sync\nDTSTART:20260615T130000Z\nLOCATION:Room 4\nEND:VEVENT\nEND:VCALENDAR",+ ),+ ),+ );++ render(<ArtifactsPage />);++ expect(await screen.findByText("Launch sync")).toBeDefined();+ });++ test("vcard cards render the contact name", async () => {+ useStorageHandler();+ server.use(+ getListWorkspaceFilesMockHandler({+ files: [+ makeFile({+ id: "vcf1",+ name: "ada.vcf",+ mime_type: "text/vcard",+ size_bytes: 300,+ }),+ ],+ offset: 0,+ has_more: false,+ }),+ http.get("/api/proxy/api/workspace/files/vcf1/preview", () =>+ HttpResponse.text(+ "BEGIN:VCARD\nFN:Ada Lovelace\nORG:Analytical Engine\nEND:VCARD",+ ),+ ),+ );++ render(<ArtifactsPage />);++ expect(await screen.findByText("Ada Lovelace")).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/CardPreview.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/CardPreview.tsxindex 763e02d7ff..2c7cd8528c 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/CardPreview.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/CardPreview.tsx@@ -1,25 +1,19 @@"use client";import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";-import { cn } from "@/lib/utils";-import { useCallback, useEffect, useState } from "react";-import {- deriveBadgeLabel,- FileIllustration,- pickFileTypeKey,-} from "../FileIllustration";-import {- getFileDownloadUrl,- getPreviewKind,- type PreviewKind,-} from "../helpers";+import { useCallback, useState } from "react";+import { getPreviewKind, type PreviewKind } from "../helpers";+import { ImagePreview, VideoPreview } from "./MediaPreview";+import { Fallback } from "./PreviewParts";+import { IcsPreview, VcardPreview } from "./StructuredPreviews";+import { CsvPreview, JsonPreview, TextSnippetPreview } from "./TextPreviews";interface Props {file: WorkspaceFileItem;}export function CardPreview({ file }: Props) {- const kind = getPreviewKind(file.mime_type, file.size_bytes);+ const kind = getPreviewKind(file.mime_type, file.size_bytes, file.name);return (<div className="relative aspect-[16/10] overflow-hidden border-b border-zinc-200 bg-zinc-100">@@ -40,145 +34,24 @@ function PreviewBody({const [hasError, setHasError] = useState(false);const handleError = useCallback(() => setHasError(true), []);- if (hasError || kind === "none") {- return <Fallback file={file} />;+ if (hasError || kind === "none") return <Fallback file={file} />;++ switch (kind) {+ case "image":+ case "pdf":+ case "office":+ return <ImagePreview file={file} onError={handleError} />;+ case "video":+ return <VideoPreview file={file} onError={handleError} />;+ case "csv":+ return <CsvPreview file={file} onError={handleError} />;+ case "json":+ return <JsonPreview file={file} onError={handleError} />;+ case "ics":+ return <IcsPreview file={file} onError={handleError} />;+ case "vcard":+ return <VcardPreview file={file} onError={handleError} />;+ default:+ return <TextSnippetPreview file={file} onError={handleError} />;}-- if (kind === "image") {- return <ImagePreview file={file} onError={handleError} />;- }-- if (kind === "video") {- return <VideoPreview file={file} onError={handleError} />;- }-- return <TextSnippetPreview file={file} onError={handleError} />;-}--function ImagePreview({- file,- onError,-}: {- file: WorkspaceFileItem;- onError: () => void;-}) {- const [isLoaded, setIsLoaded] = useState(false);-- return (- <>- {!isLoaded ? <LoadingPlaceholder file={file} /> : null}- {/* eslint-disable-next-line @next/next/no-img-element */}- <img- src={getFileDownloadUrl(file.id)}- alt={file.name}- loading="lazy"- onLoad={() => setIsLoaded(true)}- onError={onError}- className={cn(- "h-full w-full object-cover transition-opacity duration-300",- isLoaded ? "opacity-100" : "opacity-0",- )}- />- </>- );-}--function VideoPreview({- file,- onError,-}: {- file: WorkspaceFileItem;- onError: () => void;-}) {- const [isLoaded, setIsLoaded] = useState(false);-- return (- <>- {!isLoaded ? <LoadingPlaceholder file={file} /> : null}- <video- src={getFileDownloadUrl(file.id)}- preload="metadata"- muted- playsInline- onLoadedData={() => setIsLoaded(true)}- onError={onError}- className={cn(- "h-full w-full object-cover transition-opacity duration-300",- isLoaded ? "opacity-100" : "opacity-0",- )}- />- </>- );-}--function Fallback({ file }: { file: WorkspaceFileItem }) {- return (- <div className="flex h-full w-full items-center justify-center">- <FileIllustration- typeKey={pickFileTypeKey(file.mime_type)}- label={deriveBadgeLabel(file.name, file.mime_type)}- size="md"- />- </div>- );-}--function LoadingPlaceholder({ file }: { file: WorkspaceFileItem }) {- return (- <div className="absolute inset-0">- <Fallback file={file} />- <ProgressBar />- </div>- );-}--function ProgressBar() {- return (- <div- className="absolute inset-x-0 top-0 h-0.5 overflow-hidden bg-zinc-200/70"- aria-hidden- >- <div className="h-full w-1/3 animate-progress-bar rounded-full bg-zinc-500" />- </div>- );-}--const TEXT_SNIPPET_CHARS = 1500;--function TextSnippetPreview({- file,- onError,-}: {- file: WorkspaceFileItem;- onError: () => void;-}) {- const [text, setText] = useState<string | null>(null);-- useEffect(() => {- let cancelled = false;- async function load() {- try {- const res = await fetch(getFileDownloadUrl(file.id));- if (!res.ok) throw new Error(`Status ${res.status}`);- const body = await res.text();- if (!cancelled) setText(body.slice(0, TEXT_SNIPPET_CHARS));- } catch {- if (!cancelled) onError();- }- }- load();- return () => {- cancelled = true;- };- }, [file.id, onError]);-- if (text === null) {- return <LoadingPlaceholder file={file} />;- }-- return (- <pre className="h-full w-full overflow-hidden whitespace-pre-wrap break-words bg-white p-3 font-mono text-[10px] leading-[1.35] text-zinc-700">- {text}- </pre>- );}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/MediaPreview.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/MediaPreview.tsxnew file mode 100644index 0000000000..5f470299ec--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/MediaPreview.tsx@@ -0,0 +1,62 @@+"use client";++import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";+import { cn } from "@/lib/utils";+import { useState } from "react";+import { getFileDownloadUrl, getFilePreviewUrl } from "../helpers";+import { LoadingPlaceholder } from "./PreviewParts";++interface PreviewProps {+ file: WorkspaceFileItem;+ onError: () => void;+}++// Shared by image / pdf / office kinds — the backend returns a small WebP+// thumbnail for all three, so the client just paints an <img>.+export function ImagePreview({ file, onError }: PreviewProps) {+ const [isLoaded, setIsLoaded] = useState(false);++ return (+ <>+ {!isLoaded ? <LoadingPlaceholder file={file} /> : null}+ {/* eslint-disable-next-line @next/next/no-img-element */}+ <img+ src={getFilePreviewUrl(file.id, { width: 400 })}+ alt={file.name}+ loading="lazy"+ onLoad={() => setIsLoaded(true)}+ onError={onError}+ className={cn(+ "h-full w-full object-cover transition-opacity duration-300",+ isLoaded ? "opacity-100" : "opacity-0",+ )}+ />+ </>+ );+}++export function VideoPreview({ file, onError }: PreviewProps) {+ const [isLoaded, setIsLoaded] = useState(false);++ return (+ <>+ {!isLoaded ? <LoadingPlaceholder file={file} /> : null}+ <video+ src={getFileDownloadUrl(file.id)}+ preload="metadata"+ muted+ playsInline+ // Reveal on the first painted frame when available (avoids a blank+ // box); fall back to metadata so the video is never left hidden when+ // the browser only fetches metadata under preload="metadata".+ onLoadedData={() => setIsLoaded(true)}+ onLoadedMetadata={() => setIsLoaded(true)}+ onError={onError}+ className={cn(+ "h-full w-full object-cover transition-opacity duration-300",+ isLoaded ? "opacity-100" : "opacity-0",+ )}+ />+ </>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/PreviewParts.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/PreviewParts.tsxnew file mode 100644index 0000000000..18b30332bc--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/PreviewParts.tsx@@ -0,0 +1,66 @@+"use client";++import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";+import { useEffect, useState } from "react";+import {+ deriveBadgeLabel,+ FileIllustration,+ pickFileTypeKey,+} from "../FileIllustration";++export function useFileText(url: string, onError: () => void): string | null {+ const [text, setText] = useState<string | null>(null);++ useEffect(() => {+ let cancelled = false;+ setText(null);+ async function load() {+ try {+ const res = await fetch(url);+ if (!res.ok) throw new Error(`Status ${res.status}`);+ const body = await res.text();+ if (!cancelled) setText(body);+ } catch {+ if (!cancelled) onError();+ }+ }+ load();+ return () => {+ cancelled = true;+ };+ }, [url, onError]);++ return text;+}++export function Fallback({ file }: { file: WorkspaceFileItem }) {+ return (+ <div className="flex h-full w-full items-center justify-center">+ <FileIllustration+ typeKey={pickFileTypeKey(file.mime_type, file.name)}+ label={deriveBadgeLabel(file.name, file.mime_type)}+ size="md"+ />+ </div>+ );+}++export function LoadingPlaceholder({ file }: { file: WorkspaceFileItem }) {+ return (+ <div className="absolute inset-0">+ <Fallback file={file} />+ <ProgressBar />+ </div>+ );+}++export function ProgressBar() {+ return (+ <div+ className="absolute inset-x-0 top-0 h-0.5 overflow-hidden bg-zinc-200/70"+ aria-hidden+ >+ <div className="h-full w-1/3 animate-progress-bar rounded-full bg-zinc-500" />+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/StructuredPreviews.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/StructuredPreviews.tsxnew file mode 100644index 0000000000..a834a96bde--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/StructuredPreviews.tsx@@ -0,0 +1,174 @@+"use client";++import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";+import { EnvelopeSimpleIcon, PhoneIcon } from "@phosphor-icons/react";+import { getFilePreviewUrl } from "../helpers";++// Whole file (kind is gated < 110KB) via the preview endpoint, which sets+// browser cache headers — unlike /download (no-store).+const STRUCTURED_PREVIEW_BYTES = 110_000;+import {+ parseIcs,+ parseVcard,+ type IcsPreview as IcsData,+ type VcardPreview as VcardData,+} from "../parsers";+import { Fallback, LoadingPlaceholder, useFileText } from "./PreviewParts";++interface PreviewProps {+ file: WorkspaceFileItem;+ onError: () => void;+}++const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];++interface DateParts {+ year: number;+ month: number;+ day: number;+ hour: number | null;+ minute: number | null;+}++function parseDateTime(value: string | undefined): DateParts | null {+ const digits = (value ?? "").replace(/[^0-9]/g, "");+ if (digits.length < 8) return null;+ const month = Number(digits.slice(4, 6));+ const day = Number(digits.slice(6, 8));+ if (month < 1 || month > 12 || day < 1 || day > 31) return null;+ const hasTime = digits.length >= 12;+ return {+ year: Number(digits.slice(0, 4)),+ month,+ day,+ hour: hasTime ? Number(digits.slice(8, 10)) : null,+ minute: hasTime ? Number(digits.slice(10, 12)) : null,+ };+}++function weekdayLabel(dt: DateParts): string {+ return WEEKDAYS[+ new Date(Date.UTC(dt.year, dt.month - 1, dt.day)).getUTCDay()+ ];+}++function clock(hour: number, minute: number): string {+ return `${hour % 12 === 0 ? 12 : hour % 12}:${String(minute).padStart(2, "0")}`;+}++function meridiem(hour: number): string {+ return hour >= 12 ? "PM" : "AM";+}++function formatTimeRange(+ start: string | undefined,+ end: string | undefined,+): string | null {+ const s = parseDateTime(start);+ if (!s || s.hour === null || s.minute === null) return null;+ const e = parseDateTime(end);+ if (e && e.hour !== null && e.minute !== null) {+ // Collapse the meridiem when both ends share it: "3:30–4:30 PM".+ if (meridiem(s.hour) === meridiem(e.hour)) {+ return `${clock(s.hour, s.minute)}–${clock(e.hour, e.minute)} ${meridiem(e.hour)}`;+ }+ return `${clock(s.hour, s.minute)} ${meridiem(s.hour)} – ${clock(e.hour, e.minute)} ${meridiem(e.hour)}`;+ }+ return `${clock(s.hour, s.minute)} ${meridiem(s.hour)}`;+}++export function IcsPreview({ file, onError }: PreviewProps) {+ const text = useFileText(+ getFilePreviewUrl(file.id, { bytes: STRUCTURED_PREVIEW_BYTES }),+ onError,+ );+ if (text === null) return <LoadingPlaceholder file={file} />;++ const event = parseIcs(text);+ if (!event) return <Fallback file={file} />;+ return <EventCard event={event} />;+}++function EventCard({ event }: { event: IcsData }) {+ const date = parseDateTime(event.start);+ const timeRange = formatTimeRange(event.start, event.end);+ return (+ <div className="flex h-full w-full flex-col items-center justify-center gap-0.5 bg-white p-3 text-center">+ {date ? (+ <>+ <span className="text-sm font-bold uppercase leading-none tracking-wide text-red-500">+ {weekdayLabel(date)}+ </span>+ <span className="text-4xl font-bold leading-none text-zinc-900">+ {date.day}+ </span>+ </>+ ) : null}+ <span className="mt-1.5 line-clamp-2 text-sm font-medium text-zinc-800">+ {event.summary ?? "Event"}+ </span>+ {timeRange ? (+ <span className="text-xs text-zinc-600">{timeRange}</span>+ ) : null}+ </div>+ );+}++export function VcardPreview({ file, onError }: PreviewProps) {+ const text = useFileText(+ getFilePreviewUrl(file.id, { bytes: STRUCTURED_PREVIEW_BYTES }),+ onError,+ );+ if (text === null) return <LoadingPlaceholder file={file} />;++ const contact = parseVcard(text);+ if (!contact) return <Fallback file={file} />;+ return <ContactCard contact={contact} />;+}++function initials(name: string): string {+ return name+ .split(/\s+/)+ .slice(0, 2)+ .map((part) => part[0]?.toUpperCase() ?? "")+ .join("");+}++function ContactCard({ contact }: { contact: VcardData }) {+ return (+ <div className="flex h-full w-full flex-col items-center justify-center gap-1.5 bg-white p-3 text-center">+ {contact.photo ? (+ // eslint-disable-next-line @next/next/no-img-element+ <img+ src={contact.photo}+ alt={contact.name ?? "Contact"}+ className="h-14 w-14 rounded-full object-cover"+ />+ ) : (+ <div className="flex h-14 w-14 items-center justify-center rounded-full bg-zinc-200 text-lg font-semibold text-zinc-600">+ {initials(contact.name ?? "")}+ </div>+ )}+ <span className="truncate text-sm font-medium text-zinc-900">+ {contact.name}+ </span>+ {contact.title || contact.org ? (+ <span className="truncate text-xs text-zinc-500">+ {[contact.title, contact.org].filter(Boolean).join(" · ")}+ </span>+ ) : null}+ {contact.tel ? (+ <span className="flex items-center gap-1 text-xs text-zinc-500">+ <PhoneIcon size={12} className="shrink-0" />+ <span className="truncate">{contact.tel}</span>+ </span>+ ) : null}+ {contact.email ? (+ <span className="flex items-center gap-1 text-xs text-zinc-500">+ <EnvelopeSimpleIcon size={12} className="shrink-0" />+ <span className="truncate">{contact.email}</span>+ </span>+ ) : null}+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/TextPreviews.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/TextPreviews.tsxnew file mode 100644index 0000000000..b5de1ff73f--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/TextPreviews.tsx@@ -0,0 +1,100 @@+"use client";++import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";+import { getFilePreviewUrl } from "../helpers";+import { parseCsv, type CsvPreview } from "../parsers";+import { LoadingPlaceholder, useFileText } from "./PreviewParts";++const TEXT_SNIPPET_CHARS = 1500;++interface PreviewProps {+ file: WorkspaceFileItem;+ onError: () => void;+}++const preClass =+ "h-full w-full overflow-hidden whitespace-pre-wrap break-words bg-white p-3 font-mono text-[10px] leading-[1.35] text-zinc-700";++export function TextSnippetPreview({ file, onError }: PreviewProps) {+ const text = useFileText(+ getFilePreviewUrl(file.id, { bytes: 2048 }),+ onError,+ );++ if (text === null) return <LoadingPlaceholder file={file} />;+ return <pre className={preClass}>{text.slice(0, TEXT_SNIPPET_CHARS)}</pre>;+}++export function JsonPreview({ file, onError }: PreviewProps) {+ const text = useFileText(+ getFilePreviewUrl(file.id, { bytes: 4096 }),+ onError,+ );++ if (text === null) return <LoadingPlaceholder file={file} />;+ return (+ <pre className={preClass}>+ {prettyJson(text).slice(0, TEXT_SNIPPET_CHARS)}+ </pre>+ );+}++function prettyJson(text: string): string {+ try {+ // The byte-capped fetch often truncates JSON mid-value, so this only+ // succeeds for small files; otherwise show the raw text.+ return JSON.stringify(JSON.parse(text), null, 2);+ } catch {+ return text;+ }+}++export function CsvPreview({ file, onError }: PreviewProps) {+ const text = useFileText(+ getFilePreviewUrl(file.id, { bytes: 4096 }),+ onError,+ );++ if (text === null) return <LoadingPlaceholder file={file} />;++ const parsed = parseCsv(text);+ if (!parsed) {+ return <pre className={preClass}>{text.slice(0, TEXT_SNIPPET_CHARS)}</pre>;+ }+ return <CsvTable preview={parsed} />;+}++function CsvTable({ preview }: { preview: CsvPreview }) {+ const cellClass =+ "max-w-[6rem] truncate border-b border-zinc-100 px-2 py-1 text-left";+ return (+ <div className="relative h-full w-full overflow-hidden bg-white">+ <table className="w-full table-fixed border-collapse text-[9px] text-zinc-700">+ <thead>+ <tr>+ {preview.headers.map((header, i) => (+ <th+ key={i}+ className={`${cellClass} bg-zinc-50 font-semibold text-zinc-900`}+ >+ {header}+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {preview.rows.map((row, r) => (+ <tr key={r}>+ {row.map((cell, c) => (+ <td key={c} className={cellClass}>+ {cell}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ <div className="pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-white to-transparent" />+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsList.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsList.tsxindex 17dd6408f1..43a60e77df 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsList.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsList.tsx@@ -74,7 +74,7 @@ export function ArtifactsList({><FileTypeMarquee /><Text variant="h5" className="text-zinc-700">- {hasSearchTerm ? "No files match your search" : "No artifacts yet"}+ {hasSearchTerm ? "No files match your search" : "No files yet"}</Text></div>);diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileIllustration.test.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileIllustration.test.tsxindex c2d6b175d0..509d32fb75 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileIllustration.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileIllustration.test.tsx@@ -26,6 +26,11 @@ describe("pickFileTypeKey", () => {])("pickFileTypeKey(%s) === %s", (mime, expected) => {expect(pickFileTypeKey(mime)).toBe(expected);});++ test("detects React apps by .jsx/.tsx extension", () => {+ expect(pickFileTypeKey("text/plain", "App.jsx")).toBe("react");+ expect(pickFileTypeKey(undefined, "Component.tsx")).toBe("react");+ });});describe("deriveBadgeLabel", () => {@@ -68,6 +73,7 @@ describe("FileIllustration", () => {"img","html","video",+ "react","generic",] as const) {const { unmount } = render(<FileIllustration typeKey={key} />);diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileIllustration.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileIllustration.tsxindex 8d5a48487c..1136a6e410 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileIllustration.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileIllustration.tsx@@ -10,6 +10,7 @@ export type FileTypeKey =| "img"| "html"| "video"+ | "react"| "generic";interface FileTypeConfig {@@ -176,6 +177,21 @@ function ImgContent() {);}+function ReactContent() {+ return (+ <div className="flex h-16 items-center justify-center">+ <svg viewBox="-12 -12 24 24" className="h-10 w-10" aria-hidden>+ <circle r="2" fill="rgb(24 24 27 / 0.55)" />+ <g fill="none" stroke="rgb(24 24 27 / 0.35)" strokeWidth="1">+ <ellipse rx="10" ry="4" />+ <ellipse rx="10" ry="4" transform="rotate(60)" />+ <ellipse rx="10" ry="4" transform="rotate(120)" />+ </g>+ </svg>+ </div>+ );+}+export const FILE_TYPE_CONFIGS: Record<FileTypeKey, FileTypeConfig> = {pdf: {label: "PDF",@@ -213,6 +229,12 @@ export const FILE_TYPE_CONFIGS: Record<FileTypeKey, FileTypeConfig> = {badgePositionClass: "bottom-5 -right-2",content: <VideoContent />,},+ react: {+ label: "REACT",+ cardClass: "w-20 p-2.5",+ badgePositionClass: "bottom-5 -right-2",+ content: <ReactContent />,+ },generic: {label: "FILE",cardClass: "w-20 space-y-3 p-3",@@ -228,11 +250,17 @@ export const FILE_TYPE_KEYS: FileTypeKey[] = ["img","html","video",+ "react","generic",];-export function pickFileTypeKey(mimeType: string | undefined): FileTypeKey {+export function pickFileTypeKey(+ mimeType: string | undefined,+ fileName?: string,+): FileTypeKey {const mt = (mimeType ?? "").toLowerCase();+ const name = (fileName ?? "").toLowerCase();+ if (name.endsWith(".jsx") || name.endsWith(".tsx")) return "react";if (mt.startsWith("image/")) return "img";if (mt.startsWith("video/")) return "video";if (mt.includes("pdf")) return "pdf";diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.test.tsindex 0e6cf42898..c71ff1c670 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.test.ts@@ -180,9 +180,7 @@ describe("getPreviewKind", () => {test.each(["text/plain","text/html",- "application/json","application/xml",- "text/csv","text/markdown","application/javascript","application/typescript",@@ -191,8 +189,58 @@ describe("getPreviewKind", () => {expect(getPreviewKind(mt, 1_000)).toBe("text");});- test("text over the cap suppresses the preview", () => {- expect(getPreviewKind("text/plain", 500_000)).toBe("none");+ test("csv previews as 'csv'", () => {+ expect(getPreviewKind("text/csv", 1_000)).toBe("csv");+ expect(getPreviewKind("text/plain", 1_000, "data.csv")).toBe("csv");+ });++ test("json previews as 'json'", () => {+ expect(getPreviewKind("application/json", 1_000)).toBe("json");+ expect(getPreviewKind("text/plain", 1_000, "data.json")).toBe("json");+ });++ test("pdf previews as 'pdf' by mime or extension", () => {+ expect(getPreviewKind("application/pdf", 1_000)).toBe("pdf");+ expect(getPreviewKind("application/octet-stream", 1_000, "x.pdf")).toBe(+ "pdf",+ );+ });++ test("office openxml docs preview as 'office'", () => {+ expect(+ getPreviewKind(+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",+ 1_000,+ ),+ ).toBe("office");+ expect(getPreviewKind("application/octet-stream", 1_000, "deck.pptx")).toBe(+ "office",+ );+ });++ test("ics/vcard preview as cards only under the 50KB cap", () => {+ expect(getPreviewKind("text/calendar", 1_000, "e.ics")).toBe("ics");+ expect(getPreviewKind("text/vcard", 1_000, "c.vcf")).toBe("vcard");+ expect(getPreviewKind("text/calendar", 200_000, "e.ics")).toBe("none");+ });++ test("svg images are treated as text, not raster image", () => {+ expect(getPreviewKind("image/svg+xml", 1_000)).toBe("text");+ });++ test("large text/csv still previews (fetch is byte-capped)", () => {+ expect(getPreviewKind("text/plain", 5_000_000)).toBe("text");+ expect(getPreviewKind("text/csv", 5_000_000)).toBe("csv");+ });++ test("text/csv over the 50MB backend ceiling suppresses the preview", () => {+ expect(getPreviewKind("text/plain", 60_000_000)).toBe("none");+ expect(getPreviewKind("text/csv", 60_000_000)).toBe("none");+ });++ test("images/pdf over the backend ceiling suppress the preview", () => {+ expect(getPreviewKind("image/png", 11_000_000)).toBe("none");+ expect(getPreviewKind("application/pdf", 60_000_000)).toBe("none");});test("unknown binary mime types return 'none'", () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.tsindex 4d478e45dc..f6c5d3fb41 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/helpers.ts@@ -33,6 +33,18 @@ export function getFileDownloadUrl(fileId: string): string {return `/api/proxy/api/workspace/files/${encodeURIComponent(fileId)}/download`;}+export function getFilePreviewUrl(+ fileId: string,+ opts: { width?: number; bytes?: number },+): string {+ const params = new URLSearchParams();+ if (opts.width) params.set("w", String(opts.width));+ if (opts.bytes) params.set("bytes", String(opts.bytes));+ const query = params.toString();+ const base = `/api/proxy/api/workspace/files/${encodeURIComponent(fileId)}/preview`;+ return query ? `${base}?${query}` : base;+}+const BYTE_UNITS = ["B", "KB", "MB", "GB", "TB"] as const;export function formatFileSize(bytes: number): string {@@ -100,31 +112,80 @@ export function getFileTypeIcon(mimeType: string | undefined): Icon {return FileIcon;}-export type PreviewKind = "image" | "video" | "text" | "none";+export type PreviewKind =+ | "image"+ | "video"+ | "pdf"+ | "office"+ | "csv"+ | "json"+ | "ics"+ | "vcard"+ | "text"+ | "none";-const MAX_TEXT_PREVIEW_BYTES = 200_000;+// These ceilings mirror the backend preview limits exactly, so we never fire+// a preview request for a file the backend would reject (it shows an+// illustration instead). Keep in sync with PREVIEW_MAX_* in backend preview.py.const MAX_IMAGE_PREVIEW_BYTES = 10_000_000;const MAX_VIDEO_PREVIEW_BYTES = 500_000_000;+const MAX_DOC_PREVIEW_BYTES = 50_000_000;+const MAX_TEXT_PREVIEW_BYTES = 50_000_000;+// ICS/VCF are parsed whole on the client, so cap the download size.+const MAX_STRUCTURED_PREVIEW_BYTES = 110_000;++const OFFICE_MIMES = new Set([+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+]);++function isOfficeFile(mime: string, name: string): boolean {+ return (+ OFFICE_MIMES.has(mime) ||+ name.endsWith(".pptx") ||+ name.endsWith(".docx") ||+ name.endsWith(".xlsx")+ );+}export function getPreviewKind(mimeType: string | undefined,sizeBytes: number,+ fileName?: string,): PreviewKind {const mt = (mimeType ?? "").toLowerCase();- if (mt.startsWith("image/")) {+ const name = (fileName ?? "").toLowerCase();++ if (mt.startsWith("image/") && !mt.includes("svg")) {return sizeBytes > MAX_IMAGE_PREVIEW_BYTES ? "none" : "image";}if (mt.startsWith("video/")) {return sizeBytes > MAX_VIDEO_PREVIEW_BYTES ? "none" : "video";}+ if (mt === "application/pdf" || name.endsWith(".pdf")) {+ return sizeBytes > MAX_DOC_PREVIEW_BYTES ? "none" : "pdf";+ }+ if (isOfficeFile(mt, name)) {+ return sizeBytes > MAX_DOC_PREVIEW_BYTES ? "none" : "office";+ }+ if (mt.includes("calendar") || name.endsWith(".ics")) {+ return sizeBytes > MAX_STRUCTURED_PREVIEW_BYTES ? "none" : "ics";+ }+ if (mt.includes("vcard") || name.endsWith(".vcf")) {+ return sizeBytes > MAX_STRUCTURED_PREVIEW_BYTES ? "none" : "vcard";+ }++ // csv/json/text fetch only the first few KB, but still skip absurdly large+ // files to match the backend's text ceiling.if (sizeBytes > MAX_TEXT_PREVIEW_BYTES) return "none";+ if (mt.includes("csv") || name.endsWith(".csv")) return "csv";+ if (mt.includes("json") || name.endsWith(".json")) return "json";if (mt.startsWith("text/") ||mt.includes("html") ||mt.includes("xhtml") ||- mt.includes("json") ||mt.includes("xml") ||- mt.includes("csv") ||mt.includes("markdown") ||mt.includes("javascript") ||mt.includes("typescript") ||diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/parsers.test.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/parsers.test.tsnew file mode 100644index 0000000000..2ad5733fbd--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/parsers.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from "vitest";+import { parseCsv, parseIcs, parseVcard } from "./parsers";++describe("parseCsv", () => {+ it("keeps every row for a complete file (trailing newline)", () => {+ const csv = "name,age\nAlice,30\nBob,25\n";+ expect(parseCsv(csv)).toEqual({+ headers: ["name", "age"],+ rows: [+ ["Alice", "30"],+ ["Bob", "25"],+ ],+ });+ });++ it("drops the trailing partial row only when truncated mid-line", () => {+ const csv = "name,age\nAlice,30\nBo"; // no trailing newline → truncated+ expect(parseCsv(csv)).toEqual({+ headers: ["name", "age"],+ rows: [["Alice", "30"]],+ });+ });++ it("respects quoted fields containing the delimiter", () => {+ const csv = '"Doe, John",42\n"Smith, Jane",37\n';+ expect(parseCsv(csv)).toEqual({+ headers: ["Doe, John", "42"],+ rows: [["Smith, Jane", "37"]],+ });+ });++ it("unescapes doubled quotes inside quoted fields", () => {+ const csv = 'quote\n"She said ""hi"""\n';+ expect(parseCsv(csv)).toEqual({+ headers: ["quote"],+ rows: [['She said "hi"']],+ });+ });++ it("returns null for empty input", () => {+ expect(parseCsv("")).toBeNull();+ });+});++describe("parseIcs", () => {+ it("extracts event summary and times", () => {+ const ics =+ "BEGIN:VEVENT\nSUMMARY:Standup\nDTSTART:20260101T090000Z\nEND:VEVENT";+ expect(parseIcs(ics)).toMatchObject({+ summary: "Standup",+ start: "20260101T090000Z",+ });+ });+});++describe("parseVcard", () => {+ it("extracts the contact name and email", () => {+ const vcf = "BEGIN:VCARD\nFN:Jane Doe\nEMAIL:[email protected]\nEND:VCARD";+ expect(parseVcard(vcf)).toMatchObject({+ name: "Jane Doe",+ email: "[email protected]",+ });+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/parsers.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/parsers.tsnew file mode 100644index 0000000000..4dc44af129--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/parsers.ts@@ -0,0 +1,161 @@+export interface CsvPreview {+ headers: string[];+ rows: string[][];+}++const CSV_DELIMITERS = [",", ";", "\t", "|"] as const;++function sniffDelimiter(firstLine: string): string {+ let best = ",";+ let bestCount = -1;+ for (const delimiter of CSV_DELIMITERS) {+ const count = firstLine.split(delimiter).length - 1;+ if (count > bestCount) {+ best = delimiter;+ bestCount = count;+ }+ }+ return best;+}++// Quote-aware CSV field tokenizer (RFC 4180): respects quoted fields that+// contain the delimiter and "" escaped quotes. Keeps preview tables correct for+// values like `"Doe, John",42`.+function splitCsvLine(line: string, delimiter: string): string[] {+ const cells: string[] = [];+ let cell = "";+ let inQuotes = false;+ for (let i = 0; i < line.length; i++) {+ const char = line[i];+ if (inQuotes) {+ if (char === '"' && line[i + 1] === '"') {+ cell += '"';+ i++;+ } else if (char === '"') {+ inQuotes = false;+ } else {+ cell += char;+ }+ } else if (char === '"') {+ inQuotes = true;+ } else if (char === delimiter) {+ cells.push(cell);+ cell = "";+ } else {+ cell += char;+ }+ }+ cells.push(cell);+ return cells.map((value) => value.trim());+}++export function parseCsv(+ text: string,+ opts: { maxRows?: number; maxCols?: number } = {},+): CsvPreview | null {+ const maxRows = opts.maxRows ?? 6;+ const maxCols = opts.maxCols ?? 6;++ // The byte-capped fetch can cut mid-row, leaving a trailing partial line with+ // no terminating newline. Only drop the last line in that truncated case so+ // complete files keep every row.+ const truncated = text.length > 0 && !/\r?\n\s*$/.test(text);+ const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);+ if (truncated && lines.length > 1) lines.pop();+ if (lines.length === 0) return null;++ const delimiter = sniffDelimiter(lines[0]);+ const cells = lines+ .slice(0, maxRows)+ .map((line) => splitCsvLine(line, delimiter).slice(0, maxCols));++ const [headers, ...rows] = cells;+ return { headers, rows };+}++function unfold(text: string): string[] {+ // RFC 5545/6350 line folding: continuation lines start with a space or tab.+ const raw = text.split(/\r?\n/);+ const lines: string[] = [];+ for (const line of raw) {+ if ((line.startsWith(" ") || line.startsWith("\t")) && lines.length > 0) {+ lines[lines.length - 1] += line.slice(1);+ } else {+ lines.push(line);+ }+ }+ return lines;+}++function splitProperty(line: string): {+ name: string;+ params: string;+ value: string;+} {+ const colon = line.indexOf(":");+ if (colon === -1) return { name: "", params: "", value: "" };+ const head = line.slice(0, colon);+ const value = line.slice(colon + 1);+ const semi = head.indexOf(";");+ if (semi === -1) return { name: head.toUpperCase(), params: "", value };+ return {+ name: head.slice(0, semi).toUpperCase(),+ params: head.slice(semi + 1).toLowerCase(),+ value,+ };+}++export interface IcsPreview {+ summary?: string;+ start?: string;+ end?: string;+ location?: string;+}++export function parseIcs(text: string): IcsPreview | null {+ const result: IcsPreview = {};+ for (const line of unfold(text)) {+ const { name, value } = splitProperty(line);+ if (name === "SUMMARY") result.summary = value;+ else if (name === "DTSTART") result.start = value;+ else if (name === "DTEND") result.end = value;+ else if (name === "LOCATION") result.location = value;+ if (line.toUpperCase().startsWith("END:VEVENT")) break;+ }+ return result.summary || result.start ? result : null;+}++export interface VcardPreview {+ name?: string;+ org?: string;+ title?: string;+ tel?: string;+ email?: string;+ photo?: string;+}++export function parseVcard(text: string): VcardPreview | null {+ const result: VcardPreview = {};+ for (const line of unfold(text)) {+ const { name, params, value } = splitProperty(line);+ if (name === "FN") result.name = value;+ else if (name === "ORG") result.org = value.replace(/;+$/, "");+ else if (name === "TITLE") result.title = value;+ else if (name === "TEL" && !result.tel) result.tel = value;+ else if (name === "EMAIL" && !result.email) result.email = value;+ else if (name === "PHOTO" && !result.photo)+ result.photo = toPhotoSrc(params, value);+ }+ return result.name ? result : null;+}++function toPhotoSrc(params: string, value: string): string | undefined {+ if (value.startsWith("data:") || value.startsWith("http")) return value;+ // vCard 3.0: PHOTO;ENCODING=b;TYPE=JPEG:<base64>+ if (params.includes("b") || params.includes("base64")) {+ const typeMatch = params.match(/type=([a-z0-9]+)/);+ const subtype = typeMatch ? typeMatch[1] : "jpeg";+ return `data:image/${subtype};base64,${value.replace(/\s+/g, "")}`;+ }+ return undefined;+}diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsxindex a18e633e14..3b5fc2d857 100644--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx@@ -51,7 +51,7 @@ export default function ArtifactsPage() {} = useArtifactsPage();useEffect(() => {- document.title = "Artifacts – AutoGPT Platform";+ document.title = "Files – AutoGPT Platform";}, []);if (!flagReady) {@@ -73,7 +73,7 @@ export default function ArtifactsPage() {animate="show"transition={{ delay: 0 }}>- <Text variant="h3">Artifacts</Text>+ <Text variant="h3">Files</Text><Text variant="body" className="max-w-prose text-zinc-600">Every file your agents generate or use in the Builder lives here —ready to reuse, download, or share.diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 5fafb0d73b..91855bef02 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -9987,6 +9987,64 @@}}},+ "/api/workspace/files/{file_id}/preview": {+ "get": {+ "tags": ["workspace"],+ "summary": "Preview file by ID",+ "description": "Return a cheap preview of a file.\n\nImages/PDFs/Office docs are returned as a small WebP thumbnail; text-like\nfiles return only their first ``bytes`` bytes. Used by the Artifacts page so\na grid of files no longer downloads every file in full.",+ "operationId": "getWorkspaceFilePreview",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "file_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "File Id" }+ },+ {+ "name": "w",+ "in": "query",+ "required": false,+ "schema": {+ "type": "integer",+ "maximum": 1024,+ "minimum": 16,+ "default": 400,+ "title": "W"+ }+ },+ {+ "name": "bytes",+ "in": "query",+ "required": false,+ "schema": {+ "type": "integer",+ "maximum": 131072,+ "minimum": 256,+ "default": 4096,+ "title": "Bytes"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": { "application/json": { "schema": {} } }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },"/api/workspace/storage/usage": {"get": {"tags": ["workspace"],diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/Navbar.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/Navbar.tsxindex fcd600546e..c051fc6797 100644--- a/autogpt_platform/frontend/src/components/layout/Navbar/Navbar.tsx+++ b/autogpt_platform/frontend/src/components/layout/Navbar/Navbar.tsx@@ -62,7 +62,7 @@ export function Navbar() {const actualLoggedInLinks = [{ name: "Home", href: "/copilot" },{ name: "Agents", href: "/library" },- ...(isArtifactsEnabled ? [{ name: "Artifacts", href: "/artifacts" }] : []),+ ...(isArtifactsEnabled ? [{ name: "Files", href: "/artifacts" }] : []),...loggedInLinks,];