Skip to content

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

fix(backend/copilot-bot): session-scope bot file uploads so AutoPilot can read them (#13464)

Bently4b85b935bd83
diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
index 2d025507fe..919a78d2b6 100644
--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py
@@ -321,18 +321,41 @@ class BotBackend:
for s in resp.sessions
]
+ async def ensure_session(
+ self,
+ platform: str,
+ platform_user_id: str,
+ platform_server_id: str | None,
+ session_id: str | None,
+ ) -> str:
+ """Resolve (or create) the copilot session for this conversation.
+
+ Called before uploading attachments so they land in the session folder
+ (``/sessions/<id>/``) where AutoPilot reads them — the same way the web
+ UI uploads into an already-open session.
+ """
+ return await self._client.ensure_chat_session(
+ platform=Platform(platform.upper()),
+ platform_user_id=platform_user_id,
+ platform_server_id=platform_server_id,
+ session_id=session_id,
+ )
+
async def upload_workspace_files(
self,
platform: str,
platform_user_id: str,
platform_server_id: str | None,
attachments: tuple[InboundAttachment, ...],
+ session_id: str | None = None,
) -> list[WorkspaceUploadResult]:
"""Upload each attachment into the conversation owner's workspace.
- Returns one result per file (with a ``file_id`` on success or an
- ``error`` code) so the caller can attach the successes to the turn and
- tell the user about any that were rejected.
+ ``session_id`` scopes the files to the turn's session so AutoPilot can
+ read them, matching the web upload. Returns one result per file (with a
+ ``file_id`` on success or an ``error`` code) so the caller can attach
+ the successes to the turn and tell the user about any that were
+ rejected.
"""
platform_enum = Platform(platform.upper())
results: list[WorkspaceUploadResult] = []
@@ -349,6 +372,7 @@ class BotBackend:
filename=attachment.filename,
mime_type=attachment.mime_type,
content=attachment.content,
+ session_id=session_id,
)
)
)
diff --git a/autogpt_platform/backend/backend/copilot/bot/handler.py b/autogpt_platform/backend/backend/copilot/bot/handler.py
index d72feeec8d..126f0985a0 100644
--- a/autogpt_platform/backend/backend/copilot/bot/handler.py
+++ b/autogpt_platform/backend/backend/copilot/bot/handler.py
@@ -63,15 +63,57 @@ class TargetState:
# Workspace file IDs uploaded for messages in `pending`, drained together
# with them so a batched turn carries every attached file.
pending_file_ids: list[str] = field(default_factory=list)
+ # Session the pending attachments were uploaded to, carried straight to the
+ # turn so it uses the same session (not a separate Redis read that could
+ # diverge). None for text-only batches, which resolve the session normally.
+ session_id: str | None = None
class MessageHandler:
def __init__(self, api: BotBackend):
self._api = api
self._targets: dict[str, TargetState] = {}
+ # Per-target lock serialising session resolution, so two attachment
+ # messages racing on a fresh target converge on ONE session instead of
+ # each creating its own and splitting the files across them.
+ self._session_locks: dict[str, asyncio.Lock] = {}
# Strong-ref set so the GC doesn't drop fire-and-forget rename tasks.
self._rename_tasks: set[asyncio.Task[None]] = set()
+ def _session_lock(self, target_id: str) -> asyncio.Lock:
+ lock = self._session_locks.get(target_id)
+ if lock is None:
+ lock = asyncio.Lock()
+ self._session_locks[target_id] = lock
+ return lock
+
+ async def _resolve_session_for_attachments(
+ self, ctx: MessageContext, target_id: str
+ ) -> str | None:
+ """Resolve (or create) the session this message's attachments upload
+ into, so they land where the turn will read them (``/sessions/<id>/``).
+
+ Serialised per target so concurrent attachment messages converge on one
+ session instead of splitting the files. Returns None on failure — the
+ caller then reports the files as un-attachable rather than uploading
+ them somewhere AutoPilot can't see.
+ """
+ async with self._session_lock(target_id):
+ try:
+ session_id = await self._api.ensure_session(
+ platform=ctx.platform,
+ platform_user_id=ctx.user_id,
+ platform_server_id=ctx.server_id,
+ session_id=await sessions.get_session(ctx.platform, target_id),
+ )
+ await sessions.set_session(ctx.platform, target_id, session_id)
+ return session_id
+ except Exception:
+ logger.exception(
+ "Failed to resolve session for uploads (user %s)", ctx.user_id
+ )
+ return None
+
async def handle(self, ctx: MessageContext, adapter: PlatformAdapter) -> None:
if not ctx.text.strip() and not ctx.attachments:
if ctx.channel_type == "channel":
@@ -112,7 +154,28 @@ class MessageHandler:
char_count=len(ctx.text),
)
- file_ids, upload_problems = await self._upload_attachments(ctx)
+ # Attachments must be written into the turn's session folder so
+ # AutoPilot can read them (same as a web upload), and the turn must run
+ # in that same session — resolve it up front and thread it through.
+ session_id: str | None = None
+ file_ids: list[str]
+ upload_problems: list[tuple[str, str]]
+ if ctx.attachments:
+ session_id = await self._resolve_session_for_attachments(ctx, target_id)
+ if session_id is None:
+ # Without a session the files can't be made readable to
+ # AutoPilot, so report them as failed rather than uploading
+ # them somewhere it can't see.
+ file_ids = []
+ upload_problems = [
+ (a.filename, "couldn't be uploaded") for a in ctx.attachments
+ ]
+ else:
+ file_ids, upload_problems = await self._upload_attachments(
+ ctx, session_id
+ )
+ else:
+ file_ids, upload_problems = await self._upload_attachments(ctx)
# Files that didn't make it: adapter-stage (too large / failed download)
# plus upload-stage (virus / quota). Tell the user AND, below, the model
@@ -138,16 +201,19 @@ class MessageHandler:
message_text = self._message_text(ctx, include_thread_history, current_text)
if problems:
message_text += "\n\n" + _model_attachment_note(problems)
- await self._enqueue_and_process(ctx, adapter, target_id, message_text, file_ids)
+ await self._enqueue_and_process(
+ ctx, adapter, target_id, message_text, file_ids, session_id
+ )
async def _upload_attachments(
- self, ctx: MessageContext
+ self, ctx: MessageContext, session_id: str | None = None
) -> tuple[list[str], list[tuple[str, str]]]:
"""Upload the user's attachments to the workspace.
- Returns ``(file_ids, problems)`` — the IDs that succeeded, and
- ``(filename, reason)`` for the ones that were rejected — so the caller
- can attach the successes and surface the failures.
+ ``session_id`` scopes the files to the turn's session so AutoPilot can
+ read them. Returns ``(file_ids, problems)`` — the IDs that succeeded,
+ and ``(filename, reason)`` for the ones that were rejected — so the
+ caller can attach the successes and surface the failures.
"""
if not ctx.attachments:
return [], []
@@ -157,6 +223,7 @@ class MessageHandler:
platform_user_id=ctx.user_id,
platform_server_id=ctx.server_id,
attachments=ctx.attachments,
+ session_id=session_id,
)
except Exception:
# The upload path itself failed (not a per-file rejection). Don't
@@ -253,11 +320,16 @@ class MessageHandler:
target_id: str,
message_text: str | None = None,
file_ids: list[str] | None = None,
+ session_id: str | None = None,
) -> None:
state = self._targets.setdefault(target_id, TargetState())
state.pending.append((ctx.username, ctx.user_id, message_text or ctx.text))
if file_ids:
state.pending_file_ids.extend(file_ids)
+ # First attachment message in a batch pins the session; later ones
+ # resolved the same session (serialised by _session_lock), so keep it.
+ if session_id and state.session_id is None:
+ state.session_id = session_id
if state.processing:
# Another invocation is streaming for this target — it will pick
@@ -269,8 +341,10 @@ class MessageHandler:
while state.pending:
batch = list(state.pending)
batch_file_ids = list(state.pending_file_ids)
+ batch_session_id = state.session_id
state.pending.clear()
state.pending_file_ids.clear()
+ state.session_id = None
if len(batch_file_ids) > MAX_TURN_FILE_IDS:
logger.warning(
"Dropping %d batched file(s) over the per-turn cap of %d",
@@ -279,7 +353,12 @@ class MessageHandler:
)
batch_file_ids = batch_file_ids[:MAX_TURN_FILE_IDS]
await self._stream_batch(
- batch, ctx, adapter, target_id, file_ids=batch_file_ids
+ batch,
+ ctx,
+ adapter,
+ target_id,
+ file_ids=batch_file_ids,
+ session_id=batch_session_id,
)
finally:
state.processing = False
@@ -414,17 +493,23 @@ class MessageHandler:
adapter: PlatformAdapter,
target_id: str,
file_ids: list[str] | None = None,
+ session_id: str | None = None,
) -> None:
prefixed = format_batch(batch, ctx.platform)
redis = await get_redis_async()
cache_key = sessions.session_cache_key(ctx.platform, target_id)
- cached_session_id = await redis.get(cache_key)
- active_session_id = (
- cached_session_id.decode()
- if isinstance(cached_session_id, bytes)
- else cached_session_id
- )
+ if session_id is not None:
+ # Attachments were already uploaded to this session — use it
+ # directly so the turn can't diverge from where the files went.
+ active_session_id: str | None = session_id
+ else:
+ cached_session_id = await redis.get(cache_key)
+ active_session_id = (
+ cached_session_id.decode()
+ if isinstance(cached_session_id, bytes)
+ else cached_session_id
+ )
async def _on_session_id(sid: str) -> None:
nonlocal active_session_id
diff --git a/autogpt_platform/backend/backend/copilot/bot/handler_test.py b/autogpt_platform/backend/backend/copilot/bot/handler_test.py
index 1ecd3ccef9..bbccdc3205 100644
--- a/autogpt_platform/backend/backend/copilot/bot/handler_test.py
+++ b/autogpt_platform/backend/backend/copilot/bot/handler_test.py
@@ -86,6 +86,7 @@ def _api(*, server_linked: bool = True, user_linked: bool = True) -> MagicMock:
)
api.fetch_workspace_artifact = AsyncMock(return_value=None)
api.upload_workspace_files = AsyncMock(return_value=[])
+ api.ensure_session = AsyncMock(return_value="session-ensured")
async def _empty_stream(*args, **kwargs):
if False:
@@ -408,7 +409,9 @@ class TestBatching:
stream_calls: list[list] = []
- async def fake_stream_batch(batch, ctx, ad, tid, file_ids=None):
+ async def fake_stream_batch(
+ batch, ctx, ad, tid, file_ids=None, session_id=None
+ ):
stream_calls.append(list(batch))
handler._stream_batch = fake_stream_batch # type: ignore[method-assign]
@@ -429,7 +432,9 @@ class TestBatching:
seen: list[list] = []
- async def fake_stream_batch(batch, ctx, ad, tid, file_ids=None):
+ async def fake_stream_batch(
+ batch, ctx, ad, tid, file_ids=None, session_id=None
+ ):
seen.append(list(batch))
if len(seen) == 1:
# Simulate another caller appending during the first stream.
@@ -936,6 +941,26 @@ class TestMessageTextReferencedConversations:
class TestAttachments:
+ @pytest.fixture(autouse=True)
+ def _mock_redis(self):
+ # These tests drive handle() end-to-end, which touches Redis: the
+ # upload path resolves the session cache, and _stream_batch reads the
+ # per-target session key. Mock both so the tests stay hermetic.
+ redis = AsyncMock()
+ redis.get = AsyncMock(return_value=None)
+ with (
+ patch(
+ "backend.copilot.bot.handler.sessions.get_session",
+ new=AsyncMock(return_value=None),
+ ),
+ patch("backend.copilot.bot.handler.sessions.set_session", new=AsyncMock()),
+ patch(
+ "backend.copilot.bot.handler.get_redis_async",
+ new=AsyncMock(return_value=redis),
+ ),
+ ):
+ yield
+
@staticmethod
def _upload_recording_api(results):
api = _api()
@@ -945,6 +970,7 @@ class TestAttachments:
async def _recording_stream(*args, **kwargs):
captured["file_ids"] = kwargs.get("file_ids")
captured["message"] = kwargs.get("message")
+ captured["session_id"] = kwargs.get("session_id")
if False:
yield ""
@@ -978,6 +1004,50 @@ class TestAttachments:
api.upload_workspace_files.assert_awaited_once()
assert captured["file_ids"] == ["f1"]
+ @pytest.mark.asyncio
+ async def test_uploads_are_session_scoped_via_ensure_session(self):
+ results = [WorkspaceUploadResult(filename="a.png", file_id="f1")]
+ api, captured = self._upload_recording_api(results)
+ handler = MessageHandler(api)
+ adapter = _adapter()
+
+ await handler.handle(self._dm_ctx("look", [("a.png", "image/png")]), adapter)
+
+ # The session is resolved up front and threaded into BOTH the upload
+ # and the turn — the turn uses the exact session the file went to, not a
+ # separate Redis read that could diverge.
+ api.ensure_session.assert_awaited_once()
+ assert (
+ api.upload_workspace_files.await_args.kwargs["session_id"]
+ == "session-ensured"
+ )
+ assert captured["session_id"] == "session-ensured"
+
+ @pytest.mark.asyncio
+ async def test_session_resolution_failure_reports_files_as_failed(self):
+ results = [WorkspaceUploadResult(filename="a.png", file_id="f1")]
+ api, captured = self._upload_recording_api(results)
+ api.ensure_session = AsyncMock(side_effect=RuntimeError("rpc down"))
+ handler = MessageHandler(api)
+ adapter = _adapter()
+
+ await handler.handle(self._dm_ctx("look", [("a.png", "image/png")]), adapter)
+
+ # Files are NOT uploaded sessionless (where AutoPilot couldn't read
+ # them); the user is told they couldn't be attached and no file_ids
+ # reach the turn.
+ api.upload_workspace_files.assert_not_awaited()
+ assert "a.png" in adapter.send_message.await_args_list[0].args[1]
+ assert captured["file_ids"] == []
+
+ def test_session_lock_is_stable_per_target(self):
+ # Concurrent attachment messages on the same target serialise on one
+ # lock (so they converge on one session); different targets don't block.
+ handler = MessageHandler(_api())
+ lock = handler._session_lock("t-1")
+ assert handler._session_lock("t-1") is lock
+ assert handler._session_lock("t-2") is not lock
+
@pytest.mark.asyncio
async def test_failed_upload_is_reported_and_good_files_still_sent(self):
results = [
@@ -1082,7 +1152,9 @@ class TestAttachments:
adapter = _adapter()
captured: list[list[str] | None] = []
- async def fake_stream_batch(batch, ctx, ad, tid, file_ids=None):
+ async def fake_stream_batch(
+ batch, ctx, ad, tid, file_ids=None, session_id=None
+ ):
captured.append(file_ids)
handler._stream_batch = fake_stream_batch # type: ignore[method-assign]
diff --git a/autogpt_platform/backend/backend/copilot/bot/sessions.py b/autogpt_platform/backend/backend/copilot/bot/sessions.py
index b9dbf30acb..3b295fe194 100644
--- a/autogpt_platform/backend/backend/copilot/bot/sessions.py
+++ b/autogpt_platform/backend/backend/copilot/bot/sessions.py
@@ -15,6 +15,12 @@ def session_cache_key(platform: str, target_id: str) -> str:
return f"copilot-bot:session:{platform}:{target_id}"
+async def get_session(platform: str, target_id: str) -> str | None:
+ redis = await get_redis_async()
+ cached = await redis.get(session_cache_key(platform, target_id))
+ return cached.decode() if isinstance(cached, bytes) else cached
+
+
async def set_session(platform: str, target_id: str, session_id: str) -> None:
redis = await get_redis_async()
await redis.set(session_cache_key(platform, target_id), session_id, ex=SESSION_TTL)
diff --git a/autogpt_platform/backend/backend/platform_linking/chat.py b/autogpt_platform/backend/backend/platform_linking/chat.py
index 23464140b4..e39748d9e5 100644
--- a/autogpt_platform/backend/backend/platform_linking/chat.py
+++ b/autogpt_platform/backend/backend/platform_linking/chat.py
@@ -1,7 +1,6 @@
"""Chat-turn orchestration for the platform bot bridge."""
import logging
-import os
from uuid import uuid4
from backend.api.features.store.exceptions import VirusDetectedError, VirusScanError
@@ -9,6 +8,7 @@ from backend.copilot import stream_registry
from backend.copilot.executor.utils import enqueue_copilot_turn
from backend.copilot.model import (
ChatMessage,
+ ChatSession,
append_and_save_message,
create_chat_session,
get_chat_session,
@@ -79,26 +79,30 @@ async def upload_workspace_file(
request.platform_server_id,
request.platform_user_id,
)
- # Strip any directory components a (possibly hostile) client put in the
- # filename so it can't traverse the workspace path or leak ".."/separators
- # into the storage backend (e.g. GCS blob names). write_file passes the
- # filename through to storage, so use the sanitized name everywhere.
- # Basename alone still yields "."/".." for those inputs, which would re-
- # introduce a special segment into uploads/<uuid>/<name>, so reject them.
- safe_name = os.path.basename(request.filename.replace("\\", "/"))
+ # Reduce the filename to its basename so a (possibly hostile) client can't
+ # traverse the workspace path or leak ".."/separators into the storage
+ # backend. Workspace paths are POSIX, so split on "/" (after normalising
+ # backslashes) rather than os.path. Reject "."/".." which survive that.
+ safe_name = request.filename.replace("\\", "/").rsplit("/", 1)[-1]
if safe_name in {"", ".", ".."}:
safe_name = "file"
try:
workspace = await workspace_db().get_or_create_workspace(owner_user_id)
- manager = WorkspaceManager(owner_user_id, workspace.id)
+ # Session-scoped, exactly like the web upload endpoint: the file lands
+ # at /sessions/<session_id>/<name> so AutoPilot reads it during the
+ # turn. The caller resolves the session before uploading (see
+ # ensure_chat_session).
+ manager = WorkspaceManager(owner_user_id, workspace.id, request.session_id)
stored = await manager.write_file(
content=request.content,
filename=safe_name,
- # Unique sub-path so re-uploading a file with the same name (e.g.
- # two ``test.txt``) is a fresh file, not a path conflict.
- path=f"uploads/{uuid4().hex}/{safe_name}",
mime_type=request.mime_type,
metadata={"origin": "user-upload"},
+ # Re-uploading a same-named file in the conversation replaces it
+ # rather than erroring — without this a name collision raises
+ # ValueError that would be mislabelled a "too large / quota"
+ # rejection. Keeps the ValueError branch below meaning only that.
+ overwrite=True,
)
except VirusDetectedError:
return WorkspaceUploadResult(filename=request.filename, error="virus_detected")
@@ -119,26 +123,63 @@ async def upload_workspace_file(
return WorkspaceUploadResult(filename=request.filename, file_id=stored.id)
-async def start_chat_turn(request: BotChatRequest) -> ChatTurnHandle:
- """Prepare a copilot turn; caller subscribes via the returned handle.
+async def _resolve_or_create_session(
+ owner_user_id: str, session_id: str | None, source_platform: str
+) -> ChatSession:
+ """Reuse the bot's cached session, or start a fresh one.
- ``subscribe_from="0-0"`` on the handle means a late subscriber replays
- the full stream (Redis Streams, not pub/sub).
+ The bot caches session IDs across turns and a cached session can be
+ deleted from the web app in between — fall back to a new one so the
+ conversation self-heals instead of erroring.
"""
- owner_user_id = await resolve_chat_owner(request)
-
session = None
- session_id = request.session_id
if session_id:
session = await get_chat_session(session_id, owner_user_id)
if session is None:
- # The bot caches session IDs across turns and a cached session can
- # be deleted from the web app in between — fall back to a fresh one
- # so the conversation self-heals instead of erroring every turn.
session = await create_chat_session(
- owner_user_id,
- dry_run=False,
- source_platform=request.platform.value.lower(),
+ owner_user_id, dry_run=False, source_platform=source_platform
+ )
+ return session
+
+
+async def ensure_chat_session(
+ platform: Platform,
+ platform_user_id: str,
+ platform_server_id: str | None,
+ session_id: str | None,
+) -> str:
+ """Resolve (or create) the session for a bot conversation, return its ID.
+
+ Called before uploading attachments so they can be written into the
+ session folder — mirroring the web UI, which uploads into an already-open
+ session so files land at /sessions/<id>/ where AutoPilot reads them.
+ """
+ owner_user_id = await _resolve_owner(
+ platform.value, platform_server_id, platform_user_id
+ )
+ session = await _resolve_or_create_session(
+ owner_user_id, session_id, platform.value.lower()
+ )
+ return session.session_id
+
+
+async def start_chat_turn(request: BotChatRequest) -> ChatTurnHandle:
+ """Prepare a copilot turn; caller subscribes via the returned handle.
+
+ ``subscribe_from="0-0"`` on the handle means a late subscriber replays
+ the full stream (Redis Streams, not pub/sub).
+ """
+ owner_user_id = await resolve_chat_owner(request)
+ if request.file_ids and request.session_id:
+ # Attachment turn: the files were already uploaded into this session
+ # (ensure_chat_session ran first). It must still exist — silently
+ # switching to a new session would orphan those files. Fail instead.
+ session = await get_chat_session(request.session_id, owner_user_id)
+ if session is None:
+ raise NotFoundError("The session for the uploaded files no longer exists.")
+ else:
+ session = await _resolve_or_create_session(
+ owner_user_id, request.session_id, request.platform.value.lower()
)
session_id = session.session_id
diff --git a/autogpt_platform/backend/backend/platform_linking/chat_test.py b/autogpt_platform/backend/backend/platform_linking/chat_test.py
index a2300d107f..958a34cccd 100644
--- a/autogpt_platform/backend/backend/platform_linking/chat_test.py
+++ b/autogpt_platform/backend/backend/platform_linking/chat_test.py
@@ -8,7 +8,12 @@ import pytest
from backend.api.features.store.exceptions import VirusDetectedError, VirusScanError
from backend.util.exceptions import DuplicateChatMessageError, NotFoundError
-from .chat import list_user_chats, start_chat_turn, upload_workspace_file
+from .chat import (
+ ensure_chat_session,
+ list_user_chats,
+ start_chat_turn,
+ upload_workspace_file,
+)
from .models import BotChatRequest, Platform, WorkspaceUploadRequest
@@ -152,6 +157,30 @@ class TestStartChatTurn:
assert handle.session_id == "sess-fresh"
mock_create.assert_awaited_once()
+ @pytest.mark.asyncio
+ async def test_attachment_turn_with_missing_session_raises(self):
+ # An attachment turn's files are pinned to the supplied session; if it's
+ # gone, fail rather than silently switching to a new (fileless) session.
+ db_mock = MagicMock()
+ db_mock.find_user_link_owner = AsyncMock(return_value="owner-1")
+ with (
+ patch(
+ "backend.platform_linking.chat.platform_linking_db",
+ return_value=db_mock,
+ ),
+ patch(
+ "backend.platform_linking.chat.get_chat_session",
+ new=AsyncMock(return_value=None),
+ ),
+ patch(
+ "backend.platform_linking.chat.create_chat_session", new=AsyncMock()
+ ) as mock_create,
+ ):
+ with pytest.raises(NotFoundError):
+ await start_chat_turn(_request(session_id="gone", file_ids=["f1"]))
+
+ mock_create.assert_not_awaited()
+
class TestListUserChats:
@pytest.mark.asyncio
@@ -292,30 +321,42 @@ class TestUploadWorkspaceFile:
assert result.error == "upload_failed"
@pytest.mark.asyncio
- async def test_filename_path_components_are_stripped_from_storage_path(self):
+ async def test_writes_into_session_scoped_manager(self):
+ write = AsyncMock(return_value=MagicMock(id="file-1"))
+ p1, p2, p3 = self._patches(write)
+ with p1, p2, p3 as mock_wm:
+ await upload_workspace_file(self._req(session_id="sess-1"))
+ # Session-scoped manager (like the web upload) plus a flat filename —
+ # write_file defaults the path to /sessions/<id>/<name> where AutoPilot
+ # reads it. No explicit uploads/<uuid> path.
+ mock_wm.assert_called_once_with("owner-1", "ws-1", "sess-1")
+ kwargs = write.await_args.kwargs
+ assert kwargs["filename"] == "a.png"
+ assert "path" not in kwargs
+ # Overwrite so a re-uploaded same-named file replaces rather than
+ # erroring (a conflict would be mislabelled a size/quota rejection).
+ assert kwargs["overwrite"] is True
+
+ @pytest.mark.asyncio
+ async def test_filename_path_components_are_stripped(self):
write = AsyncMock(return_value=MagicMock(id="file-1"))
p1, p2, p3 = self._patches(write)
with p1, p2, p3:
await upload_workspace_file(self._req(filename="../../etc/passwd"))
- # Neither the storage path nor the filename passed to the storage
- # backend may carry traversal segments — only the sanitized basename.
+ # Only the sanitized basename reaches the storage backend.
kwargs = write.await_args.kwargs
- assert ".." not in kwargs["path"]
- assert kwargs["path"].endswith("/passwd")
assert kwargs["filename"] == "passwd"
@pytest.mark.asyncio
@pytest.mark.parametrize("name", [".", "..", "dir/..", "/"])
async def test_dot_filenames_fall_back_to_safe_name(self, name: str):
- # Basename of "."/".." is still "."/"..", which would re-introduce a
- # special segment into uploads/<uuid>/<name>; they must become "file".
+ # "."/".." survive basename stripping and would be a special path
+ # segment, so they must become "file".
write = AsyncMock(return_value=MagicMock(id="file-1"))
p1, p2, p3 = self._patches(write)
with p1, p2, p3:
await upload_workspace_file(self._req(filename=name))
- kwargs = write.await_args.kwargs
- assert kwargs["filename"] == "file"
- assert kwargs["path"].endswith("/file")
+ assert write.await_args.kwargs["filename"] == "file"
@pytest.mark.asyncio
async def test_unlinked_user_raises_not_found(self):
@@ -336,3 +377,50 @@ class TestUploadWorkspaceFile:
with p1, p2, p3:
with pytest.raises(NotFoundError):
await upload_workspace_file(self._req())
+
+
+class TestEnsureChatSession:
+ @pytest.mark.asyncio
+ async def test_reuses_valid_cached_session(self):
+ db = MagicMock()
+ db.find_user_link_owner = AsyncMock(return_value="owner-1")
+ with (
+ patch("backend.platform_linking.chat.platform_linking_db", return_value=db),
+ patch(
+ "backend.platform_linking.chat.get_chat_session",
+ new=AsyncMock(return_value=MagicMock(session_id="cached")),
+ ),
+ patch(
+ "backend.platform_linking.chat.create_chat_session", new=AsyncMock()
+ ) as mock_create,
+ ):
+ sid = await ensure_chat_session(Platform.DISCORD, "pu1", None, "cached")
+
+ assert sid == "cached"
+ mock_create.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_creates_session_when_none_cached(self):
+ db = MagicMock()
+ db.find_user_link_owner = AsyncMock(return_value="owner-1")
+ with (
+ patch("backend.platform_linking.chat.platform_linking_db", return_value=db),
+ patch(
+ "backend.platform_linking.chat.create_chat_session",
+ new=AsyncMock(return_value=MagicMock(session_id="fresh")),
+ ) as mock_create,
+ ):
+ sid = await ensure_chat_session(Platform.DISCORD, "pu1", None, None)
+
+ assert sid == "fresh"
+ assert mock_create.await_args.kwargs["source_platform"] == "discord"
+
+ @pytest.mark.asyncio
+ async def test_unlinked_dm_raises_not_found(self):
+ db = MagicMock()
+ db.find_user_link_owner = AsyncMock(return_value=None)
+ with patch(
+ "backend.platform_linking.chat.platform_linking_db", return_value=db
+ ):
+ with pytest.raises(NotFoundError):
+ await ensure_chat_session(Platform.DISCORD, "pu1", None, None)
diff --git a/autogpt_platform/backend/backend/platform_linking/manager.py b/autogpt_platform/backend/backend/platform_linking/manager.py
index 953d432c87..bef93a9a11 100644
--- a/autogpt_platform/backend/backend/platform_linking/manager.py
+++ b/autogpt_platform/backend/backend/platform_linking/manager.py
@@ -6,7 +6,12 @@ from backend.data.db_accessors import bot_analytics_db, platform_linking_db
from backend.util.service import AppService, AppServiceClient, endpoint_to_async, expose
from backend.util.settings import Settings
-from .chat import list_user_chats, start_chat_turn, upload_workspace_file
+from .chat import (
+ ensure_chat_session,
+ list_user_chats,
+ start_chat_turn,
+ upload_workspace_file,
+)
from .models import (
BotChatRequest,
BotEventInput,
@@ -77,6 +82,18 @@ class PlatformLinkingManager(AppService):
link.platform_server_id for link in links if link.platform == platform.value
]
+ @expose
+ async def ensure_chat_session(
+ self,
+ platform: Platform,
+ platform_user_id: str,
+ platform_server_id: str | None,
+ session_id: str | None,
+ ) -> str:
+ return await ensure_chat_session(
+ platform, platform_user_id, platform_server_id, session_id
+ )
+
@expose
async def start_chat_turn(self, request: BotChatRequest) -> ChatTurnHandle:
return await start_chat_turn(request)
@@ -151,6 +168,7 @@ class PlatformLinkingManagerClient(AppServiceClient):
list_user_server_ids = endpoint_to_async(
PlatformLinkingManager.list_user_server_ids
)
+ ensure_chat_session = endpoint_to_async(PlatformLinkingManager.ensure_chat_session)
start_chat_turn = endpoint_to_async(PlatformLinkingManager.start_chat_turn)
upload_workspace_file = endpoint_to_async(
PlatformLinkingManager.upload_workspace_file
diff --git a/autogpt_platform/backend/backend/platform_linking/models.py b/autogpt_platform/backend/backend/platform_linking/models.py
index b23eaeb0d3..6288ebb24e 100644
--- a/autogpt_platform/backend/backend/platform_linking/models.py
+++ b/autogpt_platform/backend/backend/platform_linking/models.py
@@ -132,6 +132,10 @@ class WorkspaceUploadRequest(BaseModel):
filename: str = Field(min_length=1, max_length=512)
mime_type: str = Field(min_length=1, max_length=255)
content: bytes
+ # Write into this session's folder (/sessions/<id>/) so AutoPilot reads the
+ # file during the turn, same as a web upload. Resolved by the caller before
+ # uploading (see ``ensure_chat_session``).
+ session_id: str | None = Field(default=None, min_length=1, max_length=255)
# ── Response Models ────────────────────────────────────────────────────