Skip to content

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

feat(backend): nested workspace folders, folder listing for AutoPilot, and expert access to the user's own files (#14773)

Reinier van der Leer5d28ec680a4f
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 845147754b..f7e4868433 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -157,6 +157,7 @@ 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
+from backend.data.workspace_folder import resolve_attachable_workspace_folders
from backend.integrations.codex.access import enforce_codex_access_http
from backend.integrations.credentials_store import provider_matches
from backend.integrations.creds_manager import IntegrationCredentialsManager
@@ -290,6 +291,12 @@ class StreamChatRequest(BaseModel):
file_ids: list[str] | None = Field(
default=None, max_length=20
) # Workspace file IDs attached to this message
+ folder_ids: list[str] | None = Field(
+ default=None,
+ max_length=5,
+ description="Workspace folder IDs attached to this message. Named in "
+ "the message for the model to open, never expanded into their files.",
+ )
model: CopilotLLMModel | None = Field(
default=None,
description="Model tier: 'standard' for the default model, 'advanced' for the highest-capability model. "
@@ -326,6 +333,7 @@ class QueuePendingMessageRequest(BaseModel):
message: str = Field(max_length=64_000)
context: dict[str, str] | None = None
file_ids: list[str] | None = Field(default=None, max_length=20)
+ folder_ids: list[str] | None = Field(default=None, max_length=5)
class PeekPendingMessagesResponse(BaseModel):
@@ -1828,6 +1836,7 @@ async def stream_chat_post(
message=message,
context=request.context,
file_ids=request.file_ids,
+ folder_ids=request.folder_ids,
expert_id=session.expert_id,
)
return _empty_ui_message_stream_response()
@@ -1901,15 +1910,18 @@ async def stream_chat_post(
# 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:
+ if request.file_ids or request.folder_ids:
files = await resolve_attachments_for_http(
user_id,
- request.file_ids,
+ request.file_ids or [],
session_id=session_id,
expert_id=session.expert_id,
)
+ folders = await resolve_attachable_workspace_folders(
+ user_id, request.folder_ids or [], expert_id=session.expert_id
+ )
sanitized_file_ids = [wf.id for wf in files] or None
- message += build_files_block(files)
+ message += build_files_block(files, folders)
# Atomically append user message to session BEFORE creating task to avoid
# race condition where GET_SESSION sees task as "running" but message isn't
@@ -2189,6 +2201,7 @@ async def queue_pending_message(
message=request.message,
context=request.context,
file_ids=request.file_ids,
+ folder_ids=request.folder_ids,
expert_id=session.expert_id,
)
diff --git a/autogpt_platform/backend/backend/api/features/workspace/folder_routes.py b/autogpt_platform/backend/backend/api/features/workspace/folder_routes.py
index a7617464d5..2d0e114134 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/folder_routes.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/folder_routes.py
@@ -16,12 +16,13 @@ from pydantic import BaseModel, Field
from backend.data.workspace import WorkspaceFile, get_or_create_workspace
from backend.data.workspace_folder import (
+ UNCHANGED,
WorkspaceFolder,
+ apply_folder_update,
bulk_move_files_to_folder,
create_folder,
delete_folder,
- list_folders,
- update_folder,
+ list_workspace_folders,
)
router = fastapi.APIRouter(
@@ -32,11 +33,18 @@ router = fastapi.APIRouter(
class WorkspaceFolderCreateRequest(BaseModel):
name: str = Field(..., min_length=1, max_length=100)
icon: str | None = None
+ # None = create at the workspace root. Reject "" so it cannot bypass the
+ # truthiness-based ownership check (422 instead of a foreign-key error).
+ parent_id: str | None = Field(None, min_length=1)
class WorkspaceFolderUpdateRequest(BaseModel):
name: str | None = Field(None, min_length=1, max_length=100)
icon: str | None = None
+ # Present-but-null means "move to the root", absent means "leave where it
+ # is", which a plain default cannot express — the handler reads
+ # ``model_fields_set`` to tell them apart.
+ parent_id: str | None = Field(None, min_length=1)
class BulkMoveFilesRequest(BaseModel):
@@ -55,11 +63,15 @@ class WorkspaceFolderListResponse(BaseModel):
summary="List workspace folders",
operation_id="listWorkspaceFolders",
)
-async def list_workspace_folders(
+async def list_workspace_folders_route(
user_id: Annotated[str, fastapi.Security(get_user_id)],
) -> WorkspaceFolderListResponse:
+ """Every folder in the workspace, flat; nesting is read off ``parent_id``.
+
+ ``file_count`` counts the files directly in each folder, not its subtree.
+ """
workspace = await get_or_create_workspace(user_id)
- folders = await list_folders(workspace.id)
+ folders = await list_workspace_folders(workspace.id)
return WorkspaceFolderListResponse(folders=folders)
@@ -68,7 +80,10 @@ async def list_workspace_folders(
summary="Create workspace folder",
operation_id="createWorkspaceFolder",
status_code=fastapi.status.HTTP_201_CREATED,
- responses={409: {"description": "A folder with this name already exists"}},
+ responses={
+ 404: {"description": "Parent folder not found"},
+ 409: {"description": "A folder with this name already exists"},
+ },
)
async def create_workspace_folder(
user_id: Annotated[str, fastapi.Security(get_user_id)],
@@ -79,6 +94,7 @@ async def create_workspace_folder(
workspace_id=workspace.id,
name=payload.name,
icon=payload.icon,
+ parent_id=payload.parent_id,
)
@@ -87,7 +103,8 @@ async def create_workspace_folder(
summary="Update workspace folder",
operation_id="updateWorkspaceFolder",
responses={
- 404: {"description": "Folder not found"},
+ 400: {"description": "A folder cannot be moved into its own subtree"},
+ 404: {"description": "Folder or destination not found"},
409: {"description": "A folder with this name already exists"},
},
)
@@ -96,10 +113,20 @@ async def update_workspace_folder(
folder_id: str,
payload: WorkspaceFolderUpdateRequest,
) -> WorkspaceFolder:
+ """Rename a folder, change its icon, and/or move it.
+
+ Sending ``parent_id: null`` moves the folder to the workspace root;
+ leaving the field out keeps it where it is. Move and rename are applied
+ together or not at all, and the new name is checked for a clash against
+ the destination.
+ """
workspace = await get_or_create_workspace(user_id)
- return await update_folder(
+ return await apply_folder_update(
folder_id=folder_id,
workspace_id=workspace.id,
+ parent_id=(
+ payload.parent_id if "parent_id" in payload.model_fields_set else UNCHANGED
+ ),
name=payload.name,
icon=payload.icon,
)
@@ -116,6 +143,7 @@ async def delete_workspace_folder(
user_id: Annotated[str, fastapi.Security(get_user_id)],
folder_id: str,
) -> Response:
+ """Delete a folder and its subfolders; their files return to the root."""
workspace = await get_or_create_workspace(user_id)
await delete_folder(folder_id=folder_id, workspace_id=workspace.id)
return Response(status_code=fastapi.status.HTTP_204_NO_CONTENT)
diff --git a/autogpt_platform/backend/backend/api/features/workspace/folder_routes_test.py b/autogpt_platform/backend/backend/api/features/workspace/folder_routes_test.py
index 9348f0386e..25f5c10357 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/folder_routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/folder_routes_test.py
@@ -5,10 +5,13 @@ import fastapi
import fastapi.testclient
import pytest
-from backend.api.features.library.exceptions import FolderAlreadyExistsError
+from backend.api.features.library.exceptions import (
+ FolderAlreadyExistsError,
+ FolderValidationError,
+)
from backend.api.features.workspace.folder_routes import router
from backend.data.workspace import Workspace, WorkspaceFile
-from backend.data.workspace_folder import WorkspaceFolder
+from backend.data.workspace_folder import UNCHANGED, WorkspaceFolder
from backend.util.exceptions import NotFoundError
app = fastapi.FastAPI()
@@ -24,6 +27,13 @@ async def _folder_exists_handler(
return fastapi.responses.JSONResponse(status_code=409, content={"detail": str(exc)})
[email protected]_handler(FolderValidationError)
+async def _folder_invalid_handler(
+ request: fastapi.Request, exc: FolderValidationError
+) -> fastapi.responses.JSONResponse:
+ return fastapi.responses.JSONResponse(status_code=400, content={"detail": str(exc)})
+
+
@app.exception_handler(NotFoundError)
async def _not_found_handler(
request: fastapi.Request, exc: NotFoundError
@@ -88,7 +98,7 @@ def test_list_folders_returns_folders(mocker):
AsyncMock(return_value=_make_workspace()),
)
mocker.patch(
- "backend.api.features.workspace.folder_routes.list_folders",
+ "backend.api.features.workspace.folder_routes.list_workspace_folders",
AsyncMock(return_value=[_make_folder(file_count=3)]),
)
@@ -113,7 +123,9 @@ def test_create_folder_success(mocker):
response = client.post("/folders", json={"name": "Invoices"})
assert response.status_code == 201
assert response.json()["name"] == "Invoices"
- create.assert_awaited_once_with(workspace_id="ws-001", name="Invoices", icon=None)
+ create.assert_awaited_once_with(
+ workspace_id="ws-001", name="Invoices", icon=None, parent_id=None
+ )
def test_create_folder_name_conflict_returns_409(mocker):
@@ -136,7 +148,7 @@ def test_update_folder_success(mocker):
AsyncMock(return_value=_make_workspace()),
)
update = mocker.patch(
- "backend.api.features.workspace.folder_routes.update_folder",
+ "backend.api.features.workspace.folder_routes.apply_folder_update",
AsyncMock(return_value=_make_folder(name="Renamed")),
)
@@ -144,7 +156,11 @@ def test_update_folder_success(mocker):
assert response.status_code == 200
assert response.json()["name"] == "Renamed"
update.assert_awaited_once_with(
- folder_id="fld-1", workspace_id="ws-001", name="Renamed", icon=None
+ folder_id="fld-1",
+ workspace_id="ws-001",
+ parent_id=UNCHANGED,
+ name="Renamed",
+ icon=None,
)
@@ -154,7 +170,7 @@ def test_update_folder_not_found_returns_404(mocker):
AsyncMock(return_value=_make_workspace()),
)
mocker.patch(
- "backend.api.features.workspace.folder_routes.update_folder",
+ "backend.api.features.workspace.folder_routes.apply_folder_update",
AsyncMock(side_effect=NotFoundError("nope")),
)
@@ -226,3 +242,77 @@ def test_bulk_move_files_to_root(mocker):
move.assert_awaited_once_with(
workspace_id="ws-001", file_ids=["f1"], folder_id=None
)
+
+
+def test_create_folder_under_a_parent(mocker):
+ mocker.patch(
+ "backend.api.features.workspace.folder_routes.get_or_create_workspace",
+ AsyncMock(return_value=_make_workspace()),
+ )
+ create = mocker.patch(
+ "backend.api.features.workspace.folder_routes.create_folder",
+ AsyncMock(return_value=_make_folder(name="2026")),
+ )
+
+ response = client.post("/folders", json={"name": "2026", "parent_id": "invoices"})
+
+ assert response.status_code == 201
+ create.assert_awaited_once_with(
+ workspace_id="ws-001", name="2026", icon=None, parent_id="invoices"
+ )
+
+
+def test_update_folder_without_parent_id_does_not_move_it(mocker):
+ """An absent field means "leave it where it is"; only a present one moves
+ the folder, which a plain default could not express."""
+ mocker.patch(
+ "backend.api.features.workspace.folder_routes.get_or_create_workspace",
+ AsyncMock(return_value=_make_workspace()),
+ )
+ update = mocker.patch(
+ "backend.api.features.workspace.folder_routes.apply_folder_update",
+ AsyncMock(return_value=_make_folder(name="Renamed")),
+ )
+
+ response = client.patch("/folders/fld-1", json={"name": "Renamed"})
+
+ assert response.status_code == 200
+ assert update.await_args.kwargs["parent_id"] is UNCHANGED
+
+
[email protected]("destination", ["invoices", None])
+def test_update_folder_moves_it_when_parent_id_is_present(mocker, destination):
+ mocker.patch(
+ "backend.api.features.workspace.folder_routes.get_or_create_workspace",
+ AsyncMock(return_value=_make_workspace()),
+ )
+ update = mocker.patch(
+ "backend.api.features.workspace.folder_routes.apply_folder_update",
+ AsyncMock(return_value=_make_folder()),
+ )
+
+ response = client.patch("/folders/fld-1", json={"parent_id": destination})
+
+ assert response.status_code == 200
+ update.assert_awaited_once_with(
+ folder_id="fld-1",
+ workspace_id="ws-001",
+ parent_id=destination,
+ name=None,
+ icon=None,
+ )
+
+
+def test_update_folder_cycle_returns_400(mocker):
+ mocker.patch(
+ "backend.api.features.workspace.folder_routes.get_or_create_workspace",
+ AsyncMock(return_value=_make_workspace()),
+ )
+ mocker.patch(
+ "backend.api.features.workspace.folder_routes.apply_folder_update",
+ AsyncMock(side_effect=FolderValidationError("cycle")),
+ )
+
+ response = client.patch("/folders/fld-1", json={"parent_id": "own-child"})
+
+ assert response.status_code == 400
diff --git a/autogpt_platform/backend/backend/api/features/workspace/routes.py b/autogpt_platform/backend/backend/api/features/workspace/routes.py
index 9ce6eb0684..dbc8c00bf1 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/routes.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/routes.py
@@ -510,8 +510,17 @@ async def list_workspace_files(
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."
+ "Only return files from this hired expert's own conversations. "
+ "Combines with folder_id, root_only and include_user_files; "
+ "cannot be combined with session_id."
+ ),
+ ),
+ include_user_files: bool = Query(
+ default=False,
+ description=(
+ "With expert_id, also return the user's own files — everything "
+ "outside /sessions/, /experts/ and /skills/ — which the expert "
+ "may read but which are not its own. Requires expert_id."
),
),
) -> ListFilesResponse:
@@ -530,9 +539,17 @@ async def list_workspace_files(
``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.
+ ``expert_id`` narrows the listing to that hired expert's own
+ conversations. It conflicts with ``session_id`` — both name which
+ conversations to show — but composes with the folder filters, which select
+ across the whole workspace. An expert the caller does not own (or no
+ longer has) yields an empty list.
+
+ ``include_user_files`` widens an ``expert_id`` listing with the user's own
+ files, which an expert may read but which are nobody's conversation. It is
+ opt-in so that a view already filtered to one expert keeps showing that
+ expert's files and nothing else; the composer's picker sends it when its
+ "only this expert" filter is switched off.
"""
# Treat empty-string session_id the same as omitted — an empty value
# would otherwise silently list files across every session instead of
@@ -554,12 +571,17 @@ 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
- ):
+ if expert_id is not None and session_id is not None:
raise fastapi.HTTPException(
status_code=400,
- detail="expert_id cannot be combined with session_id, folder_id or root_only",
+ detail="expert_id cannot be combined with session_id",
+ )
+ if include_user_files and expert_id is None:
+ # Without an expert there is no scope to widen: an unscoped listing
+ # already spans the whole workspace, so this could only mislead.
+ raise fastapi.HTTPException(
+ status_code=400,
+ detail="include_user_files requires expert_id",
)
workspace = await get_or_create_workspace(user_id)
@@ -593,12 +615,15 @@ async def list_workspace_files(
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.
+ # Fails closed: an unowned or archived expert resolves to no sessions
+ # and no user-file grant, so every branch of the filter 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
]
+ list_kwargs["include_user_files"] = (
+ include_user_files and scope.reads_user_files
+ )
files = await manager.list_files(**list_kwargs)
has_more = len(files) > limit
page = files[:limit]
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 0035d883eb..0065aeaeed 100644
--- a/autogpt_platform/backend/backend/api/features/workspace/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/workspace/routes_test.py
@@ -1204,6 +1204,7 @@ def test_list_files_filters_to_the_experts_own_conversations(
folder_id=None,
root_only=False,
allowed_path_prefixes=["/sessions/s1/", "/sessions/s2/"],
+ include_user_files=False,
)
@@ -1222,17 +1223,100 @@ def test_list_files_unowned_expert_lists_nothing(
response = client.get("/files?expert_id=expert-x")
assert response.status_code == 200
assert response.json()["files"] == []
+ # Both branches of the filter fail closed: no session prefixes, and the
+ # user-files grant is carried by the scope, never inferred from expert_id.
assert mock_instance.list_files.call_args.kwargs["allowed_path_prefixes"] == []
+ assert mock_instance.list_files.call_args.kwargs["include_user_files"] is False
+
+
+@patch("backend.api.features.workspace.routes.get_or_create_workspace")
+def test_list_files_rejects_expert_id_with_session_id(mock_get_workspace):
+ """Both name which conversations to show, so combining them is ambiguous."""
+ response = client.get("/files?expert_id=expert-a&session_id=sess-1")
+ assert response.status_code == 400
+ assert "expert_id" in response.json()["detail"]
+ mock_get_workspace.assert_not_called()
+
+
[email protected]("query", ["folder_id=fld-1", "root_only=true"])
+@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_combines_expert_id_with_the_folder_filters(
+ mock_manager_cls, mock_get_workspace, mock_resolve_scope, query
+):
+ """A folder selects across the whole workspace, which is exactly the axis
+ the picker needs while filtered to one expert."""
+ mock_get_workspace.return_value = _make_workspace()
+ mock_resolve_scope.return_value = WorkspaceScope(
+ expert_id="expert-a", session_ids=["s1"], reads_user_files=True
+ )
+ mock_instance = AsyncMock()
+ mock_instance.list_files.return_value = []
+ mock_manager_cls.return_value = mock_instance
+
+ response = client.get(f"/files?expert_id=expert-a&{query}&include_user_files=true")
+
+ assert response.status_code == 200
+ kwargs = mock_instance.list_files.call_args.kwargs
+ assert kwargs["allowed_path_prefixes"] == ["/sessions/s1/"]
+ assert kwargs["include_user_files"] is True
@pytest.mark.parametrize(
- "query", ["session_id=sess-1", "folder_id=fld-1", "root_only=true"]
+ "query,expected",
+ [
+ ("expert_id=expert-a", False),
+ ("expert_id=expert-a&include_user_files=true", True),
+ ],
)
+@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_spans_the_users_own_files_only_when_asked(
+ mock_manager_cls, mock_get_workspace, mock_resolve_scope, query, expected
+):
+ """Opt-in: a view already filtered to one expert keeps showing that
+ expert's files, so the existing "From: <expert>" tab does not silently
+ start listing every upload the user ever made."""
+ mock_get_workspace.return_value = _make_workspace()
+ mock_resolve_scope.return_value = WorkspaceScope(
+ expert_id="expert-a", session_ids=["s1"], reads_user_files=True
+ )
+ mock_instance = AsyncMock()
+ mock_instance.list_files.return_value = []
+ mock_manager_cls.return_value = mock_instance
+
+ response = client.get(f"/files?{query}")
+
+ assert response.status_code == 200
+ assert mock_instance.list_files.call_args.kwargs["include_user_files"] is expected
+
+
+@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_include_user_files_cannot_widen_a_revoked_experts_listing(
+ mock_manager_cls, mock_get_workspace, mock_resolve_scope
+):
+ """The scope decides: asking for user files does not grant them."""
+ 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&include_user_files=true")
+
+ assert response.status_code == 200
+ assert mock_instance.list_files.call_args.kwargs["include_user_files"] is False
+
+
@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}")
+def test_list_files_rejects_include_user_files_without_an_expert(mock_get_workspace):
+ response = client.get("/files?include_user_files=true")
assert response.status_code == 400
- assert "expert_id" in response.json()["detail"]
+ assert "include_user_files" in response.json()["detail"]
mock_get_workspace.assert_not_called()
diff --git a/autogpt_platform/backend/backend/copilot/pending_message_helpers.py b/autogpt_platform/backend/backend/copilot/pending_message_helpers.py
index a25631359e..f08239e005 100644
--- a/autogpt_platform/backend/backend/copilot/pending_message_helpers.py
+++ b/autogpt_platform/backend/backend/copilot/pending_message_helpers.py
@@ -34,7 +34,8 @@ 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_attachable_workspace_files
+from backend.data.workspace import build_files_block, resolve_attachable_workspace_files
+from backend.data.workspace_folder import resolve_attachable_workspace_folders
from backend.data.workspace_scope import WorkspaceAccessDeniedError
if TYPE_CHECKING:
@@ -204,6 +205,7 @@ async def queue_pending_for_http(
message: str,
context: dict[str, str] | None,
file_ids: list[str] | None,
+ folder_ids: list[str] | None,
expert_id: str | None,
) -> QueuePendingMessageResponse:
"""HTTP-facing wrapper around :func:`queue_user_message`.
@@ -216,6 +218,10 @@ async def queue_pending_for_http(
3. ``{url, content}`` dict → ``PendingMessageContext`` coercion.
4. Push via ``queue_user_message``.
+ Attached folders are appended to the message text here rather than carried
+ as a field: a pending message is rendered from ``content`` when the turn
+ drains it, and entries written by older workers are still in Redis.
+
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.
@@ -226,6 +232,11 @@ async def queue_pending_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
+ if folder_ids:
+ folders = await resolve_attachable_workspace_folders(
+ user_id, folder_ids, expert_id=expert_id
+ )
+ message += build_files_block([], folders)
# ``PendingMessageContext`` uses the default ``extra='ignore'`` so
# unknown keys in the loose HTTP-level ``context`` dict are silently
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 0835a062d0..ab9e0a7b30 100644
--- a/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.py
+++ b/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.py
@@ -204,6 +204,7 @@ async def test_queue_pending_does_not_charge_rate_on_toctou_409(
message="hi",
context=None,
file_ids=None,
+ folder_ids=None,
expert_id=None,
)
assert exc_info.value.status_code == 409
@@ -235,6 +236,7 @@ async def test_queue_pending_charges_rate_only_after_successful_push(
message="hi",
context=None,
file_ids=None,
+ folder_ids=None,
expert_id=None,
)
@@ -275,6 +277,7 @@ async def test_queue_pending_429_after_push_when_limit_exceeded(
message="hi",
context=None,
file_ids=None,
+ folder_ids=None,
expert_id=None,
)
assert exc_info.value.status_code == 429
@@ -947,6 +950,7 @@ async def test_queue_pending_rejects_file_outside_expert_scope(
message="hi",
context=None,
file_ids=["aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"],
+ folder_ids=None,
expert_id="expert-a",
)
assert exc_info.value.status_code == 400
@@ -980,9 +984,44 @@ async def test_queue_pending_resolves_files_against_the_session_expert(
message="hi",
context=None,
file_ids=["file-1"],
+ folder_ids=None,
expert_id="expert-a",
)
resolve_mock.assert_awaited_once_with(
"user-1", ["file-1"], session_id="sess-1", expert_id="expert-a"
)
+
+
+async def test_queue_pending_names_attached_folders_in_the_message(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ response = QueuePendingMessageResponse(
+ buffer_length=1,
+ max_buffer_length=MAX_PENDING_MESSAGES,
+ turn_in_flight=True,
+ )
+ queue_mock = AsyncMock(return_value=response)
+ monkeypatch.setattr(helpers_module, "queue_user_message", queue_mock)
+ monkeypatch.setattr(
+ helpers_module, "check_pending_call_rate", AsyncMock(return_value=1)
+ )
+ folder = SimpleNamespace(id="folder-1", name="Invoices", file_count=3)
+ resolve_mock = AsyncMock(return_value=[folder])
+ monkeypatch.setattr(
+ helpers_module, "resolve_attachable_workspace_folders", resolve_mock
+ )
+
+ await queue_pending_for_http(
+ session_id="sess-1",
+ user_id="user-1",
+ message="hi",
+ context=None,
+ file_ids=None,
+ folder_ids=["folder-1"],
+ expert_id="expert-a",
+ )
+
+ resolve_mock.assert_awaited_once_with("user-1", ["folder-1"], expert_id="expert-a")
+ assert "Invoices" in queue_mock.call_args.kwargs["message"]
diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.py
index 3d14e73ab6..0094e15d35 100644
--- a/autogpt_platform/backend/backend/copilot/tools/models.py
+++ b/autogpt_platform/backend/backend/copilot/tools/models.py
@@ -401,6 +401,19 @@ class WorkspaceFileInfoData(BaseModel):
size_bytes: int
+class WorkspaceFolderInfoData(BaseModel):
+ """A workspace folder as ``list_workspace_files`` reports it.
+
+ ``file_count`` counts the files directly inside; a subfolder's own files
+ are counted on that subfolder.
+ """
+
+ folder_id: str
+ name: str
+ parent_id: str | None = None
+ file_count: int
+
+
class DelegatedExpertInfo(BaseModel):
"""Identity of the expert a delegated sub-session runs as.
diff --git a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
index 70c0fb92af..a33a6d7381 100644
--- a/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/tool_schema_test.py
@@ -241,7 +241,24 @@ from ._test_data import make_session
# no-margin rule above: this lands during the v0.8.0 release while dev is
# still moving, and the two rewordings that cost 146 chars last week would
# each have reded this PR at the queue on a measured-plus-one ceiling.
-_CHAR_BUDGET = 76_300
+# Bumped 76_300 -> 76_686 for list_workspace_files' folder_id and recursive
+# arguments and the description rewrite that tells the model where the user's
+# own uploads live, plus the matching sentence in read_workspace_file. No tool
+# was added (89 either side). Measured on the branch merged with dev, which
+# here is the branch itself — it already contains dev's tip 480c6f5509:
+# dev 480c6f5509 76,245 (89 tools)
+# + this PR's two descriptions +440 76,685 (89 tools)
+# Plus one; that line carried no margin by design, and dev overtook it within
+# the day: #14779 made the session's skills first-class find_capability
+# candidates, growing find_capability and run_capability, and the merge ref
+# measured 76,714 — 28 over — with none of this branch's delta having moved.
+# Re-measured on this branch merged with dev b6b03f5e72:
+# merged tree 76,714 (89 tools)
+# + headroom +300 77,014
+# The margin is deliberate and is the same exception the wire budget's #14476
+# note names: this is queued while dev is still moving, and a measured-plus-one
+# ceiling reds the queue's merge ref on the next reworded description.
+_CHAR_BUDGET = 77_014
@pytest.fixture(scope="module")
@@ -412,10 +429,26 @@ def test_total_schema_char_budget() -> None:
# prefixes, so the higher of the two conflicting values was the floor here,
# not the answer. Carries the same deliberate margin as ``_CHAR_BUDGET``.
#
+# Raised 68_800 -> 69_156 for the same two descriptions as ``_CHAR_BUDGET``
+# above. Both file tools are in the largest session, so the whole delta lands
+# here too — but the wire form drops ``required`` and prefixes each name, so it
+# is +430 here against +440 there. Measured on the branch merged with dev,
+# which here is the branch itself (it contains dev's tip 480c6f5509):
+# dev 480c6f5509 68,725
+# + this PR's two descriptions +430 69,155
+# Plus one. Dev's 68,725 sits 75 under the old 68,800, which was the margin
+# that line took deliberately; this one takes none.
+#
# ON CONFLICT, KEEP THE HIGHER VALUE — same rule, same reason: each branch's
# CI measures only its own delta while the ceiling has to cover every in-flight
# PR together. MEASURE ON THE PR'S MERGE REF, never the branch tip.
-_SESSION_WIRE_BUDGET = 68_800
+#
+# Re-measured on this branch merged with dev b6b03f5e72, after #14779 grew
+# find_capability and run_capability: the merge ref measured 69,183, 27 over
+# the plus-one ceiling above. Same headroom, for the same reason.
+# merged tree 69,183
+# + headroom +300 69,483
+_SESSION_WIRE_BUDGET = 69_483
def test_largest_declared_session_wire_budget() -> None:
diff --git a/autogpt_platform/backend/backend/copilot/tools/workspace_files.py b/autogpt_platform/backend/backend/copilot/tools/workspace_files.py
index d087897021..b00040831a 100644
--- a/autogpt_platform/backend/backend/copilot/tools/workspace_files.py
+++ b/autogpt_platform/backend/backend/copilot/tools/workspace_files.py
@@ -4,6 +4,7 @@ import base64
import logging
import mimetypes
import os
+from collections import deque
from typing import Any, Optional
from backend.api.features.store.exceptions import VirusDetectedError, VirusScanError
@@ -22,12 +23,19 @@ from backend.copilot.tools.workdir import (
validate_ephemeral_path,
)
from backend.data.activity_event import ActivityEventDraft
+from backend.data.workspace_folder import WorkspaceFolder
from backend.data.workspace_scope import WorkspaceAccessDeniedError
from backend.util.settings import Config
from backend.util.workspace import WorkspaceManager
from .base import BaseTool
-from .models import ErrorResponse, ResponseType, ToolResponseBase, WorkspaceFileInfoData
+from .models import (
+ ErrorResponse,
+ ResponseType,
+ ToolResponseBase,
+ WorkspaceFileInfoData,
+ WorkspaceFolderInfoData,
+)
logger = logging.getLogger(__name__)
@@ -183,6 +191,10 @@ class WorkspaceFileListResponse(ToolResponseBase):
type: ResponseType = ResponseType.WORKSPACE_FILE_LIST
files: list[WorkspaceFileInfoData]
total_count: int
+ # Folders at the listed level, so the model can walk the tree without a
+ # second tool. Folders are user-level: an expert sees the whole tree and
+ # only the files inside it are filtered by its scope.
+ folders: list[WorkspaceFolderInfoData] = []
class WorkspaceFileContentResponse(ToolResponseBase):
@@ -329,7 +341,13 @@ class ListWorkspaceFilesTool(BaseTool):
@property
def description(self) -> str:
- return "List persistent workspace files. For ephemeral session files, use SDK Glob/Read instead. Optionally filter by path prefix."
+ return (
+ "List persistent workspace files, with the folders at that level. "
+ "Files uploaded on the Files page sit at the workspace root or in "
+ "a folder; pass folder_id to list one, then read a file with "
+ "read_workspace_file. For ephemeral session files, use SDK "
+ "Glob/Read instead."
+ )
@property
def parameters(self) -> dict[str, Any]:
@@ -340,6 +358,20 @@ class ListWorkspaceFilesTool(BaseTool):
"type": "string",
"description": "Filter by path prefix (e.g. '/documents/').",
},
+ "folder_id": {
+ "type": "string",
+ "description": (
+ "Files in this folder. Omit for this chat's files and "
+ "the folders at the workspace root."
+ ),
+ },
+ "recursive": {
+ "type": "boolean",
+ "description": (
+ "With folder_id, also list files in its subfolders "
+ "(default: false)."
+ ),
+ },
"limit": {
"type": "integer",
"description": "Max files to return (default 50, max 100).",
@@ -349,9 +381,9 @@ class ListWorkspaceFilesTool(BaseTool):
"include_all_sessions": {
"type": "boolean",
"description": (
- "Include files from all sessions (default: false). "
- "Expert chats only ever see files from their own "
- "conversations and ones they delegated."
+ "Include files from every chat, not just this one "
+ "(default: false). An expert chat sees its own "
+ "conversations, ones it delegated, and the user's files."
),
},
},
@@ -367,6 +399,8 @@ class ListWorkspaceFilesTool(BaseTool):
user_id: str | None,
session: ChatSession,
path_prefix: Optional[str] = None,
+ folder_id: Optional[str] = None,
+ recursive: bool = False,
limit: int = 50,
include_all_sessions: bool = False,
**kwargs,
@@ -379,13 +413,35 @@ class ListWorkspaceFilesTool(BaseTool):
limit = min(limit, 100)
+ # "" is not "no folder": it survives the manager's `is not None` test,
+ # which drops the current-session filter, and then reads as false in the
+ # query, which drops the folder filter — listing the whole workspace.
+ if folder_id is not None and not folder_id.strip():
+ return ErrorResponse(
+ message="folder_id must name a folder; omit it to list the root",
+ session_id=session_id,
+ )
+
try:
manager = await get_workspace_manager(user_id, session_id)
+ folders = await manager.list_folders()
+ descend = folder_id if recursive else None
+ subtree, unsearched = (
+ _folder_subtree(folders, descend) if descend else ([], 0)
+ )
+ list_kwargs: dict[str, Any] = (
+ {"folder_ids": subtree} if descend else {"folder_id": folder_id}
+ )
files = await manager.list_files(
- path=path_prefix, limit=limit, include_all_sessions=include_all_sessions
+ path=path_prefix,
+ limit=limit,
+ include_all_sessions=include_all_sessions,
+ **list_kwargs,
)
total = await manager.get_file_count(
- path=path_prefix, include_all_sessions=include_all_sessions
+ path=path_prefix,
+ include_all_sessions=include_all_sessions,
+ **list_kwargs,
)
file_infos = [
WorkspaceFileInfoData(
@@ -397,20 +453,47 @@ class ListWorkspaceFilesTool(BaseTool):
)
for f in files
]
+ folder_infos = [
+ WorkspaceFolderInfoData(
+ folder_id=f.id,
+ name=f.name,
+ parent_id=f.parent_id,
+ file_count=f.file_count,
+ )
+ for f in folders
+ if f.parent_id == folder_id
+ ]
scope = "all sessions" if include_all_sessions else "current session"
+ names = {f.id: f.name for f in folders}
+ where = (
+ f"folder {names.get(folder_id, folder_id)}"
+ if folder_id
+ else f"workspace ({scope})"
+ )
total_size = sum(f.size_bytes for f in file_infos)
# Build a human-readable summary so the agent can relay details.
- lines = [f"Found {len(files)} file(s) in workspace ({scope}):"]
+ lines = [f"Found {len(files)} file(s) in {where}:"]
for f in file_infos:
lines.append(f" - {f.path} ({f.size_bytes:,} bytes, {f.mime_type})")
if total > len(files):
lines.append(f" ... and {total - len(files)} more")
+ for d in folder_infos:
+ lines.append(
+ f" [folder] {d.name} ({d.file_count} file(s)), "
+ f"folder_id={d.folder_id}"
+ )
+ if unsearched:
+ lines.append(
+ f" ... and {unsearched} subfolder(s) not searched; "
+ "list them with folder_id."
+ )
lines.append(f"Total size: {total_size:,} bytes")
return WorkspaceFileListResponse(
files=file_infos,
total_count=total,
+ folders=folder_infos,
message="\n".join(lines),
session_id=session_id,
)
@@ -427,6 +510,45 @@ class ListWorkspaceFilesTool(BaseTool):
)
+# A recursive listing walks at most this many folders. Deep trees are the
+# user's own making, and an unbounded ``IN`` grows with every folder they add.
+_MAX_RECURSIVE_FOLDERS = 200
+
+
+def _folder_subtree(
+ folders: list[WorkspaceFolder], folder_id: str
+) -> tuple[list[str], int]:
+ """*folder_id* plus its descendants, capped, and how many were left out.
+
+ Nearest first, so a cap truncates the deepest folders rather than an
+ arbitrary set, and the caller can name the remainder for the model to
+ list directly. Deliberately not shared with ``workspace_folder._subtree_ids``:
+ that one walks DB rows and must not cap, since it drives a delete.
+ """
+ children: dict[str | None, list[str]] = {}
+ for folder in folders:
+ children.setdefault(folder.parent_id, []).append(folder.id)
+
+ subtree = [folder_id]
+ seen = {folder_id}
+ queue = deque([folder_id])
+ overflow = 0
+ while queue:
+ for child in children.get(queue.popleft(), []):
+ if child in seen:
+ continue
+ seen.add(child)
+ queue.append(child)
+ # Past the cap the walk keeps going but stops collecting, so the
+ # count the caller reports is every folder left out, not just the
+ # first one over the line.
+ if len(subtree) >= _MAX_RECURSIVE_FOLDERS:
+ overflow += 1
+ else:
+ subtree.append(child)
+ return subtree, overflow
+
+
class ReadWorkspaceFileTool(BaseTool):
"""Tool for reading file content from workspace."""
@@ -444,9 +566,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 (expert chats can read their own "
- "conversations and ones they delegated)."
+ "Paths resolve in the current session; use /sessions/<id>/... or "
+ "file_id to reach elsewhere. An expert chat reads its own "
+ "conversations, ones it delegated, and the user's files."
)
@property
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
index 65852b8de4..9665148596 100644
--- a/autogpt_platform/backend/backend/copilot/tools/workspace_files_isolation_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/workspace_files_isolation_test.py
@@ -32,8 +32,14 @@ def db():
db.count_workspace_files = AsyncMock(return_value=0)
db.soft_delete_workspace_file = AsyncMock()
manager = WorkspaceManager("user-1", "ws-1", "expert-a", scope=SCOPE)
+ folders = MagicMock()
+ folders.list_workspace_folders = AsyncMock(return_value=[])
with (
patch("backend.util.workspace.workspace_db", return_value=db),
+ patch(
+ "backend.util.workspace.workspace_folder_db",
+ return_value=folders,
+ ),
patch(
"backend.copilot.tools.workspace_files.get_workspace_manager",
new=AsyncMock(return_value=manager),
@@ -95,3 +101,72 @@ async def test_delete_by_foreign_file_id_is_denied(db):
assert isinstance(result, ErrorResponse)
assert result.error == "access_denied"
db.soft_delete_workspace_file.assert_not_awaited()
+
+
+# The grant a live hired expert resolves to: its own conversations plus read
+# access to the owner's own files.
+USER_FILES_SCOPE = WorkspaceScope(
+ expert_id="expert-a", session_ids=["expert-a"], reads_user_files=True
+)
+
+
+def _storage():
+ storage = AsyncMock()
+ storage.retrieve.return_value = b"allowed"
+ return storage
+
+
+def user_files_db():
+ db = MagicMock()
+ db.get_workspace_file = AsyncMock(
+ return_value=_make_workspace_file(path="/quarterly-report.pdf")
+ )
+ db.list_workspace_files = AsyncMock(return_value=[])
+ db.count_workspace_files = AsyncMock(return_value=0)
+ manager = WorkspaceManager("user-1", "ws-1", "expert-a", scope=USER_FILES_SCOPE)
+ folders = MagicMock()
+ folders.list_workspace_folders = AsyncMock(return_value=[])
+ with (
+ patch("backend.util.workspace.workspace_db", return_value=db),
+ patch(
+ "backend.util.workspace.workspace_folder_db",
+ return_value=folders,
+ ),
+ patch(
+ "backend.copilot.tools.workspace_files.get_workspace_manager",
+ new=AsyncMock(return_value=manager),
+ ),
+ patch(
+ "backend.util.workspace.get_workspace_storage",
+ new=AsyncMock(return_value=_storage()),
+ ),
+ ):
+ yield db
+
+
+async def test_expert_reads_a_root_upload_by_id(user_files_db):
+ result = await ReadWorkspaceFileTool()._execute(
+ "user-1", _session(), file_id="root-upload"
+ )
+ assert not isinstance(result, ErrorResponse)
+
+
+async def test_expert_still_cannot_read_another_experts_file(user_files_db):
+ user_files_db.get_workspace_file = AsyncMock(
+ return_value=_make_workspace_file(path="/sessions/expert-b/private.txt")
+ )
+ result = await ReadWorkspaceFileTool()._execute(
+ "user-1", _session(), file_id="foreign"
+ )
+ assert isinstance(result, ErrorResponse)
+ assert result.error == "access_denied"
+
+
+async def test_expert_listing_widens_to_user_files(user_files_db):
+ await ListWorkspaceFilesTool()._execute(
+ "user-1", _session(), include_all_sessions=True
+ )
+ kwargs = user_files_db.list_workspace_files.call_args.kwargs
+ assert kwargs["include_user_files"] is True
+ assert kwargs["allowed_path_prefixes"] == USER_FILES_SCOPE.read_prefixes
diff --git a/autogpt_platform/backend/backend/copilot/tools/workspace_folders_tool_test.py b/autogpt_platform/backend/backend/copilot/tools/workspace_folders_tool_test.py
new file mode 100644
index 0000000000..c473a3e16e
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/workspace_folders_tool_test.py
@@ -0,0 +1,176 @@
+"""``list_workspace_files`` reports the folders beside the files.
+
+Without them a chat can only reach what it already knows the id of: the
+listing defaults to the current conversation, and the user's uploads live at
+the workspace root or in a folder.
+"""
+
+from datetime import datetime, timezone
+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 (
+ _MAX_RECURSIVE_FOLDERS,
+ ListWorkspaceFilesTool,
+ WorkspaceFileListResponse,
+ _folder_subtree,
+)
+from backend.data.workspace_folder import WorkspaceFolder
+from backend.data.workspace_scope import WorkspaceScope
+from backend.util.workspace import WorkspaceManager
+
+NOW = datetime(2026, 9, 22, tzinfo=timezone.utc)
+
+
+def _folder(folder_id: str, name: str, parent_id: str | None = None, files: int = 0):
+ return WorkspaceFolder(
+ id=folder_id,
+ workspace_id="ws-1",
+ name=name,
+ parent_id=parent_id,
+ created_at=NOW,
+ updated_at=NOW,
+ file_count=files,
+ )
+
+
+TREE = [
+ _folder("invoices", "Invoices", files=2),
+ _folder("2026", "2026", parent_id="invoices", files=5),
+ _folder("q1", "Q1", parent_id="2026", files=7),
+ _folder("photos", "Photos", files=1),
+]
+
+
+def db():
+ db = MagicMock()
+ db.list_workspace_files = AsyncMock(return_value=[])
+ db.count_workspace_files = AsyncMock(return_value=0)
+ folders = MagicMock()
+ folders.list_workspace_folders = AsyncMock(return_value=TREE)
+ manager = WorkspaceManager("user-1", "ws-1", "sess-1")
+ with (
+ patch("backend.util.workspace.workspace_db", return_value=db),
+ patch(
+ "backend.util.workspace.workspace_folder_db",
+ return_value=folders,
+ ),
+ 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)
+ session.session_id = "sess-1"
+ return session
+
+
+async def _list(db, **kwargs) -> WorkspaceFileListResponse:
+ result = await ListWorkspaceFilesTool()._execute("user-1", _session(), **kwargs)
+ assert isinstance(result, WorkspaceFileListResponse)
+ return result
+
+
+async def test_a_bare_listing_reports_the_root_folders(db):
+ result = await _list(db)
+
+ assert [f.folder_id for f in result.folders] == ["invoices", "photos"]
+ assert [f.file_count for f in result.folders] == [2, 1]
+ assert "[folder] Invoices (2 file(s)), folder_id=invoices" in result.message
+
+
+async def test_folder_id_lists_that_folder_and_its_child_folders(db):
+ result = await _list(db, folder_id="invoices")
+
+ assert [f.folder_id for f in result.folders] == ["2026"]
+ assert "in folder Invoices:" in result.message
+ assert db.list_workspace_files.call_args.kwargs["folder_id"] == "invoices"
+ assert db.count_workspace_files.call_args.kwargs["folder_id"] == "invoices"
+
+
+async def test_recursive_spans_the_whole_subtree(db):
+ result = await _list(db, folder_id="invoices", recursive=True)
+
+ assert sorted(db.list_workspace_files.call_args.kwargs["folder_ids"]) == [
+ "2026",
+ "invoices",
+ "q1",
+ ]
+ # The count uses the same axis, so "... and N more" cannot outrun the page.
+ assert sorted(db.count_workspace_files.call_args.kwargs["folder_ids"]) == [
+ "2026",
+ "invoices",
+ "q1",
+ ]
+ assert [f.folder_id for f in result.folders] == ["2026"]
+
+
+async def test_an_empty_folder_id_is_refused_rather_than_listing_everything(db):
+ """An empty string is not "no folder": the manager reads it as present and
+ drops the current-session filter, then the query reads it as false and drops
+ the folder filter, so the model would get the whole workspace."""
+ result = await ListWorkspaceFilesTool()._execute("user-1", _session(), folder_id="")
+
+ assert isinstance(result, ErrorResponse)
+ db.list_workspace_files.assert_not_awaited()
+
+
+async def test_recursive_is_ignored_without_a_folder(db):
+ await _list(db, recursive=True)
+ assert db.list_workspace_files.call_args.kwargs["folder_id"] is None
+
+
+def test_the_subtree_walk_is_bounded_and_says_what_it_left_out():
+ chain = [_folder("f0", "f0")] + [
+ _folder(f"f{i}", f"f{i}", parent_id=f"f{i - 1}")
+ for i in range(1, _MAX_RECURSIVE_FOLDERS + 10)
+ ]
+ subtree, unsearched = _folder_subtree(chain, "f0")
+
+ assert len(subtree) == _MAX_RECURSIVE_FOLDERS
+ assert unsearched == len(chain) - _MAX_RECURSIVE_FOLDERS == 10
+ # Nearest first, so what is dropped is the deepest rather than an
+ # arbitrary set the caller cannot name.
+ assert subtree[:3] == ["f0", "f1", "f2"]
+
+
+def test_the_subtree_walk_terminates_on_a_cycle():
+ """The move endpoint refuses one, but data predating it must not hang."""
+ looped = [
+ _folder("a", "a", parent_id="b"),
+ _folder("b", "b", parent_id="a"),
+ ]
+ subtree, unsearched = _folder_subtree(looped, "a")
+
+ assert sorted(subtree) == ["a", "b"]
+ assert unsearched == 0
+
+
+ "scope, sees_folders",
+ [
+ (WorkspaceScope(expert_id="exp-1", session_ids=["sess-1"]), False),
+ (WorkspaceScope(expert_id="exp-1", reads_user_files=True), True),
+ (None, True),
+ ],
+)
+async def test_folders_are_listed_only_for_a_scope_that_reads_user_files(
+ db, scope, sees_folders
+):
+ manager = WorkspaceManager("user-1", "ws-1", "sess-1", scope=scope)
+ with patch(
+ "backend.copilot.tools.workspace_files.get_workspace_manager",
+ new=AsyncMock(return_value=manager),
+ ):
+ result = await _list(db)
+
+ assert bool(result.folders) is sees_folders
+ assert ("[folder]" in result.message) is sees_folders
diff --git a/autogpt_platform/backend/backend/data/db_accessors.py b/autogpt_platform/backend/backend/data/db_accessors.py
index c71578eb5d..4f6d7580e0 100644
--- a/autogpt_platform/backend/backend/data/db_accessors.py
+++ b/autogpt_platform/backend/backend/data/db_accessors.py
@@ -157,6 +157,19 @@ def workspace_db():
return workspace_db
+def workspace_folder_db():
+ if db.is_connected():
+ from backend.data import workspace_folder as _workspace_folder_db
+
+ workspace_folder_db = _workspace_folder_db
+ else:
+ from backend.util.clients import get_database_manager_async_client
+
+ workspace_folder_db = get_database_manager_async_client()
+
+ return workspace_folder_db
+
+
def workspace_skill_db():
if db.is_connected():
from backend.data import workspace_skill
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index 9fb18e53b9..82de3ffe69 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -189,6 +189,7 @@ from backend.data.workspace import (
resolve_expert_workspace_scope,
soft_delete_workspace_file,
)
+from backend.data.workspace_folder import list_workspace_folders
from backend.data.workspace_skill import publish_workspace_skill_file
from backend.platform_linking import db as platform_linking_db
from backend.util.service import (
@@ -453,6 +454,7 @@ class DatabaseManager(AppService):
get_workspace_file_by_path = _(get_workspace_file_by_path)
get_workspace_total_size = _(get_workspace_total_size)
list_workspace_files = _(list_workspace_files)
+ list_workspace_folders = _(list_workspace_folders)
soft_delete_workspace_file = _(soft_delete_workspace_file)
resolve_expert_workspace_scope = _(resolve_expert_workspace_scope)
@@ -872,6 +874,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
get_workspace_file_by_path = d.get_workspace_file_by_path
get_workspace_total_size = d.get_workspace_total_size
list_workspace_files = d.list_workspace_files
+ list_workspace_folders = d.list_workspace_folders
soft_delete_workspace_file = d.soft_delete_workspace_file
resolve_expert_workspace_scope = d.resolve_expert_workspace_scope
diff --git a/autogpt_platform/backend/backend/data/workspace.py b/autogpt_platform/backend/backend/data/workspace.py
index 9d9355c102..d75fb7d4bb 100644
--- a/autogpt_platform/backend/backend/data/workspace.py
+++ b/autogpt_platform/backend/backend/data/workspace.py
@@ -8,7 +8,7 @@ import logging
import posixpath
import re
from datetime import datetime, timezone
-from typing import Optional
+from typing import TYPE_CHECKING, Optional
import pydantic
from prisma.errors import UniqueViolationError
@@ -17,11 +17,16 @@ from prisma.types import UserWorkspaceFileWhereInput
from backend.data.skill_capacity import skill_owner_folder
from backend.data.workspace_scope import (
+ SHARED_ROOTS,
WorkspaceAccessDeniedError,
resolve_expert_workspace_scope,
)
from backend.util.json import SafeJson
+if TYPE_CHECKING:
+ # Imported for typing only: workspace_folder imports this module.
+ from backend.data.workspace_folder import WorkspaceFolder
+
_UUID_RE = re.compile(
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", re.I
)
@@ -267,8 +272,10 @@ async def list_workspace_files(
metadata_equals: Optional[dict] = None,
metadata_not_equals: Optional[dict] = None,
folder_id: Optional[str] = None,
+ folder_ids: Optional[list[str]] = None,
root_only: bool = False,
allowed_path_prefixes: Optional[list[str]] = None,
+ include_user_files: bool = False,
) -> list[WorkspaceFile]:
"""
List files in a workspace.
@@ -293,17 +300,24 @@ async def list_workspace_files(
is never SQL NULL (column default ``{}``), so whole-object
inequality is null-safe and covers untagged/legacy files.
folder_id: If set, only return files in this folder.
+ folder_ids: If set, only return files in any of these folders — a
+ folder and its descendants, for a recursive listing. An empty
+ list matches nothing. Ignored when ``folder_id`` is set.
root_only: If True, only return root-level files (folderId IS NULL).
- Ignored when ``folder_id`` is set.
+ Ignored when either folder filter 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.
+ include_user_files: Widen ``allowed_path_prefixes`` with the owner's
+ own files (see :func:`_scope_branches`). Ignored when the caller
+ passes no prefixes, which already reaches the whole workspace.
Returns:
List of WorkspaceFile instances
"""
- if allowed_path_prefixes is not None and not allowed_path_prefixes:
+ scope_branches = _scope_branches(allowed_path_prefixes, include_user_files)
+ if scope_branches is not None and not scope_branches:
return []
where_clause: UserWorkspaceFileWhereInput = {"workspaceId": workspace_id}
@@ -312,6 +326,10 @@ async def list_workspace_files(
if folder_id:
where_clause["folderId"] = folder_id
+ elif folder_ids is not None:
+ if not folder_ids:
+ return []
+ where_clause["folderId"] = {"in": folder_ids}
elif root_only:
where_clause["folderId"] = None
@@ -339,8 +357,8 @@ 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)}]
+ if scope_branches:
+ where_clause["AND"] = [{"OR": scope_branches}]
files = await UserWorkspaceFile.prisma().find_many(
where=where_clause,
@@ -351,17 +369,40 @@ 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]
+def _scope_branches(
+ allowed_path_prefixes: Optional[list[str]],
+ include_user_files: bool,
+) -> Optional[list[UserWorkspaceFileWhereInput]]:
+ """The OR-branches a scoped listing may match, or None when unscoped.
+
+ Nested under ``AND`` by the callers so the scope filter can never replace
+ another ``OR`` branch added later; scope prefixes are always rooted. An
+ empty list means the scope reaches nothing, which callers answer with an
+ empty result rather than an unfiltered query.
+ """
+ if allowed_path_prefixes is None:
+ return None
+ branches: list[UserWorkspaceFileWhereInput] = [
+ {"path": {"startswith": prefix}} for prefix in allowed_path_prefixes
+ ]
+ if include_user_files:
+ # The owner's own uploads: every path outside the managed roots, which
+ # is the SQL form of ``workspace_scope.is_user_file_path``.
+ branches.append(
+ {"NOT": [{"path": {"startswith": root}} for root in SHARED_ROOTS]}
+ )
+ return branches
async def count_workspace_files(
workspace_id: str,
path_prefix: Optional[str] = None,
include_deleted: bool = False,
+ folder_id: Optional[str] = None,
+ folder_ids: Optional[list[str]] = None,
+ root_only: bool = False,
allowed_path_prefixes: Optional[list[str]] = None,
+ include_user_files: bool = False,
) -> int:
"""
Count files in a workspace.
@@ -370,25 +411,39 @@ 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
+ folder_id: See :func:`list_workspace_files`.
+ folder_ids: See :func:`list_workspace_files`.
+ root_only: See :func:`list_workspace_files`.
allowed_path_prefixes: See :func:`list_workspace_files`.
+ include_user_files: See :func:`list_workspace_files`.
Returns:
Number of files
"""
- if allowed_path_prefixes is not None and not allowed_path_prefixes:
+ scope_branches = _scope_branches(allowed_path_prefixes, include_user_files)
+ if scope_branches is not None and not scope_branches:
return 0
where_clause: UserWorkspaceFileWhereInput = {"workspaceId": workspace_id}
if not include_deleted:
where_clause["isDeleted"] = False
+ if folder_id:
+ where_clause["folderId"] = folder_id
+ elif folder_ids is not None:
+ if not folder_ids:
+ return 0
+ where_clause["folderId"] = {"in": folder_ids}
+ elif root_only:
+ where_clause["folderId"] = None
+
if path_prefix:
# Normalize prefix
if not path_prefix.startswith("/"):
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)}]
+ if scope_branches:
+ where_clause["AND"] = [{"OR": scope_branches}]
return await UserWorkspaceFile.prisma().count(where=where_clause)
@@ -434,8 +489,9 @@ async def soft_delete_workspace_file(
"""
Soft-delete a workspace file.
- The path is modified to include a deletion timestamp to free up the original
- path for new files while preserving the record for potential recovery.
+ The row keeps the path it was deleted at: the unique index over
+ ``(workspaceId, path)`` covers live rows only, so the path is free for the
+ next write and the record still says where the file was.
Args:
file_id: The file ID
@@ -449,17 +505,11 @@ async def soft_delete_workspace_file(
if file is None:
return None
- deleted_at = datetime.now(timezone.utc)
- # Frees the path for the next write, to microseconds: `write_file` soft-deletes
- # the row it overwrites, so two writes in one second would collide here.
- deleted_path = f"{file.path}__deleted__{deleted_at.timestamp():.6f}"
-
updated = await UserWorkspaceFile.prisma().update(
where={"id": file_id},
data={
"isDeleted": True,
- "deletedAt": deleted_at,
- "path": deleted_path,
+ "deletedAt": datetime.now(timezone.utc),
},
)
@@ -500,10 +550,11 @@ async def resolve_attachable_workspace_files(
"""Resolve attachment IDs for a message sent in ``session_id``.
Personal Otto 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.
+ Expert sessions are confined to the expert's resolved scope — their own
+ conversations plus the owner's own files — so only another expert's
+ conversation file is refused, with a ``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()``.
@@ -516,29 +567,44 @@ async def resolve_attachable_workspace_files(
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."
+ "These files belong to another expert's conversations and cannot "
+ f"be attached here: {', '.join(denied)}."
)
return files
-def build_files_block(files: list[UserWorkspaceFile]) -> str:
+def build_files_block(
+ files: list[UserWorkspaceFile],
+ folders: Optional[list["WorkspaceFolder"]] = None,
+) -> str:
"""Return a formatted ``[Attached files]`` block for injection into a message.
- Returns an empty string when *files* is empty so callers can do a simple
+ An attached folder is named rather than expanded: the model opens it with
+ ``list_workspace_files``, so attaching one costs a line whatever it holds.
+
+ Returns an empty string when nothing is attached so callers can do a simple
``message += build_files_block(files)`` without an extra ``if`` check.
"""
- if not files:
+ if not files and not folders:
return ""
lines = [
f"- {f.name} ({f.mimeType}, {round(f.sizeBytes / 1024, 1)} KB), file_id={f.id}"
for f in files
]
- return (
- "\n\n[Attached files]\n"
- + "\n".join(lines)
- + "\nUse read_workspace_file with the file_id to access file contents."
- )
+ lines += [
+ f"- {d.name} (folder, {d.file_count} file(s) directly inside), folder_id={d.id}"
+ for d in folders or []
+ ]
+ hints = []
+ if files:
+ hints.append(
+ "Use read_workspace_file with the file_id to access file contents."
+ )
+ if folders:
+ hints.append(
+ "Use list_workspace_files with the folder_id to see what is in a folder."
+ )
+ return "\n\n[Attached files]\n" + "\n".join(lines) + "\n" + "\n".join(hints)
async def get_workspace_total_size(workspace_id: str) -> int:
diff --git a/autogpt_platform/backend/backend/data/workspace_attachments_test.py b/autogpt_platform/backend/backend/data/workspace_attachments_test.py
new file mode 100644
index 0000000000..f885e8455d
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/workspace_attachments_test.py
@@ -0,0 +1,116 @@
+"""What an expert chat may attach to a message, and how it is announced.
+
+An expert session is confined to its own conversations, so before this it
+could not attach a file the user uploaded on the Files page at all. It can
+now, and a folder can be attached whole: the message names it and the model
+opens it with ``list_workspace_files``.
+"""
+
+import pytest
+
+from backend.data import workspace
+from backend.data.workspace import build_files_block, resolve_attachable_workspace_files
+from backend.data.workspace_folder import WorkspaceFolder
+from backend.data.workspace_scope import WorkspaceAccessDeniedError, WorkspaceScope
+from backend.util.workspace_test import _make_workspace_file
+
+EXPERT_SCOPE = WorkspaceScope(
+ expert_id="expert-a", session_ids=["expert-a"], reads_user_files=True
+)
+
+
+class _Row:
+ """A prisma ``UserWorkspaceFile`` as the attachment resolver reads it."""
+
+ def __init__(self, file_id: str, name: str, path: str):
+ self.id = file_id
+ self.name = name
+ self.path = path
+ self.mimeType = "application/pdf"
+ self.sizeBytes = 2048
+
+
+def _resolver(mocker, rows: list[_Row]):
+ mocker.patch.object(
+ workspace, "resolve_workspace_files", mocker.AsyncMock(return_value=rows)
+ )
+ mocker.patch.object(
+ workspace,
+ "resolve_expert_workspace_scope",
+ mocker.AsyncMock(return_value=EXPERT_SCOPE),
+ )
+
+
+async def test_an_expert_may_attach_the_users_own_file(mocker):
+ rows = [_Row("f1", "quarterly-report.pdf", "/quarterly-report.pdf")]
+ _resolver(mocker, rows)
+
+ resolved = await resolve_attachable_workspace_files(
+ "user-1", ["f1"], session_id="expert-a", expert_id="expert-a"
+ )
+
+ assert [r.id for r in resolved] == ["f1"]
+
+
+async def test_another_experts_conversation_file_is_still_refused(mocker):
+ rows = [_Row("f2", "secret.pdf", "/sessions/expert-b/secret.pdf")]
+ _resolver(mocker, rows)
+
+ with pytest.raises(WorkspaceAccessDeniedError) as exc_info:
+ await resolve_attachable_workspace_files(
+ "user-1", ["f2"], session_id="expert-a", expert_id="expert-a"
+ )
+
+ assert "secret.pdf" in str(exc_info.value)
+
+
+async def test_a_revoked_expert_cannot_attach_a_user_file(mocker):
+ """``resolve_expert_workspace_scope`` fails closed for an archived or
+ foreign expert, and the user-files grant is carried, never inferred."""
+ rows = [_Row("f1", "quarterly-report.pdf", "/quarterly-report.pdf")]
+ _resolver(mocker, rows)
+ mocker.patch.object(
+ workspace,
+ "resolve_expert_workspace_scope",
+ mocker.AsyncMock(return_value=WorkspaceScope(expert_id="expert-a")),
+ )
+
+ with pytest.raises(WorkspaceAccessDeniedError):
+ await resolve_attachable_workspace_files(
+ "user-1", ["f1"], session_id="other", expert_id="expert-a"
+ )
+
+
+def _folder(name: str = "Invoices", file_count: int = 4) -> WorkspaceFolder:
+ return WorkspaceFolder(
+ id="fld-1",
+ workspace_id="ws-1",
+ name=name,
+ created_at=_make_workspace_file().created_at,
+ updated_at=_make_workspace_file().updated_at,
+ file_count=file_count,
+ )
+
+
+def test_an_attached_folder_is_named_rather_than_expanded():
+ block = build_files_block([], [_folder()])
+
+ assert "Invoices (folder, 4 file(s) directly inside), folder_id=fld-1" in block
+ assert "list_workspace_files with the folder_id" in block
+ # No per-file lines: attaching a folder costs one line whatever it holds.
+ assert "read_workspace_file" not in block
+
+
+def test_files_and_folders_share_one_block():
+ row = _Row("f1", "report.pdf", "/report.pdf")
+ block = build_files_block([row], [_folder()]) # type: ignore[list-item]
+
+ assert block.count("[Attached files]") == 1
+ assert "file_id=f1" in block
+ assert "folder_id=fld-1" in block
+ assert "read_workspace_file" in block
+
+
+def test_nothing_attached_is_an_empty_block():
+ assert build_files_block([], []) == ""
+ assert build_files_block([], None) == ""
diff --git a/autogpt_platform/backend/backend/data/workspace_folder.py b/autogpt_platform/backend/backend/data/workspace_folder.py
index 6b0570a395..fd35c24b32 100644
--- a/autogpt_platform/backend/backend/data/workspace_folder.py
+++ b/autogpt_platform/backend/backend/data/workspace_folder.py
@@ -3,7 +3,8 @@ Database CRUD operations for User Workspace Folders.
Folders are a purely DB-level organizational layer on top of workspace files —
storage paths are unaffected. A file's membership is tracked by its ``folderId``
-(null = root). Mirrors the Library folder implementation.
+(null = root) and a folder's by its ``parentId`` (null = root), so folders nest.
+Mirrors the Library folder implementation.
"""
import logging
@@ -11,17 +12,30 @@ from datetime import datetime
from typing import Optional
import pydantic
+from prisma import Prisma
from prisma.errors import UniqueViolationError
from prisma.models import UserWorkspaceFile, UserWorkspaceFolder
-from backend.api.features.library.exceptions import FolderAlreadyExistsError
+from backend.api.features.library.exceptions import (
+ FolderAlreadyExistsError,
+ FolderValidationError,
+)
from backend.data.db import transaction
-from backend.data.workspace import WorkspaceFile
+from backend.data.workspace import WorkspaceFile, get_or_create_workspace
+from backend.data.workspace_scope import resolve_expert_workspace_scope
from backend.util.exceptions import NotFoundError
logger = logging.getLogger(__name__)
+class _Unchanged:
+ """``parent_id`` absent from a PATCH: leave the folder where it is."""
+
+
+UNCHANGED = _Unchanged()
+ParentChange = Optional[str] | _Unchanged
+
+
class WorkspaceFolder(pydantic.BaseModel):
"""Pydantic model for UserWorkspaceFolder, safe for RPC transport."""
@@ -29,8 +43,10 @@ class WorkspaceFolder(pydantic.BaseModel):
workspace_id: str
name: str
icon: Optional[str] = None
+ parent_id: Optional[str] = None
created_at: datetime
updated_at: datetime
+ # Files directly in this folder; a subfolder's files are counted on it.
file_count: int = 0
@staticmethod
@@ -42,6 +58,7 @@ class WorkspaceFolder(pydantic.BaseModel):
workspace_id=folder.workspaceId,
name=folder.name,
icon=folder.icon,
+ parent_id=folder.parentId,
created_at=folder.createdAt,
updated_at=folder.updatedAt,
file_count=file_count,
@@ -100,8 +117,14 @@ async def _get_folder_record(
return folder
-async def list_folders(workspace_id: str) -> list[WorkspaceFolder]:
- """List non-deleted folders for a workspace (flat; v1 has no nesting)."""
+async def list_workspace_folders(workspace_id: str) -> list[WorkspaceFolder]:
+ """Every non-deleted folder in a workspace, flat.
+
+ Named for the workspace because the RPC surface the copilot tools reach is
+ one flat namespace that already carries the Library's ``list_folders``.
+ The tree is not materialised here: a caller builds it from ``parent_id``,
+ which costs one query however deep the nesting goes.
+ """
folders = await UserWorkspaceFolder.prisma().find_many(
where={"workspaceId": workspace_id, "isDeleted": False},
order={"name": "asc"},
@@ -117,22 +140,64 @@ async def get_folder(folder_id: str, workspace_id: str) -> WorkspaceFolder:
return WorkspaceFolder.from_db(folder, file_count=count)
-async def _root_name_taken(
+async def create_folder(
workspace_id: str,
name: str,
+ icon: Optional[str] = None,
+ parent_id: Optional[str] = None,
+) -> WorkspaceFolder:
+ """Create a folder, under *parent_id* or at the workspace root.
+
+ A parent outside this workspace, or already deleted, is a
+ :class:`NotFoundError` rather than a foreign-key error: ``parentId`` is
+ written directly and the FK only checks that the row exists.
+
+ Creating under a parent takes the workspace's hierarchy lock, because a
+ check against a live parent and an insert under it must not straddle a
+ delete of that parent's subtree.
+ """
+ create_data: dict = {
+ "name": name,
+ "Workspace": {"connect": {"id": workspace_id}},
+ }
+ if icon is not None:
+ create_data["icon"] = icon
+ if parent_id is not None:
+ create_data["Parent"] = {"connect": {"id": parent_id}}
+
+ async with transaction() as tx:
+ if parent_id is not None:
+ await _lock_workspace_hierarchy(tx, workspace_id)
+ await _get_folder_record(parent_id, workspace_id)
+ if await _name_taken(workspace_id, name, parent_id):
+ raise FolderAlreadyExistsError("A folder with this name already exists")
+
+ try:
+ folder = await UserWorkspaceFolder.prisma(tx).create(data=create_data)
+ except UniqueViolationError:
+ raise FolderAlreadyExistsError("A folder with this name already exists")
+
+ logger.info(f"Created workspace folder {folder.id} in workspace {workspace_id}")
+ return WorkspaceFolder.from_db(folder)
+
+
+async def _name_taken(
+ workspace_id: str,
+ name: str,
+ parent_id: Optional[str],
exclude_folder_id: Optional[str] = None,
) -> bool:
- """Whether a live root-level folder with this name already exists.
+ """Whether a live sibling under *parent_id* already carries this name.
- The DB unique constraint ``@@unique([workspaceId, parentId, name])`` does
- not prevent duplicates at root: v1 folders always have ``parentId = NULL``
- and Postgres treats NULLs as distinct, so the constraint never fires for
- root folders. Guard the v1 (root) case explicitly here.
+ The database enforces the same rule through two partial unique indexes —
+ one per level, because Postgres treats every NULL ``parentId`` as distinct
+ — so this check exists to answer 409 rather than a unique violation, and
+ the indexes are the race-safe backstop.
"""
where: dict = {
"workspaceId": workspace_id,
"name": name,
- "parentId": None,
+ "parentId": parent_id,
"isDeleted": False,
}
if exclude_folder_id is not None:
@@ -140,103 +205,221 @@ async def _root_name_taken(
return await UserWorkspaceFolder.prisma().find_first(where=where) is not None
-async def create_folder(
+async def update_folder(
+ folder_id: str,
workspace_id: str,
- name: str,
+ name: Optional[str] = None,
icon: Optional[str] = None,
) -> WorkspaceFolder:
- """Create a new root-level folder for the workspace."""
- if await _root_name_taken(workspace_id, name):
- raise FolderAlreadyExistsError("A folder with this name already exists")
-
- create_data: dict = {
- "name": name,
- "Workspace": {"connect": {"id": workspace_id}},
- }
- if icon is not None:
- create_data["icon"] = icon
+ """Rename a folder and/or change its icon, leaving it where it is."""
+ return await apply_folder_update(folder_id, workspace_id, name=name, icon=icon)
- try:
- folder = await UserWorkspaceFolder.prisma().create(data=create_data)
- except UniqueViolationError:
- raise FolderAlreadyExistsError("A folder with this name already exists")
- logger.info(f"Created workspace folder {folder.id} in workspace {workspace_id}")
- return WorkspaceFolder.from_db(folder)
+async def move_folder(
+ folder_id: str,
+ workspace_id: str,
+ parent_id: Optional[str],
+) -> WorkspaceFolder:
+ """Move a folder under *parent_id*, or to the workspace root when None."""
+ return await apply_folder_update(folder_id, workspace_id, parent_id=parent_id)
-async def update_folder(
+async def apply_folder_update(
folder_id: str,
workspace_id: str,
+ parent_id: ParentChange = UNCHANGED,
name: Optional[str] = None,
icon: Optional[str] = None,
) -> WorkspaceFolder:
- """Update a folder's name/icon."""
- # update() uses where={"id": ...} without workspaceId — verify ownership first.
- await _get_folder_record(folder_id, workspace_id)
+ """Move and/or rename a folder as a single write.
- if name is not None and await _root_name_taken(
- workspace_id, name, exclude_folder_id=folder_id
- ):
- raise FolderAlreadyExistsError("A folder with this name already exists")
+ One PATCH may do both, and half of it must not survive a refusal of the
+ other, so the destination check, the name check and the write share one
+ transaction and one statement. The name is checked against the folder's
+ destination rather than where it came from, since that is where it has to
+ be unique.
- update_data: dict = {}
- if name is not None:
- update_data["name"] = name
- if icon is not None:
- update_data["icon"] = icon
-
- if not update_data:
- return await get_folder(folder_id, workspace_id)
-
- # update_many (not update) so the write itself is guarded by isDeleted: a
- # folder soft-deleted concurrently after the ownership check above must not
- # be silently updated (and reported as a 200).
- try:
- updated_count = await UserWorkspaceFolder.prisma().update_many(
- where={"id": folder_id, "isDeleted": False},
- data=update_data,
- )
- except UniqueViolationError:
- raise FolderAlreadyExistsError("A folder with this name already exists")
+ A folder cannot move into its own subtree, which would detach it from the
+ root. A workspace's moves are serialized, because two of them checking at
+ once would each pass and then make the other's folder its parent.
- if updated_count == 0:
- raise NotFoundError(f"Folder #{folder_id} not found")
-
- # Re-read without an isDeleted filter so a delete racing in *after* a
- # successful update doesn't turn it into a spurious 404.
- refreshed = await UserWorkspaceFolder.prisma().find_first(
- where={"id": folder_id},
+ *parent_id* left at ``UNCHANGED`` keeps the folder where it is; ``None``
+ moves it to the workspace root.
+ """
+ moving = not isinstance(parent_id, _Unchanged)
+ async with transaction() as tx:
+ if moving or name is not None:
+ await _lock_workspace_hierarchy(tx, workspace_id)
+
+ folder = await _get_folder_record(folder_id, workspace_id)
+ destination = parent_id if moving else folder.parentId
+
+ if moving and destination is not None:
+ await _get_folder_record(destination, workspace_id)
+ if folder_id in await _ancestor_ids(workspace_id, destination):
+ raise FolderValidationError(
+ "A folder cannot be moved into itself or one of its subfolders"
+ )
+
+ if (moving or name is not None) and await _name_taken(
+ workspace_id, folder.name if name is None else name, destination, folder_id
+ ):
+ raise FolderAlreadyExistsError("A folder with this name already exists")
+
+ data: dict = {}
+ if moving:
+ data["parentId"] = destination
+ if name is not None:
+ data["name"] = name
+ if icon is not None:
+ data["icon"] = icon
+
+ if data:
+ # update_many (not update) so the write itself is guarded by
+ # isDeleted: a folder soft-deleted concurrently after the ownership
+ # check must not be updated and reported as a 200.
+ try:
+ updated_count = await UserWorkspaceFolder.prisma(tx).update_many(
+ where={"id": folder_id, "isDeleted": False},
+ data=data,
+ )
+ except UniqueViolationError:
+ raise FolderAlreadyExistsError("A folder with this name already exists")
+ if updated_count == 0:
+ raise NotFoundError(f"Folder #{folder_id} not found")
+
+ if data:
+ logger.info(f"Updated workspace folder {folder_id}: {sorted(data)}")
+ return await get_folder(folder_id, workspace_id)
+
+
+async def _lock_workspace_hierarchy(tx: Prisma, workspace_id: str) -> None:
+ """Hold the workspace's folder-hierarchy lock until the transaction ends.
+
+ Moves, parented creates and subtree deletes all check the tree and then
+ write it, so they serialize against each other or one can act on a shape
+ another has already changed.
+
+ execute_raw, not query_raw: pg_advisory_xact_lock returns void, which
+ Prisma cannot deserialize as a result column.
+ """
+ await tx.execute_raw(
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", workspace_id
)
- if refreshed is None:
- raise NotFoundError(f"Folder #{folder_id} not found")
- count = await _file_count(workspace_id, folder_id)
- return WorkspaceFolder.from_db(refreshed, file_count=count)
-async def delete_folder(folder_id: str, workspace_id: str) -> None:
+async def _ancestor_ids(workspace_id: str, folder_id: str) -> list[str]:
+ """*folder_id* and every live folder above it, nearest first.
+
+ Stops on a repeat so a cycle already in the data cannot hang the walk.
"""
- Soft-delete a folder and return its files to root.
+ by_id = {
+ f.id: f
+ for f in await UserWorkspaceFolder.prisma().find_many(
+ where={"workspaceId": workspace_id, "isDeleted": False},
+ )
+ }
+ chain: list[str] = []
+ seen: set[str] = set()
+ current: Optional[str] = folder_id
+ while current is not None and current in by_id and current not in seen:
+ seen.add(current)
+ chain.append(current)
+ current = by_id[current].parentId
+ return chain
- Files are reparented to root (``folderId = null``) in the same transaction
- so they remain visible and are never orphaned behind a hidden folder.
+
+async def delete_folder(folder_id: str, workspace_id: str) -> None:
"""
- await _get_folder_record(folder_id, workspace_id)
+ Soft-delete a folder and its subfolders, returning every file to root.
+ Files are reparented to root (``folderId = null``) rather than deleted —
+ the semantics the single-folder delete already had — so nothing is
+ orphaned behind a hidden folder, however deep it sat.
+
+ The subtree is resolved under the workspace's hierarchy lock, so a move or
+ a create cannot add a folder to it after the snapshot and leave that folder
+ live under a deleted parent, reachable from no root-anchored listing.
+ """
async with transaction() as tx:
+ await _lock_workspace_hierarchy(tx, workspace_id)
+ await _get_folder_record(folder_id, workspace_id)
+ doomed = await _subtree_ids(workspace_id, folder_id)
+
await UserWorkspaceFile.prisma(tx).update_many(
- where={"folderId": folder_id, "workspaceId": workspace_id},
+ where={"folderId": {"in": doomed}, "workspaceId": workspace_id},
data={"folderId": None},
)
# update_many with an isDeleted guard so a concurrent delete that slips
# past the ownership check above is a no-op rather than re-deleting a
# logically-deleted row (TOCTOU-safe, idempotent).
await UserWorkspaceFolder.prisma(tx).update_many(
- where={"id": folder_id, "isDeleted": False},
+ where={"id": {"in": doomed}, "isDeleted": False},
data={"isDeleted": True},
)
- logger.info(f"Soft-deleted workspace folder {folder_id}; files moved to root")
+ logger.info(
+ f"Soft-deleted workspace folder {folder_id} and {len(doomed) - 1} "
+ "subfolder(s); files moved to root"
+ )
+
+
+async def _subtree_ids(workspace_id: str, folder_id: str) -> list[str]:
+ """*folder_id* and every live folder beneath it.
+
+ One query plus a walk in Python: a user's folder list is small, and a
+ recursive CTE would mean raw SQL for no measurable gain. Uncapped, unlike
+ the model-facing ``workspace_files._folder_subtree``, because a delete has
+ to reach the whole subtree.
+ """
+ children: dict[Optional[str], list[str]] = {}
+ for f in await UserWorkspaceFolder.prisma().find_many(
+ where={"workspaceId": workspace_id, "isDeleted": False},
+ ):
+ children.setdefault(f.parentId, []).append(f.id)
+
+ subtree: list[str] = []
+ queue = [folder_id]
+ seen = {folder_id}
+ while queue:
+ current = queue.pop()
+ subtree.append(current)
+ for child in children.get(current, []):
+ if child not in seen:
+ seen.add(child)
+ queue.append(child)
+ return subtree
+
+
+async def resolve_attachable_workspace_folders(
+ user_id: str,
+ folder_ids: list[str],
+ *,
+ expert_id: str | None,
+) -> list[WorkspaceFolder]:
+ """Return the caller's own live folders among *folder_ids*.
+
+ Folders are user-level, so an expert session attaches one only if its
+ scope reads the owner's files; what it may read inside is still decided
+ per file. Unknown and cross-user IDs are silently dropped, as
+ ``resolve_workspace_files`` does.
+ """
+ if not folder_ids:
+ return []
+ if expert_id is not None:
+ scope = await resolve_expert_workspace_scope(user_id, expert_id)
+ if not scope.reads_user_files:
+ return []
+ workspace = await get_or_create_workspace(user_id)
+ folders = await UserWorkspaceFolder.prisma().find_many(
+ where={
+ "id": {"in": folder_ids},
+ "workspaceId": workspace.id,
+ "isDeleted": False,
+ },
+ )
+ counts = await _file_counts(workspace.id, [f.id for f in folders])
+ return [WorkspaceFolder.from_db(f, file_count=counts.get(f.id, 0)) for f in folders]
async def bulk_move_files_to_folder(
diff --git a/autogpt_platform/backend/backend/data/workspace_folder_db_test.py b/autogpt_platform/backend/backend/data/workspace_folder_db_test.py
new file mode 100644
index 0000000000..b281e91a5e
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/workspace_folder_db_test.py
@@ -0,0 +1,330 @@
+"""Real-database coverage for nested workspace folders.
+
+Folders are a DB-level layer over files: a file's ``folderId`` and a folder's
+``parentId`` decide the tree, and no storage path moves. These tests pin the
+three things a tree adds over a flat list — creating a child, deleting a
+subtree, and moving one without detaching it from the root.
+"""
+
+import asyncio
+import contextlib
+import uuid
+
+import pytest
+from prisma.errors import UniqueViolationError
+from prisma.models import UserWorkspace, UserWorkspaceFile, UserWorkspaceFolder
+
+from backend.api.features.library.exceptions import (
+ FolderAlreadyExistsError,
+ FolderValidationError,
+)
+from backend.data import workspace_folder
+from backend.data.user import get_or_create_user
+from backend.data.workspace import create_workspace_file, get_or_create_workspace
+from backend.data.workspace_folder import (
+ apply_folder_update,
+ bulk_move_files_to_folder,
+ create_folder,
+ delete_folder,
+ list_workspace_folders,
+ move_folder,
+ resolve_attachable_workspace_folders,
+)
+from backend.data.workspace_scope import WorkspaceScope
+from backend.util.exceptions import NotFoundError
+from backend.util.test import SpinTestServer
+
+
+async def _workspace() -> str:
+ suffix = uuid.uuid4().hex[:8]
+ user = await get_or_create_user(
+ {
+ "sub": str(uuid.uuid4()),
+ "email": f"folders-{suffix}@example.com",
+ "name": "Folder Owner",
+ }
+ )
+ workspace = await get_or_create_workspace(user.id)
+ return workspace.id
+
+
+async def _file(workspace_id: str, folder_id: str | None = None) -> str:
+ stored = await create_workspace_file(
+ workspace_id=workspace_id,
+ file_id=str(uuid.uuid4()),
+ name="doc.pdf",
+ path=f"/doc-{uuid.uuid4().hex[:8]}.pdf",
+ storage_path=f"{workspace_id}/doc.pdf",
+ mime_type="application/pdf",
+ size_bytes=3,
+ )
+ if folder_id:
+ await bulk_move_files_to_folder(workspace_id, [stored.id], folder_id)
+ return stored.id
+
+
+async def _folder_of(file_id: str) -> str | None:
+ row = await UserWorkspaceFile.prisma().find_unique(where={"id": file_id})
+ assert row is not None
+ return row.folderId
+
+
[email protected](loop_scope="session")
+async def test_a_child_folder_carries_its_parent(server: SpinTestServer):
+ workspace = await _workspace()
+ parent = await create_folder(workspace, "Invoices")
+ child = await create_folder(workspace, "2026", parent_id=parent.id)
+
+ assert child.parent_id == parent.id
+
+ listed = {f.id: f for f in await list_workspace_folders(workspace)}
+ assert listed[child.id].parent_id == parent.id
+ assert listed[parent.id].parent_id is None
+
+
[email protected](loop_scope="session")
+async def test_a_name_clash_is_scoped_to_the_parent(server: SpinTestServer):
+ """One name per level, not per workspace."""
+ workspace = await _workspace()
+ parent = await create_folder(workspace, "Invoices")
+ await create_folder(workspace, "2026", parent_id=parent.id)
+
+ with pytest.raises(FolderAlreadyExistsError):
+ await create_folder(workspace, "2026", parent_id=parent.id)
+
+ # The same name one level up is a different folder, and is allowed.
+ root_2026 = await create_folder(workspace, "2026")
+ assert root_2026.parent_id is None
+ with pytest.raises(FolderAlreadyExistsError):
+ await create_folder(workspace, "2026")
+
+
[email protected](loop_scope="session")
+async def test_the_database_refuses_a_duplicate_name_at_either_level(
+ server: SpinTestServer,
+):
+ """The partial unique indexes, reached past the app-level check: they are
+ what makes two concurrent creates safe."""
+ workspace = await _workspace()
+ parent = await create_folder(workspace, "Invoices")
+
+ for parent_id in (None, parent.id):
+ data: dict = {"name": "Duplicate", "Workspace": {"connect": {"id": workspace}}}
+ if parent_id is not None:
+ data["Parent"] = {"connect": {"id": parent_id}}
+ await UserWorkspaceFolder.prisma().create(data=data)
+ with pytest.raises(UniqueViolationError):
+ await UserWorkspaceFolder.prisma().create(data=data)
+
+
[email protected](loop_scope="session")
+async def test_deleting_a_folder_frees_its_name_at_either_level(
+ server: SpinTestServer,
+):
+ """Needs this branch's migration: before it, only the ROOT index excluded
+ soft-deleted rows, so re-creating a deleted child answered 409 forever."""
+ workspace = await _workspace()
+ parent = await create_folder(workspace, "Invoices")
+
+ for parent_id in (None, parent.id):
+ first = await create_folder(workspace, "2026", parent_id=parent_id)
+ await delete_folder(first.id, workspace)
+ again = await create_folder(workspace, "2026", parent_id=parent_id)
+ assert again.id != first.id
+
+
[email protected](loop_scope="session")
+async def test_deleting_a_folder_takes_its_subtree_and_frees_the_files(
+ server: SpinTestServer,
+):
+ workspace = await _workspace()
+ parent = await create_folder(workspace, "Invoices")
+ child = await create_folder(workspace, "2026", parent_id=parent.id)
+ grandchild = await create_folder(workspace, "Q1", parent_id=child.id)
+ sibling = await create_folder(workspace, "Photos")
+
+ deep_file = await _file(workspace, grandchild.id)
+ sibling_file = await _file(workspace, sibling.id)
+
+ await delete_folder(parent.id, workspace)
+
+ remaining = {f.id for f in await list_workspace_folders(workspace)}
+ assert remaining == {sibling.id}
+ # A grandchild left behind would keep its file hidden under a folder no
+ # listing returns; the file goes back to the root instead.
+ assert await _folder_of(deep_file) is None
+ assert await _folder_of(sibling_file) == sibling.id
+
+
[email protected](loop_scope="session")
+async def test_moving_a_folder_into_its_own_subtree_is_refused(
+ server: SpinTestServer,
+):
+ workspace = await _workspace()
+ parent = await create_folder(workspace, "Invoices")
+ child = await create_folder(workspace, "2026", parent_id=parent.id)
+ grandchild = await create_folder(workspace, "Q1", parent_id=child.id)
+
+ for destination in (grandchild.id, child.id, parent.id):
+ with pytest.raises(FolderValidationError):
+ await move_folder(parent.id, workspace, destination)
+
+ listed = {f.id: f.parent_id for f in await list_workspace_folders(workspace)}
+ assert listed[parent.id] is None
+
+
[email protected](loop_scope="session")
+async def test_moving_a_folder_under_a_parent_and_back_to_the_root(
+ server: SpinTestServer,
+):
+ workspace = await _workspace()
+ parent = await create_folder(workspace, "Invoices")
+ loose = await create_folder(workspace, "Receipts")
+
+ moved = await move_folder(loose.id, workspace, parent.id)
+ assert moved.parent_id == parent.id
+
+ back = await move_folder(loose.id, workspace, None)
+ assert back.parent_id is None
+
+
[email protected](loop_scope="session")
+async def test_two_moves_racing_into_each_other_cannot_build_a_cycle(
+ server: SpinTestServer, mocker
+):
+ """Each mover reads the ancestor chain before either writes, so without the
+ workspace move lock both pass their check and become each other's parent —
+ a subtree no root-anchored listing can reach.
+
+ Concurrency alone does not produce that interleaving, so the first mover is
+ held inside its check until the second reaches one too. Under the lock the
+ second never gets there, the wait times out, and the moves run in sequence,
+ which is the whole point.
+ """
+ workspace = await _workspace()
+ a = await create_folder(workspace, "A")
+ b = await create_folder(workspace, "B")
+
+ real_ancestors = workspace_folder._ancestor_ids
+ both_checking = asyncio.Event()
+ entered = 0
+
+ async def gated(workspace_id: str, folder_id: str) -> list[str]:
+ nonlocal entered
+ entered += 1
+ mine = entered
+ if mine > 1:
+ both_checking.set()
+ chain = await real_ancestors(workspace_id, folder_id)
+ if mine == 1:
+ with contextlib.suppress(asyncio.TimeoutError):
+ await asyncio.wait_for(both_checking.wait(), timeout=2)
+ return chain
+
+ mocker.patch.object(workspace_folder, "_ancestor_ids", gated)
+
+ outcomes = await asyncio.gather(
+ move_folder(a.id, workspace, b.id),
+ move_folder(b.id, workspace, a.id),
+ return_exceptions=True,
+ )
+
+ assert entered == 2, "both movers must have reached the cycle check"
+ refused = [o for o in outcomes if isinstance(o, FolderValidationError)]
+ assert len(refused) == 1, outcomes
+
+ parents = {f.id: f.parent_id for f in await list_workspace_folders(workspace)}
+ assert None in (parents[a.id], parents[b.id]), parents
+
+
[email protected](loop_scope="session")
+async def test_creating_under_an_unknown_parent_is_refused(server: SpinTestServer):
+ """``parentId`` is written directly and the FK only proves the row exists,
+ so a parent from another workspace has to be refused here or not at all."""
+ workspace = await _workspace()
+
+ with pytest.raises(NotFoundError):
+ await create_folder(workspace, "Orphan", parent_id=str(uuid.uuid4()))
+
+
[email protected](loop_scope="session")
+async def test_a_move_and_rename_in_one_patch_apply_together(
+ server: SpinTestServer,
+):
+ workspace = await _workspace()
+ destination = await create_folder(workspace, "Invoices")
+ moving = await create_folder(workspace, "Source")
+
+ updated = await apply_folder_update(
+ moving.id, workspace, parent_id=destination.id, name="2026"
+ )
+
+ assert (updated.parent_id, updated.name) == (destination.id, "2026")
+
+
[email protected](loop_scope="session")
+async def test_a_refused_rename_leaves_the_folder_where_it_was(
+ server: SpinTestServer,
+):
+ """The move used to be written before the rename was checked, so a PATCH
+ doing both left the folder at its new parent under its old name and the
+ client holding a 409 — half of a request it had been told failed."""
+ workspace = await _workspace()
+ destination = await create_folder(workspace, "Invoices")
+ await create_folder(workspace, "Taken", parent_id=destination.id)
+ moving = await create_folder(workspace, "Source")
+
+ with pytest.raises(FolderAlreadyExistsError):
+ await apply_folder_update(
+ moving.id, workspace, parent_id=destination.id, name="Taken"
+ )
+
+ parents = {f.id: f.parent_id for f in await list_workspace_folders(workspace)}
+ assert parents[moving.id] is None
+
+
[email protected](loop_scope="session")
+async def test_a_move_onto_a_taken_name_is_refused(server: SpinTestServer):
+ workspace = await _workspace()
+ parent = await create_folder(workspace, "Invoices")
+ await create_folder(workspace, "Receipts", parent_id=parent.id)
+ loose = await create_folder(workspace, "Receipts")
+
+ with pytest.raises(FolderAlreadyExistsError):
+ await move_folder(loose.id, workspace, parent.id)
+
+
[email protected](loop_scope="session")
+async def test_attaching_folders_drops_foreign_and_deleted_ones_and_gates_on_scope(
+ server: SpinTestServer, monkeypatch: pytest.MonkeyPatch
+):
+ workspace = await _workspace()
+ owner = await UserWorkspace.prisma().find_unique(where={"id": workspace})
+ assert owner is not None
+ mine = await create_folder(workspace, "Invoices")
+ deleted = await create_folder(workspace, "Old")
+ await delete_folder(deleted.id, workspace)
+ foreign = await create_folder(await _workspace(), "Theirs")
+ ids = [mine.id, deleted.id, foreign.id]
+
+ resolved = await resolve_attachable_workspace_folders(
+ owner.userId, ids, expert_id=None
+ )
+ assert [f.id for f in resolved] == [mine.id]
+
+ # A missing expert resolves to a fail-closed scope: no folders at all.
+ assert (
+ await resolve_attachable_workspace_folders(
+ owner.userId, ids, expert_id=str(uuid.uuid4())
+ )
+ == []
+ )
+
+ async def granted(user_id: str, expert_id: str) -> WorkspaceScope:
+ return WorkspaceScope(expert_id=expert_id, reads_user_files=True)
+
+ monkeypatch.setattr(workspace_folder, "resolve_expert_workspace_scope", granted)
+ resolved = await resolve_attachable_workspace_folders(
+ owner.userId, ids, expert_id="exp-1"
+ )
+ assert [f.id for f in resolved] == [mine.id]
diff --git a/autogpt_platform/backend/backend/data/workspace_folder_test.py b/autogpt_platform/backend/backend/data/workspace_folder_test.py
index 1b1ad25117..474916e8bd 100644
--- a/autogpt_platform/backend/backend/data/workspace_folder_test.py
+++ b/autogpt_platform/backend/backend/data/workspace_folder_test.py
@@ -19,6 +19,7 @@ def _folder_record(**overrides):
rec.workspaceId = overrides.get("workspaceId", "ws-001")
rec.name = overrides.get("name", "Reports")
rec.icon = overrides.get("icon", None)
+ rec.parentId = overrides.get("parentId", None)
rec.createdAt = datetime(2026, 1, 1, tzinfo=timezone.utc)
rec.updatedAt = datetime(2026, 1, 1, tzinfo=timezone.utc)
rec.Files = overrides.get("Files", [])
@@ -44,6 +45,8 @@ async def test_delete_folder_reparents_files_then_soft_deletes(mocker):
folder_prisma.update_many = mocker.AsyncMock(
side_effect=lambda *a, **k: calls.append("soft_delete_folder")
)
+ # The subtree walk reads the workspace's folders; this one has no children.
+ folder_prisma.find_many = mocker.AsyncMock(return_value=[_folder_record()])
mocker.patch.object(
wf.UserWorkspaceFile, "prisma", mocker.MagicMock(return_value=file_prisma)
@@ -54,7 +57,10 @@ async def test_delete_folder_reparents_files_then_soft_deletes(mocker):
@asynccontextmanager
async def _fake_tx(*args, **kwargs):
- yield None
+ # The hierarchy lock runs on the transaction, so it cannot be None.
+ tx = mocker.MagicMock()
+ tx.execute_raw = mocker.AsyncMock()
+ yield tx
mocker.patch.object(wf, "transaction", _fake_tx)
@@ -63,11 +69,11 @@ async def test_delete_folder_reparents_files_then_soft_deletes(mocker):
assert calls == ["reparent_files", "soft_delete_folder"]
# Files reparented to root (folderId=None) scoped to the workspace.
_, kwargs = file_prisma.update_many.call_args
- assert kwargs["where"] == {"folderId": "fld-1", "workspaceId": "ws-001"}
+ assert kwargs["where"] == {"folderId": {"in": ["fld-1"]}, "workspaceId": "ws-001"}
assert kwargs["data"] == {"folderId": None}
# Folder soft-deleted (not hard-deleted) with a TOCTOU-safe isDeleted guard.
_, kwargs = folder_prisma.update_many.call_args
- assert kwargs["where"] == {"id": "fld-1", "isDeleted": False}
+ assert kwargs["where"] == {"id": {"in": ["fld-1"]}, "isDeleted": False}
assert kwargs["data"] == {"isDeleted": True}
@@ -152,7 +158,10 @@ async def test_bulk_move_validates_target_folder_ownership(mocker):
@asynccontextmanager
async def _fake_tx(*args, **kwargs):
- yield None
+ # The hierarchy lock runs on the transaction, so it cannot be None.
+ tx = mocker.MagicMock()
+ tx.execute_raw = mocker.AsyncMock()
+ yield tx
mocker.patch.object(wf, "transaction", _fake_tx)
@@ -177,7 +186,10 @@ async def test_bulk_move_to_root_skips_folder_lookup(mocker):
@asynccontextmanager
async def _fake_tx(*args, **kwargs):
- yield None
+ # The hierarchy lock runs on the transaction, so it cannot be None.
+ tx = mocker.MagicMock()
+ tx.execute_raw = mocker.AsyncMock()
+ yield tx
mocker.patch.object(wf, "transaction", _fake_tx)
@@ -201,3 +213,139 @@ async def test_bulk_move_empty_file_ids_noop(mocker):
assert result == []
file_prisma.update_many.assert_not_awaited()
+
+
+def _tree(*records):
+ """A prisma mock whose ``find_many`` answers with *records*."""
+ return records
+
+
+async def test_move_folder_refuses_a_move_into_its_own_subtree(mocker):
+ """The guard walks the destination's ancestors; without it the subtree is
+ detached from the root and nothing can list it again."""
+ parent = _folder_record(id="parent", name="Parent")
+ child = _folder_record(id="child", name="Child", parentId="parent")
+ grandchild = _folder_record(id="grandchild", name="Grandchild", parentId="child")
+
+ folder_prisma = mocker.MagicMock()
+ folder_prisma.find_many = mocker.AsyncMock(
+ return_value=list(_tree(parent, child, grandchild))
+ )
+ # Everything past the guard is mocked, so removing the guard makes this
+ # test fail on the missing raise rather than on an unmocked call.
+ folder_prisma.find_first = mocker.AsyncMock(return_value=None)
+ folder_prisma.update_many = mocker.AsyncMock(return_value=1)
+ mocker.patch.object(
+ wf.UserWorkspaceFolder, "prisma", mocker.MagicMock(return_value=folder_prisma)
+ )
+ mocker.patch.object(
+ wf, "get_folder", mocker.AsyncMock(return_value=mocker.sentinel.moved)
+ )
+ records = {r.id: r for r in (parent, child, grandchild)}
+ mocker.patch.object(
+ wf,
+ "_get_folder_record",
+ mocker.AsyncMock(side_effect=lambda fid, ws: records[fid]),
+ )
+
+ for destination in ("grandchild", "child", "parent"):
+ with pytest.raises(wf.FolderValidationError):
+ await wf.move_folder("parent", "ws-001", destination)
+ folder_prisma.update_many.assert_not_awaited()
+
+
+async def test_move_folder_to_root_clears_the_parent(mocker):
+ child = _folder_record(id="child", name="Child", parentId="parent")
+
+ folder_prisma = mocker.MagicMock()
+ folder_prisma.find_first = mocker.AsyncMock(return_value=None)
+ folder_prisma.update_many = mocker.AsyncMock(return_value=1)
+ mocker.patch.object(
+ wf.UserWorkspaceFolder, "prisma", mocker.MagicMock(return_value=folder_prisma)
+ )
+ mocker.patch.object(wf, "_get_folder_record", mocker.AsyncMock(return_value=child))
+ mocker.patch.object(
+ wf, "get_folder", mocker.AsyncMock(return_value=mocker.sentinel.moved)
+ )
+
+ assert await wf.move_folder("child", "ws-001", None) is mocker.sentinel.moved
+ _, kwargs = folder_prisma.update_many.call_args
+ assert kwargs["where"] == {"id": "child", "isDeleted": False}
+ assert kwargs["data"] == {"parentId": None}
+
+
+async def test_delete_folder_takes_the_whole_subtree(mocker):
+ """A grandchild left behind would keep its files hidden under a folder no
+ listing returns."""
+ parent = _folder_record(id="parent", name="Parent")
+ child = _folder_record(id="child", name="Child", parentId="parent")
+ grandchild = _folder_record(id="grandchild", name="Grandchild", parentId="child")
+ sibling = _folder_record(id="sibling", name="Sibling")
+
+ file_prisma = mocker.MagicMock()
+ file_prisma.update_many = mocker.AsyncMock()
+ folder_prisma = mocker.MagicMock()
+ folder_prisma.update_many = mocker.AsyncMock()
+ folder_prisma.find_many = mocker.AsyncMock(
+ return_value=[parent, child, grandchild, sibling]
+ )
+ mocker.patch.object(
+ wf.UserWorkspaceFile, "prisma", mocker.MagicMock(return_value=file_prisma)
+ )
+ mocker.patch.object(
+ wf.UserWorkspaceFolder, "prisma", mocker.MagicMock(return_value=folder_prisma)
+ )
+ mocker.patch.object(wf, "_get_folder_record", mocker.AsyncMock(return_value=parent))
+
+ @asynccontextmanager
+ async def _fake_tx(*args, **kwargs):
+ # The hierarchy lock runs on the transaction, so it cannot be None.
+ tx = mocker.MagicMock()
+ tx.execute_raw = mocker.AsyncMock()
+ yield tx
+
+ mocker.patch.object(wf, "transaction", _fake_tx)
+
+ await wf.delete_folder("parent", "ws-001")
+
+ _, folder_kwargs = folder_prisma.update_many.call_args
+ assert sorted(folder_kwargs["where"]["id"]["in"]) == [
+ "child",
+ "grandchild",
+ "parent",
+ ]
+ _, file_kwargs = file_prisma.update_many.call_args
+ assert sorted(file_kwargs["where"]["folderId"]["in"]) == [
+ "child",
+ "grandchild",
+ "parent",
+ ]
+ assert file_kwargs["data"] == {"folderId": None}
+
+
+async def test_create_folder_scopes_the_name_clash_to_the_parent(mocker):
+ folder_prisma = mocker.MagicMock()
+ folder_prisma.find_first = mocker.AsyncMock(return_value=None)
+ folder_prisma.create = mocker.AsyncMock(
+ return_value=_folder_record(id="new", parentId="parent")
+ )
+ mocker.patch.object(
+ wf.UserWorkspaceFolder, "prisma", mocker.MagicMock(return_value=folder_prisma)
+ )
+ mocker.patch.object(
+ wf,
+ "_get_folder_record",
+ mocker.AsyncMock(return_value=_folder_record(id="parent")),
+ )
+
+ created = await wf.create_folder("ws-001", "Reports", parent_id="parent")
+
+ assert created.parent_id == "parent"
+ _, kwargs = folder_prisma.find_first.call_args
+ assert kwargs["where"]["parentId"] == "parent"
+ _, kwargs = folder_prisma.create.call_args
+ assert kwargs["data"]["Parent"] == {"connect": {"id": "parent"}}
diff --git a/autogpt_platform/backend/backend/data/workspace_scope.py b/autogpt_platform/backend/backend/data/workspace_scope.py
index a086fab2e6..8beed2e945 100644
--- a/autogpt_platform/backend/backend/data/workspace_scope.py
+++ b/autogpt_platform/backend/backend/data/workspace_scope.py
@@ -2,9 +2,9 @@
Resolved from persisted session attribution, never from tool arguments. An
expert session may read and write under its own conversations and its own
-skills folder, and read under conversations it delegated. ``None`` scope
-means unrestricted: the account owner acting through personal
-Otto, REST endpoints, or system paths.
+skills folder, read under conversations it delegated, and read the owner's
+own files. ``None`` scope means unrestricted: the account owner acting
+through personal Otto, REST endpoints, or system paths.
"""
import posixpath
@@ -26,9 +26,10 @@ SKILLS_ROOT = "/skills/"
SHARED_ROOTS = (SESSIONS_ROOT, SKILLS_ROOT, EXPERTS_ROOT)
EXPERT_FILE_ACCESS_DENIED = (
- "This file is outside this expert's scope. Experts can only access files "
- "from their own conversations and their own skills. Open a chat with Otto "
- "to work with other files."
+ "This file is outside this expert's scope. Experts can read your own files "
+ "and their own conversations, and can only write to their own "
+ "conversations and skills. Open a chat with Otto to work with another "
+ "expert's files."
)
EXPERT_SKILL_SCOPE_DENIED = (
"Experts can only use and manage their own skills. Open a chat with Otto "
@@ -48,6 +49,17 @@ def expert_skills_folder(expert_id: str) -> str:
return f"{EXPERTS_ROOT}{expert_id}/skills"
+def is_user_file_path(path: str) -> bool:
+ """Whether *path* is one of the owner's own files.
+
+ Everything outside the three managed roots: what the user uploads on the
+ Files page, at the workspace root or in a folder. A predicate over the
+ roots rather than a ``/`` prefix, which ``allows_path``'s ``startswith``
+ would match against every path in the workspace.
+ """
+ return not path.startswith(SHARED_ROOTS)
+
+
class WorkspaceScope(BaseModel):
"""Grants for one acting session. Safe for RPC transport.
@@ -58,10 +70,13 @@ class WorkspaceScope(BaseModel):
expert_id: str | None = None
session_ids: list[str] = Field(default_factory=list)
delegated_session_ids: list[str] = Field(default_factory=list)
- # A carried grant, never inferred from ``expert_id``: this model crosses an
- # RPC boundary and is rebuilt as this class, so a subclass that withheld the
- # folder would come back granting it.
+ # Carried grants, never inferred from ``expert_id``: this model crosses an
+ # RPC boundary and is rebuilt as this class, so a subclass that withheld a
+ # grant would come back granting it. Defaulting to False also keeps the
+ # unattributed scope (``WorkspaceScope(session_ids=[sid])``) fail-closed.
owns_skills_folder: bool = False
+ # Read-only: the owner's own files, shared by every expert they hire.
+ reads_user_files: bool = False
def with_session(self, session_id: str) -> "WorkspaceScope":
if session_id in self.session_ids:
@@ -88,6 +103,8 @@ class WorkspaceScope(BaseModel):
def allows_path(self, path: str, *, write: bool = False) -> bool:
if not path.startswith("/") or "\\" in path or posixpath.normpath(path) != path:
return False
+ if not write and self.reads_user_files and is_user_file_path(path):
+ return True
prefixes = self.write_prefixes if write else self.read_prefixes
return any(path.startswith(prefix) for prefix in prefixes)
@@ -98,9 +115,11 @@ async def resolve_expert_workspace_scope(
"""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
+ conversation keeps reaching files from earlier ones, and the owner's own
+ files are readable so an expert can work on what the owner uploaded.
+ Fails closed: a missing, archived, or foreign expert yields no grants at
+ all, user files included (callers add the current session explicitly,
+ which grants nothing beyond that one conversation). 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.
"""
@@ -131,6 +150,7 @@ async def resolve_expert_workspace_scope(
return WorkspaceScope(
expert_id=expert_id,
owns_skills_folder=True,
+ reads_user_files=True,
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
index 2d1fd80bfa..d959b802ec 100644
--- a/autogpt_platform/backend/backend/data/workspace_scope_db_test.py
+++ b/autogpt_platform/backend/backend/data/workspace_scope_db_test.py
@@ -146,3 +146,95 @@ async def test_two_experts_files_stay_separate_across_new_conversations(
)
== 0
)
+
+
[email protected](loop_scope="session")
+async def test_every_expert_reads_the_owners_own_files_and_no_more(
+ server: SpinTestServer,
+):
+ """The user's uploads live outside every managed root, so before the grant
+ an expert chat could not read or attach what the user had just uploaded."""
+ owner = await _user()
+ expert_a = await _expert(owner)
+ expert_b = await _expert(owner)
+ a_session = await create_chat_session(str(uuid.uuid4()), owner, expert_id=expert_a)
+ b_session = await create_chat_session(str(uuid.uuid4()), owner, expert_id=expert_b)
+ workspace = await get_or_create_workspace(owner)
+
+ upload = await create_workspace_file(
+ workspace_id=workspace.id,
+ file_id=str(uuid.uuid4()),
+ name="quarterly-report.pdf",
+ path=f"/quarterly-report-{uuid.uuid4().hex[:8]}.pdf",
+ storage_path=f"{workspace.id}/quarterly.pdf",
+ mime_type="application/pdf",
+ size_bytes=9,
+ )
+ a_private = await create_workspace_file(
+ workspace_id=workspace.id,
+ file_id=str(uuid.uuid4()),
+ name="notes.md",
+ path=f"/sessions/{a_session.session_id}/notes.md",
+ storage_path=f"{workspace.id}/notes.md",
+ mime_type="text/markdown",
+ size_bytes=4,
+ )
+
+ scope_a = await resolve_expert_workspace_scope(owner, expert_a)
+ scope_b = await resolve_expert_workspace_scope(owner, expert_b)
+
+ assert scope_a.reads_user_files and scope_b.reads_user_files
+ assert scope_a.allows_path(upload.path)
+ assert scope_b.allows_path(upload.path)
+ assert not scope_a.allows_path(upload.path, write=True)
+ # Expert-to-expert isolation is untouched by the grant.
+ assert scope_a.allows_path(a_private.path)
+ assert not scope_b.allows_path(a_private.path)
+
+ listed_for_b = await list_workspace_files(
+ workspace.id,
+ allowed_path_prefixes=[
+ f"/sessions/{sid}/" for sid in [*scope_b.session_ids, b_session.session_id]
+ ],
+ include_user_files=scope_b.reads_user_files,
+ )
+ assert upload.id in [f.id for f in listed_for_b]
+ assert a_private.id not in [f.id for f in listed_for_b]
+ assert (
+ await count_workspace_files(
+ workspace.id,
+ allowed_path_prefixes=[f"/sessions/{b_session.session_id}/"],
+ include_user_files=True,
+ )
+ >= 1
+ )
+
+
[email protected](loop_scope="session")
+async def test_a_revoked_expert_reads_no_user_files(server: SpinTestServer):
+ owner = await _user()
+ stranger = await _user()
+ expert = await _expert(stranger)
+ workspace = await get_or_create_workspace(owner)
+ upload = await create_workspace_file(
+ workspace_id=workspace.id,
+ file_id=str(uuid.uuid4()),
+ name="private.pdf",
+ path=f"/private-{uuid.uuid4().hex[:8]}.pdf",
+ storage_path=f"{workspace.id}/private.pdf",
+ mime_type="application/pdf",
+ size_bytes=3,
+ )
+
+ foreign_scope = await resolve_expert_workspace_scope(owner, expert)
+
+ assert not foreign_scope.reads_user_files
+ assert not foreign_scope.allows_path(upload.path)
+ assert (
+ await list_workspace_files(
+ workspace.id,
+ allowed_path_prefixes=[],
+ include_user_files=foreign_scope.reads_user_files,
+ )
+ == []
+ )
diff --git a/autogpt_platform/backend/backend/data/workspace_scope_test.py b/autogpt_platform/backend/backend/data/workspace_scope_test.py
index e6de60bfb4..e6a08d02ea 100644
--- a/autogpt_platform/backend/backend/data/workspace_scope_test.py
+++ b/autogpt_platform/backend/backend/data/workspace_scope_test.py
@@ -96,3 +96,48 @@ def test_with_session_returns_new_scope_without_mutating():
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
+
+
+# Same grants plus the owner's own files, which is what
+# ``resolve_expert_workspace_scope`` builds for a live hired expert.
+USER_FILES_SCOPE = SCOPE.model_copy(update={"reads_user_files": True})
+
+
+ "path",
+ [
+ "/root-file.txt",
+ "/Invoices/2026/march.pdf",
+ "/sessionsish/file.txt",
+ "/skillsets/private.txt",
+ ],
+)
+def test_user_files_are_readable_but_never_writable(path: str):
+ assert USER_FILES_SCOPE.allows_path(path)
+ assert not USER_FILES_SCOPE.allows_path(path, write=True)
+
+
+ "path",
+ [
+ "/sessions/expert-b/private.txt",
+ "/sessions/personal/private.txt",
+ "/skills/autopilot-skill/SKILL.md",
+ "/experts/expert-b/skills/theirs/SKILL.md",
+ "/sessions/expert-a/../../root-file.txt",
+ "root-file.txt",
+ ],
+)
+def test_the_user_files_grant_opens_nothing_under_the_managed_roots(path: str):
+ assert not USER_FILES_SCOPE.allows_path(path)
+
+
+def test_the_user_files_grant_survives_the_rpc_round_trip():
+ """Carried as a field, so a scope that denies user files cannot come back
+ granting them, and one that grants them cannot come back denying them."""
+ for scope in (SCOPE, USER_FILES_SCOPE):
+ rebuilt = WorkspaceScope.model_validate(scope.model_dump())
+ assert rebuilt.reads_user_files == scope.reads_user_files
+ assert rebuilt.allows_path("/root-file.txt") == scope.allows_path(
+ "/root-file.txt"
+ )
diff --git a/autogpt_platform/backend/backend/data/workspace_skill.py b/autogpt_platform/backend/backend/data/workspace_skill.py
index 7957d818bf..fe5e26aeb4 100644
--- a/autogpt_platform/backend/backend/data/workspace_skill.py
+++ b/autogpt_platform/backend/backend/data/workspace_skill.py
@@ -51,15 +51,17 @@ async def publish_workspace_skill_file(
if folder is None:
raise ValueError("Skill publication requires a canonical SKILL.md path")
async with _publication_transaction(write.workspace_id, folder) as tx:
- existing = await tx.userworkspacefile.find_unique(
+ # Live rows only: since paths are unique among live files, a path holds
+ # at most one, and retired roots left behind at it are history rather
+ # than something to retire again.
+ existing = await tx.userworkspacefile.find_first(
where={
- "workspaceId_path": {
- "workspaceId": write.workspace_id,
- "path": write.path,
- }
+ "workspaceId": write.workspace_id,
+ "path": write.path,
+ "isDeleted": False,
}
)
- if existing and not existing.isDeleted and not write.overwrite:
+ if existing and not write.overwrite:
return WorkspaceSkillPublication(status="exists")
origin = skill_origin(write.metadata) or SKILL_ORIGIN_USER
existing_origin = skill_origin(
@@ -67,7 +69,7 @@ async def publish_workspace_skill_file(
if existing and isinstance(existing.metadata, dict)
else None
)
- active = existing is not None and not existing.isDeleted
+ active = existing is not None
if (
active
and origin == SKILL_ORIGIN_MARKETPLACE
@@ -168,12 +170,11 @@ async def _create_root(tx: Prisma, write: WorkspaceSkillWrite) -> UserWorkspaceF
async def _replace_root(
tx: Prisma, file_id: str, write: WorkspaceSkillWrite
) -> UserWorkspaceFile:
+ # No rename: the retired row leaves the live-only unique index the moment
+ # it is marked deleted, so the replacement takes the path in the same
+ # transaction and the retired row keeps the path it was retired at.
await tx.userworkspacefile.update(
where={"id": file_id},
- data={
- "isDeleted": True,
- "deletedAt": datetime.now(timezone.utc),
- "path": f"{write.path}__deleted__{file_id}",
- },
+ data={"isDeleted": True, "deletedAt": datetime.now(timezone.utc)},
)
return await _create_root(tx, write)
diff --git a/autogpt_platform/backend/backend/data/workspace_skill_test.py b/autogpt_platform/backend/backend/data/workspace_skill_test.py
index 0f05644a23..12eb845051 100644
--- a/autogpt_platform/backend/backend/data/workspace_skill_test.py
+++ b/autogpt_platform/backend/backend/data/workspace_skill_test.py
@@ -120,12 +120,11 @@ async def test_concurrent_new_roots_cannot_both_take_last_slot(
@pytest.mark.asyncio(loop_scope="session")
async def test_upserts_at_capacity_never_expose_a_free_slot(workspace_id: str):
await seed(workspace_id, MAX_SKILLS_PER_EXPERT)
- existing = await db.prisma.userworkspacefile.find_unique(
+ existing = await db.prisma.userworkspacefile.find_first(
where={
- "workspaceId_path": {
- "workspaceId": workspace_id,
- "path": "/skills/skill-0/SKILL.md",
- }
+ "workspaceId": workspace_id,
+ "path": "/skills/skill-0/SKILL.md",
+ "isDeleted": False,
}
)
assert existing is not None
@@ -334,8 +333,8 @@ async def test_concurrent_marketplace_install_cannot_replace_owner_saved_root(
)
assert results[0].status == "stored"
assert results[1].status in {"stored", "owned"}
- row = await db.prisma.userworkspacefile.find_unique(
- where={"workspaceId_path": {"workspaceId": workspace_id, "path": saved.path}}
+ row = await db.prisma.userworkspacefile.find_first(
+ where={"workspaceId": workspace_id, "path": saved.path, "isDeleted": False}
)
assert row is not None
assert row.id == saved.file_id
diff --git a/autogpt_platform/backend/backend/data/workspace_test.py b/autogpt_platform/backend/backend/data/workspace_test.py
index 5ca82b049f..1ba0f2111b 100644
--- a/autogpt_platform/backend/backend/data/workspace_test.py
+++ b/autogpt_platform/backend/backend/data/workspace_test.py
@@ -1,56 +1,154 @@
-"""Soft-deleting a workspace file frees its path for the next write.
+"""Real-database coverage for the path a soft-deleted workspace file leaves.
-``write_file(overwrite=True)`` soft-deletes the row it replaces, so the renamed
-path is what two writes to one path race on.
+The unique index over ``(workspaceId, path)`` covers live rows only, so a
+deleted file keeps the path it was deleted at and the next write takes it.
+``write_file(overwrite=True)`` soft-deletes the row it replaces, so this is
+the path two writes to one path race on.
"""
-from datetime import datetime, timedelta, timezone
+import uuid
+from datetime import datetime, timezone
import pytest
+from prisma.errors import UniqueViolationError
+from prisma.models import UserWorkspaceFile
-from backend.data import workspace
+from backend.data import workspace as workspace_db
+from backend.data.user import get_or_create_user
+from backend.data.workspace import (
+ create_workspace_file,
+ get_or_create_workspace,
+ get_workspace_file_by_path,
+ list_workspace_files,
+ soft_delete_workspace_file,
+)
+from backend.util.test import SpinTestServer
-WITHIN_ONE_SECOND = [
- datetime(2026, 9, 14, 12, 0, 0, tzinfo=timezone.utc) + timedelta(milliseconds=ms)
- for ms in (0, 120)
-]
[email protected](loop_scope="session")
+async def test_one_path_survives_repeated_create_and_delete(server: SpinTestServer):
+ """Needs this branch's migration: the old index spanned deleted rows, so
+ only the rename-on-delete kept the path writable, and every round left
+ another row that had to be renamed out of the way first."""
+ workspace = await _workspace()
-class _Row:
- def __init__(self, path: str):
- self.id = "file-1"
- self.path = path
+ written = []
+ for _ in range(6):
+ written.append(await _write(workspace, "/a.txt"))
+ listed = await list_workspace_files(workspace)
+ assert [f.id for f in listed] == [written[-1]]
+ await soft_delete_workspace_file(written[-1], workspace)
+ assert await list_workspace_files(workspace) == []
+ assert len(set(written)) == 6
+ kept = await list_workspace_files(workspace, include_deleted=True)
+ assert {f.id for f in kept} == set(written)
+ assert {f.path for f in kept} == {"/a.txt"}
-def renames(mocker):
- """Every path ``soft_delete_workspace_file`` renames a row to, with a clock
- that advances inside one second so only the suffix separates two calls."""
- mocker.patch.object(
- workspace, "get_workspace_file", mocker.AsyncMock(return_value=_Row("/a/b.txt"))
- )
+
[email protected](loop_scope="session")
+async def test_two_deletes_at_one_instant_both_keep_the_path(
+ server: SpinTestServer, mocker
+):
+ """The case the rename could not survive: it separated deleted rows by a
+ timestamp, so two deletes close enough together collided on the very index
+ the rename exists to dodge. Freezing the clock is stronger than the second
+ the suffix once measured — nothing here reads it."""
+ workspace = await _workspace()
+ frozen = datetime(2026, 9, 22, 12, 0, 0, tzinfo=timezone.utc)
mocker.patch.object(
- workspace,
+ workspace_db,
"datetime",
- mocker.MagicMock(now=mocker.MagicMock(side_effect=WITHIN_ONE_SECOND)),
- )
- captured: list[str] = []
- prisma = mocker.MagicMock()
- prisma.update = mocker.AsyncMock(
- side_effect=lambda where, data: captured.append(data["path"])
- )
- mocker.patch.object(
- workspace.UserWorkspaceFile, "prisma", mocker.MagicMock(return_value=prisma)
+ mocker.MagicMock(now=mocker.MagicMock(return_value=frozen)),
)
- return captured
+
+ first = await _write(workspace, "/a.txt")
+ await soft_delete_workspace_file(first, workspace)
+ second = await _write(workspace, "/a.txt")
+ await soft_delete_workspace_file(second, workspace)
+
+ rows = await list_workspace_files(workspace, include_deleted=True)
+ assert {r.id for r in rows} == {first, second}
+ assert {r.path for r in rows} == {"/a.txt"}
+ assert {r.deleted_at for r in rows} == {frozen}
+
+
[email protected](loop_scope="session")
+async def test_a_deleted_file_keeps_the_path_it_was_deleted_at(
+ server: SpinTestServer,
+):
+ """What the rename cost: the record it preserved no longer said where the
+ file had been, and recovering one meant parsing a suffix back off."""
+ workspace = await _workspace()
+ file_id = await _write(workspace, "/a.txt")
+ await soft_delete_workspace_file(file_id, workspace)
+
+ row = await UserWorkspaceFile.prisma().find_unique(where={"id": file_id})
+ assert row is not None
+ assert row.path == "/a.txt"
+ assert row.isDeleted is True
-async def test_two_deletes_in_one_second_free_the_path_twice(renames: list[str]):
- """A second-resolution suffix gave both the same name, so the second rename
- failed the unique index it exists to get out of the way of — leaving a file
- the user could no longer overwrite."""
- await workspace.soft_delete_workspace_file("file-1", "ws-1")
- await workspace.soft_delete_workspace_file("file-1", "ws-1")
[email protected](loop_scope="session")
+async def test_the_database_still_refuses_two_live_files_at_one_path(
+ server: SpinTestServer,
+):
+ """``write_file(overwrite=True)`` reads this violation to learn it must
+ replace the file already there, so the index has to keep raising it."""
+ workspace = await _workspace()
+ await _write(workspace, "/a.txt")
- assert renames[0] != renames[1]
- assert all(name.startswith("/a/b.txt__deleted__") for name in renames)
+ with pytest.raises(UniqueViolationError):
+ await _write(workspace, "/a.txt")
+
+
[email protected](loop_scope="session")
+async def test_reads_pass_over_the_deleted_rows_sharing_a_path(
+ server: SpinTestServer,
+):
+ """One path may now hold several rows — one live, any number deleted — so
+ every read promising a live file has to filter for itself."""
+ workspace = await _workspace()
+ older = await _write(workspace, "/a.txt")
+ await soft_delete_workspace_file(older, workspace)
+ newer = await _write(workspace, "/a.txt")
+ await soft_delete_workspace_file(newer, workspace)
+ live = await _write(workspace, "/a.txt")
+
+ found = await get_workspace_file_by_path(workspace, "/a.txt")
+ assert found is not None and found.id == live
+
+ assert [f.id for f in await list_workspace_files(workspace)] == [live]
+ assert {
+ f.id for f in await list_workspace_files(workspace, include_deleted=True)
+ } == {
+ older,
+ newer,
+ live,
+ }
+
+
+async def _workspace() -> str:
+ suffix = uuid.uuid4().hex[:8]
+ user = await get_or_create_user(
+ {
+ "sub": str(uuid.uuid4()),
+ "email": f"file-paths-{suffix}@example.com",
+ "name": "File Owner",
+ }
+ )
+ workspace = await get_or_create_workspace(user.id)
+ return workspace.id
+
+
+async def _write(workspace_id: str, path: str) -> str:
+ stored = await create_workspace_file(
+ workspace_id=workspace_id,
+ file_id=str(uuid.uuid4()),
+ name=path.rsplit("/", 1)[-1],
+ path=path,
+ storage_path=f"{workspace_id}{path}",
+ mime_type="text/plain",
+ size_bytes=3,
+ )
+ return stored.id
diff --git a/autogpt_platform/backend/backend/util/workspace.py b/autogpt_platform/backend/backend/util/workspace.py
index 3e16185930..1738c8da66 100644
--- a/autogpt_platform/backend/backend/util/workspace.py
+++ b/autogpt_platform/backend/backend/util/workspace.py
@@ -9,12 +9,16 @@ import asyncio
import logging
import mimetypes
import uuid
-from typing import Optional
+from typing import TYPE_CHECKING, Optional
from prisma.errors import UniqueViolationError
from backend.copilot.rate_limit import get_workspace_storage_limit_bytes
-from backend.data.db_accessors import workspace_db, workspace_skill_db
+from backend.data.db_accessors import (
+ workspace_db,
+ workspace_folder_db,
+ workspace_skill_db,
+)
from backend.data.skill_capacity import (
MAX_SKILLS_PER_EXPERT,
SKILL_ORIGIN_LABELS,
@@ -36,6 +40,9 @@ 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
+if TYPE_CHECKING:
+ from backend.data.workspace_folder import WorkspaceFolder
+
def format_bytes(n: int) -> str:
"""Format bytes as a human-readable string (e.g. 250 MB, 1.0 GB)."""
@@ -117,6 +124,15 @@ class WorkspaceManager:
return allowed
return [p for p in requested if any(p.startswith(a) for a in allowed)]
+ def _include_user_files(self, requested: bool) -> bool:
+ """Whether a listing also spans the owner's own files.
+
+ A scoped manager answers from its own grant: the scope is resolved
+ from persisted attribution, so it decides both directions and a
+ caller's argument is only consulted when there is no scope to ask.
+ """
+ return self.scope.reads_user_files if self.scope is not None else requested
+
def _resolve_path(self, path: str) -> str:
"""
Resolve a path, defaulting to session folder if session_id is set.
@@ -456,6 +472,13 @@ class WorkspaceManager:
return file
+ async def list_folders(self) -> list["WorkspaceFolder"]:
+ """The folder tree; empty for a scope without the owner's files, whose
+ folders these are."""
+ if self.scope is not None and not self.scope.reads_user_files:
+ return []
+ return await workspace_folder_db().list_workspace_folders(self.workspace_id)
+
async def list_files(
self,
path: Optional[str] = None,
@@ -467,8 +490,10 @@ class WorkspaceManager:
metadata_equals: Optional[dict] = None,
metadata_not_equals: Optional[dict] = None,
folder_id: Optional[str] = None,
+ folder_ids: Optional[list[str]] = None,
root_only: bool = False,
allowed_path_prefixes: Optional[list[str]] = None,
+ include_user_files: bool = False,
) -> list[WorkspaceFile]:
"""
List files in workspace.
@@ -492,15 +517,29 @@ class WorkspaceManager:
metadata_not_equals: Match files whose ``metadata`` does not equal
this object (Artifacts "Generated" filter).
folder_id: If set, only return files in this folder.
+ folder_ids: If set, only return files in any of these folders.
root_only: If True, only return root-level files (folderId IS NULL).
+ Every folder filter is a workspace-wide axis, so any of them
+ lifts the current-session default the way
+ ``include_all_sessions`` does; an expert's scope still confines
+ the result.
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`).
+ include_user_files: Also list the owner's own files. A scoped
+ manager takes this from its scope instead
+ (see :meth:`_include_user_files`).
Returns:
List of WorkspaceFile instances
"""
- effective_path = self._get_effective_path(path, include_all_sessions)
+ effective_path = self._get_effective_path(
+ path,
+ include_all_sessions
+ or folder_id is not None
+ or folder_ids is not None
+ or root_only,
+ )
db = workspace_db()
return await db.list_workspace_files(
@@ -513,8 +552,10 @@ class WorkspaceManager:
metadata_equals=metadata_equals,
metadata_not_equals=metadata_not_equals,
folder_id=folder_id,
+ folder_ids=folder_ids,
root_only=root_only,
allowed_path_prefixes=self._allowed_prefixes(allowed_path_prefixes),
+ include_user_files=self._include_user_files(include_user_files),
)
async def delete_file(self, file_id: str) -> bool:
@@ -628,7 +669,11 @@ class WorkspaceManager:
self,
path: Optional[str] = None,
include_all_sessions: bool = False,
+ folder_id: Optional[str] = None,
+ folder_ids: Optional[list[str]] = None,
+ root_only: bool = False,
allowed_path_prefixes: Optional[list[str]] = None,
+ include_user_files: bool = False,
) -> int:
"""
Get number of files in workspace.
@@ -640,15 +685,28 @@ class WorkspaceManager:
path: Optional path prefix to filter (e.g., "/documents/")
include_all_sessions: If True, count all files in workspace.
If False (default), only count current session's files.
+ folder_id: See :meth:`list_files`.
+ folder_ids: See :meth:`list_files`.
+ root_only: See :meth:`list_files`.
Returns:
Number of files
"""
- effective_path = self._get_effective_path(path, include_all_sessions)
+ effective_path = self._get_effective_path(
+ path,
+ include_all_sessions
+ or folder_id is not None
+ or folder_ids is not None
+ or root_only,
+ )
db = workspace_db()
return await db.count_workspace_files(
self.workspace_id,
path_prefix=effective_path,
+ folder_id=folder_id,
+ folder_ids=folder_ids,
+ root_only=root_only,
allowed_path_prefixes=self._allowed_prefixes(allowed_path_prefixes),
+ include_user_files=self._include_user_files(include_user_files),
)
diff --git a/autogpt_platform/backend/backend/util/workspace_isolation_test.py b/autogpt_platform/backend/backend/util/workspace_isolation_test.py
index b46cc9a88d..174daa9730 100644
--- a/autogpt_platform/backend/backend/util/workspace_isolation_test.py
+++ b/autogpt_platform/backend/backend/util/workspace_isolation_test.py
@@ -40,6 +40,20 @@ def storage():
yield storage
[email protected](autouse=True)
+def write_infrastructure():
+ """A completed ``write_file`` reaches the quota lookup, whose DatabaseManager
+ RPC has no server here and retries for ~100 × 30 s instead of failing."""
+ with (
+ patch("backend.util.workspace.scan_content_safe", new_callable=AsyncMock),
+ patch(
+ "backend.util.workspace.get_workspace_storage_limit_bytes",
+ return_value=250 * 1024 * 1024,
+ ),
+ ):
+ yield
+
+
def _expert_manager() -> WorkspaceManager:
return WorkspaceManager("user-1", "ws-1", "expert-a", scope=SCOPE)
@@ -171,3 +185,93 @@ async def test_owner_without_scope_lists_the_requested_prefixes(db):
assert db.list_workspace_files.call_args.kwargs["allowed_path_prefixes"] == [
"/sessions/expert-b/"
]
+
+
+# What ``resolve_expert_workspace_scope`` builds for a live hired expert: the
+# same grants plus read access to the owner's own files.
+USER_FILES_SCOPE = SCOPE.model_copy(update={"reads_user_files": True})
+
+
+def _user_files_manager() -> WorkspaceManager:
+ return WorkspaceManager("user-1", "ws-1", "expert-a", scope=USER_FILES_SCOPE)
+
+
+async def test_a_user_file_is_readable_by_id(db, storage):
+ db.get_workspace_file = AsyncMock(
+ return_value=_make_workspace_file(path="/quarterly-report.pdf")
+ )
+ manager = _user_files_manager()
+
+ assert await manager.read_file_by_id("root-upload") == b"allowed"
+ assert (await manager.get_file_info("root-upload")) is not None
+ await manager.get_download_url("root-upload")
+
+
+async def test_a_user_file_is_never_writable(db, storage):
+ db.get_workspace_file = AsyncMock(
+ return_value=_make_workspace_file(path="/quarterly-report.pdf")
+ )
+
+ with pytest.raises(WorkspaceAccessDeniedError):
+ await _user_files_manager().delete_file("root-upload")
+ db.soft_delete_workspace_file.assert_not_awaited()
+
+ # A session-less manager takes the path as written, so this is the shape
+ # that actually asks to overwrite the user's own file.
+ session_less = WorkspaceManager("user-1", "ws-1", None, scope=USER_FILES_SCOPE)
+ with pytest.raises(WorkspaceAccessDeniedError):
+ await session_less.write_file(
+ b"x", "quarterly-report.pdf", path="/quarterly-report.pdf", overwrite=True
+ )
+
+
+async def test_a_root_path_written_from_a_session_lands_in_that_session(db, storage):
+ """``_resolve_path`` re-homes a bare path under the current conversation,
+ so an expert cannot address the user's own file by path at all — reaching
+ one is by file_id, which is what the tool descriptions now say."""
+ db.create_workspace_file = AsyncMock(
+ return_value=_make_workspace_file(
+ path="/sessions/expert-a/quarterly-report.pdf"
+ )
+ )
+
+ await _user_files_manager().write_file(
+ b"x", "quarterly-report.pdf", path="/quarterly-report.pdf", overwrite=True
+ )
+
+ assert (
+ db.create_workspace_file.call_args.kwargs["path"]
+ == "/sessions/expert-a/quarterly-report.pdf"
+ )
+
+
+async def test_another_experts_conversation_stays_denied_with_the_grant(db, storage):
+ with pytest.raises(WorkspaceAccessDeniedError):
+ await _user_files_manager().read_file_by_id("foreign-file")
+ storage.retrieve.assert_not_awaited()
+
+
+async def test_the_query_widens_to_user_files_only_with_the_grant(db):
+ await _user_files_manager().list_files(include_all_sessions=True)
+ assert db.list_workspace_files.call_args.kwargs["include_user_files"] is True
+ await _user_files_manager().get_file_count(include_all_sessions=True)
+ assert db.count_workspace_files.call_args.kwargs["include_user_files"] is True
+
+ await _expert_manager().list_files(include_all_sessions=True)
+ assert db.list_workspace_files.call_args.kwargs["include_user_files"] is False
+
+
+async def test_a_folder_listing_lifts_the_current_session_default(db):
+ """A folder is a workspace-wide axis: keeping the session prefix on would
+ intersect it to nothing for any file outside this conversation."""
+ manager = _user_files_manager()
+ await manager.list_files(folder_id="fld-1")
+ list_kwargs = db.list_workspace_files.call_args.kwargs
+ assert list_kwargs["path_prefix"] is None
+ assert list_kwargs["folder_id"] == "fld-1"
+ assert list_kwargs["allowed_path_prefixes"] == USER_FILES_SCOPE.read_prefixes
+
+ await manager.list_files()
+ assert (
+ db.list_workspace_files.call_args.kwargs["path_prefix"] == "/sessions/expert-a/"
+ )
diff --git a/autogpt_platform/backend/migrations/20260922003000_workspace_folder_and_file_name_freed_by_delete/migration.sql b/autogpt_platform/backend/migrations/20260922003000_workspace_folder_and_file_name_freed_by_delete/migration.sql
new file mode 100644
index 0000000000..ae13c207ec
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260922003000_workspace_folder_and_file_name_freed_by_delete/migration.sql
@@ -0,0 +1,28 @@
+-- A soft-deleted nested folder kept its name reserved under its parent forever:
+-- the Prisma-generated composite unique index carried no isDeleted predicate,
+-- while the root index added with the table has always excluded deleted rows.
+-- Nesting makes that asymmetry reachable — deleting "Invoices/2026" and
+-- creating it again answered 409 — so replace it with a partial index shaped
+-- like the root one. Named differently, and dropped from schema.prisma, so
+-- Prisma stops expecting an unqualified index it cannot express.
+DROP INDEX "UserWorkspaceFolder_workspaceId_parentId_name_key";
+
+CREATE UNIQUE INDEX "UserWorkspaceFolder_workspaceId_parentId_name_live_key" ON "UserWorkspaceFolder"("workspaceId", "parentId", "name") WHERE "isDeleted" = false;
+
+-- Files reserved their path the same way, and bought the freedom back in code:
+-- soft-delete renamed the row ("/a.txt" -> "/a.txt__deleted__<ts>"). That put
+-- the guarantee in one function rather than the schema, and it had already
+-- failed once — a second-resolution suffix gave two deletes in one second the
+-- same name, so the second rename hit the very index it exists to dodge. Give
+-- files the folders' constraint instead, and let a deleted row keep the path
+-- it was deleted at.
+DROP INDEX "UserWorkspaceFile_workspaceId_path_key";
+
+CREATE UNIQUE INDEX "UserWorkspaceFile_workspaceId_path_live_key" ON "UserWorkspaceFile"("workspaceId", "path") WHERE "isDeleted" = false;
+
+-- Give the rows the old rename mangled their paths back: the index skips
+-- deleted rows, so a restored path collides with nothing. Both suffixes ever
+-- written are matched, the integer timestamp and the microsecond one.
+UPDATE "UserWorkspaceFile"
+SET "path" = regexp_replace("path", '__deleted__[0-9]+(\.[0-9]+)?$', '')
+WHERE "isDeleted" = true AND "path" ~ '__deleted__[0-9]+(\.[0-9]+)?$';
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index cffc04a818..2665c2fb08 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -523,7 +523,10 @@ model UserWorkspaceFile {
SharedExecutionFiles SharedExecutionFile[]
SharedChatFiles SharedChatFile[]
- @@unique([workspaceId, path])
+ // Paths are unique among LIVE files, which Prisma cannot express: the rule is
+ // a partial unique index created in migrations
+ // ("UserWorkspaceFile_workspaceId_path_live_key"). A soft-deleted row keeps
+ // the path it was deleted at.
@@index([workspaceId, isDeleted])
@@index([folderId])
}
@@ -541,7 +544,7 @@ model UserWorkspaceFolder {
name String
icon String?
- // Forward-compat for nesting; unused by the v1 API (always null).
+ // Null = a folder at the workspace root.
parentId String?
Parent UserWorkspaceFolder? @relation("WorkspaceFolderHierarchy", fields: [parentId], references: [id], onDelete: Cascade)
Children UserWorkspaceFolder[] @relation("WorkspaceFolderHierarchy")
@@ -550,7 +553,9 @@ model UserWorkspaceFolder {
Files UserWorkspaceFile[]
- @@unique([workspaceId, parentId, name])
+ // Names are unique among LIVE siblings, which Prisma cannot express: both
+ // rules are partial unique indexes created in migrations
+ // ("..._workspaceId_parentId_name_live_key" and "..._workspaceId_name_root_key").
@@index([workspaceId, isDeleted])
}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index e19303e97a..d09d9aad1c 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -16223,7 +16223,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.\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.",
+ "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 that hired expert's own\nconversations. It conflicts with ``session_id`` — both name which\nconversations to show — but composes with the folder filters, which select\nacross the whole workspace. An expert the caller does not own (or no\nlonger has) yields an empty list.\n\n``include_user_files`` widens an ``expert_id`` listing with the user's own\nfiles, which an expert may read but which are nobody's conversation. It is\nopt-in so that a view already filtered to one expert keeps showing that\nexpert's files and nothing else; the composer's picker sends it when its\n\"only this expert\" filter is switched off.",
"operationId": "listWorkspaceFiles",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -16319,10 +16319,22 @@
{ "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.",
+ "description": "Only return files from this hired expert's own conversations. Combines with folder_id, root_only and include_user_files; cannot be combined with session_id.",
"title": "Expert Id"
},
- "description": "Only return files from this hired expert's conversations. Cannot be combined with session_id, folder_id or root_only."
+ "description": "Only return files from this hired expert's own conversations. Combines with folder_id, root_only and include_user_files; cannot be combined with session_id."
+ },
+ {
+ "name": "include_user_files",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "boolean",
+ "description": "With expert_id, also return the user's own files — everything outside /sessions/, /experts/ and /skills/ — which the expert may read but which are not its own. Requires expert_id.",
+ "default": false,
+ "title": "Include User Files"
+ },
+ "description": "With expert_id, also return the user's own files — everything outside /sessions/, /experts/ and /skills/ — which the expert may read but which are not its own. Requires expert_id."
}
],
"responses": {
@@ -16594,6 +16606,7 @@
"get": {
"tags": ["workspace"],
"summary": "List workspace folders",
+ "description": "Every folder in the workspace, flat; nesting is read off ``parent_id``.\n\n``file_count`` counts the files directly in each folder, not its subtree.",
"operationId": "listWorkspaceFolders",
"responses": {
"200": {
@@ -16638,6 +16651,7 @@
"401": {
"$ref": "#/components/responses/HTTP401NotAuthenticatedError"
},
+ "404": { "description": "Parent folder not found" },
"409": { "description": "A folder with this name already exists" },
"422": {
"description": "Validation Error",
@@ -16696,6 +16710,7 @@
"delete": {
"tags": ["workspace"],
"summary": "Delete workspace folder",
+ "description": "Delete a folder and its subfolders; their files return to the root.",
"operationId": "deleteWorkspaceFolder",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -16725,6 +16740,7 @@
"patch": {
"tags": ["workspace"],
"summary": "Update workspace folder",
+ "description": "Rename a folder, change its icon, and/or move it.\n\nSending ``parent_id: null`` moves the folder to the workspace root;\nleaving the field out keeps it where it is. Move and rename are applied\ntogether or not at all, and the new name is checked for a clash against\nthe destination.",
"operationId": "updateWorkspaceFolder",
"security": [{ "HTTPBearerJWT": [] }],
"parameters": [
@@ -16754,10 +16770,13 @@
}
}
},
+ "400": {
+ "description": "A folder cannot be moved into its own subtree"
+ },
"401": {
"$ref": "#/components/responses/HTTP401NotAuthenticatedError"
},
- "404": { "description": "Folder not found" },
+ "404": { "description": "Folder or destination not found" },
"409": { "description": "A folder with this name already exists" },
"422": {
"description": "Validation Error",
@@ -27632,6 +27651,13 @@
{ "type": "null" }
],
"title": "File Ids"
+ },
+ "folder_ids": {
+ "anyOf": [
+ { "items": { "type": "string" }, "type": "array", "maxItems": 5 },
+ { "type": "null" }
+ ],
+ "title": "Folder Ids"
}
},
"type": "object",
@@ -29989,6 +30015,14 @@
],
"title": "File Ids"
},
+ "folder_ids": {
+ "anyOf": [
+ { "items": { "type": "string" }, "type": "array", "maxItems": 5 },
+ { "type": "null" }
+ ],
+ "title": "Folder Ids",
+ "description": "Workspace folder IDs attached to this message. Named in the message for the model to open, never expanded into their files."
+ },
"model": {
"anyOf": [
{ "type": "string", "enum": ["standard", "advanced"] },
@@ -33206,6 +33240,10 @@
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Icon"
},
+ "parent_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Parent Id"
+ },
"created_at": {
"type": "string",
"format": "date-time",
@@ -33238,6 +33276,10 @@
"icon": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Icon"
+ },
+ "parent_id": {
+ "anyOf": [{ "type": "string", "minLength": 1 }, { "type": "null" }],
+ "title": "Parent Id"
}
},
"type": "object",
@@ -33268,6 +33310,10 @@
"icon": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Icon"
+ },
+ "parent_id": {
+ "anyOf": [{ "type": "string", "minLength": 1 }, { "type": "null" }],
+ "title": "Parent Id"
}
},
"type": "object",