Skip to content

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

fix(backend): keep each expert's workspace files separate from other experts (#14426)

Ubbeb870314777ab
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 32090bd534..80d37c0565 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -59,6 +59,7 @@ from backend.copilot.pending_message_helpers import (
StreamRegistryUnavailable,
is_turn_in_flight,
queue_pending_for_http,
+ resolve_attachments_for_http,
)
from backend.copilot.pending_messages import (
clear_pending_messages_unsafe,
@@ -143,7 +144,7 @@ from backend.copilot.transports import (
from backend.data.credit import UsageTransactionMetadata, get_user_credit_model
from backend.data.redis_client import get_redis_async
from backend.data.understanding import get_business_understanding
-from backend.data.workspace import build_files_block, resolve_workspace_files
+from backend.data.workspace import build_files_block
from backend.integrations.codex.access import enforce_codex_access_http
from backend.util.background import spawn_background_task
from backend.util.exceptions import InsufficientBalanceError, NotFoundError
@@ -1669,6 +1670,7 @@ async def stream_chat_post(
message=message,
context=request.context,
file_ids=request.file_ids,
+ expert_id=session.expert_id,
)
return _empty_ui_message_stream_response()
except HTTPException as exc:
@@ -1727,9 +1729,16 @@ async def stream_chat_post(
# Enrich message with file metadata if file_ids are provided.
# Also sanitise file_ids so only validated, workspace-scoped IDs are
# forwarded downstream (e.g. to the executor via enqueue_copilot_turn).
+ # Expert sessions may only attach files from the expert's own
+ # conversations; anything else is a 400 rather than a silent drop.
sanitized_file_ids: list[str] | None = None
if request.file_ids:
- files = await resolve_workspace_files(user_id, request.file_ids)
+ files = await resolve_attachments_for_http(
+ user_id,
+ request.file_ids,
+ session_id=session_id,
+ expert_id=session.expert_id,
+ )
sanitized_file_ids = [wf.id for wf in files] or None
message += build_files_block(files)
@@ -2009,6 +2018,7 @@ async def queue_pending_message(
message=request.message,
context=request.context,
file_ids=request.file_ids,
+ expert_id=session.expert_id,
)
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
index 186ad1cfd1..aa8da7c7ca 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
@@ -1,6 +1,7 @@
"""Tests for chat API routes: session title update, file attachment validation, usage, and rate limiting."""
from datetime import UTC, datetime, timedelta
+from types import SimpleNamespace
from typing import get_args
from unittest.mock import AsyncMock, MagicMock
@@ -18,6 +19,7 @@ from backend.copilot.offers import EntitlementUnavailable
from backend.copilot.rate_limit import SubscriptionTier
from backend.copilot.tools.models import ExpertSoulUpdatedResponse
from backend.data.model import OAuth2Credentials
+from backend.data.workspace_scope import WorkspaceScope
from backend.integrations.codex.auth_bundle import (
CodexAuthBundleV1,
CodexAuthTokensV1,
@@ -718,6 +720,84 @@ def test_file_ids_scoped_to_workspace(mocker: pytest_mock.MockerFixture):
assert call_kwargs["where"]["isDeleted"] is False
+# ─── Expert sessions: attachments stay inside the expert's scope ────────
+
+ATTACHED_FILE_ID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
+
+
+def _workspace_file(path: str) -> SimpleNamespace:
+ return SimpleNamespace(
+ id=ATTACHED_FILE_ID,
+ name=path.rsplit("/", 1)[-1],
+ path=path,
+ mimeType="text/plain",
+ sizeBytes=1024,
+ )
+
+
+def _mock_attached_files(mocker: pytest_mock.MockerFixture, path: str) -> AsyncMock:
+ mocker.patch(
+ "backend.data.workspace.resolve_workspace_files",
+ new=AsyncMock(return_value=[_workspace_file(path)]),
+ )
+ return mocker.patch(
+ "backend.data.workspace.resolve_expert_workspace_scope",
+ new=AsyncMock(
+ return_value=WorkspaceScope(expert_id="expert-a", session_ids=["older"])
+ ),
+ )
+
+
+def test_expert_session_rejects_files_outside_its_scope(
+ mocker: pytest_mock.MockerFixture,
+):
+ mocks = _mock_stream_internals(mocker)
+ mocks.session.expert_id = "expert-a"
+ _mock_attached_files(mocker, "/sessions/other-expert/secret.txt")
+
+ response = client.post(
+ "/sessions/sess-1/stream",
+ json={"message": "hi", "file_ids": [ATTACHED_FILE_ID]},
+ )
+
+ assert response.status_code == 400
+ assert "secret.txt" in response.json()["detail"]
+ mocks.enqueue.assert_not_awaited()
+
+
+def test_expert_session_accepts_files_from_its_own_conversations(
+ mocker: pytest_mock.MockerFixture,
+):
+ mocks = _mock_stream_internals(mocker)
+ mocks.session.expert_id = "expert-a"
+ scope_mock = _mock_attached_files(mocker, "/sessions/sess-1/notes.txt")
+
+ response = client.post(
+ "/sessions/sess-1/stream",
+ json={"message": "hi", "file_ids": [ATTACHED_FILE_ID]},
+ )
+
+ assert response.status_code == 200
+ scope_mock.assert_awaited_once_with(TEST_USER_ID, "expert-a")
+ assert mocks.enqueue.await_args.kwargs["file_ids"] == [ATTACHED_FILE_ID]
+
+
+def test_personal_session_attaches_any_workspace_file(
+ mocker: pytest_mock.MockerFixture,
+):
+ mocks = _mock_stream_internals(mocker)
+ scope_mock = _mock_attached_files(mocker, "/sessions/expert-b-session/report.txt")
+
+ response = client.post(
+ "/sessions/sess-1/stream",
+ json={"message": "hi", "file_ids": [ATTACHED_FILE_ID]},
+ )
+
+ assert response.status_code == 200
+ scope_mock.assert_not_awaited()
+ assert mocks.enqueue.await_args.kwargs["file_ids"] == [ATTACHED_FILE_ID]
+
+
# ─── Rate limit → 429 ─────────────────────────────────────────────────
diff --git a/autogpt_platform/backend/backend/api/features/workspace/routes.py b/autogpt_platform/backend/backend/api/features/workspace/routes.py
index 1ba04f55aa..40c5bacfd1 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/routes.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/routes.py
@@ -6,17 +6,19 @@ import asyncio
import logging
import os
import re
-from typing import Annotated, Literal
+from typing import Annotated, Any, Literal
from urllib.parse import quote
import fastapi
from autogpt_libs.auth.dependencies import get_user_id, requires_user
from fastapi import Query, UploadFile
from fastapi.responses import Response
-from pydantic import BaseModel, Field
+from prisma.errors import UniqueViolationError
+from pydantic import BaseModel, Field, field_validator
from backend.api.features.store.exceptions import VirusDetectedError, VirusScanError
from backend.api.features.workspace.preview import build_preview_response
+from backend.copilot.db import get_chat_session_expert_ids
from backend.copilot.rate_limit import get_workspace_storage_limit_bytes
from backend.data.workspace import (
WorkspaceFile,
@@ -25,6 +27,11 @@ from backend.data.workspace import (
get_workspace,
get_workspace_file,
get_workspace_total_size,
+ rename_workspace_file,
+)
+from backend.data.workspace_scope import (
+ resolve_expert_workspace_scope,
+ session_path_prefix,
)
from backend.util.settings import Config
from backend.util.workspace import WorkspaceManager, format_bytes
@@ -152,6 +159,9 @@ class WorkspaceFileItem(BaseModel):
metadata: dict = Field(default_factory=dict)
origin: Literal["uploaded", "generated"]
created_at: str
+ # Hired expert whose conversation the file lives in; None for personal
+ # AutoPilot chats, Builder output and uploads outside a chat.
+ expert_id: str | None = None
class ListFilesResponse(BaseModel):
@@ -160,6 +170,18 @@ class ListFilesResponse(BaseModel):
has_more: bool = False
+class RenameFileRequest(BaseModel):
+ name: str = Field(min_length=1, max_length=255)
+
+ @field_validator("name")
+ @classmethod
+ def _plain_file_name(cls, value: str) -> str:
+ name = value.strip()
+ if not name or name in {".", ".."} or "/" in name or "\\" in name:
+ raise ValueError("File name must be a plain name without slashes")
+ return name
+
+
# Exact metadata stamped on user uploads by ``upload_file``. Used to split
# "Uploaded" vs "Generated" on the Artifacts page.
_UPLOADED_METADATA = {"origin": "user-upload"}
@@ -252,6 +274,36 @@ async def delete_workspace_file(
return DeleteFileResponse(deleted=True)
+ "/files/{file_id}",
+ summary="Rename a workspace file",
+ operation_id="renameWorkspaceFile",
+ responses={
+ 404: {"description": "File not found"},
+ 409: {"description": "A file with this name already exists here"},
+ },
+)
+async def rename_workspace_file_route(
+ user_id: Annotated[str, fastapi.Security(get_user_id)],
+ file_id: str,
+ payload: RenameFileRequest,
+) -> WorkspaceFileItem:
+ """Rename a file; it stays in its folder and conversation."""
+ workspace = await get_workspace(user_id)
+ if workspace is None:
+ raise fastapi.HTTPException(status_code=404, detail="Workspace not found")
+ try:
+ renamed = await rename_workspace_file(file_id, workspace.id, payload.name)
+ except UniqueViolationError:
+ raise fastapi.HTTPException(
+ status_code=409, detail="A file with this name already exists here"
+ )
+ if renamed is None:
+ raise fastapi.HTTPException(status_code=404, detail="File not found")
+ expert_by_session = await _expert_ids_by_session(user_id, [renamed])
+ return _to_file_item(renamed, expert_by_session)
+
+
@router.post(
"/files/upload",
summary="Upload file to workspace",
@@ -373,10 +425,49 @@ async def get_storage_usage(
)
+_SESSION_PATH_RE = re.compile(r"^/sessions/([^/]+)/")
+
+
+def _session_id_of(path: str) -> str | None:
+ match = _SESSION_PATH_RE.match(path)
+ return match.group(1) if match else None
+
+
+async def _expert_ids_by_session(
+ user_id: str, files: list[WorkspaceFile]
+) -> dict[str, str | None]:
+ """Attribute listed files to the expert whose conversation they live in."""
+ session_ids = sorted({sid for f in files if (sid := _session_id_of(f.path))})
+ if not session_ids:
+ return {}
+ return await get_chat_session_expert_ids(user_id, session_ids)
+
+
+def _to_file_item(
+ f: WorkspaceFile, expert_by_session: dict[str, str | None]
+) -> WorkspaceFileItem:
+ session_id_of_file = _session_id_of(f.path)
+ return WorkspaceFileItem(
+ id=f.id,
+ name=f.name,
+ path=f.path,
+ mime_type=f.mime_type,
+ size_bytes=f.size_bytes,
+ folder_id=f.folder_id,
+ metadata=f.metadata or {},
+ origin=_derive_origin(f.metadata),
+ created_at=f.created_at.isoformat(),
+ expert_id=(
+ expert_by_session.get(session_id_of_file) if session_id_of_file else None
+ ),
+ )
+
+
@router.get(
"/files",
summary="List workspace files",
operation_id="listWorkspaceFiles",
+ responses={400: {"description": "Conflicting filters"}},
)
async def list_workspace_files(
user_id: Annotated[str, fastapi.Security(get_user_id)],
@@ -410,6 +501,14 @@ async def list_workspace_files(
default=False,
description="Only return root-level files (not in any folder).",
),
+ expert_id: str | None = Query(
+ default=None,
+ min_length=1,
+ description=(
+ "Only return files from this hired expert's conversations. "
+ "Cannot be combined with session_id, folder_id or root_only."
+ ),
+ ),
) -> ListFilesResponse:
"""
List files in the user's workspace.
@@ -425,6 +524,10 @@ async def list_workspace_files(
``root_only``) are distinct, mutually exclusive axes, and ``folder_id`` and
``root_only`` likewise conflict; passing conflicting filters returns a 400
rather than silently yielding an empty list.
+
+ ``expert_id`` narrows the listing to files from that hired expert's own
+ conversations. It excludes the other axes for the same reason. An expert
+ the caller does not own (or no longer has) yields an empty list.
"""
# Treat empty-string session_id the same as omitted — an empty value
# would otherwise silently list files across every session instead of
@@ -446,6 +549,13 @@ async def list_workspace_files(
status_code=400,
detail="folder_id and root_only are mutually exclusive",
)
+ if expert_id is not None and (
+ session_id is not None or folder_id is not None or root_only
+ ):
+ raise fastapi.HTTPException(
+ status_code=400,
+ detail="expert_id cannot be combined with session_id, folder_id or root_only",
+ )
workspace = await get_or_create_workspace(user_id)
manager = WorkspaceManager(user_id, workspace.id, session_id)
@@ -467,7 +577,7 @@ async def list_workspace_files(
name_contains = (q or "").strip() or None
# Fetch one extra to compute has_more without a separate count query.
- files = await manager.list_files(
+ list_kwargs: dict[str, Any] = dict(
limit=limit + 1,
offset=offset,
include_all_sessions=include_all,
@@ -477,24 +587,20 @@ async def list_workspace_files(
folder_id=folder_id,
root_only=root_only,
)
+ if expert_id is not None:
+ # Fails closed: an unowned or archived expert resolves to no sessions,
+ # and an empty prefix list matches nothing.
+ scope = await resolve_expert_workspace_scope(user_id, expert_id)
+ list_kwargs["allowed_path_prefixes"] = [
+ session_path_prefix(sid) for sid in scope.session_ids
+ ]
+ files = await manager.list_files(**list_kwargs)
has_more = len(files) > limit
page = files[:limit]
+ expert_by_session = await _expert_ids_by_session(user_id, page)
return ListFilesResponse(
- files=[
- WorkspaceFileItem(
- id=f.id,
- name=f.name,
- path=f.path,
- mime_type=f.mime_type,
- size_bytes=f.size_bytes,
- folder_id=f.folder_id,
- metadata=f.metadata or {},
- origin=_derive_origin(f.metadata),
- created_at=f.created_at.isoformat(),
- )
- for f in page
- ],
+ files=[_to_file_item(f, expert_by_session) for f in page],
offset=offset,
has_more=has_more,
)
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 5df821907a..c6f07e7d7d 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/routes_test.py
@@ -5,9 +5,11 @@ from unittest.mock import AsyncMock, MagicMock, patch
import fastapi
import fastapi.testclient
import pytest
+from prisma.errors import UniqueViolationError
from backend.api.features.workspace.routes import router
from backend.data.workspace import Workspace, WorkspaceFile
+from backend.data.workspace_scope import WorkspaceScope
app = fastapi.FastAPI()
app.include_router(router)
@@ -1160,3 +1162,169 @@ class TestCreateFileDownloadResponse:
file = _make_file(storage_path="gcs://bucket/file.txt")
with pytest.raises(RuntimeError, match="Also failed"):
await create_file_download_response(file)
+
+
+# -- list_workspace_files: expert filter + attribution --
+
+
+@patch("backend.api.features.workspace.routes.resolve_expert_workspace_scope")
+@patch("backend.api.features.workspace.routes.get_or_create_workspace")
+@patch("backend.api.features.workspace.routes.WorkspaceManager")
+def test_list_files_filters_to_the_experts_own_conversations(
+ mock_manager_cls, mock_get_workspace, mock_resolve_scope, test_user_id
+):
+ mock_get_workspace.return_value = _make_workspace(user_id=test_user_id)
+ mock_resolve_scope.return_value = WorkspaceScope(
+ expert_id="expert-a",
+ session_ids=["s1", "s2"],
+ delegated_session_ids=["delegated"],
+ )
+ mock_instance = AsyncMock()
+ mock_instance.list_files.return_value = []
+ mock_manager_cls.return_value = mock_instance
+
+ response = client.get("/files?expert_id=expert-a&q=plan")
+ assert response.status_code == 200
+ mock_resolve_scope.assert_awaited_once_with(test_user_id, "expert-a")
+ mock_instance.list_files.assert_called_once_with(
+ limit=201,
+ offset=0,
+ include_all_sessions=True,
+ name_contains="plan",
+ metadata_equals=None,
+ metadata_not_equals=None,
+ folder_id=None,
+ root_only=False,
+ allowed_path_prefixes=["/sessions/s1/", "/sessions/s2/"],
+ )
+
+
+@patch("backend.api.features.workspace.routes.resolve_expert_workspace_scope")
+@patch("backend.api.features.workspace.routes.get_or_create_workspace")
+@patch("backend.api.features.workspace.routes.WorkspaceManager")
+def test_list_files_unowned_expert_lists_nothing(
+ mock_manager_cls, mock_get_workspace, mock_resolve_scope
+):
+ mock_get_workspace.return_value = _make_workspace()
+ mock_resolve_scope.return_value = WorkspaceScope(expert_id="expert-x")
+ mock_instance = AsyncMock()
+ mock_instance.list_files.return_value = []
+ mock_manager_cls.return_value = mock_instance
+
+ response = client.get("/files?expert_id=expert-x")
+ assert response.status_code == 200
+ assert response.json()["files"] == []
+ assert mock_instance.list_files.call_args.kwargs["allowed_path_prefixes"] == []
+
+
+ "query", ["session_id=sess-1", "folder_id=fld-1", "root_only=true"]
+)
+@patch("backend.api.features.workspace.routes.get_or_create_workspace")
+def test_list_files_rejects_expert_id_with_other_axes(mock_get_workspace, query):
+ response = client.get(f"/files?expert_id=expert-a&{query}")
+ assert response.status_code == 400
+ assert "expert_id" in response.json()["detail"]
+ mock_get_workspace.assert_not_called()
+
+
+@patch("backend.api.features.workspace.routes.get_chat_session_expert_ids")
+@patch("backend.api.features.workspace.routes.get_or_create_workspace")
+@patch("backend.api.features.workspace.routes.WorkspaceManager")
+def test_list_files_attributes_each_file_to_its_expert(
+ mock_manager_cls, mock_get_workspace, mock_expert_ids, test_user_id
+):
+ mock_get_workspace.return_value = _make_workspace(user_id=test_user_id)
+ mock_expert_ids.return_value = {"sess-a": "expert-a", "sess-p": None}
+ mock_instance = AsyncMock()
+ mock_instance.list_files.return_value = [
+ _make_file(id="f1", path="/sessions/sess-a/plan.md"),
+ _make_file(id="f2", path="/sessions/sess-p/notes.md"),
+ _make_file(id="f3", path="/report.pdf"),
+ ]
+ mock_manager_cls.return_value = mock_instance
+
+ response = client.get("/files")
+ assert response.status_code == 200
+ assert [f["expert_id"] for f in response.json()["files"]] == [
+ "expert-a",
+ None,
+ None,
+ ]
+ mock_expert_ids.assert_awaited_once_with(test_user_id, ["sess-a", "sess-p"])
+
+
+@patch("backend.api.features.workspace.routes.get_chat_session_expert_ids")
+@patch("backend.api.features.workspace.routes.get_or_create_workspace")
+@patch("backend.api.features.workspace.routes.WorkspaceManager")
+def test_list_files_skips_the_session_lookup_without_session_paths(
+ mock_manager_cls, mock_get_workspace, mock_expert_ids
+):
+ mock_get_workspace.return_value = _make_workspace()
+ mock_instance = AsyncMock()
+ mock_instance.list_files.return_value = [_make_file(id="f1", path="/report.pdf")]
+ mock_manager_cls.return_value = mock_instance
+
+ response = client.get("/files")
+ assert response.status_code == 200
+ assert response.json()["files"][0]["expert_id"] is None
+ mock_expert_ids.assert_not_called()
+
+
+# -- rename_workspace_file tests --
+
+
+def _unique_violation() -> UniqueViolationError:
+ return UniqueViolationError(
+ {"user_facing_error": {"message": "Unique constraint failed: (`path`)"}}
+ )
+
+
+@patch("backend.api.features.workspace.routes.get_chat_session_expert_ids")
+@patch("backend.api.features.workspace.routes.rename_workspace_file")
+@patch("backend.api.features.workspace.routes.get_workspace")
+def test_rename_file_success(mock_get_workspace, mock_rename, mock_expert_ids):
+ mock_get_workspace.return_value = _make_workspace()
+ mock_rename.return_value = _make_file(
+ id="f1", name="plan.md", path="/sessions/sess-a/plan.md"
+ )
+ mock_expert_ids.return_value = {"sess-a": "expert-a"}
+
+ response = client.patch("/files/f1", json={"name": " plan.md "})
+ assert response.status_code == 200
+ data = response.json()
+ assert data["name"] == "plan.md"
+ assert data["path"] == "/sessions/sess-a/plan.md"
+ assert data["expert_id"] == "expert-a"
+ mock_rename.assert_awaited_once_with("f1", "ws-001", "plan.md")
+
+
+@patch("backend.api.features.workspace.routes.rename_workspace_file")
+@patch("backend.api.features.workspace.routes.get_workspace")
+def test_rename_file_not_found(mock_get_workspace, mock_rename):
+ mock_get_workspace.return_value = _make_workspace()
+ mock_rename.return_value = None
+
+ response = client.patch("/files/missing", json={"name": "plan.md"})
+ assert response.status_code == 404
+ assert "File not found" in response.text
+
+
+@patch("backend.api.features.workspace.routes.rename_workspace_file")
+@patch("backend.api.features.workspace.routes.get_workspace")
+def test_rename_file_conflict(mock_get_workspace, mock_rename):
+ mock_get_workspace.return_value = _make_workspace()
+ mock_rename.side_effect = _unique_violation()
+
+ response = client.patch("/files/f1", json={"name": "taken.md"})
+ assert response.status_code == 409
+ assert "already exists" in response.text
+
+
[email protected]("name", ["", " ", ".", "..", "a/b.txt", "a\\b.txt"])
+@patch("backend.api.features.workspace.routes.rename_workspace_file")
+@patch("backend.api.features.workspace.routes.get_workspace")
+def test_rename_file_rejects_bad_names(mock_get_workspace, mock_rename, name):
+ response = client.patch("/files/f1", json={"name": name})
+ assert response.status_code == 422
+ mock_rename.assert_not_called()
diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.py
index c96930f46d..256300993b 100644
--- a/autogpt_platform/backend/backend/copilot/baseline/service.py
+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py
@@ -2079,12 +2079,25 @@ async def stream_chat_completion_baseline(
if message and is_user_message:
transcript_builder.append_user(content=user_message_for_transcript or message)
- # --- File attachments (feature parity with SDK path) ---
working_dir: str | None = None
- attachment_hint = ""
- image_blocks: list[dict[str, Any]] = []
if file_ids and user_id:
working_dir = tempfile.mkdtemp(prefix=f"copilot-baseline-{session_id[:8]}-")
+
+ # Propagate execution context so tool handlers can read session-level
+ # flags. This must precede attachment resolution: the workspace manager
+ # derives the expert's file scope from the session set here.
+ set_execution_context(
+ user_id,
+ session,
+ sandbox=e2b_sandbox,
+ sdk_cwd=working_dir,
+ permissions=permissions,
+ )
+
+ # --- File attachments (feature parity with SDK path) ---
+ attachment_hint = ""
+ image_blocks: list[dict[str, Any]] = []
+ if file_ids and user_id and working_dir:
attachment_hint, image_blocks = await _prepare_baseline_attachments(
file_ids, user_id, session_id, working_dir
)
@@ -2158,15 +2171,6 @@ async def stream_chat_completion_baseline(
list[ChatCompletionToolParam], _mark_tools_with_cache_control(tools)
)
- # Propagate execution context so tool handlers can read session-level flags.
- set_execution_context(
- user_id,
- session,
- sandbox=e2b_sandbox,
- sdk_cwd=working_dir,
- permissions=permissions,
- )
-
yield StreamStart(messageId=message_id, sessionId=session_id)
# Propagate user/session context to Langfuse so all LLM calls within
diff --git a/autogpt_platform/backend/backend/copilot/baseline/service_unit_test.py b/autogpt_platform/backend/backend/copilot/baseline/service_unit_test.py
index 2dcf65d6a7..f37779ab1c 100644
--- a/autogpt_platform/backend/backend/copilot/baseline/service_unit_test.py
+++ b/autogpt_platform/backend/backend/copilot/baseline/service_unit_test.py
@@ -35,6 +35,7 @@ from backend.copilot.baseline.service import (
_supports_prompt_cache_markers,
stream_chat_completion_baseline,
)
+from backend.copilot.context import get_execution_context, set_execution_context
from backend.copilot.expert_context import ExpertSessionUnavailableError
from backend.copilot.model import ChatMessage, ChatSession
from backend.copilot.model_router import ResolvedModel
@@ -2963,6 +2964,94 @@ async def _run_baseline_until_experts_gate(
return is_feature_enabled_mock
+class _StopAtAttachments(Exception):
+ """Raised by a mocked ``_prepare_baseline_attachments`` to abort
+ ``stream_chat_completion_baseline`` the moment the attachment step runs."""
+
+
+async def test_execution_context_is_set_before_attachments_are_prepared() -> None:
+ """Attachment resolution derives the expert's file scope from the execution
+ context, so the context must already name the session when it runs."""
+ session = ChatSession.new("user-1", dry_run=False, expert_id="expert-1")
+ session.title = "already titled"
+ seen: list[tuple[str | None, ChatSession | None]] = []
+
+ async def capture(*_args: object, **_kwargs: object) -> None:
+ seen.append(get_execution_context())
+ raise _StopAtAttachments
+
+ with (
+ patch(
+ "backend.copilot.baseline.service.build_expert_identity_suffix",
+ new=AsyncMock(return_value=""),
+ ),
+ patch(
+ "backend.copilot.baseline.service.drain_pending_safe",
+ new=AsyncMock(return_value=[]),
+ ),
+ patch(
+ "backend.copilot.baseline.service._resolve_baseline_model",
+ new=AsyncMock(
+ return_value=ResolvedModel(
+ model="anthropic/claude-sonnet-4-6", source="env"
+ )
+ ),
+ ),
+ patch(
+ "backend.copilot.baseline.service.normalize_model_for_transport",
+ new=MagicMock(side_effect=lambda model, cfg=None: model),
+ ),
+ patch(
+ "backend.copilot.tools.e2b_sandbox.get_or_create_sandbox",
+ new=AsyncMock(return_value=None),
+ ),
+ patch(
+ "backend.copilot.baseline.service._build_system_prompt",
+ new=AsyncMock(return_value=("system prompt", None)),
+ ),
+ patch(
+ "backend.copilot.baseline.service.is_enabled_for_user",
+ new=AsyncMock(return_value=False),
+ ),
+ patch(
+ "backend.copilot.baseline.service.is_feature_enabled",
+ new=AsyncMock(return_value=False),
+ ),
+ patch(
+ "backend.copilot.baseline.service.build_builder_system_prompt_suffix",
+ new=AsyncMock(return_value=""),
+ ),
+ patch(
+ "backend.copilot.baseline.service.extract_context_messages",
+ new=AsyncMock(return_value=[]),
+ ),
+ patch(
+ "backend.copilot.baseline.service._compress_session_messages",
+ new=AsyncMock(return_value=[]),
+ ),
+ patch(
+ "backend.copilot.baseline.service._prepare_baseline_attachments",
+ new=AsyncMock(side_effect=capture),
+ ),
+ pytest.raises(_StopAtAttachments),
+ ):
+ try:
+ async for _ in stream_chat_completion_baseline(
+ session_id=session.session_id,
+ message=None,
+ is_user_message=False,
+ user_id="user-1",
+ session=session,
+ file_ids=["file-1"],
+ ):
+ pass
+ finally:
+ set_execution_context(None, None)
+
+ assert seen == [("user-1", session)]
+
+
class TestBaselineExpertsFlagGuard:
"""``experts_enabled = bool(user_id) and await is_feature_enabled(...)``:
an anonymous turn (``user_id=None``) must fail closed WITHOUT resolving
diff --git a/autogpt_platform/backend/backend/copilot/context.py b/autogpt_platform/backend/backend/copilot/context.py
index b5a422fde4..6b3f4cab0a 100644
--- a/autogpt_platform/backend/backend/copilot/context.py
+++ b/autogpt_platform/backend/backend/copilot/context.py
@@ -12,6 +12,7 @@ from typing import TYPE_CHECKING
from backend.copilot.model import ChatSession
from backend.data.db_accessors import workspace_db
+from backend.data.workspace_scope import WorkspaceAccessDeniedError, WorkspaceScope
from backend.util.workspace import WorkspaceManager
if TYPE_CHECKING:
@@ -269,15 +270,43 @@ def resolve_sandbox_path(path: str) -> str:
return normalized
+async def current_workspace_scope(
+ user_id: str, session_id: str
+) -> WorkspaceScope | None:
+ """Resolve the file grants for the turn currently executing.
+
+ The scope derives from the server-resolved session the executor placed
+ in the execution context — never from a session or expert ID a tool
+ argument names. Personal AutoPilot turns are unrestricted: the account
+ owner is acting. Without an executing session nobody can be attributed,
+ so access fails closed to ``session_id`` alone.
+ """
+ _, session = get_execution_context()
+ if session is None:
+ return WorkspaceScope(session_ids=[session_id])
+ if session.user_id != user_id:
+ raise WorkspaceAccessDeniedError(
+ "Workspace access denied: the executing session belongs to another user."
+ )
+ if session.expert_id is None:
+ return None
+ scope = await workspace_db().resolve_expert_workspace_scope(
+ user_id, session.expert_id
+ )
+ return scope.with_session(session.session_id)
+
+
async def get_workspace_manager(user_id: str, session_id: str) -> WorkspaceManager:
"""Create a session-scoped :class:`WorkspaceManager`.
Placed here (rather than in ``tools/workspace_files``) so that modules
like ``sdk/file_ref`` can import it without triggering the heavy
- ``tools/__init__`` import chain.
+ ``tools/__init__`` import chain. Expert turns get a manager confined to
+ the expert's resolved scope (see :func:`current_workspace_scope`).
"""
workspace = await workspace_db().get_or_create_workspace(user_id)
- return WorkspaceManager(user_id, workspace.id, session_id)
+ scope = await current_workspace_scope(user_id, session_id)
+ return WorkspaceManager(user_id, workspace.id, session_id, scope=scope)
def is_allowed_local_path(path: str, sdk_cwd: str | None = None) -> bool:
diff --git a/autogpt_platform/backend/backend/copilot/context_isolation_test.py b/autogpt_platform/backend/backend/copilot/context_isolation_test.py
new file mode 100644
index 0000000000..b68cf4603b
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/context_isolation_test.py
@@ -0,0 +1,64 @@
+"""``get_workspace_manager`` derives the expert scope from the executing
+session placed in the context by the executor — never from arguments."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.copilot.context import get_workspace_manager, set_execution_context
+from backend.copilot.model import ChatSession
+from backend.data.workspace_scope import WorkspaceAccessDeniedError, WorkspaceScope
+
+
+def db():
+ db = MagicMock()
+ db.get_or_create_workspace = AsyncMock(return_value=MagicMock(id="ws-1"))
+ db.resolve_expert_workspace_scope = AsyncMock(
+ return_value=WorkspaceScope(expert_id="expert-a", session_ids=["older"])
+ )
+ with patch("backend.copilot.context.workspace_db", return_value=db):
+ yield db
+ set_execution_context(None, None)
+
+
+async def test_expert_turn_gets_scoped_manager_including_current_session(db):
+ session = ChatSession.new("user-1", dry_run=False, expert_id="expert-a")
+ set_execution_context("user-1", session)
+ manager = await get_workspace_manager("user-1", session.session_id)
+ assert manager.scope is not None
+ assert manager.scope.session_ids == ["older", session.session_id]
+ db.resolve_expert_workspace_scope.assert_awaited_once_with("user-1", "expert-a")
+
+
+async def test_scope_follows_the_executing_session_not_the_requested_one(db):
+ session = ChatSession.new("user-1", dry_run=False, expert_id="expert-a")
+ set_execution_context("user-1", session)
+ manager = await get_workspace_manager("user-1", "some-other-session")
+ assert manager.scope is not None
+ assert manager.scope.expert_id == "expert-a"
+
+
+async def test_personal_autopilot_turn_is_unrestricted(db):
+ session = ChatSession.new("user-1", dry_run=False)
+ set_execution_context("user-1", session)
+ manager = await get_workspace_manager("user-1", session.session_id)
+ assert manager.scope is None
+ db.resolve_expert_workspace_scope.assert_not_awaited()
+
+
+async def test_outside_a_turn_fails_closed_to_the_requested_session(db):
+ set_execution_context(None, None)
+ manager = await get_workspace_manager("user-1", "session-1")
+ assert manager.scope is not None
+ assert manager.scope.expert_id is None
+ assert manager.scope.session_ids == ["session-1"]
+ assert not manager.scope.allows_path("/sessions/other/file.txt")
+ db.resolve_expert_workspace_scope.assert_not_awaited()
+
+
+async def test_session_of_another_user_is_refused(db):
+ session = ChatSession.new("someone-else", dry_run=False, expert_id="expert-a")
+ set_execution_context("someone-else", session)
+ with pytest.raises(WorkspaceAccessDeniedError):
+ await get_workspace_manager("user-1", session.session_id)
diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.py
index 2aa1493551..b17d728fb1 100644
--- a/autogpt_platform/backend/backend/copilot/db.py
+++ b/autogpt_platform/backend/backend/copilot/db.py
@@ -69,6 +69,20 @@ MAX_LOADED_CHAT_MESSAGES = 1000
# guarantee already apply, and the cap-hit signal lives in ``has_more``.
+async def get_chat_session_expert_ids(
+ user_id: str, session_ids: list[str]
+) -> dict[str, str | None]:
+ """Map each of *user_id*'s sessions in *session_ids* to the expert it is
+ scoped to (``None`` for a personal AutoPilot session). Sessions that do
+ not belong to the user are left out."""
+ if not session_ids:
+ return {}
+ rows = await PrismaChatSession.prisma().find_many(
+ where={"id": {"in": session_ids}, "userId": user_id}
+ )
+ return {row.id: row.expertId for row in rows}
+
+
async def get_chat_session_metadata(session_id: str) -> ChatSessionInfo | None:
"""Get chat session metadata (without messages) for ownership validation."""
session = await PrismaChatSession.prisma().find_unique(
diff --git a/autogpt_platform/backend/backend/copilot/pending_message_helpers.py b/autogpt_platform/backend/backend/copilot/pending_message_helpers.py
index bc1c9b18a1..16ab4cb6f3 100644
--- a/autogpt_platform/backend/backend/copilot/pending_message_helpers.py
+++ b/autogpt_platform/backend/backend/copilot/pending_message_helpers.py
@@ -34,9 +34,12 @@ from backend.copilot.stream_registry import get_session_meta_key
from backend.data.db_accessors import chat_db
from backend.data.redis_client import get_redis_async
from backend.data.redis_helpers import incr_with_ttl
-from backend.data.workspace import resolve_workspace_files
+from backend.data.workspace import resolve_attachable_workspace_files
+from backend.data.workspace_scope import WorkspaceAccessDeniedError
if TYPE_CHECKING:
+ from prisma.models import UserWorkspaceFile
+
from backend.copilot.model import ChatSession
from backend.copilot.transcript_builder import TranscriptBuilder
@@ -171,6 +174,23 @@ async def queue_user_message(
)
+async def resolve_attachments_for_http(
+ user_id: str,
+ file_ids: list[str],
+ *,
+ session_id: str,
+ expert_id: str | None,
+) -> list["UserWorkspaceFile"]:
+ """Resolve attachment IDs for an HTTP request, mapping an expert-scope
+ violation to a 400 so the stream and pending routes answer alike."""
+ try:
+ return await resolve_attachable_workspace_files(
+ user_id, file_ids, session_id=session_id, expert_id=expert_id
+ )
+ except WorkspaceAccessDeniedError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
async def queue_pending_for_http(
*,
session_id: str,
@@ -178,23 +198,27 @@ async def queue_pending_for_http(
message: str,
context: dict[str, str] | None,
file_ids: list[str] | None,
+ expert_id: str | None,
) -> QueuePendingMessageResponse:
"""HTTP-facing wrapper around :func:`queue_user_message`.
Owns the HTTP-only concerns for the pending-message route:
1. Per-user call-rate cap (429 on overflow).
- 2. File-ID sanitisation against the user's own workspace.
+ 2. File-ID sanitisation against the user's own workspace and, for an
+ expert session, the expert's file scope (400 on a foreign file).
3. ``{url, content}`` dict → ``PendingMessageContext`` coercion.
4. Push via ``queue_user_message``.
- Raises :class:`HTTPException` with status 429 if the rate cap is hit;
- otherwise returns the ``QueuePendingMessageResponse`` the handler can
- serialise 1:1.
+ Raises :class:`HTTPException` with status 429 if the rate cap is hit or
+ 400 if an expert session attaches a file outside its scope; otherwise
+ returns the ``QueuePendingMessageResponse`` the handler can serialise 1:1.
"""
sanitized_file_ids: list[str] | None = None
if file_ids:
- files = await resolve_workspace_files(user_id, file_ids)
+ files = await resolve_attachments_for_http(
+ user_id, file_ids, session_id=session_id, expert_id=expert_id
+ )
sanitized_file_ids = [wf.id for wf in files] or None
# ``PendingMessageContext`` uses the default ``extra='ignore'`` so
diff --git a/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.py b/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.py
index 95f81e2272..3e48f3272d 100644
--- a/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.py
+++ b/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.py
@@ -1,5 +1,6 @@
"""Unit tests for pending_message_helpers."""
+from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock
@@ -20,6 +21,7 @@ from backend.copilot.pending_message_helpers import (
queue_pending_for_http,
)
from backend.copilot.pending_messages import MAX_PENDING_MESSAGES, PendingMessage
+from backend.data.workspace_scope import WorkspaceAccessDeniedError
# ── check_pending_call_rate ────────────────────────────────────────────
@@ -190,7 +192,9 @@ async def test_queue_pending_does_not_charge_rate_on_toctou_409(
rate_mock = AsyncMock(return_value=1)
monkeypatch.setattr(helpers_module, "check_pending_call_rate", rate_mock)
monkeypatch.setattr(
- helpers_module, "resolve_workspace_files", AsyncMock(return_value=[])
+ helpers_module,
+ "resolve_attachable_workspace_files",
+ AsyncMock(return_value=[]),
)
with pytest.raises(HTTPException) as exc_info:
@@ -200,6 +204,7 @@ async def test_queue_pending_does_not_charge_rate_on_toctou_409(
message="hi",
context=None,
file_ids=None,
+ expert_id=None,
)
assert exc_info.value.status_code == 409
rate_mock.assert_not_awaited()
@@ -219,7 +224,9 @@ async def test_queue_pending_charges_rate_only_after_successful_push(
rate_mock = AsyncMock(return_value=PENDING_CALL_LIMIT)
monkeypatch.setattr(helpers_module, "check_pending_call_rate", rate_mock)
monkeypatch.setattr(
- helpers_module, "resolve_workspace_files", AsyncMock(return_value=[])
+ helpers_module,
+ "resolve_attachable_workspace_files",
+ AsyncMock(return_value=[]),
)
result = await queue_pending_for_http(
@@ -228,6 +235,7 @@ async def test_queue_pending_charges_rate_only_after_successful_push(
message="hi",
context=None,
file_ids=None,
+ expert_id=None,
)
assert result is response
@@ -255,7 +263,9 @@ async def test_queue_pending_429_after_push_when_limit_exceeded(
AsyncMock(return_value=PENDING_CALL_LIMIT + 1),
)
monkeypatch.setattr(
- helpers_module, "resolve_workspace_files", AsyncMock(return_value=[])
+ helpers_module,
+ "resolve_attachable_workspace_files",
+ AsyncMock(return_value=[]),
)
with pytest.raises(HTTPException) as exc_info:
@@ -265,6 +275,7 @@ async def test_queue_pending_429_after_push_when_limit_exceeded(
message="hi",
context=None,
file_ids=None,
+ expert_id=None,
)
assert exc_info.value.status_code == 429
queue_mock.assert_awaited_once()
@@ -835,3 +846,69 @@ async def test_persist_pending_swallows_requeue_errors(
)
# Still returns False (rolled back) — exception was logged + swallowed.
assert ok is False
+
+
+# ── queue_pending_for_http: expert file scope ─────────────────────────
+
+
+async def test_queue_pending_rejects_file_outside_expert_scope(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ queue_mock = AsyncMock()
+ monkeypatch.setattr(helpers_module, "queue_user_message", queue_mock)
+ monkeypatch.setattr(
+ helpers_module, "check_pending_call_rate", AsyncMock(return_value=1)
+ )
+ monkeypatch.setattr(
+ helpers_module,
+ "resolve_attachable_workspace_files",
+ AsyncMock(side_effect=WorkspaceAccessDeniedError("outside: secret.pdf")),
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ await queue_pending_for_http(
+ session_id="sess-1",
+ user_id="user-1",
+ message="hi",
+ context=None,
+ file_ids=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],
+ expert_id="expert-a",
+ )
+ assert exc_info.value.status_code == 400
+ assert "secret.pdf" in exc_info.value.detail
+ queue_mock.assert_not_awaited()
+
+
+async def test_queue_pending_resolves_files_against_the_session_expert(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ response = QueuePendingMessageResponse(
+ buffer_length=1,
+ max_buffer_length=MAX_PENDING_MESSAGES,
+ turn_in_flight=True,
+ )
+ monkeypatch.setattr(
+ helpers_module, "queue_user_message", AsyncMock(return_value=response)
+ )
+ monkeypatch.setattr(
+ helpers_module, "check_pending_call_rate", AsyncMock(return_value=1)
+ )
+ resolve_mock = AsyncMock(return_value=[SimpleNamespace(id="file-1")])
+ monkeypatch.setattr(
+ helpers_module, "resolve_attachable_workspace_files", resolve_mock
+ )
+
+ await queue_pending_for_http(
+ session_id="sess-1",
+ user_id="user-1",
+ message="hi",
+ context=None,
+ file_ids=["file-1"],
+ expert_id="expert-a",
+ )
+
+ resolve_mock.assert_awaited_once_with(
+ "user-1", ["file-1"], session_id="sess-1", expert_id="expert-a"
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py b/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
index 962baa9e69..7deb42c88c 100644
--- a/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
+++ b/autogpt_platform/backend/backend/copilot/tools/continue_run_block.py
@@ -151,6 +151,7 @@ class ContinueRunBlockTool(BaseTool):
dry_run=False,
organization_id=session.organization_id,
team_id=session.team_id,
+ expert_id=session.expert_id,
)
# Delete review record after successful execution (one-time use)
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.py
index 64ca2b9419..e7c5e40215 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py
@@ -210,9 +210,13 @@ async def execute_block(
dry_run: bool,
organization_id: str | None = None,
team_id: str | None = None,
+ expert_id: str | None = None,
) -> ToolResponseBase:
"""Execute a block with full context setup, credential injection, and error handling.
+ ``expert_id`` is the session's expert; it attributes the run so
+ ``workspace://`` inputs resolve inside that expert's file scope.
+
This is the shared execution path used by both ``run_block`` (after review
check) and ``continue_run_block`` (after approval).
@@ -290,6 +294,7 @@ async def execute_block(
user_timezone=user_timezone,
organization_id=organization_id,
team_id=team_id,
+ expert_id=expert_id,
)
exec_kwargs: dict[str, Any] = {
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
index b3176fe51e..5f232d700b 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
@@ -1840,3 +1840,58 @@ class TestRequireLibraryCheck:
session = make_session("user-lib-check", guide_read=False, library_check=False)
session.metadata.builder_graph_id = "some-graph-id"
assert require_library_check(session, "create_agent") is None
+
+
+class TestExecuteBlockExpertFileScope:
+ """A ``workspace://`` block input is a second door into the workspace, so
+ the run it belongs to must carry the session's expert."""
+
+ async def test_expert_block_run_cannot_read_another_sessions_file(self):
+ result = await _store_workspace_file("/sessions/personal/private.txt")
+ assert isinstance(result, ErrorResponse)
+ assert "outside this expert's scope" in result.message
+
+ async def test_expert_block_run_reads_its_own_session_file(self):
+ result = await _store_workspace_file(f"/sessions/{_SESSION}/notes.txt")
+ assert isinstance(result, BlockOutputResponse)
+ assert result.success is True
+
+
+async def _store_workspace_file(path: str):
+ """Run FileStoreBlock on ``workspace://<path>`` in an expert session."""
+ from backend.blocks.basic import FileStoreBlock
+ from backend.data.workspace_scope import WorkspaceScope
+ from backend.util.workspace_test import _make_workspace_file
+
+ scope_db = MagicMock()
+ scope_db.resolve_expert_workspace_scope = AsyncMock(
+ return_value=WorkspaceScope(expert_id="expert-a")
+ )
+ files = MagicMock()
+ files.get_workspace_file_by_path = AsyncMock(
+ return_value=_make_workspace_file(path=path)
+ )
+ storage = AsyncMock()
+ storage.retrieve.return_value = b"secret"
+ credit_patch, _ = _patch_credit_db()
+
+ with (
+ _patch_workspace(),
+ credit_patch,
+ patch("backend.data.db_accessors.workspace_db", return_value=scope_db),
+ patch("backend.util.workspace.workspace_db", return_value=files),
+ patch("backend.util.workspace.get_workspace_storage", return_value=storage),
+ patch("backend.util.file.scan_content_safe", AsyncMock()),
+ patch("backend.util.file.get_cloud_storage_handler", AsyncMock()),
+ ):
+ return await execute_block(
+ block=FileStoreBlock(),
+ block_id="cbb50872-625b-42f0-8203-a2ae78242d8a",
+ input_data={"file_in": f"workspace://{path}", "base_64": True},
+ user_id=_USER,
+ session_id=_SESSION,
+ node_exec_id="exec-scope",
+ matched_credentials={},
+ dry_run=False,
+ expert_id="expert-a",
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block.py b/autogpt_platform/backend/backend/copilot/tools/run_block.py
index fee9813221..54726984d2 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_block.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_block.py
@@ -208,6 +208,7 @@ class RunBlockTool(BaseTool):
dry_run=True,
organization_id=session.organization_id,
team_id=session.team_id,
+ expert_id=session.expert_id,
)
# Show block details when required inputs are not yet provided
@@ -294,6 +295,7 @@ class RunBlockTool(BaseTool):
dry_run=dry_run,
organization_id=session.organization_id,
team_id=session.team_id,
+ expert_id=session.expert_id,
)
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
index 3765085bbf..2c66ca4f9a 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
@@ -1242,6 +1242,70 @@ class TestExecuteBlockUserTimezoneAccessor:
assert ctx.user_timezone == "America/New_York" # type: ignore[attr-defined]
+class TestExecuteBlockExpertAttribution:
+ """A block run from an expert chat must carry the expert on its execution
+ context, so ``workspace://`` inputs resolve inside that expert's scope."""
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_expert_id_is_plumbed_into_the_execution_context(self):
+ from backend.copilot.tools.helpers import execute_block
+
+ mock_block = make_mock_block_with_schema(
+ block_id="scope-block-id",
+ name="Scope Block",
+ input_properties={},
+ required_fields=[],
+ )
+
+ captured: dict[str, object] = {}
+
+ async def _capture_ctx(_input, **kwargs):
+ captured["ctx"] = kwargs["execution_context"]
+ yield "result", "ok"
+
+ mock_block.execute = _capture_ctx
+
+ rpc_client = MagicMock()
+ rpc_client.get_user_by_id = AsyncMock(return_value=MagicMock(timezone="UTC"))
+ mock_workspace_db = MagicMock()
+ mock_workspace_db.get_or_create_workspace = AsyncMock(
+ return_value=MagicMock(id="ws-scope")
+ )
+
+ with (
+ patch("backend.copilot.tools.helpers.user_db", return_value=rpc_client),
+ patch(
+ "backend.copilot.tools.helpers.workspace_db",
+ return_value=mock_workspace_db,
+ ),
+ patch(
+ "backend.copilot.tools.helpers.credit_db",
+ return_value=_StubCreditDB(),
+ ),
+ patch(
+ "backend.copilot.tools.helpers.block_usage_cost",
+ return_value=(0, {}),
+ ),
+ ):
+ response = await execute_block(
+ block=mock_block,
+ block_id="scope-block-id",
+ input_data={},
+ user_id="u-scope",
+ session_id="s-scope",
+ node_exec_id="n-scope",
+ matched_credentials={},
+ dry_run=False,
+ expert_id="expert-a",
+ )
+
+ assert isinstance(response, BlockOutputResponse)
+ ctx = captured["ctx"]
+ assert ctx is not None
+ assert ctx.expert_id == "expert-a" # type: ignore[attr-defined]
+ assert ctx.session_id == "s-scope" # type: ignore[attr-defined]
+
+
class _StubCreditDB:
async def get_credits(self, _user_id: str) -> int:
return 10_000
diff --git a/autogpt_platform/backend/backend/copilot/tools/workspace_files.py b/autogpt_platform/backend/backend/copilot/tools/workspace_files.py
index 91aa4d0cac..94d9d404e8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/workspace_files.py
+++ b/autogpt_platform/backend/backend/copilot/tools/workspace_files.py
@@ -20,6 +20,7 @@ from backend.copilot.context import (
from backend.copilot.model import ChatSession
from backend.copilot.tools.sandbox import make_session_path
from backend.data.activity_event import ActivityEventDraft
+from backend.data.workspace_scope import WorkspaceAccessDeniedError
from backend.util.settings import Config
from backend.util.workspace import WorkspaceManager
@@ -427,7 +428,11 @@ class ListWorkspaceFilesTool(BaseTool):
},
"include_all_sessions": {
"type": "boolean",
- "description": "Include files from all sessions (default: false).",
+ "description": (
+ "Include files from all sessions (default: false). "
+ "Expert chats only ever see files from their own "
+ "conversations and ones they delegated."
+ ),
},
},
"required": [],
@@ -489,6 +494,10 @@ class ListWorkspaceFilesTool(BaseTool):
message="\n".join(lines),
session_id=session_id,
)
+ except WorkspaceAccessDeniedError as e:
+ return ErrorResponse(
+ message=str(e), error="access_denied", session_id=session_id
+ )
except Exception as e:
logger.error(f"Error listing workspace files: {e}", exc_info=True)
return ErrorResponse(
@@ -515,7 +524,9 @@ class ReadWorkspaceFileTool(BaseTool):
"Small text/image files return inline; large/binary return metadata+URL. "
"Use save_to_path to copy to working dir for processing. "
"Use offset/length for paginated reads. "
- "Paths scoped to current session; use /sessions/<id>/... for cross-session access."
+ "Paths scoped to current session; use /sessions/<id>/... for "
+ "cross-session access (expert chats can read their own "
+ "conversations and ones they delegated)."
)
@property
@@ -725,6 +736,10 @@ class ReadWorkspaceFileTool(BaseTool):
)
except FileNotFoundError as e:
return ErrorResponse(message=str(e), session_id=session_id)
+ except WorkspaceAccessDeniedError as e:
+ return ErrorResponse(
+ message=str(e), error="access_denied", session_id=session_id
+ )
except Exception as e:
logger.error(f"Error reading workspace file: {e}", exc_info=True)
return ErrorResponse(
@@ -774,7 +789,9 @@ class WriteWorkspaceFileTool(BaseTool):
"Write a file to persistent workspace (survives across sessions). "
"Provide exactly one of: content (text), content_base64 (binary), "
f"or source_path (copy from working dir). Max {_MAX_FILE_SIZE_MB}MB. "
- "Paths scoped to current session; use /sessions/<id>/... for cross-session access."
+ "Paths scoped to current session; use /sessions/<id>/... for "
+ "cross-session access (expert chats are limited to their own "
+ "conversations)."
)
@property
@@ -977,6 +994,10 @@ class WriteWorkspaceFileTool(BaseTool):
except VirusScanError as e:
logger.error(f"Virus scan infrastructure error: {e}", exc_info=True)
return ErrorResponse(message=str(e), session_id=session_id)
+ except WorkspaceAccessDeniedError as e:
+ return ErrorResponse(
+ message=str(e), error="access_denied", session_id=session_id
+ )
except ValueError as e:
msg = str(e)
if msg.startswith("Storage limit exceeded"):
@@ -1097,6 +1118,10 @@ class DeleteWorkspaceFileTool(BaseTool):
),
session_id=session_id,
)
+ except WorkspaceAccessDeniedError as e:
+ return ErrorResponse(
+ message=str(e), error="access_denied", session_id=session_id
+ )
except Exception as e:
logger.error(f"Error deleting workspace file: {e}", exc_info=True)
return ErrorResponse(
diff --git a/autogpt_platform/backend/backend/copilot/tools/workspace_files_isolation_test.py b/autogpt_platform/backend/backend/copilot/tools/workspace_files_isolation_test.py
new file mode 100644
index 0000000000..65852b8de4
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/workspace_files_isolation_test.py
@@ -0,0 +1,97 @@
+"""Workspace tools cannot reach outside an expert session's scope through
+``include_all_sessions``, explicit ``/sessions/<id>/`` paths, or file IDs."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.copilot.model import ChatSession
+from backend.copilot.tools.models import ErrorResponse
+from backend.copilot.tools.workspace_files import (
+ DeleteWorkspaceFileTool,
+ ListWorkspaceFilesTool,
+ ReadWorkspaceFileTool,
+ WorkspaceFileListResponse,
+ WriteWorkspaceFileTool,
+)
+from backend.data.workspace_scope import WorkspaceScope
+from backend.util.workspace import WorkspaceManager
+from backend.util.workspace_test import _make_workspace_file
+
+SCOPE = WorkspaceScope(expert_id="expert-a", session_ids=["expert-a"])
+
+
+def db():
+ db = MagicMock()
+ db.get_workspace_file = AsyncMock(
+ return_value=_make_workspace_file(path="/sessions/expert-b/private.txt")
+ )
+ db.get_workspace_file_by_path = AsyncMock(return_value=_make_workspace_file())
+ db.list_workspace_files = AsyncMock(return_value=[])
+ db.count_workspace_files = AsyncMock(return_value=0)
+ db.soft_delete_workspace_file = AsyncMock()
+ manager = WorkspaceManager("user-1", "ws-1", "expert-a", scope=SCOPE)
+ with (
+ patch("backend.util.workspace.workspace_db", return_value=db),
+ patch(
+ "backend.copilot.tools.workspace_files.get_workspace_manager",
+ new=AsyncMock(return_value=manager),
+ ),
+ ):
+ yield db
+
+
+def _session() -> ChatSession:
+ session = ChatSession.new("user-1", dry_run=False, expert_id="expert-a")
+ session.session_id = "expert-a"
+ return session
+
+
+async def test_include_all_sessions_is_confined_to_the_scope(db):
+ result = await ListWorkspaceFilesTool()._execute(
+ "user-1", _session(), include_all_sessions=True
+ )
+ assert isinstance(result, WorkspaceFileListResponse)
+ assert (
+ db.list_workspace_files.call_args.kwargs["allowed_path_prefixes"]
+ == SCOPE.read_prefixes
+ )
+
+
+async def test_read_by_foreign_file_id_is_denied(db):
+ result = await ReadWorkspaceFileTool()._execute(
+ "user-1", _session(), file_id="foreign"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "access_denied"
+
+
+async def test_read_by_explicit_foreign_path_is_denied(db):
+ result = await ReadWorkspaceFileTool()._execute(
+ "user-1", _session(), path="/sessions/expert-b/private.txt"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "access_denied"
+ db.get_workspace_file_by_path.assert_not_awaited()
+
+
+async def test_write_into_foreign_session_is_denied(db):
+ result = await WriteWorkspaceFileTool()._execute(
+ "user-1",
+ _session(),
+ filename="x.txt",
+ content="x",
+ path="/sessions/expert-b/x.txt",
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "access_denied"
+
+
+async def test_delete_by_foreign_file_id_is_denied(db):
+ result = await DeleteWorkspaceFileTool()._execute(
+ "user-1", _session(), file_id="foreign"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "access_denied"
+ db.soft_delete_workspace_file.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index d7bb57b628..701393e9a8 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -179,6 +179,7 @@ from backend.data.workspace import (
get_workspace_file_by_path,
get_workspace_total_size,
list_workspace_files,
+ resolve_expert_workspace_scope,
soft_delete_workspace_file,
)
from backend.platform_linking import db as platform_linking_db
@@ -441,6 +442,7 @@ class DatabaseManager(AppService):
get_workspace_total_size = _(get_workspace_total_size)
list_workspace_files = _(list_workspace_files)
soft_delete_workspace_file = _(soft_delete_workspace_file)
+ resolve_expert_workspace_scope = _(resolve_expert_workspace_scope)
# ============ Understanding ============ #
get_business_understanding = _(get_business_understanding)
@@ -831,6 +833,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
get_workspace_total_size = d.get_workspace_total_size
list_workspace_files = d.list_workspace_files
soft_delete_workspace_file = d.soft_delete_workspace_file
+ resolve_expert_workspace_scope = d.resolve_expert_workspace_scope
# ============ Credits ============ #
spend_credits = d.spend_credits
diff --git a/autogpt_platform/backend/backend/data/workspace.py b/autogpt_platform/backend/backend/data/workspace.py
index 122a966bc7..b104ba966c 100644
--- a/autogpt_platform/backend/backend/data/workspace.py
+++ b/autogpt_platform/backend/backend/data/workspace.py
@@ -5,6 +5,7 @@ This module provides functions for managing user workspaces and workspace files.
"""
import logging
+import posixpath
import re
from datetime import datetime, timezone
from typing import Optional
@@ -14,6 +15,10 @@ from prisma.errors import UniqueViolationError
from prisma.models import UserWorkspace, UserWorkspaceFile
from prisma.types import UserWorkspaceFileWhereInput
+from backend.data.workspace_scope import (
+ WorkspaceAccessDeniedError,
+ resolve_expert_workspace_scope,
+)
from backend.util.json import SafeJson
_UUID_RE = re.compile(
@@ -262,6 +267,7 @@ async def list_workspace_files(
metadata_not_equals: Optional[dict] = None,
folder_id: Optional[str] = None,
root_only: bool = False,
+ allowed_path_prefixes: Optional[list[str]] = None,
) -> list[WorkspaceFile]:
"""
List files in a workspace.
@@ -288,10 +294,16 @@ async def list_workspace_files(
folder_id: If set, only return files in this folder.
root_only: If True, only return root-level files (folderId IS NULL).
Ignored when ``folder_id`` is set.
+ allowed_path_prefixes: When set, only files whose path starts with
+ one of these prefixes are returned (ANDed with ``path_prefix``).
+ An empty list matches nothing. Used to apply an expert session's
+ resolved scope inside the query so pagination stays correct.
Returns:
List of WorkspaceFile instances
"""
+ if allowed_path_prefixes is not None and not allowed_path_prefixes:
+ return []
where_clause: UserWorkspaceFileWhereInput = {"workspaceId": workspace_id}
if not include_deleted:
@@ -326,6 +338,9 @@ async def list_workspace_files(
if name_contains:
where_clause["name"] = {"contains": name_contains, "mode": "insensitive"}
+ if allowed_path_prefixes:
+ where_clause["AND"] = [{"OR": _path_prefix_filters(allowed_path_prefixes)}]
+
files = await UserWorkspaceFile.prisma().find_many(
where=where_clause,
order={"createdAt": "desc"},
@@ -335,10 +350,17 @@ async def list_workspace_files(
return [WorkspaceFile.from_db(f) for f in files]
+def _path_prefix_filters(prefixes: list[str]) -> list[UserWorkspaceFileWhereInput]:
+ """Nested under ``AND`` so the scope filter can never replace another
+ ``OR`` branch a caller adds later; scope prefixes are always rooted."""
+ return [{"path": {"startswith": prefix}} for prefix in prefixes]
+
+
async def count_workspace_files(
workspace_id: str,
path_prefix: Optional[str] = None,
include_deleted: bool = False,
+ allowed_path_prefixes: Optional[list[str]] = None,
) -> int:
"""
Count files in a workspace.
@@ -347,10 +369,13 @@ async def count_workspace_files(
workspace_id: The workspace ID
path_prefix: Optional path prefix to filter (e.g., "/sessions/abc123/")
include_deleted: Whether to include soft-deleted files
+ allowed_path_prefixes: See :func:`list_workspace_files`.
Returns:
Number of files
"""
+ if allowed_path_prefixes is not None and not allowed_path_prefixes:
+ return 0
where_clause: UserWorkspaceFileWhereInput = {"workspaceId": workspace_id}
if not include_deleted:
where_clause["isDeleted"] = False
@@ -361,9 +386,39 @@ async def count_workspace_files(
path_prefix = f"/{path_prefix}"
where_clause["path"] = {"startswith": path_prefix}
+ if allowed_path_prefixes:
+ where_clause["AND"] = [{"OR": _path_prefix_filters(allowed_path_prefixes)}]
+
return await UserWorkspaceFile.prisma().count(where=where_clause)
+async def rename_workspace_file(
+ file_id: str,
+ workspace_id: str,
+ name: str,
+) -> Optional[WorkspaceFile]:
+ """Rename a file in place: its virtual path keeps its folder and gets the
+ new name; the storage blob is untouched.
+
+ Raises ``UniqueViolationError`` when another file already lives at the
+ resulting path, so the caller can answer with a conflict.
+
+ Returns the updated file, or None when it does not exist in the workspace.
+ """
+ file = await get_workspace_file(file_id, workspace_id)
+ if file is None:
+ return None
+ new_path = posixpath.join(posixpath.dirname(file.path), name)
+ updated = await UserWorkspaceFile.prisma().update(
+ where={"id": file_id},
+ data={"name": name, "path": new_path},
+ )
+ if updated is None:
+ return None
+ logger.info(f"Renamed workspace file {file_id} to {new_path}")
+ return WorkspaceFile.from_db(updated)
+
+
async def soft_delete_workspace_file(
file_id: str,
workspace_id: str,
@@ -427,6 +482,38 @@ async def resolve_workspace_files(
)
+async def resolve_attachable_workspace_files(
+ user_id: str,
+ file_ids: list[str],
+ *,
+ session_id: str,
+ expert_id: str | None,
+) -> list[UserWorkspaceFile]:
+ """Resolve attachment IDs for a message sent in ``session_id``.
+
+ Personal AutoPilot sessions may attach any file in the owner's workspace.
+ Expert sessions are confined to the expert's resolved scope: attaching a
+ file from another expert's conversations raises
+ ``WorkspaceAccessDeniedError`` naming the files, so the caller can surface
+ a clear error instead of leaking the file's metadata into the turn.
+
+ Runs in the API server with direct DB access, so the resolver is called
+ in-process; code in the executor must go through ``workspace_db()``.
+ """
+ files = await resolve_workspace_files(user_id, file_ids)
+ if expert_id is None or not files:
+ return files
+ scope = await resolve_expert_workspace_scope(user_id, expert_id)
+ scope = scope.with_session(session_id)
+ denied = [f.name for f in files if not scope.allows_path(f.path)]
+ if denied:
+ raise WorkspaceAccessDeniedError(
+ "These files are outside this expert's conversations and cannot be "
+ f"attached here: {', '.join(denied)}. Upload them in this chat instead."
+ )
+ return files
+
+
def build_files_block(files: list[UserWorkspaceFile]) -> str:
"""Return a formatted ``[Attached files]`` block for injection into a message.
diff --git a/autogpt_platform/backend/backend/data/workspace_scope.py b/autogpt_platform/backend/backend/data/workspace_scope.py
new file mode 100644
index 0000000000..969ff1569a
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/workspace_scope.py
@@ -0,0 +1,114 @@
+"""Trusted file scope for expert chat sessions.
+
+Resolved from persisted session attribution, never from tool arguments. An
+expert session may read and write under its own conversations, read under
+conversations it delegated, and read the account's skills registry. ``None``
+scope means unrestricted: the account owner acting through personal
+AutoPilot, REST endpoints, or system paths.
+"""
+
+import posixpath
+from typing import cast
+
+import prisma
+from prisma.enums import ResourceVisibility
+from prisma.models import ChatSession as PrismaChatSession
+from prisma.models import Expert as PrismaExpert
+from pydantic import BaseModel, Field
+
+SESSIONS_ROOT = "/sessions/"
+SKILLS_ROOT = "/skills/"
+
+EXPERT_FILE_ACCESS_DENIED = (
+ "This file is outside this expert's scope. Experts can only access files "
+ "from their own conversations. Open personal AutoPilot to work with other "
+ "files."
+)
+
+
+class WorkspaceAccessDeniedError(PermissionError):
+ """A workspace operation fell outside the caller's resolved scope."""
+
+
+def session_path_prefix(session_id: str) -> str:
+ return f"{SESSIONS_ROOT}{session_id}/"
+
+
+class WorkspaceScope(BaseModel):
+ """Grants for one acting session. Safe for RPC transport.
+
+ ``expert_id`` is ``None`` when nobody could be attributed; such a scope
+ only carries the sessions a caller added explicitly.
+ """
+
+ expert_id: str | None = None
+ session_ids: list[str] = Field(default_factory=list)
+ delegated_session_ids: list[str] = Field(default_factory=list)
+
+ def with_session(self, session_id: str) -> "WorkspaceScope":
+ if session_id in self.session_ids:
+ return self
+ return self.model_copy(update={"session_ids": [*self.session_ids, session_id]})
+
+ @property
+ def write_prefixes(self) -> list[str]:
+ return [session_path_prefix(s) for s in self.session_ids]
+
+ @property
+ def read_prefixes(self) -> list[str]:
+ return (
+ self.write_prefixes
+ + [session_path_prefix(s) for s in self.delegated_session_ids]
+ + [SKILLS_ROOT]
+ )
+
+ def allows_path(self, path: str, *, write: bool = False) -> bool:
+ if not path.startswith("/") or "\\" in path or posixpath.normpath(path) != path:
+ return False
+ prefixes = self.write_prefixes if write else self.read_prefixes
+ return any(path.startswith(prefix) for prefix in prefixes)
+
+
+async def resolve_expert_workspace_scope(
+ user_id: str, expert_id: str
+) -> WorkspaceScope:
+ """Resolve the grants for *expert_id* owned by *user_id*.
+
+ Own conversations are every session attributed to the expert, so a new
+ conversation keeps reaching files from earlier ones. Fails closed: a
+ missing, archived, or foreign expert yields no session grants at all
+ (callers add the current session explicitly). The ``visibility`` filter
+ mirrors ``experts_db.get_expert``: hired experts are PRIVATE in v1, and
+ a TEAM/ORG expert must not read files until sharing rules exist for it.
+ """
+ expert = await PrismaExpert.prisma().find_first(
+ where={
+ "id": expert_id,
+ "ownerUserId": user_id,
+ "isTemplate": False,
+ "isArchived": False,
+ "visibility": ResourceVisibility.PRIVATE,
+ }
+ )
+ if expert is None:
+ return WorkspaceScope(expert_id=expert_id)
+
+ own_sessions = await PrismaChatSession.prisma().find_many(
+ where={"userId": user_id, "expertId": expert_id}
+ )
+ delegated_sessions = await PrismaChatSession.prisma().find_many(
+ where={
+ "userId": user_id,
+ "metadata": cast(
+ prisma.types.JsonFilter,
+ {"path": ["delegated_by_expert_id"], "equals": prisma.Json(expert_id)},
+ ),
+ }
+ )
+ return WorkspaceScope(
+ expert_id=expert_id,
+ session_ids=[row.id for row in own_sessions],
+ delegated_session_ids=[
+ row.id for row in delegated_sessions if row.expertId != expert_id
+ ],
+ )
diff --git a/autogpt_platform/backend/backend/data/workspace_scope_db_test.py b/autogpt_platform/backend/backend/data/workspace_scope_db_test.py
new file mode 100644
index 0000000000..ec5c73244a
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/workspace_scope_db_test.py
@@ -0,0 +1,144 @@
+"""Real-database coverage for the expert scope resolver: own and delegated
+conversations, the JSON metadata filter, and two-expert file isolation that
+survives new conversations."""
+
+import uuid
+
+import prisma.models
+import pytest
+
+from backend.copilot.db import create_chat_session
+from backend.copilot.model import ChatSessionMetadata
+from backend.data.user import get_or_create_user
+from backend.data.workspace import (
+ count_workspace_files,
+ create_workspace_file,
+ get_or_create_workspace,
+ list_workspace_files,
+)
+from backend.data.workspace_scope import resolve_expert_workspace_scope
+from backend.util.test import SpinTestServer
+
+
+async def _user() -> str:
+ suffix = uuid.uuid4().hex[:8]
+ user = await get_or_create_user(
+ {
+ "sub": str(uuid.uuid4()),
+ "email": f"scope-{suffix}@example.com",
+ "name": "Scope Owner",
+ }
+ )
+ return user.id
+
+
+async def _expert(user_id: str) -> str:
+ row = await prisma.models.Expert.prisma().create(
+ data={
+ "ownerUserId": user_id,
+ "name": "Nova",
+ "role": "",
+ "identity": "nova",
+ "skills": [],
+ }
+ )
+ return row.id
+
+
[email protected](loop_scope="session")
+async def test_resolver_collects_own_and_delegated_conversations(
+ server: SpinTestServer,
+):
+ owner = await _user()
+ expert_a = await _expert(owner)
+ expert_b = await _expert(owner)
+ own = await create_chat_session(str(uuid.uuid4()), owner, expert_id=expert_a)
+ foreign = await create_chat_session(str(uuid.uuid4()), owner, expert_id=expert_b)
+ personal = await create_chat_session(str(uuid.uuid4()), owner)
+ delegated = await create_chat_session(
+ str(uuid.uuid4()),
+ owner,
+ expert_id=expert_b,
+ metadata=ChatSessionMetadata(
+ delegated_by_expert_id=expert_a, delegated_by_session_id=own.session_id
+ ),
+ )
+
+ scope = await resolve_expert_workspace_scope(owner, expert_a)
+
+ assert scope.session_ids == [own.session_id]
+ assert scope.delegated_session_ids == [delegated.session_id]
+ assert scope.allows_path(f"/sessions/{own.session_id}/x.txt", write=True)
+ assert scope.allows_path(f"/sessions/{delegated.session_id}/x.txt")
+ assert not scope.allows_path(f"/sessions/{delegated.session_id}/x.txt", write=True)
+ assert not scope.allows_path(f"/sessions/{foreign.session_id}/x.txt")
+ assert not scope.allows_path(f"/sessions/{personal.session_id}/x.txt")
+ assert scope.allows_path("/skills/autopilot/SKILL.md")
+ assert not scope.allows_path("/skills/autopilot/SKILL.md", write=True)
+
+
[email protected](loop_scope="session")
+async def test_resolver_fails_closed_for_foreign_or_archived_expert(
+ server: SpinTestServer,
+):
+ owner = await _user()
+ stranger = await _user()
+ expert = await _expert(stranger)
+ session = await create_chat_session(str(uuid.uuid4()), stranger, expert_id=expert)
+
+ foreign_scope = await resolve_expert_workspace_scope(owner, expert)
+ assert foreign_scope.session_ids == []
+ assert foreign_scope.delegated_session_ids == []
+ assert not foreign_scope.allows_path(f"/sessions/{session.session_id}/x.txt")
+
+ await prisma.models.Expert.prisma().update(
+ where={"id": expert}, data={"isArchived": True}
+ )
+ archived_scope = await resolve_expert_workspace_scope(stranger, expert)
+ assert archived_scope.session_ids == []
+ assert not archived_scope.allows_path(f"/sessions/{session.session_id}/x.txt")
+
+
[email protected](loop_scope="session")
+async def test_two_experts_files_stay_separate_across_new_conversations(
+ server: SpinTestServer,
+):
+ owner = await _user()
+ expert_a = await _expert(owner)
+ expert_b = await _expert(owner)
+ a_first = await create_chat_session(str(uuid.uuid4()), owner, expert_id=expert_a)
+ workspace = await get_or_create_workspace(owner)
+ stored = await create_workspace_file(
+ workspace_id=workspace.id,
+ file_id=str(uuid.uuid4()),
+ name="plan.md",
+ path=f"/sessions/{a_first.session_id}/plan.md",
+ storage_path=f"{workspace.id}/plan.md",
+ mime_type="text/markdown",
+ size_bytes=4,
+ )
+
+ a_new = await create_chat_session(str(uuid.uuid4()), owner, expert_id=expert_a)
+ b_new = await create_chat_session(str(uuid.uuid4()), owner, expert_id=expert_b)
+ scope_a = await resolve_expert_workspace_scope(owner, expert_a)
+ scope_a = scope_a.with_session(a_new.session_id)
+ scope_b = await resolve_expert_workspace_scope(owner, expert_b)
+ scope_b = scope_b.with_session(b_new.session_id)
+
+ assert scope_a.allows_path(stored.path)
+ assert not scope_b.allows_path(stored.path)
+
+ listed_for_a = await list_workspace_files(
+ workspace.id, allowed_path_prefixes=scope_a.read_prefixes
+ )
+ listed_for_b = await list_workspace_files(
+ workspace.id, allowed_path_prefixes=scope_b.read_prefixes
+ )
+ assert [f.id for f in listed_for_a] == [stored.id]
+ assert listed_for_b == []
+ assert (
+ await count_workspace_files(
+ workspace.id, allowed_path_prefixes=scope_b.read_prefixes
+ )
+ == 0
+ )
diff --git a/autogpt_platform/backend/backend/data/workspace_scope_test.py b/autogpt_platform/backend/backend/data/workspace_scope_test.py
new file mode 100644
index 0000000000..6a5996a6b6
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/workspace_scope_test.py
@@ -0,0 +1,74 @@
+import pytest
+
+from backend.data import workspace as workspace_module
+from backend.data.workspace_scope import WorkspaceScope, resolve_expert_workspace_scope
+
+SCOPE = WorkspaceScope(
+ expert_id="expert-a",
+ session_ids=["expert-a", "expert-a-old"],
+ delegated_session_ids=["sub-1"],
+)
+
+
+ "path",
+ ["/sessions/expert-a/file.txt", "/sessions/expert-a-old/nested/file.txt"],
+)
+def test_own_conversations_are_readable_and_writable(path: str):
+ assert SCOPE.allows_path(path)
+ assert SCOPE.allows_path(path, write=True)
+
+
+ "path",
+ [
+ "/sessions/sub-1/result.json",
+ "/skills/autopilot-skill/SKILL.md",
+ "/skills/autopilot-skill/references/notes.md",
+ ],
+)
+def test_delegated_conversations_and_skills_registry_are_read_only(path: str):
+ assert SCOPE.allows_path(path)
+ assert not SCOPE.allows_path(path, write=True)
+
+
+ "path",
+ [
+ "/sessions/expert-b/private.txt",
+ "/sessions/personal/private.txt",
+ "/sessions/expert-a-older/private.txt",
+ "/sessions/expert-a/../expert-b/private.txt",
+ "/sessions/expert-a//file.txt",
+ "sessions/expert-a/file.txt",
+ "/sessions/expert-a/..\\expert-b/x",
+ "/skills",
+ "/skillsets/private.txt",
+ "/experts/expert-a/skills/mine/SKILL.md",
+ "/root-file.txt",
+ ],
+)
+def test_everything_else_is_denied(path: str):
+ assert not SCOPE.allows_path(path)
+ assert not SCOPE.allows_path(path, write=True)
+
+
+def test_session_only_scope_carries_no_expert_grants():
+ scope = WorkspaceScope(session_ids=["only"])
+ assert scope.expert_id is None
+ assert scope.allows_path("/sessions/only/file.txt", write=True)
+ assert not scope.allows_path("/sessions/other/file.txt")
+
+
+def test_resolver_is_reachable_through_the_direct_db_accessor():
+ assert (
+ workspace_module.resolve_expert_workspace_scope
+ is resolve_expert_workspace_scope
+ )
+
+
+def test_with_session_returns_new_scope_without_mutating():
+ widened = SCOPE.with_session("expert-a-new")
+ assert "expert-a-new" in widened.session_ids
+ assert "expert-a-new" not in SCOPE.session_ids
+ assert widened.with_session("expert-a-new") is widened
diff --git a/autogpt_platform/backend/backend/platform_linking/db.py b/autogpt_platform/backend/backend/platform_linking/db.py
index 9fb58f3373..f376e38834 100644
--- a/autogpt_platform/backend/backend/platform_linking/db.py
+++ b/autogpt_platform/backend/backend/platform_linking/db.py
@@ -16,6 +16,11 @@ from prisma.models import PlatformLink, PlatformLinkToken, PlatformUserLink
from backend.copilot.db import get_chat_session_metadata
from backend.data.db import transaction
from backend.data.workspace import get_workspace, get_workspace_file
+from backend.data.workspace_scope import (
+ WorkspaceAccessDeniedError,
+ WorkspaceScope,
+ resolve_expert_workspace_scope,
+)
from backend.util.exceptions import (
LinkAlreadyExistsError,
LinkFlowMismatchError,
@@ -514,7 +519,9 @@ async def fetch_workspace_artifact(
The session→user→workspace→file chain is load-bearing: the LLM emits
arbitrary ``workspace://`` URIs in the chat stream, so we must never
serve a file just because the bot claimed an ID — only files owned by
- the same user the session belongs to are returned.
+ the same user the session belongs to are returned. An expert session is
+ further confined to that expert's file scope, exactly like the copilot
+ tools; a file outside it is treated as not found.
"""
session = await get_chat_session_metadata(session_id)
if session is None:
@@ -545,11 +552,26 @@ async def fetch_workspace_artifact(
)
return None
+ scope: WorkspaceScope | None = None
+ if session.expert_id is not None:
+ scope = await resolve_expert_workspace_scope(session.user_id, session.expert_id)
+ scope = scope.with_session(session_id)
manager = WorkspaceManager(
- user_id=session.user_id, workspace_id=workspace.id, session_id=session_id
+ user_id=session.user_id,
+ workspace_id=workspace.id,
+ session_id=session_id,
+ scope=scope,
)
try:
content = await manager.read_file_by_id(file_id)
+ except WorkspaceAccessDeniedError:
+ logger.warning(
+ "fetch_workspace_artifact: file %s is outside the scope of expert "
+ "session %s",
+ file_id,
+ session_id,
+ )
+ return None
except FileNotFoundError:
# DB row exists but the storage blob is gone — genuinely unexpected,
# so keep this one at warning level.
diff --git a/autogpt_platform/backend/backend/platform_linking/db_test.py b/autogpt_platform/backend/backend/platform_linking/db_test.py
index 70d79b40d3..2b7e7bcc1a 100644
--- a/autogpt_platform/backend/backend/platform_linking/db_test.py
+++ b/autogpt_platform/backend/backend/platform_linking/db_test.py
@@ -2,10 +2,12 @@
from contextlib import asynccontextmanager
from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from backend.data.workspace_scope import WorkspaceAccessDeniedError, WorkspaceScope
from backend.util.exceptions import (
LinkAlreadyExistsError,
LinkFlowMismatchError,
@@ -23,6 +25,7 @@ from .db import (
create_user_link_token,
delete_server_link,
delete_user_link,
+ fetch_workspace_artifact,
get_link_token_info,
get_link_token_status,
refresh_server_link_name,
@@ -554,3 +557,85 @@ class TestRefreshServerLinkName:
)
# Must not raise.
await refresh_server_link_name("DISCORD", "g1", "x")
+
+
+# ── Fetch workspace artifact: expert file scope ─────────────────────
+
+
+def _artifact_patches(*, expert_id: str | None, manager: MagicMock):
+ session = SimpleNamespace(user_id="user-1", expert_id=expert_id)
+ file = SimpleNamespace(name="report.txt", mime_type="text/plain", size_bytes=10)
+ return (
+ patch(
+ "backend.platform_linking.db.get_chat_session_metadata",
+ new=AsyncMock(return_value=session),
+ ),
+ patch(
+ "backend.platform_linking.db.get_workspace",
+ new=AsyncMock(return_value=SimpleNamespace(id="ws-1")),
+ ),
+ patch(
+ "backend.platform_linking.db.get_workspace_file",
+ new=AsyncMock(return_value=file),
+ ),
+ patch("backend.platform_linking.db.WorkspaceManager", return_value=manager),
+ )
+
+
+class TestFetchWorkspaceArtifactExpertScope:
+ @pytest.mark.asyncio
+ async def test_expert_session_cannot_fetch_a_file_outside_its_scope(self):
+ scope = WorkspaceScope(expert_id="expert-a", session_ids=["older"])
+ manager = MagicMock()
+ manager.read_file_by_id = AsyncMock(
+ side_effect=WorkspaceAccessDeniedError("denied")
+ )
+ session_p, workspace_p, file_p, manager_p = _artifact_patches(
+ expert_id="expert-a", manager=manager
+ )
+ with (
+ session_p,
+ workspace_p,
+ file_p,
+ manager_p as manager_cls,
+ patch(
+ "backend.platform_linking.db.resolve_expert_workspace_scope",
+ new=AsyncMock(return_value=scope),
+ ) as resolve_mock,
+ ):
+ result = await fetch_workspace_artifact("sess-1", "file-1", max_bytes=100)
+
+ assert result is None
+ resolve_mock.assert_awaited_once_with("user-1", "expert-a")
+ manager_cls.assert_called_once_with(
+ user_id="user-1",
+ workspace_id="ws-1",
+ session_id="sess-1",
+ scope=scope.with_session("sess-1"),
+ )
+
+ @pytest.mark.asyncio
+ async def test_personal_session_keeps_owner_access(self):
+ manager = MagicMock()
+ manager.read_file_by_id = AsyncMock(return_value=b"data")
+ session_p, workspace_p, file_p, manager_p = _artifact_patches(
+ expert_id=None, manager=manager
+ )
+ with (
+ session_p,
+ workspace_p,
+ file_p,
+ manager_p as manager_cls,
+ patch(
+ "backend.platform_linking.db.resolve_expert_workspace_scope",
+ new=AsyncMock(),
+ ) as resolve_mock,
+ ):
+ result = await fetch_workspace_artifact("sess-1", "file-1", max_bytes=100)
+
+ assert result is not None
+ assert result.content == b"data"
+ resolve_mock.assert_not_awaited()
+ manager_cls.assert_called_once_with(
+ user_id="user-1", workspace_id="ws-1", session_id="sess-1", scope=None
+ )
diff --git a/autogpt_platform/backend/backend/util/file.py b/autogpt_platform/backend/backend/util/file.py
index c8e58ee1d6..2edf53403e 100644
--- a/autogpt_platform/backend/backend/util/file.py
+++ b/autogpt_platform/backend/backend/util/file.py
@@ -20,6 +20,7 @@ MAX_FILE_SIZE_BYTES = Config().max_file_size_mb * 1024 * 1024
if TYPE_CHECKING:
from backend.data.execution import ExecutionContext
+ from backend.data.workspace_scope import WorkspaceScope
class WorkspaceUri(BaseModel):
@@ -116,6 +117,33 @@ def clean_exec_files(graph_exec_id: str, file: str = "") -> None:
shutil.rmtree(exec_path)
+async def _expert_workspace_scope(
+ execution_context: "ExecutionContext",
+) -> "WorkspaceScope | None":
+ """Confine blocks an expert runs from its chat to the expert's own files.
+
+ Mirrors the copilot tools: a block run inside an expert's conversation can
+ only resolve ``workspace://`` references inside that expert's
+ conversations. Expert-attributed runs without a session (schedules,
+ webhooks, presets) write their outputs at the workspace root, so they
+ keep the owner's full workspace until they get a folder of their own.
+ Runs without expert attribution keep it too.
+ """
+ if (
+ not execution_context.expert_id
+ or not execution_context.session_id
+ or not execution_context.user_id
+ ):
+ return None
+ # Import here to avoid circular import (see store_media_file)
+ from backend.data.db_accessors import workspace_db
+
+ scope = await workspace_db().resolve_expert_workspace_scope(
+ execution_context.user_id, execution_context.expert_id
+ )
+ return scope.with_session(execution_context.session_id)
+
+
async def store_media_file(
file: MediaFileType,
execution_context: "ExecutionContext",
@@ -160,7 +188,10 @@ async def store_media_file(
workspace_manager: WorkspaceManager | None = None
if execution_context.workspace_id:
workspace_manager = WorkspaceManager(
- user_id, execution_context.workspace_id, execution_context.session_id
+ user_id,
+ execution_context.workspace_id,
+ execution_context.session_id,
+ scope=await _expert_workspace_scope(execution_context),
)
# Build base path
base_path = Path(get_exec_file_path(graph_exec_id, ""))
diff --git a/autogpt_platform/backend/backend/util/file_test.py b/autogpt_platform/backend/backend/util/file_test.py
index 9b87df0417..5d8e546f12 100644
--- a/autogpt_platform/backend/backend/util/file_test.py
+++ b/autogpt_platform/backend/backend/util/file_test.py
@@ -8,6 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.data.execution import ExecutionContext
+from backend.data.workspace_scope import WorkspaceAccessDeniedError, WorkspaceScope
from backend.util.file import (
is_media_file_ref,
parse_data_uri,
@@ -38,13 +39,11 @@ class TestFileCloudIntegration:
cloud_path = "gcs://test-bucket/uploads/456/source.txt"
cloud_content = b"cloud file content"
- with patch(
- "backend.util.file.get_cloud_storage_handler"
- ) as mock_handler_getter, patch(
- "backend.util.file.scan_content_safe"
- ) as mock_scan, patch(
- "backend.util.file.Path"
- ) as mock_path_class:
+ with (
+ patch("backend.util.file.get_cloud_storage_handler") as mock_handler_getter,
+ patch("backend.util.file.scan_content_safe") as mock_scan,
+ patch("backend.util.file.Path") as mock_path_class,
+ ):
# Mock cloud storage handler
mock_handler = MagicMock()
@@ -115,17 +114,13 @@ class TestFileCloudIntegration:
cloud_path = "gcs://test-bucket/uploads/456/image.png"
cloud_content = b"\\x89PNG\\r\\n\\x1a\\n\\x00\\x00\\x00\\rIHDR" # PNG header
- with patch(
- "backend.util.file.get_cloud_storage_handler"
- ) as mock_handler_getter, patch(
- "backend.util.file.scan_content_safe"
- ) as mock_scan, patch(
- "backend.util.file.get_mime_type"
- ) as mock_mime, patch(
- "backend.util.file.base64.b64encode"
- ) as mock_b64, patch(
- "backend.util.file.Path"
- ) as mock_path_class:
+ with (
+ patch("backend.util.file.get_cloud_storage_handler") as mock_handler_getter,
+ patch("backend.util.file.scan_content_safe") as mock_scan,
+ patch("backend.util.file.get_mime_type") as mock_mime,
+ patch("backend.util.file.base64.b64encode") as mock_b64,
+ patch("backend.util.file.Path") as mock_path_class,
+ ):
# Mock cloud storage handler
mock_handler = MagicMock()
@@ -174,17 +169,13 @@ class TestFileCloudIntegration:
graph_exec_id = "test-exec-123"
data_uri = "data:text/plain;base64,SGVsbG8gd29ybGQ="
- with patch(
- "backend.util.file.get_cloud_storage_handler"
- ) as mock_handler_getter, patch(
- "backend.util.file.scan_content_safe"
- ) as mock_scan, patch(
- "backend.util.file.base64.b64decode"
- ) as mock_b64decode, patch(
- "backend.util.file.uuid.uuid4"
- ) as mock_uuid, patch(
- "backend.util.file.Path"
- ) as mock_path_class:
+ with (
+ patch("backend.util.file.get_cloud_storage_handler") as mock_handler_getter,
+ patch("backend.util.file.scan_content_safe") as mock_scan,
+ patch("backend.util.file.base64.b64decode") as mock_b64decode,
+ patch("backend.util.file.uuid.uuid4") as mock_uuid,
+ patch("backend.util.file.Path") as mock_path_class,
+ ):
# Mock cloud storage handler
mock_handler = MagicMock()
@@ -260,13 +251,11 @@ class TestFileCloudIntegration:
local_file = "test_video.mp4"
file_content = b"fake video content"
- with patch(
- "backend.util.file.get_cloud_storage_handler"
- ) as mock_handler_getter, patch(
- "backend.util.file.scan_content_safe"
- ) as mock_scan, patch(
- "backend.util.file.Path"
- ) as mock_path_class:
+ with (
+ patch("backend.util.file.get_cloud_storage_handler") as mock_handler_getter,
+ patch("backend.util.file.scan_content_safe") as mock_scan,
+ patch("backend.util.file.Path") as mock_path_class,
+ ):
# Mock cloud storage handler - not a cloud path
mock_handler = MagicMock()
@@ -312,13 +301,11 @@ class TestFileCloudIntegration:
local_file = "infected.exe"
file_content = b"malicious content"
- with patch(
- "backend.util.file.get_cloud_storage_handler"
- ) as mock_handler_getter, patch(
- "backend.util.file.scan_content_safe"
- ) as mock_scan, patch(
- "backend.util.file.Path"
- ) as mock_path_class:
+ with (
+ patch("backend.util.file.get_cloud_storage_handler") as mock_handler_getter,
+ patch("backend.util.file.scan_content_safe") as mock_scan,
+ patch("backend.util.file.Path") as mock_path_class,
+ ):
# Mock cloud storage handler - not a cloud path
mock_handler = MagicMock()
@@ -508,3 +495,114 @@ class TestResolveMediaContent:
ctx,
return_format="for_local_processing",
)
+
+
+# ---------------------------------------------------------------------------
+# store_media_file: expert-attributed runs
+# ---------------------------------------------------------------------------
+
+
+class TestStoreMediaFileExpertScope:
+ """Blocks an expert runs from its chat resolve ``workspace://`` refs inside
+ the expert's own conversations only; session-less and owner runs keep the
+ full workspace."""
+
+ @pytest.mark.asyncio
+ async def test_expert_run_confines_workspace_refs_to_the_expert(self):
+ ctx = ExecutionContext(
+ user_id="user-1",
+ graph_exec_id="exec-1",
+ workspace_id="ws-1",
+ session_id="sess-1",
+ expert_id="expert-a",
+ )
+ scope = WorkspaceScope(expert_id="expert-a", session_ids=["older"])
+ db = MagicMock()
+ db.resolve_expert_workspace_scope = AsyncMock(return_value=scope)
+ manager = MagicMock()
+ manager.read_file_by_id = AsyncMock(
+ side_effect=WorkspaceAccessDeniedError("denied")
+ )
+ with (
+ patch(
+ "backend.util.file.get_cloud_storage_handler",
+ new=AsyncMock(return_value=MagicMock()),
+ ),
+ patch("backend.data.db_accessors.workspace_db", return_value=db),
+ patch(
+ "backend.util.workspace.WorkspaceManager", return_value=manager
+ ) as manager_cls,
+ pytest.raises(WorkspaceAccessDeniedError),
+ ):
+ await store_media_file(
+ MediaFileType("workspace://foreign-file"),
+ ctx,
+ return_format="for_local_processing",
+ )
+
+ db.resolve_expert_workspace_scope.assert_awaited_once_with("user-1", "expert-a")
+ manager_cls.assert_called_once_with(
+ "user-1", "ws-1", "sess-1", scope=scope.with_session("sess-1")
+ )
+
+ @pytest.mark.asyncio
+ async def test_expert_run_without_a_session_keeps_the_full_workspace(self):
+ """Scheduled, webhook and preset runs of an expert's workflow have no
+ chat session and write at the workspace root, so they stay unscoped."""
+ ctx = ExecutionContext(
+ user_id="user-1",
+ graph_exec_id="exec-1",
+ workspace_id="ws-1",
+ expert_id="expert-a",
+ )
+ manager = MagicMock()
+ manager.read_file_by_id = AsyncMock(side_effect=RuntimeError("stop"))
+ with (
+ patch(
+ "backend.util.file.get_cloud_storage_handler",
+ new=AsyncMock(return_value=MagicMock()),
+ ),
+ patch("backend.data.db_accessors.workspace_db") as workspace_db,
+ patch(
+ "backend.util.workspace.WorkspaceManager", return_value=manager
+ ) as manager_cls,
+ pytest.raises(RuntimeError, match="stop"),
+ ):
+ await store_media_file(
+ MediaFileType("workspace://any-file"),
+ ctx,
+ return_format="for_local_processing",
+ )
+
+ workspace_db.assert_not_called()
+ manager_cls.assert_called_once_with("user-1", "ws-1", None, scope=None)
+
+ @pytest.mark.asyncio
+ async def test_owner_run_keeps_the_full_workspace(self):
+ ctx = ExecutionContext(
+ user_id="user-1",
+ graph_exec_id="exec-1",
+ workspace_id="ws-1",
+ session_id="sess-1",
+ )
+ manager = MagicMock()
+ manager.read_file_by_id = AsyncMock(side_effect=RuntimeError("stop"))
+ with (
+ patch(
+ "backend.util.file.get_cloud_storage_handler",
+ new=AsyncMock(return_value=MagicMock()),
+ ),
+ patch("backend.data.db_accessors.workspace_db") as workspace_db,
+ patch(
+ "backend.util.workspace.WorkspaceManager", return_value=manager
+ ) as manager_cls,
+ pytest.raises(RuntimeError, match="stop"),
+ ):
+ await store_media_file(
+ MediaFileType("workspace://any-file"),
+ ctx,
+ return_format="for_local_processing",
+ )
+
+ workspace_db.assert_not_called()
+ manager_cls.assert_called_once_with("user-1", "ws-1", "sess-1", scope=None)
diff --git a/autogpt_platform/backend/backend/util/workspace.py b/autogpt_platform/backend/backend/util/workspace.py
index 681d5ffd19..f93e0875bc 100644
--- a/autogpt_platform/backend/backend/util/workspace.py
+++ b/autogpt_platform/backend/backend/util/workspace.py
@@ -16,6 +16,11 @@ from prisma.errors import UniqueViolationError
from backend.copilot.rate_limit import get_workspace_storage_limit_bytes
from backend.data.db_accessors import workspace_db
from backend.data.workspace import WorkspaceFile
+from backend.data.workspace_scope import (
+ EXPERT_FILE_ACCESS_DENIED,
+ WorkspaceAccessDeniedError,
+ WorkspaceScope,
+)
from backend.util.settings import Config
from backend.util.virus_scanner import scan_content_safe
from backend.util.workspace_storage import compute_file_checksum, get_workspace_storage
@@ -48,7 +53,11 @@ class WorkspaceManager:
"""
def __init__(
- self, user_id: str, workspace_id: str, session_id: Optional[str] = None
+ self,
+ user_id: str,
+ workspace_id: str,
+ session_id: Optional[str] = None,
+ scope: Optional[WorkspaceScope] = None,
):
"""
Initialize WorkspaceManager.
@@ -57,13 +66,46 @@ class WorkspaceManager:
user_id: The user's ID
workspace_id: The workspace ID
session_id: Optional session ID for session-scoped file access
+ scope: Resolved grants for an expert session. ``None`` means the
+ account owner is acting and every file in the workspace is
+ reachable. When set, every operation — by path or by file ID,
+ including listings and counts — is confined to the scope.
"""
self.user_id = user_id
self.workspace_id = workspace_id
self.session_id = session_id
+ self.scope = scope
# Session path prefix for file isolation
self.session_path = f"/sessions/{session_id}" if session_id else ""
+ def _authorize_path(self, path: str, *, write: bool = False) -> None:
+ if self.scope is not None and not self.scope.allows_path(path, write=write):
+ logger.warning(
+ "Workspace access denied for expert %s (write=%s): %s",
+ self.scope.expert_id,
+ write,
+ path,
+ )
+ raise WorkspaceAccessDeniedError(EXPERT_FILE_ACCESS_DENIED)
+
+ def _authorize_file(self, file: WorkspaceFile, *, write: bool = False) -> None:
+ self._authorize_path(file.path, write=write)
+
+ def _allowed_prefixes(
+ self, requested: Optional[list[str]] = None
+ ) -> Optional[list[str]]:
+ """Prefixes a listing may span: the scope's, narrowed to ``requested``.
+
+ A requested prefix survives only if it lies inside a scope prefix, so
+ this argument can narrow an expert's reach but never widen it.
+ """
+ if self.scope is None:
+ return requested
+ allowed = self.scope.read_prefixes
+ if requested is None:
+ return allowed
+ return [p for p in requested if any(p.startswith(a) for a in allowed)]
+
def _resolve_path(self, path: str) -> str:
"""
Resolve a path, defaulting to session folder if session_id is set.
@@ -137,6 +179,7 @@ class WorkspaceManager:
"""
db = workspace_db()
resolved_path = self._resolve_path(path)
+ self._authorize_path(resolved_path)
file = await db.get_workspace_file_by_path(self.workspace_id, resolved_path)
if file is None:
raise FileNotFoundError(f"File not found at path: {resolved_path}")
@@ -161,6 +204,7 @@ class WorkspaceManager:
file = await db.get_workspace_file(file_id, self.workspace_id)
if file is None:
raise FileNotFoundError(f"File not found: {file_id}")
+ self._authorize_file(file)
storage = await get_workspace_storage()
return await storage.retrieve(file.storage_path)
@@ -218,6 +262,7 @@ class WorkspaceManager:
# Resolve path with session prefix
path = self._resolve_path(path)
+ self._authorize_path(path, write=True)
# Enforce per-user workspace storage quota (tier-based).
# For overwrites, subtract the existing file's size so replacing a file
@@ -355,6 +400,7 @@ class WorkspaceManager:
metadata_not_equals: Optional[dict] = None,
folder_id: Optional[str] = None,
root_only: bool = False,
+ allowed_path_prefixes: Optional[list[str]] = None,
) -> list[WorkspaceFile]:
"""
List files in workspace.
@@ -379,6 +425,9 @@ class WorkspaceManager:
this object (Artifacts "Generated" filter).
folder_id: If set, only return files in this folder.
root_only: If True, only return root-level files (folderId IS NULL).
+ allowed_path_prefixes: Only list files under these prefixes. When
+ the manager carries a scope the prefixes are intersected with
+ it (see :meth:`_allowed_prefixes`).
Returns:
List of WorkspaceFile instances
@@ -397,6 +446,7 @@ class WorkspaceManager:
metadata_not_equals=metadata_not_equals,
folder_id=folder_id,
root_only=root_only,
+ allowed_path_prefixes=self._allowed_prefixes(allowed_path_prefixes),
)
async def delete_file(self, file_id: str) -> bool:
@@ -413,6 +463,7 @@ class WorkspaceManager:
file = await db.get_workspace_file(file_id, self.workspace_id)
if file is None:
return False
+ self._authorize_file(file, write=True)
# Delete from storage
storage = await get_workspace_storage()
@@ -459,6 +510,7 @@ class WorkspaceManager:
file = await db.get_workspace_file(file_id, self.workspace_id)
if file is None:
raise FileNotFoundError(f"File not found: {file_id}")
+ self._authorize_file(file)
storage = await get_workspace_storage()
return await storage.get_download_url(file.storage_path, expires_in)
@@ -471,10 +523,20 @@ class WorkspaceManager:
file_id: The file's ID
Returns:
- WorkspaceFile instance or None
+ WorkspaceFile instance, or None when no such file exists.
+
+ Raises:
+ WorkspaceAccessDeniedError: the file exists but lies outside this
+ manager's scope. Deliberately not folded into ``None`` so an
+ expert sees "access denied" rather than "not found" for a
+ file it cannot reach; every caller either surfaces it as such
+ or treats it like any other failure to read the file.
"""
db = workspace_db()
- return await db.get_workspace_file(file_id, self.workspace_id)
+ file = await db.get_workspace_file(file_id, self.workspace_id)
+ if file is not None:
+ self._authorize_file(file)
+ return file
async def get_file_info_by_path(self, path: str) -> Optional[WorkspaceFile]:
"""
@@ -491,12 +553,14 @@ class WorkspaceManager:
"""
db = workspace_db()
resolved_path = self._resolve_path(path)
+ self._authorize_path(resolved_path)
return await db.get_workspace_file_by_path(self.workspace_id, resolved_path)
async def get_file_count(
self,
path: Optional[str] = None,
include_all_sessions: bool = False,
+ allowed_path_prefixes: Optional[list[str]] = None,
) -> int:
"""
Get number of files in workspace.
@@ -516,5 +580,7 @@ class WorkspaceManager:
db = workspace_db()
return await db.count_workspace_files(
- self.workspace_id, path_prefix=effective_path
+ self.workspace_id,
+ path_prefix=effective_path,
+ allowed_path_prefixes=self._allowed_prefixes(allowed_path_prefixes),
)
diff --git a/autogpt_platform/backend/backend/util/workspace_isolation_test.py b/autogpt_platform/backend/backend/util/workspace_isolation_test.py
new file mode 100644
index 0000000000..8033586cf2
--- /dev/null
+++ b/autogpt_platform/backend/backend/util/workspace_isolation_test.py
@@ -0,0 +1,164 @@
+"""Expert-scoped WorkspaceManager: every path- and ID-based operation must
+stay inside the expert's resolved grants."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+from backend.data.workspace_scope import WorkspaceAccessDeniedError, WorkspaceScope
+from backend.util.workspace import WorkspaceManager
+from backend.util.workspace_test import _make_workspace_file
+
+SCOPE = WorkspaceScope(
+ expert_id="expert-a",
+ session_ids=["expert-a", "expert-a-old"],
+ delegated_session_ids=["sub-1"],
+)
+
+
+def db():
+ db = MagicMock()
+ db.get_workspace_file = AsyncMock(
+ return_value=_make_workspace_file(path="/sessions/expert-b/private.txt")
+ )
+ db.get_workspace_file_by_path = AsyncMock(return_value=_make_workspace_file())
+ db.list_workspace_files = AsyncMock(return_value=[])
+ db.count_workspace_files = AsyncMock(return_value=0)
+ db.soft_delete_workspace_file = AsyncMock()
+ db.get_workspace_total_size = AsyncMock(return_value=0)
+ with patch("backend.util.workspace.workspace_db", return_value=db):
+ yield db
+
+
+def storage():
+ storage = AsyncMock()
+ storage.retrieve.return_value = b"allowed"
+ with patch("backend.util.workspace.get_workspace_storage", return_value=storage):
+ yield storage
+
+
+def _expert_manager() -> WorkspaceManager:
+ return WorkspaceManager("user-1", "ws-1", "expert-a", scope=SCOPE)
+
+
+def _skills_manager() -> WorkspaceManager:
+ """Session-less manager, as the skills registry builds it."""
+ return WorkspaceManager("user-1", "ws-1", None, scope=SCOPE)
+
+
+ "operation", ["read_file_by_id", "get_file_info", "delete_file", "get_download_url"]
+)
+async def test_foreign_file_id_is_denied(db, storage, operation: str):
+ with pytest.raises(WorkspaceAccessDeniedError):
+ await getattr(_expert_manager(), operation)("foreign-file")
+ storage.retrieve.assert_not_awaited()
+ storage.delete.assert_not_awaited()
+ storage.get_download_url.assert_not_awaited()
+ db.soft_delete_workspace_file.assert_not_awaited()
+
+
+ "path",
+ [
+ "/sessions/expert-b/private.txt",
+ "/sessions/personal/private.txt",
+ "/sessions/expert-a-older/private.txt",
+ "/sessions/expert-a/../expert-b/private.txt",
+ ],
+)
+async def test_explicit_paths_cannot_escape_scope(db, path: str):
+ manager = _expert_manager()
+ with pytest.raises(WorkspaceAccessDeniedError):
+ await manager.read_file(path)
+ with pytest.raises(WorkspaceAccessDeniedError):
+ await manager.get_file_info_by_path(path)
+ with pytest.raises(WorkspaceAccessDeniedError):
+ await manager.write_file(b"x", "private.txt", path=path, overwrite=True)
+ db.get_workspace_file_by_path.assert_not_awaited()
+
+
+ "path",
+ ["/skills/autopilot/SKILL.md", "/skills/autopilot/references/file.txt"],
+)
+async def test_skills_registry_is_readable_but_not_writable(db, storage, path: str):
+ assert await _skills_manager().read_file(path) == b"allowed"
+ with pytest.raises(WorkspaceAccessDeniedError):
+ await _skills_manager().write_file(b"x", "f", path=path, overwrite=True)
+
+
+ "path",
+ [
+ "relative.txt",
+ "/sessions/expert-a-old/file.txt",
+ "/sessions/sub-1/result.json",
+ ],
+)
+async def test_own_and_delegated_paths_are_readable(db, storage, path: str):
+ assert await _expert_manager().read_file(path) == b"allowed"
+
+
+ "path",
+ ["/experts/expert-a/skills/mine/SKILL.md", "/root-file.txt"],
+)
+async def test_paths_outside_any_grant_are_denied(db, path: str):
+ with pytest.raises(WorkspaceAccessDeniedError):
+ await _skills_manager().read_file(path)
+ db.get_workspace_file_by_path.assert_not_awaited()
+
+
+async def test_delegated_session_is_not_writable(db):
+ with pytest.raises(WorkspaceAccessDeniedError):
+ await _expert_manager().write_file(
+ b"x", "f", path="/sessions/sub-1/result.json", overwrite=True
+ )
+
+
+async def test_listing_and_counts_are_filtered_inside_the_query(db):
+ manager = _expert_manager()
+ await manager.list_files(include_all_sessions=True, limit=1, offset=4)
+ await manager.get_file_count(include_all_sessions=True)
+ list_kwargs = db.list_workspace_files.call_args.kwargs
+ assert list_kwargs["allowed_path_prefixes"] == SCOPE.read_prefixes
+ assert list_kwargs["path_prefix"] is None
+ assert list_kwargs["offset"] == 4
+ count_kwargs = db.count_workspace_files.call_args.kwargs
+ assert count_kwargs["allowed_path_prefixes"] == SCOPE.read_prefixes
+
+
+async def test_owner_without_scope_keeps_full_access(db, storage):
+ manager = WorkspaceManager("user-1", "ws-1", "personal")
+ assert await manager.read_file("/sessions/expert-b/private.txt") == b"allowed"
+ assert await manager.read_file_by_id("foreign-file") == b"allowed"
+ await manager.list_files(include_all_sessions=True)
+ assert db.list_workspace_files.call_args.kwargs["allowed_path_prefixes"] is None
+
+
+async def test_requested_prefixes_are_narrowed_to_the_scope(db):
+ manager = _expert_manager()
+ await manager.list_files(
+ include_all_sessions=True,
+ allowed_path_prefixes=["/sessions/expert-a/", "/sessions/expert-b/"],
+ )
+ assert db.list_workspace_files.call_args.kwargs["allowed_path_prefixes"] == [
+ "/sessions/expert-a/"
+ ]
+ await manager.get_file_count(
+ include_all_sessions=True, allowed_path_prefixes=["/sessions/expert-b/"]
+ )
+ assert db.count_workspace_files.call_args.kwargs["allowed_path_prefixes"] == []
+
+
+async def test_owner_without_scope_lists_the_requested_prefixes(db):
+ manager = WorkspaceManager("user-1", "ws-1", "personal")
+ await manager.list_files(
+ include_all_sessions=True, allowed_path_prefixes=["/sessions/expert-b/"]
+ )
+ assert db.list_workspace_files.call_args.kwargs["allowed_path_prefixes"] == [
+ "/sessions/expert-b/"
+ ]
diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/PlatformChrome.tsx b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/PlatformChrome.tsx
index 19154a7126..c0e5e59c49 100644
--- a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/PlatformChrome.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/PlatformChrome.tsx
@@ -20,6 +20,7 @@ import { WorkspaceFilesTrigger } from "../copilot/components/WorkspaceFilesTrigg
import { PaywallGate } from "../PaywallGate/PaywallGate";
import { ArtifactsPanelNavCollapse } from "./components/ArtifactsPanelNavCollapse/ArtifactsPanelNavCollapse";
import { BuilderSidebarAutoClose } from "./components/BuilderSidebarAutoClose/BuilderSidebarAutoClose";
+import { InsetHeaderActions } from "./components/InsetHeaderActions/InsetHeaderActions";
import { InsetHeaderTitle } from "./components/InsetHeaderTitle/InsetHeaderTitle";
import { usePlatformChrome } from "./usePlatformChrome";
@@ -103,6 +104,7 @@ export function PlatformChrome({ children }: Props) {
</div>
)}
<InsetHeaderTitle />
+ <InsetHeaderActions />
</div>
</header>
<AdminImpersonationBanner />
diff --git a/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/InsetHeaderActions/InsetHeaderActions.tsx b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/InsetHeaderActions/InsetHeaderActions.tsx
new file mode 100644
index 0000000000..2fd6dec611
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/PlatformChrome/components/InsetHeaderActions/InsetHeaderActions.tsx
@@ -0,0 +1,28 @@
+"use client";
+
+import { StorageUsage } from "@/app/(platform)/artifacts/components/StorageUsage/StorageUsage";
+import { usePathname } from "next/navigation";
+import type { ComponentType } from "react";
+
+// Right-hand companions to the inset header title, keyed the same way as
+// ROUTE_TITLES so a route's title and its header widget stay together.
+const ROUTE_ACTIONS: Record<string, ComponentType> = {
+ "/artifacts": StorageUsage,
+};
+
+export function InsetHeaderActions() {
+ const pathname = usePathname();
+ const match = pathname
+ ? Object.entries(ROUTE_ACTIONS).find(
+ ([href]) => pathname === href || pathname.startsWith(`${href}/`),
+ )
+ : undefined;
+ if (!match) return null;
+ const Actions = match[1];
+
+ return (
+ <div className="pointer-events-auto ml-auto hidden items-center md:flex">
+ <Actions />
+ </div>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/folders.test.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/folders.test.tsx
index 1472b88a35..1855f4070c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/folders.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/__tests__/folders.test.tsx
@@ -1,4 +1,4 @@
-import { describe, expect, test, vi } from "vitest";
+import { beforeEach, describe, expect, test, vi } from "vitest";
import {
fireEvent,
@@ -9,6 +9,7 @@ import {
import userEvent from "@testing-library/user-event";
import { server } from "@/mocks/mock-server";
import { http, HttpResponse } from "msw";
+import { getListExpertIdentitiesMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";
import {
getGetWorkspaceStorageUsageMockHandler,
getListWorkspaceFilesMockHandler,
@@ -24,6 +25,12 @@ vi.mock("@/services/feature-flags/use-get-flag", () => ({
useFlagStatus: () => ({ enabled: true, ready: true }),
}));
+// The generated default answers with random experts, which would render
+// random filter tabs on the page under test.
+beforeEach(() => {
+ server.use(getListExpertIdentitiesMockHandler([]));
+});
+
vi.mock("next/navigation", () => ({
useRouter: () => ({
push: vi.fn(),
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 54a027f378..6b1264a6a4 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
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
fireEvent,
@@ -8,12 +8,14 @@ import {
} from "@/tests/integrations/test-utils";
import { server } from "@/mocks/mock-server";
import { http, HttpResponse } from "msw";
+import { getListExpertIdentitiesMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";
import {
getGetWorkspaceStorageUsageMockHandler,
getListWorkspaceFilesMockHandler,
getListWorkspaceFilesMockHandler401,
getListWorkspaceFoldersMockHandler,
} from "@/app/api/__generated__/endpoints/workspace/workspace.msw";
+import type { ExpertIdentity } from "@/app/api/__generated__/models/expertIdentity";
import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
const { setFlagStatusMock, uploadFileDirectMock } = vi.hoisted(() => {
@@ -30,10 +32,17 @@ afterEach(() => {
uploadFileDirectMock.mockReset();
});
+// The generated default answers with random experts, which would render
+// random filter tabs; tests that care register their own roster.
+beforeEach(() => {
+ server.use(getListExpertIdentitiesMockHandler([]));
+});
+
vi.mock("@/services/feature-flags/use-get-flag", () => ({
Flag: {
ARTIFACTS_PAGE: "artifacts-page",
AUTOGPT_NEW_LAYOUT: "autogpt-new-layout",
+ HIRE_EXPERTS: "hire-experts",
},
useGetFlag: (flag: string) => flag !== "autogpt-new-layout",
useFlagStatus: () => setFlagStatusMock(),
@@ -113,6 +122,27 @@ function useFilesHandler(files: WorkspaceFileItem[]) {
);
}
+const HIRED_EXPERTS: ExpertIdentity[] = [
+ {
+ id: "expert-a",
+ name: "Nova",
+ avatar_url: null,
+ role: "Analyst",
+ is_archived: false,
+ },
+ {
+ id: "expert-b",
+ name: "Kai",
+ avatar_url: null,
+ role: "Writer",
+ is_archived: true,
+ },
+];
+
+function useExpertsHandler(experts: ExpertIdentity[] = HIRED_EXPERTS) {
+ server.use(getListExpertIdentitiesMockHandler(experts));
+}
+
// The row's name button is the tooltip trigger; focusing it opens the large
// preview without waiting for the hover delay.
async function openHoverPreview() {
@@ -727,3 +757,159 @@ describe("ArtifactsPage - file viewer modal", () => {
).toBeDefined();
});
});
+
+describe("ArtifactsPage - expert filter", () => {
+ test("offers hired experts and narrows the listing to the chosen one", async () => {
+ useStorageHandler();
+ useExpertsHandler();
+ const requests: { expertId: string | null; rootOnly: string | null }[] = [];
+ server.use(
+ http.get("/api/proxy/api/workspace/files", ({ request }) => {
+ const params = new URL(request.url).searchParams;
+ requests.push({
+ expertId: params.get("expert_id"),
+ rootOnly: params.get("root_only"),
+ });
+ return HttpResponse.json({ files: [], offset: 0, has_more: false });
+ }),
+ );
+
+ render(<ArtifactsPage />);
+
+ const novaTab = await screen.findByRole("tab", { name: "Nova" });
+ expect(screen.getByRole("tab", { name: "Everyone" })).toBeDefined();
+ // A fired expert is history, not a filter you can pick.
+ expect(screen.queryByRole("tab", { name: "Kai" })).toBeNull();
+
+ fireEvent.click(novaTab);
+
+ await waitFor(() => {
+ const last = requests[requests.length - 1];
+ expect(last.expertId).toBe("expert-a");
+ expect(last.rootOnly).toBe("false");
+ });
+ expect(novaTab.getAttribute("aria-selected")).toBe("true");
+ });
+
+ test("labels each file with the expert whose conversation it came from", async () => {
+ useStorageHandler();
+ useExpertsHandler();
+ useFilesHandler([
+ makeFile({ id: "f1", name: "plan.md", expert_id: "expert-a" }),
+ makeFile({ id: "f2", name: "notes.md", expert_id: null }),
+ ]);
+ server.use(getListWorkspaceFoldersMockHandler({ folders: [] }));
+
+ render(<ArtifactsPage />);
+
+ expect(await screen.findByText("notes.md")).toBeDefined();
+ const badges = await screen.findAllByTestId("artifacts-expert-badge");
+ expect(badges).toHaveLength(1);
+ expect(badges[0].textContent).toBe("Nova");
+ });
+
+ test("hides the expert filter when no expert is hired", async () => {
+ useStorageHandler();
+ useExpertsHandler([]);
+ useFilesHandler([]);
+ server.use(getListWorkspaceFoldersMockHandler({ folders: [] }));
+
+ render(<ArtifactsPage />);
+
+ expect(await screen.findByText("No files yet")).toBeDefined();
+ expect(screen.queryByTestId("artifacts-expert-filter")).toBeNull();
+ });
+});
+
+describe("ArtifactsPage - empty state", () => {
+ test("offers an upload and a new task when the workspace is empty", async () => {
+ useStorageHandler();
+ useFilesHandler([]);
+ server.use(getListWorkspaceFoldersMockHandler({ folders: [] }));
+
+ render(<ArtifactsPage />);
+
+ await screen.findByTestId("artifacts-empty");
+ expect(
+ screen.getByRole("button", { name: /upload a file/i }),
+ ).toBeDefined();
+ expect(screen.getByRole("link", { name: /start a task/i })).toBeDefined();
+ });
+
+ test("keeps the search empty state free of calls to action", async () => {
+ useStorageHandler();
+ useFilesHandler([]);
+ server.use(getListWorkspaceFoldersMockHandler({ folders: [] }));
+
+ render(<ArtifactsPage />);
+
+ await screen.findByTestId("artifacts-empty");
+ fireEvent.change(screen.getByPlaceholderText(/search/i), {
+ target: { value: "zzz" },
+ });
+
+ expect(await screen.findByText("No files match your search")).toBeDefined();
+ expect(screen.queryByRole("button", { name: /upload a file/i })).toBeNull();
+ expect(screen.queryByRole("link", { name: /start a task/i })).toBeNull();
+ });
+});
+
+describe("ArtifactsPage - rename", () => {
+ test("the row's pencil opens a dialog that patches the file name", async () => {
+ useStorageHandler();
+ useFilesHandler([makeFile({ id: "f1", name: "old.txt" })]);
+ server.use(getListWorkspaceFoldersMockHandler({ folders: [] }));
+ let patchedName: string | null = null;
+ server.use(
+ http.patch("/api/proxy/api/workspace/files/f1", async ({ request }) => {
+ const body = (await request.json()) as { name?: string };
+ patchedName = body.name ?? null;
+ return HttpResponse.json(
+ makeFile({ id: "f1", name: body.name ?? "old.txt" }),
+ );
+ }),
+ );
+
+ render(<ArtifactsPage />);
+
+ fireEvent.click(await screen.findByLabelText("Rename old.txt"));
+ const input = await screen.findByLabelText(/file name/i);
+ expect((input as HTMLInputElement).value).toBe("old.txt");
+ fireEvent.change(input, { target: { value: "new.txt" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ await waitFor(() => expect(patchedName).toBe("new.txt"));
+ });
+
+ test("clicking inside the rename dialog does not open the viewer", async () => {
+ useStorageHandler();
+ useFilesHandler([makeFile({ id: "f1", name: "old.txt" })]);
+ server.use(getListWorkspaceFoldersMockHandler({ folders: [] }));
+
+ render(<ArtifactsPage />);
+
+ fireEvent.click(await screen.findByLabelText("Rename old.txt"));
+ const input = await screen.findByLabelText(/file name/i);
+ fireEvent.click(input);
+
+ expect(screen.queryByTestId("file-viewer")).toBeNull();
+ expect(screen.getByLabelText(/file name/i)).toBeDefined();
+ });
+
+ test("rejects a name with a slash before sending anything", async () => {
+ useStorageHandler();
+ useFilesHandler([makeFile({ id: "f1", name: "old.txt" })]);
+ server.use(getListWorkspaceFoldersMockHandler({ folders: [] }));
+
+ render(<ArtifactsPage />);
+
+ fireEvent.click(await screen.findByLabelText("Rename old.txt"));
+ const input = await screen.findByLabelText(/file name/i);
+ fireEvent.change(input, { target: { value: "a/b.txt" } });
+
+ expect(await screen.findByText(/cannot contain slashes/i)).toBeDefined();
+ expect(
+ (screen.getByTestId("rename-file-submit") as HTMLButtonElement).disabled,
+ ).toBe(true);
+ });
+});
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 7454be4cac..49c5b32cc1 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
@@ -6,6 +6,7 @@ import { Text } from "@/components/atoms/Text/Text";
import { motion, useReducedMotion } from "framer-motion";
import type { Variants } from "framer-motion";
import { useFileDrag } from "../../WorkspaceFolders/useFileDrag";
+import { ExpertBadge } from "../ExpertBadge";
import { FileActionsMenu } from "../FileActionsMenu";
import {
formatFileSize,
@@ -13,22 +14,31 @@ import {
getFileTypeIcon,
getFileTypeLabel,
} from "../helpers";
+import { STAGGER_CAP, STAGGER_STEP_S } from "../ArtifactsTable/row-layout";
import { CardPreview } from "./CardPreview";
interface Props {
file: WorkspaceFileItem;
onOpen: (file: WorkspaceFileItem) => void;
+ /** Position in the grid; drives the small entrance stagger. */
+ index?: number;
}
+// Cards animate on their own mount so one added by an upload or a refetch
+// is never left in its hidden start state (see row-layout.ts).
const CARD_VARIANTS: Variants = {
hidden: { opacity: 0, y: 8, scale: 0.98, filter: "blur(8px)" },
- show: {
+ show: (index: number = 0) => ({
opacity: 1,
y: 0,
scale: 1,
filter: "blur(0px)",
- transition: { duration: 0.4, ease: [0.16, 1, 0.3, 1] },
- },
+ transition: {
+ duration: 0.4,
+ ease: [0.16, 1, 0.3, 1],
+ delay: Math.min(index, STAGGER_CAP) * STAGGER_STEP_S,
+ },
+ }),
};
const REDUCED_CARD_VARIANTS: Variants = {
@@ -36,7 +46,7 @@ const REDUCED_CARD_VARIANTS: Variants = {
show: { opacity: 1, transition: { duration: 0.2 } },
};
-export function ArtifactCard({ file, onOpen }: Props) {
+export function ArtifactCard({ file, onOpen, index = 0 }: Props) {
const typeIcon = getFileTypeIcon(file.mime_type, file.name);
const reduceMotion = useReducedMotion();
const { handleDragStart, handleDragEnd } = useFileDrag(file.id, file.name);
@@ -44,6 +54,9 @@ export function ArtifactCard({ file, onOpen }: Props) {
return (
<motion.li
variants={reduceMotion ? REDUCED_CARD_VARIANTS : CARD_VARIANTS}
+ custom={index}
+ initial={reduceMotion ? false : "hidden"}
+ animate="show"
style={{ willChange: "transform, opacity, filter" }}
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"
@@ -73,11 +86,14 @@ export function ArtifactCard({ file, onOpen }: Props) {
>
{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 className="flex min-w-0 items-center gap-2">
+ <Text variant="small" className="truncate text-zinc-500">
+ {getFileTypeLabel(file.mime_type, file.name)} ·{" "}
+ {formatFileSize(file.size_bytes)} ·{" "}
+ {formatRelativeDate(file.created_at)}
+ </Text>
+ <ExpertBadge expertId={file.expert_id} className="shrink-0" />
+ </div>
</div>
<div className="pointer-events-auto">
<FileActionsMenu file={file} />
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsGrid.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsGrid.tsx
index 8f20e4e907..4ebe21fc7a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsGrid.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsGrid.tsx
@@ -6,11 +6,12 @@ import { motion, useReducedMotion } from "framer-motion";
import type { Variants } from "framer-motion";
import { ArtifactCard } from "./ArtifactCard/ArtifactCard";
import { EmptyState } from "./EmptyState";
+import type { EmptyStateContent } from "./helpers";
interface Props {
files: WorkspaceFileItem[];
isLoading: boolean;
- emptyMessage: string;
+ emptyState: EmptyStateContent;
compactEmpty: boolean;
listKey: string;
onOpen: (file: WorkspaceFileItem) => void;
@@ -26,7 +27,7 @@ const GRID_VARIANTS: Variants = {
export function ArtifactsGrid({
files,
isLoading,
- emptyMessage,
+ emptyState,
compactEmpty,
listKey,
onOpen,
@@ -47,7 +48,7 @@ export function ArtifactsGrid({
}
if (files.length === 0) {
- return <EmptyState message={emptyMessage} compact={compactEmpty} />;
+ return <EmptyState content={emptyState} compact={compactEmpty} />;
}
return (
@@ -59,8 +60,8 @@ export function ArtifactsGrid({
initial={reduceMotion ? false : "hidden"}
animate={reduceMotion ? undefined : "show"}
>
- {files.map((file) => (
- <ArtifactCard key={file.id} file={file} onOpen={onOpen} />
+ {files.map((file, index) => (
+ <ArtifactCard key={file.id} file={file} onOpen={onOpen} index={index} />
))}
</motion.ul>
);
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 af2cf8a51d..143ceb16d1 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
@@ -8,6 +8,7 @@ import { FileViewerModal } from "../FileViewerModal/FileViewerModal";
import { WorkspaceFolders } from "../WorkspaceFolders/WorkspaceFolders";
import { ArtifactsGrid } from "./ArtifactsGrid";
import { ArtifactsTable } from "./ArtifactsTable/ArtifactsTable";
+import type { EmptyStateContent } from "./helpers";
import { LoadMoreSentinel } from "./LoadMoreSentinel";
interface Props {
@@ -15,7 +16,7 @@ interface Props {
isLoading: boolean;
isError: boolean;
error: unknown;
- emptyMessage: string;
+ emptyState: EmptyStateContent;
compactEmpty: boolean;
hasMore: boolean;
isLoadingMore: boolean;
@@ -31,7 +32,7 @@ export function ArtifactsList({
isLoading,
isError,
error,
- emptyMessage,
+ emptyState,
compactEmpty,
hasMore,
isLoadingMore,
@@ -64,7 +65,7 @@ export function ArtifactsList({
<ArtifactsGrid
files={files}
isLoading={isLoading}
- emptyMessage={emptyMessage}
+ emptyState={emptyState}
compactEmpty={compactEmpty}
listKey={listKey}
onOpen={setOpenFile}
@@ -74,7 +75,7 @@ export function ArtifactsList({
<ArtifactsTable
files={files}
isLoading={isLoading}
- emptyMessage={emptyMessage}
+ emptyState={emptyState}
compactEmpty={compactEmpty}
listKey={listKey}
showFolders={showFolders}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/ArtifactsTable.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/ArtifactsTable.tsx
index aef2774eea..1afbeaad7a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/ArtifactsTable.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/ArtifactsTable.tsx
@@ -7,6 +7,7 @@ import { cn } from "@/lib/utils";
import { motion, useReducedMotion } from "framer-motion";
import type { Variants } from "framer-motion";
import { EmptyState } from "../EmptyState";
+import type { EmptyStateContent } from "../helpers";
import { FileRow } from "./FileRow";
import { FolderRows } from "./FolderRows";
import { SkeletonRow } from "./SkeletonRow";
@@ -15,7 +16,7 @@ import { DATE_CELL_CLASS, ROW_GRID_CLASS, SIZE_CELL_CLASS } from "./row-layout";
interface Props {
files: WorkspaceFileItem[];
isLoading: boolean;
- emptyMessage: string;
+ emptyState: EmptyStateContent;
compactEmpty: boolean;
listKey: string;
showFolders: boolean;
@@ -33,7 +34,7 @@ const LIST_VARIANTS: Variants = {
export function ArtifactsTable({
files,
isLoading,
- emptyMessage,
+ emptyState,
compactEmpty,
listKey,
showFolders,
@@ -84,14 +85,19 @@ export function ArtifactsTable({
))}
</li>
) : (
- files.map((file) => (
- <FileRow key={file.id} file={file} onOpen={onOpen} />
+ files.map((file, index) => (
+ <FileRow
+ key={file.id}
+ file={file}
+ onOpen={onOpen}
+ index={index}
+ />
))
)}
</motion.ul>
</TooltipProvider>
{!isLoading && files.length === 0 ? (
- <EmptyState message={emptyMessage} compact={compactEmpty} />
+ <EmptyState content={emptyState} compact={compactEmpty} />
) : null}
</div>
);
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/FileRow.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/FileRow.tsx
index 47b4f237e9..c99868ad44 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/FileRow.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/FileRow.tsx
@@ -9,8 +9,13 @@ import {
TooltipTrigger,
} from "@/components/atoms/Tooltip/BaseTooltip";
import { cn } from "@/lib/utils";
+import { PencilEdit02Icon } from "@hugeicons/core-free-icons";
+import { Icon } from "@/components/atoms/Icon/Icon";
import { motion, useReducedMotion } from "framer-motion";
+import { useState } from "react";
+import { RenameFileDialog } from "../../RenameFileDialog/RenameFileDialog";
import { useFileDrag } from "../../WorkspaceFolders/useFileDrag";
+import { ExpertBadge } from "../ExpertBadge";
import { FileActionsMenu } from "../FileActionsMenu";
import { formatDayLabel, formatFileSize, formatFullDate } from "../helpers";
import { FilePreviewCard } from "./FilePreviewCard";
@@ -28,6 +33,8 @@ import {
interface Props {
file: WorkspaceFileItem;
onOpen: (file: WorkspaceFileItem) => void;
+ /** Position in the list; drives the small entrance stagger. */
+ index?: number;
}
// Long enough that skimming down the list doesn't flash previews; short
@@ -35,13 +42,17 @@ interface Props {
// provider's skip delay opens the next preview immediately.
const PREVIEW_DELAY_MS = 450;
-export function FileRow({ file, onOpen }: Props) {
+export function FileRow({ file, onOpen, index = 0 }: Props) {
const reduceMotion = useReducedMotion();
const { handleDragStart, handleDragEnd } = useFileDrag(file.id, file.name);
+ const [isRenameOpen, setIsRenameOpen] = useState(false);
return (
<motion.li
variants={reduceMotion ? REDUCED_ROW_VARIANTS : ROW_VARIANTS}
+ custom={index}
+ initial={reduceMotion ? false : "hidden"}
+ animate="show"
className={cn(
ROW_GRID_CLASS,
"group cursor-pointer px-2 transition-colors has-[[data-state=open]]:bg-zinc-50 hover:bg-zinc-50",
@@ -54,39 +65,55 @@ export function FileRow({ file, onOpen }: Props) {
>
{/* The name is the row's accessible control: it takes focus, Enter
bubbles a click up to the row, and hovering (or focusing) it opens
- the large preview. */}
- <Tooltip delayDuration={PREVIEW_DELAY_MS}>
- <TooltipTrigger asChild>
- <button
- type="button"
- className={NAME_BUTTON_CLASS}
- data-testid="artifacts-card-open"
- >
- <FileThumbnail file={file} />
- <Text
- variant="body-medium"
- as="span"
- className="truncate text-zinc-900"
+ the large preview. The rename pencil sits beside it, outside the
+ preview trigger. */}
+ <div className="flex min-w-0 items-center gap-1 justify-self-start">
+ <Tooltip delayDuration={PREVIEW_DELAY_MS}>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ className={NAME_BUTTON_CLASS}
+ data-testid="artifacts-card-open"
>
- {file.name}
- </Text>
- </button>
- </TooltipTrigger>
- <TooltipPortal>
- {/* aria-label keeps Radix from mirroring the whole card into its
+ <FileThumbnail file={file} />
+ <Text
+ variant="body-medium"
+ as="span"
+ className="truncate text-zinc-900"
+ >
+ {file.name}
+ </Text>
+ <ExpertBadge expertId={file.expert_id} className="shrink-0" />
+ </button>
+ </TooltipTrigger>
+ <TooltipPortal>
+ {/* aria-label keeps Radix from mirroring the whole card into its
visually-hidden tooltip copy (which would fetch previews twice). */}
- <TooltipContent
- aria-label={`Preview of ${file.name}`}
- side="right"
- align="center"
- sideOffset={16}
- collisionPadding={16}
- className="max-w-none rounded-2xl border border-zinc-200 bg-white p-0 text-sm shadow-xl shadow-black/10 outline-none"
- >
- <FilePreviewCard file={file} />
- </TooltipContent>
- </TooltipPortal>
- </Tooltip>
+ <TooltipContent
+ aria-label={`Preview of ${file.name}`}
+ side="right"
+ align="center"
+ sideOffset={16}
+ collisionPadding={16}
+ className="max-w-none rounded-2xl border border-zinc-200 bg-white p-0 text-sm shadow-xl shadow-black/10 outline-none"
+ >
+ <FilePreviewCard file={file} />
+ </TooltipContent>
+ </TooltipPortal>
+ </Tooltip>
+ <button
+ type="button"
+ aria-label={`Rename ${file.name}`}
+ className="inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-zinc-400 opacity-0 transition-opacity group-hover:opacity-100 hover:bg-zinc-100 hover:text-zinc-900 focus-visible:opacity-100"
+ onClick={(e) => {
+ e.stopPropagation();
+ setIsRenameOpen(true);
+ }}
+ data-testid="artifacts-rename"
+ >
+ <Icon icon={PencilEdit02Icon} size={16} />
+ </button>
+ </div>
<Text
variant="body"
as="span"
@@ -111,6 +138,18 @@ export function FileRow({ file, onOpen }: Props) {
>
<FileActionsMenu file={file} />
</div>
+ {isRenameOpen && (
+ // The dialog portals out of the row in the DOM, but React events still
+ // bubble through the component tree, so its clicks must not reach the
+ // row's open handler.
+ <div onClick={(e) => e.stopPropagation()}>
+ <RenameFileDialog
+ file={file}
+ isOpen={isRenameOpen}
+ setIsOpen={setIsRenameOpen}
+ />
+ </div>
+ )}
</motion.li>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/row-layout.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/row-layout.ts
index 056657e32e..6afa19f0f3 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/row-layout.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ArtifactsTable/row-layout.ts
@@ -9,16 +9,28 @@ export const DATE_CELL_CLASS = "hidden truncate sm:block";
export const SIZE_CELL_CLASS = "hidden tabular-nums md:block";
export const ACTIONS_CELL_CLASS = "flex min-w-10 justify-end";
+// Sized to its content (its wrapper is not stretched across the column) so
+// the hover preview, which anchors to this button, opens beside the name.
export const NAME_BUTTON_CLASS =
"flex min-w-0 items-center gap-4 rounded-xl py-2.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-zinc-400";
+// Rows animate on their own mount (not via the list's orchestration) so a row
+// added by an upload or a refetch is never left in its hidden start state.
+// The delay grows with position, capped so appended pages don't wait long.
+export const STAGGER_CAP = 8;
+export const STAGGER_STEP_S = 0.03;
+
export const ROW_VARIANTS: Variants = {
hidden: { opacity: 0, y: 6 },
- show: {
+ show: (index: number = 0) => ({
opacity: 1,
y: 0,
- transition: { duration: 0.3, ease: [0.16, 1, 0.3, 1] },
- },
+ transition: {
+ duration: 0.3,
+ ease: [0.16, 1, 0.3, 1],
+ delay: Math.min(index, STAGGER_CAP) * STAGGER_STEP_S,
+ },
+ }),
};
export const REDUCED_ROW_VARIANTS: Variants = {
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/EmptyState.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/EmptyState.tsx
index 3da8077f91..59fc096907 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/EmptyState.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/EmptyState.tsx
@@ -1,14 +1,27 @@
+"use client";
+
+import { Button } from "@/components/atoms/Button/Button";
+import { Icon } from "@/components/atoms/Icon/Icon";
import { Text } from "@/components/atoms/Text/Text";
-import { FileTypeMarquee } from "./FileTypeMarquee";
+import { PlusSignIcon, Upload03Icon } from "@hugeicons/core-free-icons";
+import { motion, useReducedMotion } from "framer-motion";
+import { useNewMenu } from "../NewMenu/useNewMenu";
+import type { EmptyStateContent } from "./helpers";
+
+const EASE_OUT_QUINT = [0.22, 1, 0.36, 1] as const;
interface Props {
- message: string;
- // When folders are already listed, a full marquee empty state would sit
- // right under them and read as contradictory; show a single quiet line.
+ content: EmptyStateContent;
+ // When folders are already listed, a full empty state would sit right
+ // under them and read as contradictory; show a single quiet line.
compact?: boolean;
}
-export function EmptyState({ message, compact = false }: Props) {
+export function EmptyState({ content, compact = false }: Props) {
+ const shouldReduceMotion = useReducedMotion();
+ const { fileInputRef, isUploading, openFilePicker, handleFilesSelected } =
+ useNewMenu(content.uploadFolderId);
+
if (compact) {
return (
<Text
@@ -16,20 +29,176 @@ export function EmptyState({ message, compact = false }: Props) {
className="px-2 py-6 text-zinc-500"
data-testid="artifacts-empty"
>
- {message}
+ {content.title}
</Text>
);
}
+ function fadeUp(delay: number) {
+ if (shouldReduceMotion) {
+ return {
+ initial: { opacity: 0 },
+ animate: { opacity: 1 },
+ transition: { duration: 0.2, delay: 0 },
+ };
+ }
+ return {
+ initial: { opacity: 0, y: 8 },
+ animate: { opacity: 1, y: 0 },
+ transition: { duration: 0.35, ease: EASE_OUT_QUINT, delay },
+ };
+ }
+
+ const hasActions = content.showUpload || content.chatHref !== null;
+
return (
<div
- className="flex min-h-[20rem] flex-col items-center justify-center gap-4 p-8 text-center"
+ className="flex flex-col items-center justify-center gap-8 px-6 py-16 text-center"
data-testid="artifacts-empty"
>
- <FileTypeMarquee />
- <Text variant="h5" className="text-zinc-700">
- {message}
- </Text>
+ <motion.div {...fadeUp(0)}>
+ <StackedFilesIllustration />
+ </motion.div>
+
+ <div className="flex max-w-md flex-col items-center gap-2">
+ <motion.div {...fadeUp(0.28)}>
+ <Text variant="h3" className="text-zinc-900">
+ {content.title}
+ </Text>
+ </motion.div>
+ <motion.div {...fadeUp(0.36)}>
+ <Text variant="body" className="text-zinc-500">
+ {content.description}
+ </Text>
+ </motion.div>
+ </div>
+
+ {hasActions ? (
+ <div className="flex flex-col items-center gap-3 sm:flex-row">
+ {content.showUpload ? (
+ <motion.div {...fadeUp(0.44)}>
+ <Button
+ variant="primary"
+ size="large"
+ onClick={openFilePicker}
+ disabled={isUploading}
+ leftIcon={<Icon icon={Upload03Icon} className="h-4 w-4" />}
+ >
+ {isUploading ? "Uploading…" : "Upload a file"}
+ </Button>
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ className="hidden"
+ tabIndex={-1}
+ aria-hidden
+ onChange={handleFilesSelected}
+ data-testid="artifacts-empty-upload-input"
+ />
+ </motion.div>
+ ) : null}
+ {content.chatHref ? (
+ <motion.div {...fadeUp(0.5)}>
+ <Button
+ as="NextLink"
+ href={content.chatHref}
+ variant={content.showUpload ? "secondary" : "primary"}
+ size="large"
+ leftIcon={<Icon icon={PlusSignIcon} className="h-4 w-4" />}
+ >
+ {content.chatLabel}
+ </Button>
+ </motion.div>
+ ) : null}
+ </div>
+ ) : null}
</div>
);
}
+
+// Three fanned documents, drawn in the same palette as the library's
+// stacked cards so the two empty states read as one family.
+const SHEETS = [
+ { rotate: -10, x: 88, opacity: 0.55 },
+ { rotate: 8, x: 176, opacity: 0.8 },
+ { rotate: 0, x: 132, opacity: 1 },
+];
+
+function StackedFilesIllustration() {
+ const shouldReduceMotion = useReducedMotion();
+
+ return (
+ <svg
+ width="320"
+ height="160"
+ viewBox="0 0 320 160"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ aria-hidden="true"
+ className="select-none"
+ >
+ {SHEETS.map((sheet, i) => (
+ <motion.g
+ key={i}
+ initial={
+ shouldReduceMotion
+ ? { opacity: 0 }
+ : { opacity: 0, y: 12, scale: 0.97 }
+ }
+ animate={
+ shouldReduceMotion
+ ? { opacity: sheet.opacity }
+ : { opacity: sheet.opacity, y: 0, scale: 1 }
+ }
+ transition={{
+ duration: shouldReduceMotion ? 0.2 : 0.45,
+ ease: EASE_OUT_QUINT,
+ delay: shouldReduceMotion ? 0 : i * 0.08,
+ }}
+ style={{ transformOrigin: "160px 96px", transformBox: "fill-box" }}
+ >
+ <Sheet x={sheet.x} rotate={sheet.rotate} />
+ </motion.g>
+ ))}
+ </svg>
+ );
+}
+
+function Sheet({ x, rotate }: { x: number; rotate: number }) {
+ const width = 100;
+ const height = 124;
+ const y = 18;
+ const fold = 22;
+ const padding = 16;
+ const cx = x + width / 2;
+ const cy = y + height / 2;
+
+ return (
+ <g transform={`rotate(${rotate} ${cx} ${cy})`}>
+ <path
+ d={`M${x + 12} ${y}H${x + width - fold}L${x + width} ${y + fold}V${y + height - 12}a12 12 0 0 1-12 12H${x + 12}a12 12 0 0 1-12-12V${y + 12}a12 12 0 0 1 12-12Z`}
+ fill="white"
+ stroke="#E4E4E7"
+ strokeWidth={1}
+ />
+ <path
+ d={`M${x + width - fold} ${y}V${y + fold}H${x + width}`}
+ fill="#F4F4F5"
+ stroke="#E4E4E7"
+ strokeWidth={1}
+ />
+ {[0, 1, 2, 3].map((line) => (
+ <rect
+ key={line}
+ x={x + padding}
+ y={y + 40 + line * 16}
+ width={line === 3 ? width * 0.4 : width - padding * 2}
+ height={6}
+ rx={3}
+ fill="#E4E4E7"
+ />
+ ))}
+ </g>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ExpertBadge.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ExpertBadge.tsx
new file mode 100644
index 0000000000..a99f944905
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/ExpertBadge.tsx
@@ -0,0 +1,36 @@
+"use client";
+
+import { useExpertMap } from "@/app/(platform)/copilot/useExpertMap";
+import { Badge } from "@/components/atoms/Badge/Badge";
+import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";
+import { cn } from "@/lib/utils";
+
+interface Props {
+ expertId: string | null | undefined;
+ className?: string;
+}
+
+export function ExpertBadge({ expertId, className }: Props) {
+ const { expertsById } = useExpertMap();
+ const expert = expertId ? expertsById.get(expertId) : undefined;
+ if (!expert) return null;
+
+ return (
+ <span
+ className={cn("inline-flex items-center", className)}
+ title={`From ${expert.name}`}
+ data-testid="artifacts-expert-badge"
+ >
+ <Badge variant="info" size="small" className="pl-1">
+ <span aria-hidden className="flex shrink-0">
+ <ExpertAvatar
+ name={expert.name}
+ avatarUrl={expert.avatarUrl}
+ size={14}
+ />
+ </span>
+ {expert.name}
+ </Badge>
+ </span>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileActionsMenu.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileActionsMenu.tsx
index 379671e485..db6b81208f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileActionsMenu.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileActionsMenu.tsx
@@ -17,9 +17,11 @@ import {
LinkSquare01Icon,
Loading03Icon,
MoreHorizontalIcon,
+ PencilEdit02Icon,
} from "@hugeicons/core-free-icons";
import Link from "next/link";
import { MoveToFolderDialog } from "../MoveToFolderDialog/MoveToFolderDialog";
+import { RenameFileDialog } from "../RenameFileDialog/RenameFileDialog";
import { useFileActionsMenu } from "./useFileActionsMenu";
interface Props {
@@ -33,6 +35,8 @@ export function FileActionsMenu({ file, className }: Props) {
goHref,
isMoveOpen,
setIsMoveOpen,
+ isRenameOpen,
+ setIsRenameOpen,
isDownloading,
isDeleting,
handleDownload,
@@ -80,6 +84,16 @@ export function FileActionsMenu({ file, className }: Props) {
</DropdownMenuItem>
{/* preventDefault keeps the menu mounted while the dialog opens, so
the menu's focus return doesn't fight the dialog for focus. */}
+ <DropdownMenuItem
+ onSelect={(e) => {
+ e.preventDefault();
+ setIsRenameOpen(true);
+ }}
+ data-testid="artifacts-rename-menu"
+ >
+ <Icon icon={PencilEdit02Icon} size={16} className="mr-2" />
+ Rename
+ </DropdownMenuItem>
<DropdownMenuItem
onSelect={(e) => {
e.preventDefault();
@@ -110,6 +124,13 @@ export function FileActionsMenu({ file, className }: Props) {
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
+ {isRenameOpen && (
+ <RenameFileDialog
+ file={file}
+ isOpen={isRenameOpen}
+ setIsOpen={setIsRenameOpen}
+ />
+ )}
{isMoveOpen && (
<MoveToFolderDialog
fileId={file.id}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileTypeMarquee.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileTypeMarquee.tsx
deleted file mode 100644
index 07da5f7e4d..0000000000
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/FileTypeMarquee.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-"use client";
-
-import { FILE_TYPE_KEYS, FileIllustration } from "./FileIllustration";
-
-export function FileTypeMarquee() {
- const items = [...FILE_TYPE_KEYS, ...FILE_TYPE_KEYS];
-
- return (
- <div
- className="pointer-events-none relative mx-auto w-full max-w-lg overflow-hidden [mask-image:linear-gradient(to_right,transparent,black_15%,black_85%,transparent)]"
- data-testid="artifacts-file-type-marquee"
- >
- <div className="flex w-max animate-marquee-x items-end gap-4 py-2">
- {items.map((key, i) => (
- <div key={`${key}-${i}`} className="px-4 py-3">
- <FileIllustration typeKey={key} />
- </div>
- ))}
- </div>
- </div>
- );
-}
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 c9311a40f5..2b32b1ed53 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
@@ -337,9 +337,80 @@ export function getEmptyMessage(opts: {
hasSearchTerm: boolean;
isInFolder: boolean;
hasFolders: boolean;
+ hasExpertFilter?: boolean;
}): string {
if (opts.hasSearchTerm) return "No files match your search";
+ if (opts.hasExpertFilter) return "No files from this expert yet";
if (opts.isInFolder) return "This folder is empty";
if (opts.hasFolders) return "No files at the root yet";
return "No files yet";
}
+
+export interface EmptyStateContent {
+ title: string;
+ description: string;
+ showUpload: boolean;
+ uploadFolderId: string | null;
+ chatHref: string | null;
+ chatLabel: string;
+}
+
+export function getEmptyState(opts: {
+ hasSearchTerm: boolean;
+ isInFolder: boolean;
+ hasFolders: boolean;
+ folderId: string | null;
+ expert: { id: string; name: string | null } | null;
+}): EmptyStateContent {
+ const title = getEmptyMessage({
+ hasSearchTerm: opts.hasSearchTerm,
+ isInFolder: opts.isInFolder,
+ hasFolders: opts.hasFolders,
+ hasExpertFilter: opts.expert !== null,
+ });
+ const base: EmptyStateContent = {
+ title,
+ description: "",
+ showUpload: false,
+ uploadFolderId: opts.folderId,
+ chatHref: null,
+ chatLabel: "Start a task",
+ };
+ if (opts.hasSearchTerm) {
+ return {
+ ...base,
+ description: "Try another name, or clear the search to see everything.",
+ };
+ }
+ if (opts.expert) {
+ const name = opts.expert.name;
+ return {
+ ...base,
+ description: `Files ${name ?? "this expert"} creates while working on a task will show up here.`,
+ chatHref: name
+ ? `/copilot?expertId=${encodeURIComponent(opts.expert.id)}`
+ : null,
+ chatLabel: name ? `Chat with ${name}` : base.chatLabel,
+ };
+ }
+ if (opts.isInFolder) {
+ return {
+ ...base,
+ description: "Upload a file here, or drag one in from the list.",
+ showUpload: true,
+ };
+ }
+ if (opts.hasFolders) {
+ return {
+ ...base,
+ description: "Your files live inside the folders above.",
+ };
+ }
+ return {
+ ...base,
+ description:
+ "Files your team generates and files you upload will show up here.",
+ showUpload: true,
+ chatHref: "/copilot",
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/useFileActionsMenu.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/useFileActionsMenu.ts
index 8e8297db48..f83cea9ab2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/useFileActionsMenu.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ArtifactsList/useFileActionsMenu.ts
@@ -13,6 +13,7 @@ import { deriveFileOrigin, downloadFileBlob } from "./helpers";
export function useFileActionsMenu(file: WorkspaceFileItem) {
const origin = deriveFileOrigin(file.path);
const [isMoveOpen, setIsMoveOpen] = useState(false);
+ const [isRenameOpen, setIsRenameOpen] = useState(false);
const [isDownloading, setIsDownloading] = useState(false);
const { toast } = useToast();
const queryClient = useQueryClient();
@@ -77,6 +78,8 @@ export function useFileActionsMenu(file: WorkspaceFileItem) {
goHref: origin.href,
isMoveOpen,
setIsMoveOpen,
+ isRenameOpen,
+ setIsRenameOpen,
isDownloading,
isDeleting,
handleDownload,
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ExpertFilter/ExpertFilter.test.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ExpertFilter/ExpertFilter.test.tsx
new file mode 100644
index 0000000000..3e29f85381
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ExpertFilter/ExpertFilter.test.tsx
@@ -0,0 +1,55 @@
+import { describe, expect, test, vi } from "vitest";
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+
+import { ExpertFilter } from "./ExpertFilter";
+
+const EXPERTS = [
+ { id: "expert-a", name: "Nova", avatarUrl: "https://cdn.test/nova.png" },
+ { id: "expert-b", name: "Kai", avatarUrl: null },
+];
+
+describe("ExpertFilter", () => {
+ test("renders Everyone plus one tab per expert", () => {
+ render(<ExpertFilter experts={EXPERTS} value={null} onChange={() => {}} />);
+ expect(screen.getByRole("tab", { name: "Everyone" })).toBeDefined();
+ expect(screen.getByRole("tab", { name: "Nova" })).toBeDefined();
+ expect(screen.getByRole("tab", { name: "Kai" })).toBeDefined();
+ });
+
+ test("marks the selected expert as active", () => {
+ render(
+ <ExpertFilter experts={EXPERTS} value="expert-b" onChange={() => {}} />,
+ );
+ expect(
+ screen.getByRole("tab", { name: "Kai" }).getAttribute("aria-selected"),
+ ).toBe("true");
+ expect(
+ screen
+ .getByRole("tab", { name: "Everyone" })
+ .getAttribute("aria-selected"),
+ ).toBe("false");
+ });
+
+ test("forwards the expert id, and null for Everyone", () => {
+ const onChange = vi.fn();
+ render(<ExpertFilter experts={EXPERTS} value={null} onChange={onChange} />);
+ fireEvent.click(screen.getByRole("tab", { name: "Nova" }));
+ expect(onChange).toHaveBeenCalledWith("expert-a");
+ fireEvent.click(screen.getByRole("tab", { name: "Everyone" }));
+ expect(onChange).toHaveBeenCalledWith(null);
+ });
+
+ test("renders nothing when no expert is hired and none is selected", () => {
+ render(<ExpertFilter experts={[]} value={null} onChange={() => {}} />);
+ expect(screen.queryByRole("tablist")).toBeNull();
+ });
+
+ test("keeps Everyone so a filter on a fired expert can be cleared", () => {
+ const onChange = vi.fn();
+ render(
+ <ExpertFilter experts={[]} value="expert-gone" onChange={onChange} />,
+ );
+ fireEvent.click(screen.getByRole("tab", { name: "Everyone" }));
+ expect(onChange).toHaveBeenCalledWith(null);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ExpertFilter/ExpertFilter.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ExpertFilter/ExpertFilter.tsx
new file mode 100644
index 0000000000..0e269376dc
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/ExpertFilter/ExpertFilter.tsx
@@ -0,0 +1,112 @@
+"use client";
+
+import { Text } from "@/components/atoms/Text/Text";
+import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";
+import { cn } from "@/lib/utils";
+import { LayoutGroup, motion, type Transition } from "framer-motion";
+
+export interface ExpertFilterOption {
+ id: string;
+ name: string;
+ avatarUrl: string | null;
+}
+
+interface Props {
+ experts: ExpertFilterOption[];
+ value: string | null;
+ onChange: (expertId: string | null) => void;
+}
+
+const snappySpring: Transition = {
+ type: "spring",
+ stiffness: 350,
+ damping: 30,
+ mass: 1,
+};
+
+export function ExpertFilter({ experts, value, onChange }: Props) {
+ // Keep the control while a selection exists so a filter on an expert who
+ // has since been fired can still be cleared.
+ if (experts.length === 0 && value === null) return null;
+
+ return (
+ <LayoutGroup id="artifacts-expert-filter">
+ <div className="flex flex-col gap-1">
+ <Text variant="small" as="span" className="pl-4 text-zinc-500">
+ From
+ </Text>
+ <div
+ role="tablist"
+ aria-label="Filter by expert"
+ className="flex flex-wrap items-center gap-1"
+ data-testid="artifacts-expert-filter"
+ >
+ <ExpertTab
+ label="Everyone"
+ active={value === null}
+ onClick={() => onChange(null)}
+ testId="artifacts-expert-filter-everyone"
+ />
+ {experts.map((expert) => (
+ <ExpertTab
+ key={expert.id}
+ label={expert.name}
+ avatarUrl={expert.avatarUrl}
+ active={value === expert.id}
+ onClick={() => onChange(expert.id)}
+ testId={`artifacts-expert-filter-${expert.id}`}
+ />
+ ))}
+ </div>
+ </div>
+ </LayoutGroup>
+ );
+}
+
+interface ExpertTabProps {
+ label: string;
+ active: boolean;
+ onClick: () => void;
+ testId: string;
+ /** Present for expert tabs; "Everyone" has no avatar. */
+ avatarUrl?: string | null;
+}
+
+function ExpertTab({
+ label,
+ active,
+ onClick,
+ testId,
+ avatarUrl,
+}: ExpertTabProps) {
+ const hasAvatar = avatarUrl !== undefined;
+ return (
+ <button
+ type="button"
+ role="tab"
+ aria-selected={active}
+ onClick={onClick}
+ className={cn(
+ "relative flex max-w-48 items-center gap-2 rounded-full py-1.5 text-sm font-medium outline-none transition-colors focus-visible:ring-2 focus-visible:ring-zinc-400",
+ hasAvatar ? "pl-1.5 pr-3.5" : "px-4",
+ active ? "text-zinc-900" : "text-zinc-500 hover:text-zinc-900",
+ )}
+ data-testid={testId}
+ >
+ {active ? (
+ <motion.span
+ layoutId="artifacts-expert-active"
+ className="absolute inset-0 rounded-full bg-zinc-100"
+ transition={snappySpring}
+ />
+ ) : null}
+ {hasAvatar ? (
+ // Decorative: the label carries the name for assistive tech.
+ <span aria-hidden className="relative z-10 shrink-0">
+ <ExpertAvatar name={label} avatarUrl={avatarUrl} size={22} />
+ </span>
+ ) : null}
+ <span className="relative z-10 truncate">{label}</span>
+ </button>
+ );
+}
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 55696d3035..86c1e5a9bc 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
@@ -1,5 +1,6 @@
"use client";
+import { Text } from "@/components/atoms/Text/Text";
import { cn } from "@/lib/utils";
import { LayoutGroup, motion, type Transition } from "framer-motion";
import type { OriginFilter as OriginFilterValue } from "../../useArtifactsPage";
@@ -30,20 +31,25 @@ const snappySpring: Transition = {
export function OriginFilter({ value, onChange }: Props) {
return (
<LayoutGroup id="artifacts-origin-filter">
- <div
- role="tablist"
- aria-label="Filter by source"
- className="flex items-center gap-1"
- data-testid="artifacts-origin-filter"
- >
- {OPTIONS.map((opt) => (
- <OriginTab
- key={opt.value}
- option={opt}
- active={value === opt.value}
- onClick={() => onChange(opt.value)}
- />
- ))}
+ <div className="flex flex-col gap-1">
+ <Text variant="small" as="span" className="pl-4 text-zinc-500">
+ Type
+ </Text>
+ <div
+ role="tablist"
+ aria-label="Filter by type"
+ className="flex items-center gap-1"
+ data-testid="artifacts-origin-filter"
+ >
+ {OPTIONS.map((opt) => (
+ <OriginTab
+ key={opt.value}
+ option={opt}
+ active={value === opt.value}
+ onClick={() => onChange(opt.value)}
+ />
+ ))}
+ </div>
</div>
</LayoutGroup>
);
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/RenameFileDialog/RenameFileDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/RenameFileDialog/RenameFileDialog.tsx
new file mode 100644
index 0000000000..2345713102
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/RenameFileDialog/RenameFileDialog.tsx
@@ -0,0 +1,55 @@
+"use client";
+
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+import { Button } from "@/components/atoms/Button/Button";
+import { Input } from "@/components/atoms/Input/Input";
+import { Dialog } from "@/components/molecules/Dialog/Dialog";
+import { isKey } from "@/lib/keyboard";
+import { useRenameFileDialog } from "./useRenameFileDialog";
+
+interface Props {
+ file: WorkspaceFileItem;
+ isOpen: boolean;
+ setIsOpen: (open: boolean) => void;
+}
+
+export function RenameFileDialog({ file, isOpen, setIsOpen }: Props) {
+ const { name, setName, validationError, canSubmit, isPending, handleSubmit } =
+ useRenameFileDialog(file, () => setIsOpen(false));
+
+ return (
+ <Dialog
+ controlled={{ isOpen, set: setIsOpen }}
+ styling={{ maxWidth: "28rem" }}
+ title="Rename file"
+ >
+ <Dialog.Content>
+ <div className="flex flex-col gap-3">
+ <Input
+ id="rename-file-name"
+ label="File name"
+ placeholder="Enter file name"
+ value={name}
+ error={validationError ?? undefined}
+ onChange={(e) => setName(e.target.value)}
+ onKeyDown={(e) => {
+ if (isKey(e, "Enter")) handleSubmit();
+ }}
+ className="w-full"
+ wrapperClassName="!mb-0"
+ />
+ <Button
+ variant="primary"
+ className="mt-2"
+ disabled={!canSubmit}
+ loading={isPending}
+ onClick={handleSubmit}
+ data-testid="rename-file-submit"
+ >
+ Save
+ </Button>
+ </div>
+ </Dialog.Content>
+ </Dialog>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/RenameFileDialog/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/RenameFileDialog/helpers.ts
new file mode 100644
index 0000000000..eca6b5ebc9
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/RenameFileDialog/helpers.ts
@@ -0,0 +1,10 @@
+export const MAX_FILE_NAME_LENGTH = 255;
+
+export function validateFileName(name: string): string | null {
+ if (name.length === 0) return "Enter a file name";
+ if (name.length > MAX_FILE_NAME_LENGTH) return "That name is too long";
+ if (name === "." || name === "..") return "That is not a valid file name";
+ if (name.includes("/") || name.includes("\\"))
+ return "File names cannot contain slashes";
+ return null;
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/RenameFileDialog/useRenameFileDialog.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/RenameFileDialog/useRenameFileDialog.ts
new file mode 100644
index 0000000000..4fbe73c612
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/RenameFileDialog/useRenameFileDialog.ts
@@ -0,0 +1,54 @@
+import { useRenameWorkspaceFile } from "@/app/api/__generated__/endpoints/workspace/workspace";
+import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
+import { useToast } from "@/components/molecules/Toast/use-toast";
+import { useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+import { ARTIFACTS_LIST_QUERY_KEY } from "../../useArtifactsPage";
+import { validateFileName } from "./helpers";
+
+export function useRenameFileDialog(
+ file: WorkspaceFileItem,
+ onRenamed: () => void,
+) {
+ const [name, setName] = useState(file.name);
+ const { toast } = useToast();
+ const queryClient = useQueryClient();
+ const { mutateAsync: rename, isPending } = useRenameWorkspaceFile({
+ mutation: {
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ARTIFACTS_LIST_QUERY_KEY });
+ toast({ title: "File renamed" });
+ onRenamed();
+ },
+ onError: (error) => {
+ toast({
+ title: "Failed to rename file",
+ description:
+ error instanceof Error ? error.message : "Please try again.",
+ variant: "destructive",
+ });
+ },
+ },
+ });
+
+ const trimmed = name.trim();
+ const validationError = validateFileName(trimmed);
+ const isUnchanged = trimmed === file.name;
+ const canSubmit = validationError === null && !isUnchanged && !isPending;
+
+ function handleSubmit() {
+ if (!canSubmit) return;
+ rename({ fileId: file.id, data: { name: trimmed } }).catch(() => {
+ // Already surfaced by the mutation's onError toast.
+ });
+ }
+
+ return {
+ name,
+ setName,
+ validationError: trimmed.length > 0 ? validationError : null,
+ canSubmit,
+ isPending,
+ handleSubmit,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/StorageUsage/StorageUsage.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/StorageUsage/StorageUsage.tsx
index 61d0b63f43..4fc30491a0 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/components/StorageUsage/StorageUsage.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/components/StorageUsage/StorageUsage.tsx
@@ -1,19 +1,12 @@
"use client";
import { useGetWorkspaceStorageUsage } from "@/app/api/__generated__/endpoints/workspace/workspace";
+import { Progress } from "@/components/atoms/Progress/Progress";
import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
import { Text } from "@/components/atoms/Text/Text";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/components/atoms/Tooltip/BaseTooltip";
import { cn } from "@/lib/utils";
import { formatFileSize } from "../ArtifactsList/helpers";
-const SEGMENT_COUNT = 40;
-
export function StorageUsage() {
const { data, isLoading, isError } = useGetWorkspaceStorageUsage({
query: {
@@ -24,14 +17,11 @@ export function StorageUsage() {
if (isLoading) {
return (
<div
- className="flex w-full flex-col gap-2"
+ className="flex items-center gap-3"
data-testid="storage-usage-loading"
>
- <Skeleton className="h-3 w-24" />
- <div className="flex items-center gap-3">
- <Skeleton className="h-8 flex-1 rounded-md" />
- <Skeleton className="h-3 w-32" />
- </div>
+ <Skeleton className="h-1.5 w-32 rounded-full" />
+ <Skeleton className="h-3 w-28" />
</div>
);
}
@@ -39,53 +29,35 @@ export function StorageUsage() {
if (isError || !data) return null;
const percent = Math.min(Math.max(data.used_percent, 0), 100);
- const filled = Math.round((percent / 100) * SEGMENT_COUNT);
- const filledColor = percent > 95 ? "bg-red-400" : "bg-purple-300";
- const usedLabel = `${Math.round(percent)}% used`;
- const leftLabel = `${Math.max(0, Math.round(100 - percent))}% left`;
+ const usedLabel = `${Math.round(percent)}% of storage used`;
return (
- <div className="flex w-full flex-col gap-2" data-testid="storage-usage">
- <Text variant="body-medium" className="text-zinc-800">
+ <div
+ className="flex items-center gap-3"
+ title={usedLabel}
+ data-testid="storage-usage"
+ >
+ <Text variant="small" as="span" className="text-zinc-500">
Storage
</Text>
- <div className="flex items-center gap-3">
- <TooltipProvider delayDuration={400} skipDelayDuration={120}>
- <div
- role="progressbar"
- aria-valuenow={percent}
- aria-valuemin={0}
- aria-valuemax={100}
- aria-label={`${usedLabel}, ${leftLabel}`}
- className="flex h-8 flex-1 items-center gap-[3px]"
- >
- {Array.from({ length: SEGMENT_COUNT }).map((_, i) => {
- const isFilled = i < filled;
- return (
- <Tooltip key={i} delayDuration={400}>
- <TooltipTrigger asChild>
- <div
- className={cn(
- "h-full w-[3px] flex-1 rounded-full transition duration-200 ease-out hover:-translate-y-1.5 motion-reduce:transition-none motion-reduce:hover:translate-y-0",
- isFilled ? filledColor : "bg-zinc-300",
- )}
- />
- </TooltipTrigger>
- <TooltipContent side="top" sideOffset={6}>
- {isFilled ? usedLabel : leftLabel}
- </TooltipContent>
- </Tooltip>
- );
- })}
- </div>
- </TooltipProvider>
- <Text variant="body" className="shrink-0 text-zinc-500">
- <span className="font-medium text-zinc-900">
- {formatFileSize(data.used_bytes)}
- </span>{" "}
- of {formatFileSize(data.limit_bytes)} used
- </Text>
- </div>
+ <Progress
+ value={percent}
+ role="progressbar"
+ aria-valuenow={percent}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-label={usedLabel}
+ className={cn(
+ "h-1.5 w-32 bg-zinc-100",
+ percent > 95 ? "[&>div]:bg-red-400" : "[&>div]:bg-zinc-400",
+ )}
+ />
+ <Text variant="small" as="span" className="text-zinc-500">
+ <span className="font-medium text-zinc-700">
+ {formatFileSize(data.used_bytes)}
+ </span>{" "}
+ of {formatFileSize(data.limit_bytes)}
+ </Text>
</div>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx b/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx
index 555e348bff..302249b15d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/page.tsx
@@ -8,10 +8,12 @@ import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";
import { Text } from "@/components/atoms/Text/Text";
import { Flag, useFlagStatus } from "@/services/feature-flags/use-get-flag";
import { usePlatformChrome } from "@/app/(platform)/PlatformChrome/usePlatformChrome";
+import { useExpertMap } from "@/app/(platform)/copilot/useExpertMap";
import { ArtifactsSearchBar } from "./components/ArtifactsSearchBar/ArtifactsSearchBar";
import { ArtifactsList } from "./components/ArtifactsList/ArtifactsList";
-import { getEmptyMessage } from "./components/ArtifactsList/helpers";
+import { getEmptyState } from "./components/ArtifactsList/helpers";
import { NewMenu } from "./components/NewMenu/NewMenu";
+import { ExpertFilter } from "./components/ExpertFilter/ExpertFilter";
import { OriginFilter } from "./components/OriginFilter/OriginFilter";
import { StorageUsage } from "./components/StorageUsage/StorageUsage";
import { ViewToggle } from "./components/ViewToggle/ViewToggle";
@@ -61,6 +63,8 @@ export default function ArtifactsPage() {
setOriginFilter,
selectedFolderId,
setSelectedFolderId,
+ expertFilter,
+ setExpertFilter,
view,
setView,
hasMore,
@@ -68,11 +72,13 @@ export default function ArtifactsPage() {
loadMore,
} = useArtifactsPage();
const { folders, isLoading: isFoldersLoading } = useArtifactsFolders();
+ const { activeExperts, expertsById } = useExpertMap();
const isSearching = searchTerm.length > 0;
const isInFolder = selectedFolderId !== null;
+ const isFilteringByExpert = expertFilter !== null;
const selectedFolder = folders.find((f) => f.id === selectedFolderId);
- const showFolders = !isInFolder && !isSearching;
+ const showFolders = !isInFolder && !isSearching && !isFilteringByExpert;
const hasFolders = showFolders && folders.length > 0;
// At the root the empty state depends on whether folders exist, so hold
// the loading state until both queries have settled.
@@ -82,6 +88,11 @@ export default function ArtifactsPage() {
document.title = "Files – AutoGPT Platform";
}, []);
+ function handleExpertFilterChange(expertId: string | null) {
+ setExpertFilter(expertId);
+ if (expertId) setSelectedFolderId(null);
+ }
+
if (!flagReady) {
return <ArtifactsPageSkeleton showNewLayout={showNewLayout} />;
}
@@ -93,21 +104,32 @@ export default function ArtifactsPage() {
return (
<main className={showNewLayout ? NEW_LAYOUT_MAIN : CLASSIC_MAIN}>
+ {/* Under the new layout the chrome's inset header owns the title row and
+ shows storage usage beside it (see InsetHeaderActions). */}
+ {!showNewLayout ? (
+ <motion.div
+ className="flex items-center justify-between gap-4"
+ variants={variants}
+ initial="hidden"
+ animate="show"
+ transition={{ delay: 0 }}
+ >
+ <Text variant="h3">Files</Text>
+ <StorageUsage />
+ </motion.div>
+ ) : null}
<div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
<motion.div
- className="flex flex-col gap-1"
variants={variants}
initial="hidden"
animate="show"
transition={{ delay: 0 }}
>
- {!showNewLayout && <Text variant="h3">Files</Text>}
<Text
variant={showNewLayout ? "large" : "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.
+ Find here every file generated by your team or uploaded by you.
</Text>
</motion.div>
<motion.div
@@ -126,12 +148,18 @@ export default function ArtifactsPage() {
</div>
<div className="flex flex-wrap items-center justify-between gap-4">
<motion.div
+ className="flex flex-wrap items-center gap-x-32 gap-y-2"
variants={variants}
initial="hidden"
animate="show"
transition={{ delay: reduceMotion ? 0 : 0.16 }}
>
<OriginFilter value={originFilter} onChange={setOriginFilter} />
+ <ExpertFilter
+ experts={activeExperts}
+ value={expertFilter}
+ onChange={handleExpertFilterChange}
+ />
</motion.div>
<motion.div
variants={variants}
@@ -166,30 +194,28 @@ export default function ArtifactsPage() {
isLoading={isListLoading}
isError={isError}
error={error}
- emptyMessage={getEmptyMessage({
+ emptyState={getEmptyState({
hasSearchTerm: isSearching,
isInFolder,
hasFolders,
+ folderId: selectedFolderId,
+ expert: expertFilter
+ ? {
+ id: expertFilter,
+ name: expertsById.get(expertFilter)?.name ?? null,
+ }
+ : null,
})}
compactEmpty={hasFolders}
hasMore={hasMore}
isLoadingMore={isLoadingMore}
onLoadMore={loadMore}
- listKey={`${originFilter}|${debouncedSearch}|${selectedFolderId ?? "root"}`}
+ listKey={`${originFilter}|${expertFilter ?? "everyone"}|${debouncedSearch}|${selectedFolderId ?? "root"}`}
view={view}
showFolders={showFolders}
onSelectFolder={setSelectedFolderId}
/>
</motion.div>
- <motion.div
- className="w-full pt-4 md:w-2/5"
- variants={variants}
- initial="hidden"
- animate="show"
- transition={{ delay: reduceMotion ? 0 : 0.32 }}
- >
- <StorageUsage />
- </motion.div>
</main>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts b/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts
index 6aa1a3c272..8fd1586dc4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/artifacts/useArtifactsPage.ts
@@ -17,6 +17,7 @@ export function useArtifactsPage() {
const [searchTerm, setSearchTerm] = useState("");
const [originFilter, setOriginFilter] = useState<OriginFilter>("all");
const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null);
+ const [expertFilter, setExpertFilter] = useState<string | null>(null);
const [view, setView] = useState<ArtifactsView>("list");
const debouncedSearch = useDebouncedValue(
@@ -26,12 +27,15 @@ export function useArtifactsPage() {
const q = debouncedSearch || undefined;
const origin = originFilter === "all" ? undefined : originFilter;
+ // An expert filter spans every file from that expert's conversations, so
+ // the folder axes are dropped: the API rejects combining them.
+ const expertId = expertFilter ?? undefined;
// No folder selected → show only root-level files; a folder is selected →
// scope the listing to that folder.
- const folderId = selectedFolderId ?? undefined;
+ const folderId = expertId ? undefined : (selectedFolderId ?? undefined);
// While searching, span the whole workspace (including files inside folders)
// so global search isn't limited to root-level files.
- const rootOnly = selectedFolderId === null && !q;
+ const rootOnly = !expertId && selectedFolderId === null && !q;
const query = useInfiniteQuery({
queryKey: [
@@ -41,6 +45,7 @@ export function useArtifactsPage() {
origin: origin ?? null,
folderId: folderId ?? null,
rootOnly,
+ expertId: expertId ?? null,
},
] as const,
queryFn: ({ pageParam }) =>
@@ -51,6 +56,7 @@ export function useArtifactsPage() {
origin,
folder_id: folderId,
root_only: rootOnly,
+ expert_id: expertId,
}),
initialPageParam: 0,
getNextPageParam: (lastPage, allPages) => {
@@ -76,6 +82,8 @@ export function useArtifactsPage() {
setOriginFilter,
selectedFolderId,
setSelectedFolderId,
+ expertFilter,
+ setExpertFilter,
view,
setView,
hasMore: !!query.hasNextPage,
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx
index 7d887fcd80..276cbe5771 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx
@@ -379,6 +379,7 @@ export const ChatContainer = ({
onDroppedFilesConsumed={onDroppedFilesConsumed}
hasSession={!!sessionId}
sessionId={sessionId}
+ expertId={expertIdentity?.id ?? null}
voiceToggle={
isVoiceModeEnabled ? (
<VoiceModeButton
@@ -441,6 +442,7 @@ export const ChatContainer = ({
isInteractionLocked={isSendLocked || !!isAdoptingExpertSession}
isKickoffStarting={isKickoffStarting}
expertName={expertIdentity?.name}
+ expertId={expertIdentity?.id ?? null}
/>
)}
</div>
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx
index cac4b11149..155636649c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/ChatInput.tsx
@@ -94,6 +94,9 @@ interface Props {
/** Compact composer for side panels: tighter radius, flat shadow, smaller
* controls, and no per-message connection chip. */
variant?: "default" | "compact";
+ /** Expert the chat is scoped to. Workspace-file suggestions and the picker
+ * then only offer files from that expert's conversations. */
+ expertId?: string | null;
}
export function ChatInput({
@@ -116,6 +119,7 @@ export function ChatInput({
voiceToggle,
voiceBar,
variant = "default",
+ expertId = null,
}: Props) {
const { isDryRun, setIsDryRun } = useCopilotUIStore();
// Still the CHAT_MODE_OPTION flag, which no longer names what it gates: the
@@ -193,6 +197,7 @@ export function ChatInput({
value,
setValue,
addWorkspaceFile: handleWorkspaceFileSelected,
+ expertId,
});
const [isEnqueueing, setIsEnqueueing] = useState(false);
@@ -486,9 +491,11 @@ export function ChatInput({
</InputGroup>
{showWorkspaceFiles && (
<WorkspaceFilePicker
+ key={expertId ?? "everyone"}
isOpen={isPickerOpen}
onClose={() => setIsPickerOpen(false)}
onConfirm={handleWorkspaceFilesConfirmed}
+ expertId={expertId}
/>
)}
</form>
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFilePicker.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFilePicker.tsx
index 783c0f1291..cae6335e84 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFilePicker.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/WorkspaceFilePicker.tsx
@@ -13,10 +13,16 @@ interface Props {
isOpen: boolean;
onClose: () => void;
onConfirm: (items: WorkspaceFileItem[]) => void;
+ expertId?: string | null;
}
-export function WorkspaceFilePicker({ isOpen, onClose, onConfirm }: Props) {
- const picker = useWorkspaceFilePicker({ enabled: isOpen });
+export function WorkspaceFilePicker({
+ isOpen,
+ onClose,
+ onConfirm,
+ expertId,
+}: Props) {
+ const picker = useWorkspaceFilePicker({ enabled: isOpen, expertId });
function handleOpenChange(open: boolean) {
if (!open) {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/__tests__/WorkspaceFilePicker.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/__tests__/WorkspaceFilePicker.test.tsx
index 9f5fa600a9..911ab1cbee 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/__tests__/WorkspaceFilePicker.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/__tests__/WorkspaceFilePicker.test.tsx
@@ -1,4 +1,9 @@
-import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
import { WorkspaceFilePicker } from "../WorkspaceFilePicker";
@@ -21,6 +26,78 @@ afterEach(() => {
});
describe("WorkspaceFilePicker", () => {
+ it("scopes the listing to the expert the chat is addressed to", async () => {
+ mockListWorkspaceFiles.mockResolvedValue({
+ status: 200,
+ data: { files: [FILE], has_more: false },
+ });
+
+ render(
+ <WorkspaceFilePicker
+ isOpen={true}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ expertId="expert-a"
+ />,
+ );
+
+ await screen.findByText("alpha.txt");
+ expect(mockListWorkspaceFiles).toHaveBeenCalledWith(
+ expect.objectContaining({ expert_id: "expert-a" }),
+ );
+ });
+
+ it("drops the previous expert's files while the next expert's listing is pending", async () => {
+ mockListWorkspaceFiles.mockResolvedValueOnce({
+ status: 200,
+ data: { files: [FILE], has_more: false },
+ });
+ const { rerender } = render(
+ <WorkspaceFilePicker
+ isOpen={true}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ expertId="expert-a"
+ />,
+ );
+ await screen.findByText("alpha.txt");
+
+ // Expert B's request never settles within the test: A's file must not
+ // stay on screen as a placeholder in the meantime.
+ mockListWorkspaceFiles.mockReturnValue(new Promise(() => {}));
+ rerender(
+ <WorkspaceFilePicker
+ isOpen={true}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ expertId="expert-b"
+ />,
+ );
+
+ await waitFor(() => expect(screen.queryByText("alpha.txt")).toBeNull());
+ expect(mockListWorkspaceFiles).toHaveBeenLastCalledWith(
+ expect.objectContaining({ expert_id: "expert-b" }),
+ );
+ });
+
+ it("lists the whole workspace for a personal chat", async () => {
+ mockListWorkspaceFiles.mockResolvedValue({
+ status: 200,
+ data: { files: [FILE], has_more: false },
+ });
+
+ render(
+ <WorkspaceFilePicker
+ isOpen={true}
+ onClose={vi.fn()}
+ onConfirm={vi.fn()}
+ />,
+ );
+
+ await screen.findByText("alpha.txt");
+ expect(mockListWorkspaceFiles.mock.calls[0][0].expert_id).toBeUndefined();
+ });
+
it("lists workspace files and confirms the selection", async () => {
mockListWorkspaceFiles.mockResolvedValue({
status: 200,
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/useWorkspaceFilePicker.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/useWorkspaceFilePicker.ts
index 0d379ab933..c974123b19 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/useWorkspaceFilePicker.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/WorkspaceFilePicker/useWorkspaceFilePicker.ts
@@ -1,11 +1,7 @@
import { listWorkspaceFiles } from "@/app/api/__generated__/endpoints/workspace/workspace";
import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
-import {
- type InfiniteData,
- keepPreviousData,
- useInfiniteQuery,
-} from "@tanstack/react-query";
+import { type InfiniteData, useInfiniteQuery } from "@tanstack/react-query";
import { useState } from "react";
const SEARCH_DEBOUNCE_MS = 250;
@@ -13,7 +9,13 @@ const PAGE_SIZE = 50;
type ListPage = Awaited<ReturnType<typeof listWorkspaceFiles>>;
-export function useWorkspaceFilePicker({ enabled }: { enabled: boolean }) {
+interface Args {
+ enabled: boolean;
+ /** Expert the chat is scoped to; lists only files that expert can attach. */
+ expertId?: string | null;
+}
+
+export function useWorkspaceFilePicker({ enabled, expertId }: Args) {
const [searchTerm, setSearchTerm] = useState("");
// Keep the full item (not just id) so a selection survives a search that
// pages the file off the currently-loaded list.
@@ -28,16 +30,30 @@ export function useWorkspaceFilePicker({ enabled }: { enabled: boolean }) {
const q = debouncedSearch || undefined;
const query = useInfiniteQuery({
- queryKey: ["workspace-file-picker", "list", { q: q ?? null }] as const,
+ queryKey: [
+ "workspace-file-picker",
+ "list",
+ { q: q ?? null, expertId: expertId ?? null },
+ ] as const,
queryFn: ({ pageParam }) =>
- listWorkspaceFiles({ limit: PAGE_SIZE, offset: pageParam, q }),
+ listWorkspaceFiles({
+ limit: PAGE_SIZE,
+ offset: pageParam,
+ q,
+ expert_id: expertId ?? undefined,
+ }),
initialPageParam: 0,
getNextPageParam: (lastPage, allPages) => {
if (lastPage.status !== 200) return undefined;
if (!lastPage.data.has_more) return undefined;
return countLoadedFiles(allPages);
},
- placeholderData: keepPreviousData,
+ // Keep the previous page while a search refines the same expert's list,
+ // but never show one expert's files while another's request is pending.
+ placeholderData: (previousData, previousQuery) =>
+ previousQuery?.queryKey[2].expertId === (expertId ?? null)
+ ? previousData
+ : undefined,
enabled,
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatMentions.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatMentions.ts
index d0e001ab4f..73605698d4 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatMentions.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/useChatMentions.ts
@@ -2,7 +2,7 @@ import { listWorkspaceFiles } from "@/app/api/__generated__/endpoints/workspace/
import type { WorkspaceFileItem } from "@/app/api/__generated__/models/workspaceFileItem";
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
import { useKeyboardNav } from "@/components/organisms/SearchCommandModal/useKeyboardNav";
-import { keepPreviousData, useQuery } from "@tanstack/react-query";
+import { useQuery } from "@tanstack/react-query";
import type { KeyboardEvent } from "react";
import { useState } from "react";
import { isKey } from "@/lib/keyboard";
@@ -22,6 +22,8 @@ interface Args {
value: string;
setValue: (value: string) => void;
addWorkspaceFile: (item: WorkspaceFileItem) => void;
+ /** Expert the chat is scoped to; suggests only files that expert can attach. */
+ expertId?: string | null;
}
/**
@@ -35,6 +37,7 @@ export function useChatMentions({
value,
setValue,
addWorkspaceFile,
+ expertId,
}: Args) {
const [active, setActive] = useState<ActiveMention | null>(null);
const isOpen = enabled && active !== null;
@@ -45,14 +48,25 @@ export function useChatMentions({
);
const search = useQuery({
- queryKey: ["chat-mention", "workspace-files", debouncedQuery],
+ queryKey: [
+ "chat-mention",
+ "workspace-files",
+ debouncedQuery,
+ expertId ?? null,
+ ] as const,
queryFn: () =>
listWorkspaceFiles({
limit: MENTION_RESULT_LIMIT,
q: debouncedQuery || undefined,
+ expert_id: expertId ?? undefined,
}),
enabled: isOpen,
- placeholderData: keepPreviousData,
+ // Keep results while the same expert's query refines; drop them when the
+ // chat switches expert so no foreign file can be picked mid-request.
+ placeholderData: (previousData, previousQuery) =>
+ previousQuery?.queryKey[3] === (expertId ?? null)
+ ? previousData
+ : undefined,
});
const files =
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx
index c8042ee838..c3fb82ada6 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx
@@ -43,6 +43,8 @@ interface Props {
isInteractionLocked?: boolean;
isKickoffStarting?: boolean;
expertName?: string;
+ /** Expert the new conversation will address; scopes workspace-file pickers. */
+ expertId?: string | null;
/** Voice-mode toggle, rendered beside the mic. Absent when the flag is off. */
voiceToggle?: ReactNode;
}
@@ -56,6 +58,7 @@ export function EmptySession({
isInteractionLocked,
isKickoffStarting,
expertName,
+ expertId = null,
voiceToggle,
}: Props) {
const { user } = useAuth();
@@ -214,6 +217,7 @@ export function EmptySession({
}
droppedFiles={droppedFiles}
onDroppedFilesConsumed={onDroppedFilesConsumed}
+ expertId={expertId}
recipientPicker={
isExpertsEnabled ? (
<RecipientChip
diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useHireFlow.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useHireFlow.tsx
index a8456f6afa..53a8bc3c7e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useHireFlow.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/experts/[expertId]/useHireFlow.tsx
@@ -24,7 +24,13 @@ function celebrate(result: HireResult) {
: undefined,
variant: "success",
action: (
- <Button as="NextLink" href="/team" variant="ghost" size="small">
+ <Button
+ as="NextLink"
+ href="/team"
+ variant="outline"
+ size="small"
+ className="border-white text-white hover:border-white hover:bg-white/15 hover:text-white"
+ >
View team
</Button>
),
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 56c1d9ad76..76f43f4acf 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -14939,7 +14939,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 Uploaded (user-uploaded) and Generated (agent/block output) files.\n\n``session_id`` (a per-session view) and the folder filters (``folder_id`` /\n``root_only``) are distinct, mutually exclusive axes, and ``folder_id`` and\n``root_only`` likewise conflict; passing conflicting filters returns a 400\nrather than silently yielding an empty list.",
+ "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.\n\n``session_id`` (a per-session view) and the folder filters (``folder_id`` /\n``root_only``) are distinct, mutually exclusive axes, and ``folder_id`` and\n``root_only`` likewise conflict; passing conflicting filters returns a 400\nrather than silently yielding an empty list.\n\n``expert_id`` narrows the listing to files from that hired expert's own\nconversations. It excludes the other axes for the same reason. An expert\nthe caller does not own (or no longer has) yields an empty list.",
"operationId": "listWorkspaceFiles",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -15025,6 +15025,20 @@
"title": "Root Only"
},
"description": "Only return root-level files (not in any folder)."
+ },
+ {
+ "name": "expert_id",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ { "type": "string", "minLength": 1 },
+ { "type": "null" }
+ ],
+ "description": "Only return files from this hired expert's conversations. Cannot be combined with session_id, folder_id or root_only.",
+ "title": "Expert Id"
+ },
+ "description": "Only return files from this hired expert's conversations. Cannot be combined with session_id, folder_id or root_only."
}
],
"responses": {
@@ -15036,6 +15050,7 @@
}
}
},
+ "400": { "description": "Conflicting filters" },
"401": {
"$ref": "#/components/responses/HTTP401NotAuthenticatedError"
},
@@ -15149,6 +15164,52 @@
}
}
}
+ },
+ "patch": {
+ "tags": ["workspace"],
+ "summary": "Rename a workspace file",
+ "description": "Rename a file; it stays in its folder and conversation.",
+ "operationId": "renameWorkspaceFile",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "file_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "File Id" }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/RenameFileRequest" }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/WorkspaceFileItem" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "404": { "description": "File not found" },
+ "409": { "description": "A file with this name already exists here" },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
}
},
"/api/workspace/files/{file_id}/download": {
@@ -25701,6 +25762,19 @@
],
"title": "RefundRequest"
},
+ "RenameFileRequest": {
+ "properties": {
+ "name": {
+ "type": "string",
+ "maxLength": 255,
+ "minLength": 1,
+ "title": "Name"
+ }
+ },
+ "type": "object",
+ "required": ["name"],
+ "title": "RenameFileRequest"
+ },
"RequestTopUp": {
"properties": {
"credit_amount": { "type": "integer", "title": "Credit Amount" }
@@ -30377,7 +30451,11 @@
"enum": ["uploaded", "generated"],
"title": "Origin"
},
- "created_at": { "type": "string", "title": "Created At" }
+ "created_at": { "type": "string", "title": "Created At" },
+ "expert_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Expert Id"
+ }
},
"type": "object",
"required": [