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(platform): fix Files page bugs — origin filter, code/markdown previews, viewer modal (#13304)

Abhimanyu Yadav4bfbb720c31f
diff --git a/autogpt_platform/backend/backend/api/features/workspace/preview.py b/autogpt_platform/backend/backend/api/features/workspace/preview.py
index 2895d94bc6..e577100fc2 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/preview.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/preview.py
@@ -61,6 +61,12 @@ _TEXT_HINTS = (
"markdown",
"svg",
)
+# Extension fallback for Markdown only. ``mimetypes.guess_type`` returns
+# ``None``/``application/octet-stream`` for ``.md`` on many systems, which would
+# 415 a file the Artifacts card renders as a content preview. Other text/code
+# types fall back to a static illustration on the frontend and never request a
+# preview, so they don't need an extension fallback here.
+_TEXT_EXTENSIONS = frozenset({"md", "markdown", "mdx"})
_EMBEDDED_THUMBNAILS = (
"docprops/thumbnail.jpeg",
"docprops/thumbnail.jpg",
@@ -93,7 +99,7 @@ async def _dispatch_preview(
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):
+ if _is_text_like(mime, file.name):
_ensure_size(file, PREVIEW_MAX_TEXT_BYTES)
content = await _text_preview(file, max_bytes)
return Response(
@@ -107,8 +113,11 @@ async def _dispatch_preview(
)
-def _is_text_like(mime: str) -> bool:
- return mime.startswith("text/") or any(hint in mime for hint in _TEXT_HINTS)
+def _is_text_like(mime: str, name: str = "") -> bool:
+ if mime.startswith("text/") or any(hint in mime for hint in _TEXT_HINTS):
+ return True
+ ext = name.rsplit(".", 1)[-1].lower() if "." in name else ""
+ return ext in _TEXT_EXTENSIONS
def _ensure_size(file: WorkspaceFile, limit: int) -> None:
diff --git a/autogpt_platform/backend/backend/api/features/workspace/preview_test.py b/autogpt_platform/backend/backend/api/features/workspace/preview_test.py
index 4a8584d0ee..d7892401b8 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/preview_test.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/preview_test.py
@@ -202,6 +202,27 @@ def test_text_preview_caps_bytes(mocker):
storage.retrieve_partial.assert_awaited_once_with("local://test.bin", 512)
+def test_markdown_preview_served_despite_non_text_mime(mocker):
+ # `.md` often stores as application/octet-stream (mimetypes can't guess it),
+ # but the extension fallback must still serve it as text.
+ _mock_lookups(
+ mocker,
+ _make_file(
+ name="README.md",
+ path="/README.md",
+ mime_type="application/octet-stream",
+ ),
+ )
+ storage = _mock_storage(mocker, b"# Title\n\nbody")
+ _mock_redis(mocker)
+
+ response = client.get("/files/file-001/preview?bytes=4096")
+
+ assert response.status_code == 200
+ assert response.content == b"# Title\n\nbody"
+ storage.retrieve_partial.assert_awaited_once()
+
+
def test_preview_404_when_file_missing(mocker):
mocker.patch(
"backend.api.features.workspace.routes.get_workspace",
diff --git a/autogpt_platform/backend/backend/api/features/workspace/routes.py b/autogpt_platform/backend/backend/api/features/workspace/routes.py
index bcdf87b24e..cf957ce746 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/routes.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/routes.py
@@ -149,6 +149,7 @@ class WorkspaceFileItem(BaseModel):
mime_type: str
size_bytes: int
metadata: dict = Field(default_factory=dict)
+ origin: Literal["uploaded", "generated"]
created_at: str
@@ -158,6 +159,18 @@ class ListFilesResponse(BaseModel):
has_more: bool = False
+# Exact metadata stamped on user uploads by ``upload_file``. Used to split
+# "Uploaded" vs "Generated" on the Artifacts page.
+_UPLOADED_METADATA = {"origin": "user-upload"}
+
+
+def _derive_origin(metadata: dict | None) -> Literal["uploaded", "generated"]:
+ """Classify a file as user-uploaded vs agent/block-generated."""
+ if (metadata or {}).get("origin") == "user-upload":
+ return "uploaded"
+ return "generated"
+
+
@router.get(
"/files/{file_id}/download",
summary="Download file by ID",
@@ -377,13 +390,14 @@ async def list_workspace_files(
"embedding generation."
),
),
- origin: Literal["builder", "autopilot"] | None = Query(
+ origin: Literal["uploaded", "generated"] | None = Query(
default=None,
description=(
- "Filter by upload origin. ``autopilot`` matches files stored "
- "under ``/sessions/...`` (CoPilot chat uploads); ``builder`` "
- "matches everything else. Ignored when ``session_id`` is set "
- "(session scoping already implies origin)."
+ "Filter by file origin. ``uploaded`` matches files the user "
+ "uploaded (``metadata.origin == 'user-upload'``, set by the "
+ "upload endpoint for both Builder and CoPilot uploads); "
+ "``generated`` matches everything else (agent/block output). "
+ "Ignored when ``session_id`` is set."
),
),
) -> ListFilesResponse:
@@ -395,7 +409,7 @@ async def list_workspace_files(
via `limit`/`offset`; `has_more` indicates whether additional pages exist.
The Artifacts page uses ``q`` for name search and ``origin`` to filter
- between Builder (root-level) and Autopilot (session-scoped) uploads.
+ between Uploaded (user-uploaded) and Generated (agent/block output) files.
"""
workspace = await get_or_create_workspace(user_id)
@@ -407,26 +421,29 @@ async def list_workspace_files(
manager = WorkspaceManager(user_id, workspace.id, session_id)
include_all = session_id is None
- # Origin → path filter. Only applied when not session-scoped, since
- # session_id already pins the origin.
- list_path: str | None = None
- path_not_starts_with: str | None = None
+ # Origin → metadata filter. Uploads carry an exact ``{"origin":
+ # "user-upload"}`` metadata; everything else (agent/block output, which
+ # stores ``{}`` or other metadata) is "generated". ``metadata`` is never
+ # SQL NULL (column default ``{}``), so whole-object (in)equality is
+ # null-safe. Only applied when not session-scoped.
+ metadata_equals: dict | None = None
+ metadata_not_equals: dict | None = None
if session_id is None and origin is not None:
- if origin == "autopilot":
- list_path = "/sessions/"
- else: # "builder"
- path_not_starts_with = "/sessions/"
+ if origin == "uploaded":
+ metadata_equals = _UPLOADED_METADATA
+ else: # "generated"
+ metadata_not_equals = _UPLOADED_METADATA
name_contains = (q or "").strip() or None
# Fetch one extra to compute has_more without a separate count query.
files = await manager.list_files(
- path=list_path,
limit=limit + 1,
offset=offset,
include_all_sessions=include_all,
name_contains=name_contains,
- path_not_starts_with=path_not_starts_with,
+ metadata_equals=metadata_equals,
+ metadata_not_equals=metadata_not_equals,
)
has_more = len(files) > limit
page = files[:limit]
@@ -440,6 +457,7 @@ async def list_workspace_files(
mime_type=f.mime_type,
size_bytes=f.size_bytes,
metadata=f.metadata or {},
+ origin=_derive_origin(f.metadata),
created_at=f.created_at.isoformat(),
)
for f in page
diff --git a/autogpt_platform/backend/backend/api/features/workspace/routes_test.py b/autogpt_platform/backend/backend/api/features/workspace/routes_test.py
index c0937a45d2..538b6ad04b 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/routes_test.py
@@ -104,14 +104,60 @@ def test_list_files_returns_all_when_no_session(mock_manager_cls, mock_get_works
assert data["offset"] == 0
assert data["files"][0]["id"] == "f1"
assert data["files"][0]["metadata"] == {"origin": "user-upload"}
+ assert data["files"][0]["origin"] == "uploaded"
assert data["files"][1]["id"] == "f2"
+ assert data["files"][1]["origin"] == "generated"
mock_instance.list_files.assert_called_once_with(
- path=None,
limit=201,
offset=0,
include_all_sessions=True,
name_contains=None,
- path_not_starts_with=None,
+ metadata_equals=None,
+ metadata_not_equals=None,
+ )
+
+
+@patch("backend.api.features.workspace.routes.get_or_create_workspace")
+@patch("backend.api.features.workspace.routes.WorkspaceManager")
+def test_list_files_uploaded_origin_filters_on_metadata(
+ mock_manager_cls, mock_get_workspace
+):
+ mock_get_workspace.return_value = _make_workspace()
+ mock_instance = AsyncMock()
+ mock_instance.list_files.return_value = []
+ mock_manager_cls.return_value = mock_instance
+
+ response = client.get("/files?origin=uploaded")
+ assert response.status_code == 200
+ mock_instance.list_files.assert_called_once_with(
+ limit=201,
+ offset=0,
+ include_all_sessions=True,
+ name_contains=None,
+ metadata_equals={"origin": "user-upload"},
+ metadata_not_equals=None,
+ )
+
+
+@patch("backend.api.features.workspace.routes.get_or_create_workspace")
+@patch("backend.api.features.workspace.routes.WorkspaceManager")
+def test_list_files_generated_origin_excludes_uploads(
+ mock_manager_cls, mock_get_workspace
+):
+ mock_get_workspace.return_value = _make_workspace()
+ mock_instance = AsyncMock()
+ mock_instance.list_files.return_value = []
+ mock_manager_cls.return_value = mock_instance
+
+ response = client.get("/files?origin=generated")
+ assert response.status_code == 200
+ mock_instance.list_files.assert_called_once_with(
+ limit=201,
+ offset=0,
+ include_all_sessions=True,
+ name_contains=None,
+ metadata_equals=None,
+ metadata_not_equals={"origin": "user-upload"},
)
@@ -133,12 +179,12 @@ def test_list_files_scopes_to_session_when_provided(
assert data["has_more"] is False
mock_manager_cls.assert_called_once_with(test_user_id, "ws-001", "sess-123")
mock_instance.list_files.assert_called_once_with(
- path=None,
limit=201,
offset=0,
include_all_sessions=False,
name_contains=None,
- path_not_starts_with=None,
+ metadata_equals=None,
+ metadata_not_equals=None,
)
@@ -554,12 +600,12 @@ def test_list_files_has_more_true_when_limit_exceeded(
assert data["files"][0]["id"] == "f1"
assert data["files"][1]["id"] == "f2"
mock_instance.list_files.assert_called_once_with(
- path=None,
limit=3,
offset=0,
include_all_sessions=True,
name_contains=None,
- path_not_starts_with=None,
+ metadata_equals=None,
+ metadata_not_equals=None,
)
@@ -594,58 +640,12 @@ def test_list_files_offset_is_echoed_back(mock_manager_cls, mock_get_workspace):
assert response.status_code == 200
assert response.json()["offset"] == 50
mock_instance.list_files.assert_called_once_with(
- path=None,
limit=11,
offset=50,
include_all_sessions=True,
name_contains=None,
- path_not_starts_with=None,
- )
-
-
-@patch("backend.api.features.workspace.routes.get_or_create_workspace")
-@patch("backend.api.features.workspace.routes.WorkspaceManager")
-def test_list_files_origin_autopilot_scopes_to_sessions_path(
- mock_manager_cls, mock_get_workspace
-):
- """origin=autopilot maps to path='/sessions/' on the manager call."""
- mock_get_workspace.return_value = _make_workspace()
- mock_instance = AsyncMock()
- mock_instance.list_files.return_value = []
- mock_manager_cls.return_value = mock_instance
-
- response = client.get("/files?origin=autopilot")
- assert response.status_code == 200
- mock_instance.list_files.assert_called_once_with(
- path="/sessions/",
- limit=201,
- offset=0,
- include_all_sessions=True,
- name_contains=None,
- path_not_starts_with=None,
- )
-
-
-@patch("backend.api.features.workspace.routes.get_or_create_workspace")
-@patch("backend.api.features.workspace.routes.WorkspaceManager")
-def test_list_files_origin_builder_excludes_sessions_path(
- mock_manager_cls, mock_get_workspace
-):
- """origin=builder maps to path_not_starts_with='/sessions/'."""
- mock_get_workspace.return_value = _make_workspace()
- mock_instance = AsyncMock()
- mock_instance.list_files.return_value = []
- mock_manager_cls.return_value = mock_instance
-
- response = client.get("/files?origin=builder")
- assert response.status_code == 200
- mock_instance.list_files.assert_called_once_with(
- path=None,
- limit=201,
- offset=0,
- include_all_sessions=True,
- name_contains=None,
- path_not_starts_with="/sessions/",
+ metadata_equals=None,
+ metadata_not_equals=None,
)
@@ -660,15 +660,15 @@ def test_list_files_origin_ignored_when_session_id_set(
mock_instance.list_files.return_value = []
mock_manager_cls.return_value = mock_instance
- response = client.get("/files?origin=builder&session_id=sess-123")
+ response = client.get("/files?origin=generated&session_id=sess-123")
assert response.status_code == 200
mock_instance.list_files.assert_called_once_with(
- path=None,
limit=201,
offset=0,
include_all_sessions=False,
name_contains=None,
- path_not_starts_with=None,
+ metadata_equals=None,
+ metadata_not_equals=None,
)
@@ -684,12 +684,12 @@ def test_list_files_q_search_passed_through(mock_manager_cls, mock_get_workspace
response = client.get("/files?q=report")
assert response.status_code == 200
mock_instance.list_files.assert_called_once_with(
- path=None,
limit=201,
offset=0,
include_all_sessions=True,
name_contains="report",
- path_not_starts_with=None,
+ metadata_equals=None,
+ metadata_not_equals=None,
)
@@ -705,12 +705,12 @@ def test_list_files_blank_q_becomes_none(mock_manager_cls, mock_get_workspace):
response = client.get("/files?q=%20%20%20")
assert response.status_code == 200
mock_instance.list_files.assert_called_once_with(
- path=None,
limit=201,
offset=0,
include_all_sessions=True,
name_contains=None,
- path_not_starts_with=None,
+ metadata_equals=None,
+ metadata_not_equals=None,
)
@@ -723,15 +723,15 @@ def test_list_files_q_and_origin_combine(mock_manager_cls, mock_get_workspace):
mock_instance.list_files.return_value = []
mock_manager_cls.return_value = mock_instance
- response = client.get("/files?q=report&origin=autopilot")
+ response = client.get("/files?q=report&origin=generated")
assert response.status_code == 200
mock_instance.list_files.assert_called_once_with(
- path="/sessions/",
limit=201,
offset=0,
include_all_sessions=True,
name_contains="report",
- path_not_starts_with=None,
+ metadata_equals=None,
+ metadata_not_equals={"origin": "user-upload"},
)
@@ -751,12 +751,12 @@ def test_list_files_empty_session_id_treated_as_omitted(
# Manager should be constructed with session_id=None, not ""
mock_manager_cls.assert_called_once_with(test_user_id, "ws-001", None)
mock_instance.list_files.assert_called_once_with(
- path=None,
limit=201,
offset=0,
include_all_sessions=True,
name_contains=None,
- path_not_starts_with=None,
+ metadata_equals=None,
+ metadata_not_equals=None,
)
diff --git a/autogpt_platform/backend/backend/data/workspace.py b/autogpt_platform/backend/backend/data/workspace.py
index 11a3014ea4..83f7ae65fe 100644
--- a/autogpt_platform/backend/backend/data/workspace.py
+++ b/autogpt_platform/backend/backend/data/workspace.py
@@ -256,6 +256,8 @@ async def list_workspace_files(
limit: Optional[int] = None,
offset: int = 0,
name_contains: Optional[str] = None,
+ metadata_equals: Optional[dict] = None,
+ metadata_not_equals: Optional[dict] = None,
) -> list[WorkspaceFile]:
"""
List files in a workspace.
@@ -263,15 +265,22 @@ async def list_workspace_files(
Args:
workspace_id: The workspace ID
path_prefix: Optional path prefix to filter (e.g., "/documents/")
- path_not_starts_with: Optional path prefix to *exclude* — used by
- the Artifacts page to filter out session-scoped (autopilot)
- uploads when the user picks the "Builder" origin filter.
+ path_not_starts_with: Optional path prefix to *exclude* from results.
+ Generic path filter; the Artifacts origin filter is handled
+ separately via ``metadata_equals``/``metadata_not_equals``.
include_deleted: Whether to include soft-deleted files
limit: Maximum number of files to return
offset: Number of files to skip
name_contains: Case-insensitive substring filter applied to
``name``. Used by /search/global so files are findable by
literal name match without waiting on async embedding.
+ metadata_equals: Match files whose ``metadata`` JSON equals this
+ object exactly. Used by the Artifacts page "Uploaded" filter
+ (``{"origin": "user-upload"}``).
+ metadata_not_equals: Match files whose ``metadata`` JSON does *not*
+ equal this object. Used by the "Generated" filter. ``metadata``
+ is never SQL NULL (column default ``{}``), so whole-object
+ inequality is null-safe and covers untagged/legacy files.
Returns:
List of WorkspaceFile instances
@@ -287,10 +296,20 @@ async def list_workspace_files(
path_prefix = f"/{path_prefix}"
where_clause["path"] = {"startswith": path_prefix}
+ not_clause: list[UserWorkspaceFileWhereInput] = []
if path_not_starts_with:
if not path_not_starts_with.startswith("/"):
path_not_starts_with = f"/{path_not_starts_with}"
- where_clause["NOT"] = [{"path": {"startswith": path_not_starts_with}}]
+ not_clause.append({"path": {"startswith": path_not_starts_with}})
+
+ if metadata_equals is not None:
+ where_clause["metadata"] = {"equals": SafeJson(metadata_equals)}
+
+ if metadata_not_equals is not None:
+ not_clause.append({"metadata": {"equals": SafeJson(metadata_not_equals)}})
+
+ if not_clause:
+ where_clause["NOT"] = not_clause
if name_contains:
where_clause["name"] = {"contains": name_contains, "mode": "insensitive"}
diff --git a/autogpt_platform/backend/backend/util/workspace.py b/autogpt_platform/backend/backend/util/workspace.py
index bdec9cdd3c..3346a31e7f 100644
--- a/autogpt_platform/backend/backend/util/workspace.py
+++ b/autogpt_platform/backend/backend/util/workspace.py
@@ -351,6 +351,8 @@ class WorkspaceManager:
include_all_sessions: bool = False,
name_contains: Optional[str] = None,
path_not_starts_with: Optional[str] = None,
+ metadata_equals: Optional[dict] = None,
+ metadata_not_equals: Optional[dict] = None,
) -> list[WorkspaceFile]:
"""
List files in workspace.
@@ -365,9 +367,14 @@ class WorkspaceManager:
include_all_sessions: If True, list files from all sessions.
If False (default), only list current session's files.
name_contains: Case-insensitive substring filter on the file name.
- path_not_starts_with: Path prefix to exclude from results.
- Used by the Artifacts page to surface only Builder-origin
- files (i.e. those not under ``/sessions/``).
+ path_not_starts_with: Optional path prefix to exclude from results.
+ Generic path filter; origin-based filtering for the Artifacts
+ page is handled separately via ``metadata_equals`` /
+ ``metadata_not_equals``.
+ metadata_equals: Match files whose ``metadata`` equals this object
+ exactly (Artifacts "Uploaded" filter).
+ metadata_not_equals: Match files whose ``metadata`` does not equal
+ this object (Artifacts "Generated" filter).
Returns:
List of WorkspaceFile instances
@@ -382,6 +389,8 @@ class WorkspaceManager:
limit=limit,
offset=offset,
name_contains=name_contains,
+ metadata_equals=metadata_equals,
+ metadata_not_equals=metadata_not_equals,
)
async def delete_file(self, file_id: str) -> bool:
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.tsx
index 299d0e257c..5236e36760 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
@@ -61,6 +61,7 @@ function makeFile(
mime_type: "text/plain",
size_bytes: 1024,
metadata: {},
+ origin: "generated",
created_at: "2026-05-01T00:00:00Z",
...overrides,
};
@@ -231,6 +232,27 @@ describe("ArtifactsPage - card menu", () => {
expect(await screen.findByText("menu-target.txt")).toBeDefined();
expect(screen.getByTestId("artifacts-card-menu")).toBeDefined();
});
+
+ test("clicking the card opens the file viewer modal", async () => {
+ useStorageHandler();
+ server.use(
+ getListWorkspaceFilesMockHandler({
+ files: [makeFile({ id: "open-me", name: "open-me.txt" })],
+ offset: 0,
+ has_more: false,
+ }),
+ http.get("/api/proxy/api/workspace/files/open-me/download", () =>
+ HttpResponse.text("hello world"),
+ ),
+ );
+
+ render(<ArtifactsPage />);
+
+ const opener = await screen.findByTestId("artifacts-card-open");
+ fireEvent.click(opener);
+
+ expect(await screen.findByTestId("file-viewer")).toBeDefined();
+ });
});
describe("ArtifactsPage - rich previews", () => {
@@ -350,4 +372,142 @@ describe("ArtifactsPage - rich previews", () => {
expect(await screen.findByText("Ada Lovelace")).toBeDefined();
});
+
+ test("markdown cards render their formatted content", async () => {
+ useStorageHandler();
+ server.use(
+ getListWorkspaceFilesMockHandler({
+ files: [
+ makeFile({ id: "md1", name: "notes.md", mime_type: "text/markdown" }),
+ ],
+ offset: 0,
+ has_more: false,
+ }),
+ http.get("/api/proxy/api/workspace/files/md1/preview", () =>
+ HttpResponse.text("# Heading One\n\nbody paragraph"),
+ ),
+ );
+
+ render(<ArtifactsPage />);
+
+ expect(await screen.findByText("Heading One")).toBeDefined();
+ expect(await screen.findByText("body paragraph")).toBeDefined();
+ });
+});
+
+describe("ArtifactsPage - file viewer modal", () => {
+ test("opening a markdown file shows a Source toggle that flips to Preview", async () => {
+ useStorageHandler();
+ server.use(
+ getListWorkspaceFilesMockHandler({
+ files: [
+ makeFile({ id: "md2", name: "doc.md", mime_type: "text/markdown" }),
+ ],
+ offset: 0,
+ has_more: false,
+ }),
+ http.get("/api/proxy/api/workspace/files/md2/preview", () =>
+ HttpResponse.text("# Title"),
+ ),
+ http.get("/api/proxy/api/workspace/files/md2/download", () =>
+ HttpResponse.text("# Title"),
+ ),
+ );
+
+ render(<ArtifactsPage />);
+
+ fireEvent.click(await screen.findByTestId("artifacts-card-open"));
+ expect(await screen.findByTestId("file-viewer")).toBeDefined();
+
+ const sourceButton = await screen.findByRole("button", {
+ name: /source/i,
+ });
+ fireEvent.click(sourceButton);
+
+ expect(
+ await screen.findByRole("button", { name: /preview/i }),
+ ).toBeDefined();
+ });
+
+ test("opening a non-previewable file shows the download-only message", async () => {
+ useStorageHandler();
+ server.use(
+ getListWorkspaceFilesMockHandler({
+ files: [
+ makeFile({
+ id: "zip1",
+ name: "archive.zip",
+ mime_type: "application/zip",
+ }),
+ ],
+ offset: 0,
+ has_more: false,
+ }),
+ );
+
+ render(<ArtifactsPage />);
+
+ fireEvent.click(await screen.findByTestId("artifacts-card-open"));
+
+ expect(await screen.findByText(/can't be previewed/i)).toBeDefined();
+ });
+
+ test("opening an uploaded file resolves its source ref", async () => {
+ useStorageHandler();
+ server.use(
+ getListWorkspaceFilesMockHandler({
+ files: [
+ makeFile({
+ id: "up1",
+ name: "uploaded.md",
+ mime_type: "text/markdown",
+ origin: "uploaded",
+ }),
+ ],
+ offset: 0,
+ has_more: false,
+ }),
+ http.get("/api/proxy/api/workspace/files/up1/preview", () =>
+ HttpResponse.text("# uploaded"),
+ ),
+ http.get("/api/proxy/api/workspace/files/up1/download", () =>
+ HttpResponse.text("# uploaded"),
+ ),
+ );
+
+ render(<ArtifactsPage />);
+
+ fireEvent.click(await screen.findByTestId("artifacts-card-open"));
+ expect(await screen.findByTestId("file-viewer")).toBeDefined();
+ });
+
+ test("the viewer download button recovers after a failed fetch", async () => {
+ useStorageHandler();
+ server.use(
+ getListWorkspaceFilesMockHandler({
+ files: [
+ makeFile({ id: "dl1", name: "doc.md", mime_type: "text/markdown" }),
+ ],
+ offset: 0,
+ has_more: false,
+ }),
+ http.get("/api/proxy/api/workspace/files/dl1/preview", () =>
+ HttpResponse.text("# doc"),
+ ),
+ http.get(
+ "/api/proxy/api/workspace/files/dl1/download",
+ () => new HttpResponse("nope", { status: 500 }),
+ ),
+ );
+
+ render(<ArtifactsPage />);
+
+ fireEvent.click(await screen.findByTestId("artifacts-card-open"));
+ fireEvent.click(await screen.findByTestId("file-viewer-download"));
+
+ // After the failed download settles, the button returns to its idle label.
+ expect(
+ await screen.findByRole("button", { name: /^download$/i }),
+ ).toBeDefined();
+ });
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/ArtifactCard.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/ArtifactCard.tsx
index 3acd6e48bb..d467eb0bdc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/ArtifactCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactCard/ArtifactCard.tsx
@@ -26,9 +26,9 @@ import Link from "next/link";
import { useState } from "react";
import {
deriveFileOrigin,
+ downloadFileBlob,
formatFileSize,
formatRelativeDate,
- getFileDownloadUrl,
getFileTypeIcon,
getFileTypeLabel,
} from "../helpers";
@@ -36,6 +36,7 @@ import { CardPreview } from "./CardPreview";
interface Props {
file: WorkspaceFileItem;
+ onOpen: (file: WorkspaceFileItem) => void;
}
const CARD_VARIANTS: Variants = {
@@ -54,41 +55,55 @@ const REDUCED_CARD_VARIANTS: Variants = {
show: { opacity: 1, transition: { duration: 0.2 } },
};
-export function ArtifactCard({ file }: Props) {
+export function ArtifactCard({ file, onOpen }: Props) {
const origin = deriveFileOrigin(file.path);
const goLabel = origin.kind === "session" ? "Open chat" : "Open in Builder";
- const TypeIcon = getFileTypeIcon(file.mime_type);
+ const TypeIcon = getFileTypeIcon(file.mime_type, file.name);
const reduceMotion = useReducedMotion();
return (
<motion.li
variants={reduceMotion ? REDUCED_CARD_VARIANTS : CARD_VARIANTS}
style={{ willChange: "transform, opacity, filter" }}
- className="group flex flex-col overflow-hidden rounded-2xl border border-zinc-200 bg-white transition-colors hover:border-zinc-300"
+ className="group relative flex flex-col overflow-hidden rounded-2xl border border-zinc-200 bg-white transition-colors hover:border-zinc-300"
data-testid="artifacts-list-item"
>
- <CardPreview file={file} />
- <div className="flex items-center gap-3 p-3">
- <TypeIcon
- size={20}
- weight="regular"
- className="shrink-0 text-zinc-500"
- />
- <div className="flex min-w-0 flex-1 flex-col">
- <Text
- variant="body-medium"
- className="truncate text-zinc-900"
- title={file.name}
- >
- {file.name}
- </Text>
- <Text variant="small" className="truncate text-zinc-500">
- {getFileTypeLabel(file.mime_type)} ·{" "}
- {formatFileSize(file.size_bytes)} ·{" "}
- {formatRelativeDate(file.created_at)}
- </Text>
+ {/* Full-card click target: opening the file is the primary action.
+ Sits behind the content (z-0); the content is pointer-events-none so
+ clicks fall through, except the kebab menu which re-enables them. */}
+ <button
+ type="button"
+ onClick={() => onOpen(file)}
+ aria-label={`Open ${file.name}`}
+ className="absolute inset-0 z-0 cursor-pointer"
+ data-testid="artifacts-card-open"
+ />
+ <div className="pointer-events-none relative z-10">
+ <CardPreview file={file} />
+ <div className="flex items-center gap-3 p-3">
+ <TypeIcon
+ size={20}
+ weight="regular"
+ className="shrink-0 text-zinc-500"
+ />
+ <div className="flex min-w-0 flex-1 flex-col">
+ <Text
+ variant="body-medium"
+ className="truncate text-zinc-900"
+ title={file.name}
+ >
+ {file.name}
+ </Text>
+ <Text variant="small" className="truncate text-zinc-500">
+ {getFileTypeLabel(file.mime_type, file.name)} ·{" "}
+ {formatFileSize(file.size_bytes)} ·{" "}
+ {formatRelativeDate(file.created_at)}
+ </Text>
+ </div>
+ <div className="pointer-events-auto">
+ <CardMenu file={file} goLabel={goLabel} goHref={origin.href} />
+ </div>
</div>
- <CardMenu file={file} goLabel={goLabel} goHref={origin.href} />
</div>
</motion.li>
);
@@ -130,18 +145,7 @@ function CardMenu({
if (isDownloading) return;
setIsDownloading(true);
try {
- const res = await fetch(getFileDownloadUrl(file.id));
- if (!res.ok) throw new Error(`Download failed: ${res.status}`);
- const blob = await res.blob();
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = file.name;
- document.body.appendChild(a);
- a.click();
- a.remove();
- // Defer revocation so browsers (Firefox/Edge) have time to start the download.
- setTimeout(() => URL.revokeObjectURL(url), 0);
+ await downloadFileBlob(file.id, file.name);
} catch (error) {
toast({
title: "Failed to download file",
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.tsx
index 2c7cd8528c..b4d3b1e0ab 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
@@ -6,7 +6,7 @@ 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";
+import { CsvPreview, MarkdownPreview } from "./TextPreviews";
interface Props {
file: WorkspaceFileItem;
@@ -45,13 +45,15 @@ function PreviewBody({
return <VideoPreview file={file} onError={handleError} />;
case "csv":
return <CsvPreview file={file} onError={handleError} />;
- case "json":
- return <JsonPreview file={file} onError={handleError} />;
+ case "markdown":
+ return <MarkdownPreview file={file} onError={handleError} />;
case "ics":
return <IcsPreview file={file} onError={handleError} />;
case "vcard":
return <VcardPreview file={file} onError={handleError} />;
+ // json / text / code render as a generic file card (with a language
+ // badge) — the grid is for scanning, not reading raw source.
default:
- return <TextSnippetPreview file={file} onError={handleError} />;
+ return <Fallback file={file} />;
}
}
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.tsx
index b5de1ff73f..9309a67f55 100644
--- 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.tsx
@@ -1,6 +1,8 @@
"use client";
import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+import ReactMarkdown, { type Components } from "react-markdown";
+import remarkGfm from "remark-gfm";
import { getFilePreviewUrl } from "../helpers";
import { parseCsv, type CsvPreview } from "../parsers";
import { LoadingPlaceholder, useFileText } from "./PreviewParts";
@@ -15,41 +17,74 @@ interface PreviewProps {
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,
- );
+// Fetch a larger slice and show more rows than the default so the card table
+// fills the preview area; the container clips overflow under the bottom fade.
+const CSV_PREVIEW_BYTES = 16384;
+const CSV_PREVIEW_MAX_ROWS = 20;
- if (text === null) return <LoadingPlaceholder file={file} />;
- return <pre className={preClass}>{text.slice(0, TEXT_SNIPPET_CHARS)}</pre>;
-}
-
-export function JsonPreview({ file, onError }: PreviewProps) {
+export function CsvPreview({ file, onError }: PreviewProps) {
const text = useFileText(
- getFilePreviewUrl(file.id, { bytes: 4096 }),
+ getFilePreviewUrl(file.id, { bytes: CSV_PREVIEW_BYTES }),
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;
+ const parsed = parseCsv(text, { maxRows: CSV_PREVIEW_MAX_ROWS });
+ if (!parsed) {
+ return <pre className={preClass}>{text.slice(0, TEXT_SNIPPET_CHARS)}</pre>;
}
+ return <CsvTable preview={parsed} />;
}
-export function CsvPreview({ file, onError }: PreviewProps) {
+// Compact element map so rendered markdown stays legible inside the small
+// card preview — no typography plugin is installed, so default element sizes
+// (huge h1, etc.) would overflow without these overrides.
+const MARKDOWN_COMPONENTS: Components = {
+ h1: ({ children }) => (
+ <p className="mb-1 text-[11px] font-semibold text-zinc-900">{children}</p>
+ ),
+ h2: ({ children }) => (
+ <p className="mb-1 text-[11px] font-semibold text-zinc-900">{children}</p>
+ ),
+ h3: ({ children }) => (
+ <p className="mb-0.5 text-[10px] font-semibold text-zinc-800">{children}</p>
+ ),
+ p: ({ children }) => (
+ <p className="mb-1 text-[10px] leading-[1.4] text-zinc-600">{children}</p>
+ ),
+ ul: ({ children }) => (
+ <ul className="mb-1 ml-3 list-disc text-[10px] text-zinc-600">
+ {children}
+ </ul>
+ ),
+ ol: ({ children }) => (
+ <ol className="mb-1 ml-3 list-decimal text-[10px] text-zinc-600">
+ {children}
+ </ol>
+ ),
+ li: ({ children }) => <li className="mb-0.5">{children}</li>,
+ a: ({ children }) => <span className="text-violet-600">{children}</span>,
+ code: ({ children }) => (
+ <code className="rounded bg-zinc-100 px-1 font-mono text-[9px]">
+ {children}
+ </code>
+ ),
+ pre: ({ children }) => (
+ <pre className="mb-1 overflow-hidden rounded bg-zinc-100 p-1.5 font-mono text-[9px] text-zinc-700">
+ {children}
+ </pre>
+ ),
+ blockquote: ({ children }) => (
+ <blockquote className="mb-1 border-l-2 border-zinc-200 pl-2 text-[10px] text-zinc-500">
+ {children}
+ </blockquote>
+ ),
+ hr: () => <hr className="my-1 border-zinc-100" />,
+ img: () => null,
+};
+
+export function MarkdownPreview({ file, onError }: PreviewProps) {
const text = useFileText(
getFilePreviewUrl(file.id, { bytes: 4096 }),
onError,
@@ -57,11 +92,19 @@ export function CsvPreview({ file, onError }: PreviewProps) {
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} />;
+ return (
+ <div className="relative h-full w-full overflow-hidden bg-white">
+ <div className="h-full w-full overflow-hidden p-3">
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm]}
+ components={MARKDOWN_COMPONENTS}
+ >
+ {text.slice(0, TEXT_SNIPPET_CHARS)}
+ </ReactMarkdown>
+ </div>
+ <div className="pointer-events-none absolute inset-x-0 bottom-0 h-6 bg-gradient-to-t from-white to-transparent" />
+ </div>
+ );
}
function CsvTable({ preview }: { preview: CsvPreview }) {
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.tsx
index 43a60e77df..1d0d626cad 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
@@ -6,7 +6,9 @@ import { Text } from "@/components/atoms/Text/Text";
import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";
import { motion, useReducedMotion } from "framer-motion";
import type { Variants } from "framer-motion";
+import { useState } from "react";
import { ArtifactCard } from "./ArtifactCard/ArtifactCard";
+import { FileViewerModal } from "../FileViewerModal/FileViewerModal";
import { FileTypeMarquee } from "./FileTypeMarquee";
import { LoadMoreSentinel } from "./LoadMoreSentinel";
@@ -41,6 +43,7 @@ export function ArtifactsList({
listKey,
}: Props) {
const reduceMotion = useReducedMotion();
+ const [openFile, setOpenFile] = useState<WorkspaceFileItem | null>(null);
if (isLoading) {
return (
@@ -91,7 +94,7 @@ export function ArtifactsList({
animate={reduceMotion ? undefined : "show"}
>
{files.map((file) => (
- <ArtifactCard key={file.id} file={file} />
+ <ArtifactCard key={file.id} file={file} onOpen={setOpenFile} />
))}
</motion.ul>
<LoadMoreSentinel
@@ -99,6 +102,13 @@ export function ArtifactsList({
isLoading={isLoadingMore}
onLoadMore={onLoadMore}
/>
+ {openFile ? (
+ <FileViewerModal
+ key={openFile.id}
+ file={openFile}
+ onClose={() => setOpenFile(null)}
+ />
+ ) : null}
</>
);
}
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.tsx
index 509d32fb75..940b23d22f 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
@@ -31,6 +31,13 @@ describe("pickFileTypeKey", () => {
expect(pickFileTypeKey("text/plain", "App.jsx")).toBe("react");
expect(pickFileTypeKey(undefined, "Component.tsx")).toBe("react");
});
+
+ test("detects code by extension even when the MIME is misleading", () => {
+ // `.ts` resolves to video/mp2t in the browser/OS MIME database.
+ expect(pickFileTypeKey("video/mp2t", "main.ts")).toBe("code");
+ expect(pickFileTypeKey("text/plain", "script.py")).toBe("code");
+ expect(pickFileTypeKey(undefined, "query.sql")).toBe("code");
+ });
});
describe("deriveBadgeLabel", () => {
@@ -74,6 +81,7 @@ describe("FileIllustration", () => {
"html",
"video",
"react",
+ "code",
"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.tsx
index 1136a6e410..fdf68bea7f 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
@@ -2,6 +2,7 @@
import { cn } from "@/lib/utils";
import type { ReactNode } from "react";
+import { isCodeFile } from "./helpers";
export type FileTypeKey =
| "pdf"
@@ -11,6 +12,7 @@ export type FileTypeKey =
| "html"
| "video"
| "react"
+ | "code"
| "generic";
interface FileTypeConfig {
@@ -192,6 +194,31 @@ function ReactContent() {
);
}
+function CodeContent() {
+ // Indented "code lines" with a leading angle-bracket motif — visually
+ // distinct from the flat GenericTextContent so code reads as code at a glance.
+ const lines = [
+ { pl: "", w: "w-3" },
+ { pl: "pl-2", w: "w-4" },
+ { pl: "pl-4", w: "w-2.5" },
+ { pl: "pl-4", w: "w-3.5" },
+ { pl: "pl-2", w: "w-2" },
+ { pl: "", w: "w-3" },
+ ];
+ return (
+ <div className="space-y-1.5">
+ {lines.map((line, i) => (
+ <div key={i} className={cn("flex items-center gap-1", line.pl)}>
+ <div className="font-mono text-[5px] leading-none text-zinc-900/40">
+ {i === 0 ? "<" : i === lines.length - 1 ? "/>" : "·"}
+ </div>
+ <div className={cn("h-[3px] rounded-full bg-zinc-900/20", line.w)} />
+ </div>
+ ))}
+ </div>
+ );
+}
+
export const FILE_TYPE_CONFIGS: Record<FileTypeKey, FileTypeConfig> = {
pdf: {
label: "PDF",
@@ -235,6 +262,12 @@ export const FILE_TYPE_CONFIGS: Record<FileTypeKey, FileTypeConfig> = {
badgePositionClass: "bottom-5 -right-2",
content: <ReactContent />,
},
+ code: {
+ label: "CODE",
+ cardClass: "w-20 space-y-1.5 p-2.5",
+ badgePositionClass: "bottom-5 -right-2",
+ content: <CodeContent />,
+ },
generic: {
label: "FILE",
cardClass: "w-20 space-y-3 p-3",
@@ -251,6 +284,7 @@ export const FILE_TYPE_KEYS: FileTypeKey[] = [
"html",
"video",
"react",
+ "code",
"generic",
];
@@ -261,6 +295,9 @@ export function pickFileTypeKey(
const mt = (mimeType ?? "").toLowerCase();
const name = (fileName ?? "").toLowerCase();
if (name.endsWith(".jsx") || name.endsWith(".tsx")) return "react";
+ // Extension-first for code: `.ts` resolves to `video/mp2t`, so a MIME-first
+ // check would render TypeScript as a video.
+ if (isCodeFile(name)) return "code";
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.ts
index c71ff1c670..3aa62cda29 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
@@ -2,12 +2,15 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
deriveFileOrigin,
+ downloadFileBlob,
formatFileSize,
formatRelativeDate,
getFileDownloadUrl,
+ getFilePreviewUrl,
getFileTypeIcon,
getFileTypeLabel,
getPreviewKind,
+ isCodeFile,
} from "./helpers";
describe("deriveFileOrigin", () => {
@@ -58,6 +61,70 @@ describe("getFileDownloadUrl", () => {
});
});
+describe("getFilePreviewUrl", () => {
+ test("returns the base url with no query when no opts are given", () => {
+ expect(getFilePreviewUrl("f1", {})).toBe(
+ "/api/proxy/api/workspace/files/f1/preview",
+ );
+ });
+
+ test("adds the width param", () => {
+ expect(getFilePreviewUrl("f1", { width: 400 })).toBe(
+ "/api/proxy/api/workspace/files/f1/preview?w=400",
+ );
+ });
+
+ test("adds the bytes param", () => {
+ expect(getFilePreviewUrl("f1", { bytes: 4096 })).toBe(
+ "/api/proxy/api/workspace/files/f1/preview?bytes=4096",
+ );
+ });
+
+ test("combines width and bytes and url-encodes the id", () => {
+ expect(getFilePreviewUrl("a b", { width: 400, bytes: 4096 })).toBe(
+ "/api/proxy/api/workspace/files/a%20b/preview?w=400&bytes=4096",
+ );
+ });
+});
+
+describe("downloadFileBlob", () => {
+ const realCreate = URL.createObjectURL;
+ const realRevoke = URL.revokeObjectURL;
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ URL.createObjectURL = realCreate;
+ URL.revokeObjectURL = realRevoke;
+ });
+
+ test("fetches the download url and triggers an anchor click", async () => {
+ URL.createObjectURL = vi.fn(() => "blob:mock");
+ URL.revokeObjectURL = vi.fn();
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue(new Response(new Blob(["hi"]), { status: 200 }));
+ const clickSpy = vi
+ .spyOn(HTMLAnchorElement.prototype, "click")
+ .mockImplementation(() => {});
+
+ await downloadFileBlob("file 1", "out.txt");
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/api/proxy/api/workspace/files/file%201/download",
+ );
+ expect(clickSpy).toHaveBeenCalled();
+ expect(URL.createObjectURL).toHaveBeenCalled();
+ });
+
+ test("throws when the response is not ok", async () => {
+ vi.spyOn(globalThis, "fetch").mockResolvedValue(
+ new Response("nope", { status: 404 }),
+ );
+
+ await expect(downloadFileBlob("f", "n")).rejects.toThrow(/404/);
+ });
+});
+
describe("formatFileSize", () => {
test.each([
[0, "0 B"],
@@ -181,7 +248,6 @@ describe("getPreviewKind", () => {
"text/plain",
"text/html",
"application/xml",
- "text/markdown",
"application/javascript",
"application/typescript",
"application/yaml",
@@ -189,6 +255,14 @@ describe("getPreviewKind", () => {
expect(getPreviewKind(mt, 1_000)).toBe("text");
});
+ test("markdown previews as 'markdown' so the card renders its content", () => {
+ expect(getPreviewKind("text/markdown", 1_000)).toBe("markdown");
+ expect(getPreviewKind("text/plain", 1_000, "README.md")).toBe("markdown");
+ expect(getPreviewKind("application/octet-stream", 1_000, "notes.mdx")).toBe(
+ "markdown",
+ );
+ });
+
test("csv previews as 'csv'", () => {
expect(getPreviewKind("text/csv", 1_000)).toBe("csv");
expect(getPreviewKind("text/plain", 1_000, "data.csv")).toBe("csv");
@@ -251,3 +325,30 @@ describe("getPreviewKind", () => {
expect(getPreviewKind(undefined, 100)).toBe("none");
});
});
+
+describe("source code files (`.ts` → video/mp2t MIME)", () => {
+ test("isCodeFile matches code extensions, not media", () => {
+ expect(isCodeFile("main.ts")).toBe(true);
+ expect(isCodeFile("App.tsx")).toBe(true);
+ expect(isCodeFile("script.py")).toBe(true);
+ expect(isCodeFile("style.css")).toBe(true);
+ expect(isCodeFile("clip.mp4")).toBe(false);
+ expect(isCodeFile("photo.png")).toBe(false);
+ expect(isCodeFile("notes.txt")).toBe(false);
+ expect(isCodeFile(undefined)).toBe(false);
+ });
+
+ test("a .ts file with video/mp2t MIME previews as text, not video", () => {
+ expect(getPreviewKind("video/mp2t", 1_000, "main.ts")).toBe("text");
+ });
+
+ test("a .ts file labels as Code, not Video", () => {
+ expect(getFileTypeLabel("video/mp2t", "main.ts")).toBe("Code");
+ });
+
+ test("a .ts file uses the code icon, not the video-camera icon", () => {
+ const codeIcon = getFileTypeIcon("video/mp2t", "main.ts");
+ const videoIcon = getFileTypeIcon("video/mp4", "clip.mp4");
+ expect(codeIcon).not.toBe(videoIcon);
+ });
+});
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.ts
index f6c5d3fb41..9b9157ad2a 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,27 @@ export function getFileDownloadUrl(fileId: string): string {
return `/api/proxy/api/workspace/files/${encodeURIComponent(fileId)}/download`;
}
+// Fetches the file as a blob and triggers a browser download. Throws on a
+// non-OK response so callers can surface the error (toast) and toggle their
+// own loading state.
+export async function downloadFileBlob(
+ fileId: string,
+ fileName: string,
+): Promise<void> {
+ const res = await fetch(getFileDownloadUrl(fileId));
+ if (!res.ok) throw new Error(`Download failed: ${res.status}`);
+ const blob = await res.blob();
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = fileName;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ // Defer revocation so browsers (Firefox/Edge) have time to start the download.
+ setTimeout(() => URL.revokeObjectURL(url), 0);
+}
+
export function getFilePreviewUrl(
fileId: string,
opts: { width?: number; bytes?: number },
@@ -79,7 +100,65 @@ export function formatRelativeDate(input: string | Date): string {
});
}
-export function getFileTypeLabel(mimeType: string | undefined): string {
+// Source-code extensions whose MIME type is ambiguous or actively misleading
+// in the browser/OS database — most notably `.ts`, which resolves to
+// `video/mp2t` (MPEG transport stream) and would otherwise render as a video.
+// Classifying these by extension keeps source files out of the media path.
+// Mirrors the copilot ArtifactPanel classifier, which is also extension-first.
+const CODE_EXTENSIONS = new Set([
+ "ts",
+ "tsx",
+ "js",
+ "jsx",
+ "mjs",
+ "cjs",
+ "mts",
+ "cts",
+ "py",
+ "rb",
+ "go",
+ "rs",
+ "java",
+ "kt",
+ "kts",
+ "c",
+ "h",
+ "cpp",
+ "cc",
+ "hpp",
+ "cs",
+ "php",
+ "swift",
+ "scala",
+ "sh",
+ "bash",
+ "zsh",
+ "css",
+ "scss",
+ "sass",
+ "less",
+ "sql",
+ "yaml",
+ "yml",
+ "toml",
+ "ini",
+ "vue",
+ "svelte",
+ "dart",
+ "lua",
+ "r",
+]);
+
+export function isCodeFile(fileName: string | undefined): boolean {
+ const ext = (fileName ?? "").toLowerCase().match(/\.([a-z0-9]+)$/);
+ return ext ? CODE_EXTENSIONS.has(ext[1]) : false;
+}
+
+export function getFileTypeLabel(
+ mimeType: string | undefined,
+ fileName?: string,
+): string {
+ if (isCodeFile(fileName)) return "Code";
const mt = (mimeType ?? "").toLowerCase();
if (mt.startsWith("image/")) return "Image";
if (mt.startsWith("video/")) return "Video";
@@ -94,7 +173,11 @@ export function getFileTypeLabel(mimeType: string | undefined): string {
return "Generated file";
}
-export function getFileTypeIcon(mimeType: string | undefined): Icon {
+export function getFileTypeIcon(
+ mimeType: string | undefined,
+ fileName?: string,
+): Icon {
+ if (isCodeFile(fileName)) return CodeIcon;
const mt = (mimeType ?? "").toLowerCase();
if (mt.startsWith("image/")) return ImageIcon;
if (mt.startsWith("video/")) return VideoCameraIcon;
@@ -119,6 +202,7 @@ export type PreviewKind =
| "office"
| "csv"
| "json"
+ | "markdown"
| "ics"
| "vcard"
| "text"
@@ -157,6 +241,12 @@ export function getPreviewKind(
const mt = (mimeType ?? "").toLowerCase();
const name = (fileName ?? "").toLowerCase();
+ // Extension-first for source code: `.ts` & friends carry misleading MIME
+ // types (e.g. `video/mp2t`). Render them as a generic file card, not media.
+ if (isCodeFile(name)) {
+ return sizeBytes > MAX_TEXT_PREVIEW_BYTES ? "none" : "text";
+ }
+
if (mt.startsWith("image/") && !mt.includes("svg")) {
return sizeBytes > MAX_IMAGE_PREVIEW_BYTES ? "none" : "image";
}
@@ -181,12 +271,19 @@ export function getPreviewKind(
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.includes("markdown") ||
+ name.endsWith(".md") ||
+ name.endsWith(".markdown") ||
+ name.endsWith(".mdx")
+ ) {
+ return "markdown";
+ }
if (
mt.startsWith("text/") ||
mt.includes("html") ||
mt.includes("xhtml") ||
mt.includes("xml") ||
- mt.includes("markdown") ||
mt.includes("javascript") ||
mt.includes("typescript") ||
mt.includes("yaml")
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/FileViewerModal/FileViewerModal.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/FileViewerModal/FileViewerModal.tsx
new file mode 100644
index 0000000000..e095780e67
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/FileViewerModal/FileViewerModal.tsx
@@ -0,0 +1,181 @@
+"use client";
+
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+import { ArtifactContent } from "@/app/(platform)/copilot/components/ArtifactPanel/components/ArtifactContent";
+import { classifyArtifact } from "@/app/(platform)/copilot/components/ArtifactPanel/helpers";
+import type { ArtifactRef } from "@/app/(platform)/copilot/store";
+import { Button } from "@/components/atoms/Button/Button";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import { CodeIcon, DownloadSimpleIcon, EyeIcon } from "@phosphor-icons/react";
+import { useState } from "react";
+import { downloadFileBlob, getFileDownloadUrl } from "../ArtifactsList/helpers";
+
+interface Props {
+ file: WorkspaceFileItem | null;
+ onClose: () => void;
+}
+
+const VIEWER_STYLING = {
+ width: "90vw",
+ maxWidth: "1100px",
+ height: "85vh",
+ padding: "1rem",
+};
+
+export function FileViewerModal({ file, onClose }: Props) {
+ // Parent conditionally renders this and keys it by file id, so each open
+ // mounts a fresh instance and per-file view state starts at preview.
+ const [isSourceView, setIsSourceView] = useState(false);
+
+ if (!file) return null;
+
+ const classification = classifyArtifact(
+ file.mime_type ?? null,
+ file.name,
+ file.size_bytes,
+ );
+ const artifact = toArtifactRef(file);
+
+ return (
+ <Dialog
+ controlled={{
+ isOpen: true,
+ set: (open) => {
+ if (!open) onClose();
+ },
+ }}
+ styling={VIEWER_STYLING}
+ title={
+ <Header
+ name={file.name}
+ fileId={file.id}
+ showSourceToggle={classification.hasSourceToggle}
+ isSourceView={isSourceView}
+ onToggleSource={() => setIsSourceView((v) => !v)}
+ />
+ }
+ >
+ <Dialog.Content>
+ <div className="flex h-full min-h-0 flex-col" data-testid="file-viewer">
+ {classification.openable ? (
+ <ArtifactContent
+ artifact={artifact}
+ isSourceView={isSourceView}
+ classification={classification}
+ />
+ ) : (
+ <DownloadOnly
+ name={file.name}
+ downloadUrl={getFileDownloadUrl(file.id)}
+ />
+ )}
+ </div>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
+
+interface HeaderProps {
+ name: string;
+ fileId: string;
+ showSourceToggle: boolean;
+ isSourceView: boolean;
+ onToggleSource: () => void;
+}
+
+function Header({
+ name,
+ fileId,
+ showSourceToggle,
+ isSourceView,
+ onToggleSource,
+}: HeaderProps) {
+ const { toast } = useToast();
+ const [isDownloading, setIsDownloading] = useState(false);
+
+ async function handleDownload() {
+ if (isDownloading) return;
+ setIsDownloading(true);
+ try {
+ await downloadFileBlob(fileId, name);
+ } catch (error) {
+ toast({
+ title: "Failed to download file",
+ description:
+ error instanceof Error ? error.message : "Please try again.",
+ variant: "destructive",
+ });
+ } finally {
+ setIsDownloading(false);
+ }
+ }
+
+ return (
+ // pr-12 leaves room for the Dialog's absolute close button.
+ <div className="flex w-full flex-col gap-2 pr-12">
+ <span className="min-w-0 truncate text-base font-medium text-zinc-900">
+ {name}
+ </span>
+ <div className="flex items-center gap-2">
+ {showSourceToggle ? (
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={onToggleSource}
+ leftIcon={
+ isSourceView ? <EyeIcon size={14} /> : <CodeIcon size={14} />
+ }
+ >
+ {isSourceView ? "Preview" : "Source"}
+ </Button>
+ ) : null}
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={handleDownload}
+ loading={isDownloading}
+ leftIcon={<DownloadSimpleIcon size={14} />}
+ data-testid="file-viewer-download"
+ >
+ {isDownloading ? "Downloading…" : "Download"}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function DownloadOnly({
+ name,
+ downloadUrl,
+}: {
+ name: string;
+ downloadUrl: string;
+}) {
+ return (
+ <div className="flex h-full flex-col items-center justify-center gap-3 text-center">
+ <p className="text-sm text-zinc-500">
+ This file type can&apos;t be previewed.
+ </p>
+ <a
+ href={downloadUrl}
+ download={name}
+ className="inline-flex items-center gap-1.5 rounded-md border border-zinc-200 bg-white px-3 py-1.5 text-sm font-medium text-zinc-700 transition-colors hover:bg-zinc-50"
+ >
+ <DownloadSimpleIcon size={16} />
+ Download
+ </a>
+ </div>
+ );
+}
+
+function toArtifactRef(file: WorkspaceFileItem): ArtifactRef {
+ return {
+ id: file.id,
+ title: file.name,
+ mimeType: file.mime_type ?? null,
+ sourceUrl: getFileDownloadUrl(file.id),
+ origin: file.origin === "uploaded" ? "user-upload" : "agent",
+ sizeBytes: file.size_bytes,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/OriginFilter/OriginFilter.stories.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/OriginFilter/OriginFilter.stories.tsx
index e608b0b62b..5616f3f4c8 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/OriginFilter/OriginFilter.stories.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/OriginFilter/OriginFilter.stories.tsx
@@ -15,14 +15,14 @@ const meta: Meta<typeof OriginFilter> = {
"Segmented pill filter for the Artifacts page. The active pill " +
"slides between options via Framer Motion's shared `layoutId`. " +
"Drives the `origin` query param on `useListWorkspaceFiles` " +
- "(builder vs autopilot, all = no filter).",
+ "(uploaded vs generated, all = no filter).",
},
},
},
argTypes: {
value: {
control: { type: "radio" },
- options: ["all", "builder", "autopilot"] satisfies OriginFilterValue[],
+ options: ["all", "uploaded", "generated"] satisfies OriginFilterValue[],
description: "Currently selected origin filter.",
},
onChange: {
@@ -39,12 +39,12 @@ export const All: Story = {
args: { value: "all" },
};
-export const Builder: Story = {
- args: { value: "builder" },
+export const Uploaded: Story = {
+ args: { value: "uploaded" },
};
-export const Autopilot: Story = {
- args: { value: "autopilot" },
+export const Generated: Story = {
+ args: { value: "generated" },
};
export const Interactive: Story = {
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/OriginFilter/OriginFilter.test.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/OriginFilter/OriginFilter.test.tsx
index a3fda433c9..6dd15b25ab 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/OriginFilter/OriginFilter.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/OriginFilter/OriginFilter.test.tsx
@@ -7,29 +7,29 @@ describe("OriginFilter", () => {
test("renders all three tabs", () => {
render(<OriginFilter value="all" onChange={() => {}} />);
expect(screen.getByRole("tab", { name: /all/i })).toBeDefined();
- expect(screen.getByRole("tab", { name: /builder/i })).toBeDefined();
- expect(screen.getByRole("tab", { name: /autopilot/i })).toBeDefined();
+ expect(screen.getByRole("tab", { name: /uploaded/i })).toBeDefined();
+ expect(screen.getByRole("tab", { name: /generated/i })).toBeDefined();
});
test("marks the active tab as aria-selected", () => {
- render(<OriginFilter value="builder" onChange={() => {}} />);
- const builder = screen.getByRole("tab", { name: /builder/i });
+ render(<OriginFilter value="uploaded" onChange={() => {}} />);
+ const uploaded = screen.getByRole("tab", { name: /uploaded/i });
const all = screen.getByRole("tab", { name: /all/i });
- expect(builder.getAttribute("aria-selected")).toBe("true");
+ expect(uploaded.getAttribute("aria-selected")).toBe("true");
expect(all.getAttribute("aria-selected")).toBe("false");
});
test("clicking a tab forwards the value to onChange", () => {
const onChange = vi.fn();
render(<OriginFilter value="all" onChange={onChange} />);
- fireEvent.click(screen.getByRole("tab", { name: /autopilot/i }));
- expect(onChange).toHaveBeenCalledWith("autopilot");
+ fireEvent.click(screen.getByRole("tab", { name: /generated/i }));
+ expect(onChange).toHaveBeenCalledWith("generated");
});
test("clicking the already-active tab still fires onChange (caller decides)", () => {
const onChange = vi.fn();
- render(<OriginFilter value="builder" onChange={onChange} />);
- fireEvent.click(screen.getByRole("tab", { name: /builder/i }));
- expect(onChange).toHaveBeenCalledWith("builder");
+ render(<OriginFilter value="uploaded" onChange={onChange} />);
+ fireEvent.click(screen.getByRole("tab", { name: /uploaded/i }));
+ expect(onChange).toHaveBeenCalledWith("uploaded");
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/OriginFilter/OriginFilter.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/OriginFilter/OriginFilter.tsx
index ca6fa20a38..14204a4a94 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/OriginFilter/OriginFilter.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/OriginFilter/OriginFilter.tsx
@@ -2,9 +2,9 @@
import { cn } from "@/lib/utils";
import {
- HouseLineIcon,
ListBulletsIcon,
SparkleIcon,
+ UploadSimpleIcon,
type Icon,
} from "@phosphor-icons/react";
import { LayoutGroup, motion, type Transition } from "framer-motion";
@@ -23,8 +23,8 @@ interface Option {
const OPTIONS: Option[] = [
{ value: "all", label: "All", Icon: ListBulletsIcon },
- { value: "builder", label: "Builder", Icon: HouseLineIcon },
- { value: "autopilot", label: "Autopilot", Icon: SparkleIcon },
+ { value: "uploaded", label: "Uploaded", Icon: UploadSimpleIcon },
+ { value: "generated", label: "Generated", Icon: SparkleIcon },
];
const snappySpring: Transition = {
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts
index c6c3ac7738..56df6010e2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts
@@ -1,13 +1,9 @@
import { useEffect, useState } from "react";
import { listWorkspaceFiles } from "@/app/api/__generated__/endpoints/workspace/workspace";
import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
-import {
- type InfiniteData,
- keepPreviousData,
- useInfiniteQuery,
-} from "@tanstack/react-query";
+import { type InfiniteData, useInfiniteQuery } from "@tanstack/react-query";
-export type OriginFilter = "all" | "builder" | "autopilot";
+export type OriginFilter = "all" | "uploaded" | "generated";
const SEARCH_DEBOUNCE_MS = 250;
const ARTIFACTS_PAGE_SIZE = 50;
@@ -46,7 +42,10 @@ export function useArtifactsPage() {
if (!lastPage.data.has_more) return undefined;
return countLoadedFiles(allPages);
},
- placeholderData: keepPreviousData,
+ // No keepPreviousData: switching tabs/search must not flash the previous
+ // filter's files. Without it, an uncached filter shows the loading
+ // skeleton (isLoading) until its real results arrive; a cached filter
+ // still renders instantly from cache.
});
return {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
index 8e2670b662..808cabe5b8 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx
@@ -27,6 +27,7 @@ import {
CircleNotch,
DotsThree,
DownloadSimpleIcon,
+ FilesIcon,
MagnifyingGlassIcon,
PencilSimpleIcon,
PlusCircleIcon,
@@ -65,6 +66,7 @@ export function ChatSidebar() {
setSearchOpen,
} = useCopilotUIStore();
const isChatSearchEnabled = useGetFlag(Flag.CHAT_SEARCH);
+ const isArtifactsEnabled = useGetFlag(Flag.ARTIFACTS_PAGE);
const router = useRouter();
const sessionNeedsReload = useCopilotChatRuntimeStore(
(state) => state.sessionNeedsReload,
@@ -334,6 +336,18 @@ export function ChatSidebar() {
<MagnifyingGlassIcon className="!size-5" />
</ShadcnButton>
) : null}
+ {isArtifactsEnabled ? (
+ <ShadcnButton
+ type="button"
+ variant="ghost"
+ size="icon-sm"
+ aria-label="Files"
+ onClick={() => router.push("/artifacts")}
+ className="rounded-full text-zinc-600 hover:bg-zinc-100"
+ >
+ <FilesIcon className="!size-5" />
+ </ShadcnButton>
+ ) : null}
<UsagePopover />
<NotificationToggle />
<SidebarTrigger />
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 72e4042270..95dc757c69 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -10900,7 +10900,7 @@
"get": {
"tags": ["workspace"],
"summary": "List workspace files",
- "description": "List files in the user's workspace.\n\nWhen session_id is provided, only files for that session are returned.\nOtherwise, all files across sessions are listed. Results are paginated\nvia `limit`/`offset`; `has_more` indicates whether additional pages exist.\n\nThe Artifacts page uses ``q`` for name search and ``origin`` to filter\nbetween Builder (root-level) and Autopilot (session-scoped) uploads.",
+ "description": "List files in the user's workspace.\n\nWhen session_id is provided, only files for that session are returned.\nOtherwise, all files across sessions are listed. Results are paginated\nvia `limit`/`offset`; `has_more` indicates whether additional pages exist.\n\nThe Artifacts page uses ``q`` for name search and ``origin`` to filter\nbetween Uploaded (user-uploaded) and Generated (agent/block output) files.",
"operationId": "listWorkspaceFiles",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -10953,13 +10953,13 @@
"required": false,
"schema": {
"anyOf": [
- { "enum": ["builder", "autopilot"], "type": "string" },
+ { "enum": ["uploaded", "generated"], "type": "string" },
{ "type": "null" }
],
- "description": "Filter by upload origin. ``autopilot`` matches files stored under ``/sessions/...`` (CoPilot chat uploads); ``builder`` matches everything else. Ignored when ``session_id`` is set (session scoping already implies origin).",
+ "description": "Filter by file origin. ``uploaded`` matches files the user uploaded (``metadata.origin == 'user-upload'``, set by the upload endpoint for both Builder and CoPilot uploads); ``generated`` matches everything else (agent/block output). Ignored when ``session_id`` is set.",
"title": "Origin"
},
- "description": "Filter by upload origin. ``autopilot`` matches files stored under ``/sessions/...`` (CoPilot chat uploads); ``builder`` matches everything else. Ignored when ``session_id`` is set (session scoping already implies origin)."
+ "description": "Filter by file origin. ``uploaded`` matches files the user uploaded (``metadata.origin == 'user-upload'``, set by the upload endpoint for both Builder and CoPilot uploads); ``generated`` matches everything else (agent/block output). Ignored when ``session_id`` is set."
}
],
"responses": {
@@ -22545,6 +22545,11 @@
"type": "object",
"title": "Metadata"
},
+ "origin": {
+ "type": "string",
+ "enum": ["uploaded", "generated"],
+ "title": "Origin"
+ },
"created_at": { "type": "string", "title": "Created At" }
},
"type": "object",
@@ -22554,6 +22559,7 @@
"path",
"mime_type",
"size_bytes",
+ "origin",
"created_at"
],
"title": "WorkspaceFileItem"
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/Navbar.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/Navbar.tsx
index c051fc6797..dc0385f040 100644
--- a/autogpt_platform/frontend/src/components/layout/Navbar/Navbar.tsx
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/Navbar.tsx
@@ -10,7 +10,6 @@ import { NAVBAR_HEIGHT_PX } from "@/lib/constants";
import { useBreakpoint } from "@/lib/hooks/useBreakpoint";
import { useSupabase } from "@/lib/supabase/hooks/useSupabase";
import { environment } from "@/services/environment";
-import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { AccountMenu } from "./components/AccountMenu/AccountMenu";
import { FeedbackButton } from "./components/FeedbackButton";
import { AgentActivityDropdown } from "./components/AgentActivityDropdown/AgentActivityDropdown";
@@ -26,7 +25,6 @@ const MOBILE_NAV_ICONS: Readonly<Record<string, IconType>> = {
"/build": IconType.Builder,
"/copilot": IconType.Chat,
"/library": IconType.Library,
- "/artifacts": IconType.UploadCloud,
"/monitor": IconType.Library,
};
@@ -57,12 +55,11 @@ export function Navbar() {
const shouldShowPreviewBanner = Boolean(isLoggedIn && previewBranchName);
- const isArtifactsEnabled = useGetFlag(Flag.ARTIFACTS_PAGE);
-
+ // Files is reached via the icon in the CoPilot sidebar (gated by
+ // ARTIFACTS_PAGE), not the top nav — it's an entry point, not a product.
const actualLoggedInLinks = [
{ name: "Home", href: "/copilot" },
{ name: "Agents", href: "/library" },
- ...(isArtifactsEnabled ? [{ name: "Files", href: "/artifacts" }] : []),
...loggedInLinks,
];
diff --git a/autogpt_platform/frontend/src/components/layout/Navbar/components/NavbarLink.tsx b/autogpt_platform/frontend/src/components/layout/Navbar/components/NavbarLink.tsx
index 18ec893c8e..59913cdd75 100644
--- a/autogpt_platform/frontend/src/components/layout/Navbar/components/NavbarLink.tsx
+++ b/autogpt_platform/frontend/src/components/layout/Navbar/components/NavbarLink.tsx
@@ -2,8 +2,7 @@
import { cn } from "@/lib/utils";
import {
- FilesIcon,
- Laptop,
+ Laptop as LaptopIcon,
ListChecksIcon,
} from "@phosphor-icons/react/dist/ssr";
import Link from "next/link";
@@ -61,7 +60,7 @@ export function NavbarLink({ name, href }: Props) {
</div>
)}
{href === "/monitor" && (
- <Laptop
+ <LaptopIcon
className={cn(
iconBaseClass,
isActive && "text-white dark:text-black",
@@ -86,14 +85,6 @@ export function NavbarLink({ name, href }: Props) {
)}
/>
)}
- {href === "/artifacts" && (
- <FilesIcon
- className={cn(
- "h-5 w-5 shrink-0",
- isActive && "text-white dark:text-black",
- )}
- />
- )}
<Text
variant="h5"
className={cn(