AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): share agent chat results via public link (#13081)
Nicholas Tindled8d5d5f2bebc
diff --git a/.gitignore b/.gitignoreindex a70415df80..8c315deece 100644--- a/.gitignore+++ b/.gitignore@@ -211,3 +211,4 @@ test-screenshots/# (``.ign.testing.lock``), and any future ``.ign*`` variant..ign***/.ign*+.claude/scheduled_tasks.lockdiff --git a/autogpt_platform/backend/backend/api/features/chat/share.py b/autogpt_platform/backend/backend/api/features/chat/share.pynew file mode 100644index 0000000000..fdac2c5256--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/chat/share.py@@ -0,0 +1,239 @@+"""HTTP routes for sharing chat sessions.++Three groups of routes:++- **Owner-only** — list linked-execution candidates, enable share with+ opt-ins, disable share. Mirrors the ``/graphs/.../share`` shape on+ :mod:`backend.api.features.v1` for execution sharing.+- **Public-by-token** — the public viewer reads through these+ unauthenticated routes; the share token is the bearer credential.+ Same enumeration defenses as execution sharing (strict UUID path+ validation, allowlist lookup, uniform 404).+"""++import logging+from typing import Annotated++from autogpt_libs import auth+from fastapi import APIRouter, Body, HTTPException, Path, Response, Security+from pydantic import BaseModel+from starlette.status import HTTP_204_NO_CONTENT++from backend.api.features.workspace.routes import create_file_download_response+from backend.copilot.sharing import db as share_db+from backend.copilot.sharing.models import SharedChatMessagesPage, SharedChatSession+from backend.data.sharing.tokens import SHARE_TOKEN_PATTERN+from backend.data.workspace import get_workspace_file_by_id+from backend.util.feature_flag import Flag, is_feature_enabled+from backend.util.settings import Settings++logger = logging.getLogger(__name__)+settings = Settings()+++# --------------------------------------------------------------------------+# Owner-only routes — mounted at the chat router's prefix (``/api/chat``).+# --------------------------------------------------------------------------++owner_router = APIRouter(tags=["chat", "share"])+++class ChatShareStateResponse(BaseModel):+ """Surfaces the chat's current share state so the modal can open+ in the right mode (share-vs-revoke) without an extra round-trip.++ The three counts power the consent-disclosure block above the+ toggle so the owner sees exactly what they're about to expose.+ They reflect live state — sharing is live (not snapshot-at-enable),+ so these numbers are also a lower bound for what subsequent+ viewers will see if more messages / runs / files land before+ revocation.+ """++ is_shared: bool = False+ share_token: str | None = None+ auto_share_executions: bool = False+ message_count: int = 0+ linked_run_count: int = 0+ file_count: int = 0+++class EnableShareRequest(BaseModel):+ """Whether to auto-link every ``run_agent`` execution in this chat.++ When true, the backend creates ``ChatLinkedShare`` rows for every+ existing agent run AND auto-links any new runs that land while the+ share is active. When false, only the chat messages are shared+ (cards in the viewer render in their "execution not shared" state).+ """++ auto_share_executions: bool = False+++class ShareResponse(BaseModel):+ share_url: str+ share_token: str+++@owner_router.get("/sessions/{session_id}/share/state")+async def get_chat_share_state(+ session_id: Annotated[str, Path],+ user_id: Annotated[str, Security(auth.get_user_id)],+) -> ChatShareStateResponse:+ """Return the chat's current share state.++ The share modal calls this on open so it can render in the right+ mode (share-vs-revoke) and pre-select the auto-share toggle.+ """+ state = await share_db.get_chat_share_state(session_id=session_id, user_id=user_id)+ return ChatShareStateResponse(+ is_shared=state.is_shared,+ share_token=state.share_token,+ auto_share_executions=state.auto_share_executions,+ message_count=state.message_count,+ linked_run_count=state.linked_run_count,+ file_count=state.file_count,+ )+++@owner_router.post(+ "/sessions/{session_id}/share",+ responses={+ 403: {"description": "Chat sharing is not enabled for this user"},+ 404: {"description": "Chat session not found for user"},+ },+)+async def enable_chat_sharing(+ session_id: Annotated[str, Path],+ user_id: Annotated[str, Security(auth.get_user_id)],+ body: EnableShareRequest = Body(default_factory=EnableShareRequest),+) -> ShareResponse:+ """Enable sharing for a chat session.++ Flag-gated: refuses with 403 when ``chat-sharing`` is off so a stale+ frontend cannot enable shares post-rollback.+ """+ if not await is_feature_enabled(Flag.CHAT_SHARING, user_id):+ raise HTTPException(status_code=403, detail="Chat sharing is not enabled")++ base_url = settings.config.frontend_base_url+ if not base_url:+ # Fail fast rather than handing the user a localhost URL that+ # only works on the backend host. This catches deployment+ # misconfigurations at share-enable time instead of silently+ # shipping broken share URLs to end users.+ logger.error("frontend_base_url is not configured; refusing to enable share")+ raise HTTPException(+ status_code=500, detail="Sharing is not configured on this deployment"+ )++ try:+ share_token = await share_db.enable_chat_session_share(+ session_id=session_id,+ user_id=user_id,+ auto_share_executions=body.auto_share_executions,+ )+ except ValueError as exc:+ raise HTTPException(status_code=404, detail=str(exc))++ return ShareResponse(+ share_url=f"{base_url}/share/chat/{share_token}",+ share_token=share_token,+ )+++@owner_router.delete(+ "/sessions/{session_id}/share",+ status_code=HTTP_204_NO_CONTENT,+)+async def disable_chat_sharing(+ session_id: Annotated[str, Path],+ user_id: Annotated[str, Security(auth.get_user_id)],+) -> None:+ """Revoke sharing for a chat session.++ Cascade-revokes linked executions whose share originated here+ (``sharedVia == CHAT_LINK``). User-initiated execution shares+ survive — see :func:`backend.copilot.sharing.db.disable_chat_session_share`.+ """+ try:+ await share_db.disable_chat_session_share(+ session_id=session_id, user_id=user_id+ )+ except ValueError as exc:+ raise HTTPException(status_code=404, detail=str(exc))+++# --------------------------------------------------------------------------+# Public routes — mounted at ``/api/public/shared/chats``.+# Stays on even when ``chat-sharing`` flag is off so revoked-then-fixed+# rollbacks don't break already-shared URLs mid-flight.+# --------------------------------------------------------------------------++public_router = APIRouter(tags=["chat", "share", "public"])+++@public_router.get(+ "/{share_token}",+ responses={404: {"description": "Shared chat not found"}},+)+async def get_shared_chat(+ share_token: Annotated[str, Path(pattern=SHARE_TOKEN_PATTERN)],+) -> SharedChatSession:+ session = await share_db.get_chat_session_by_share_token(share_token)+ if not session:+ raise HTTPException(status_code=404, detail="Shared chat not found")+ return session+++@public_router.get(+ "/{share_token}/messages",+ responses={+ 400: {"description": "Invalid limit (must be 1..200)"},+ 404: {"description": "Shared chat not found"},+ },+)+async def get_shared_chat_messages(+ share_token: Annotated[str, Path(pattern=SHARE_TOKEN_PATTERN)],+ limit: int = 50,+ before_sequence: int | None = None,+) -> SharedChatMessagesPage:+ if not 1 <= limit <= 200:+ raise HTTPException(status_code=400, detail="limit must be in [1, 200]")+ page = await share_db.get_shared_chat_messages_paginated(+ share_token, limit=limit, before_sequence=before_sequence+ )+ if page is None:+ raise HTTPException(status_code=404, detail="Shared chat not found")+ return page+++@public_router.get(+ "/{share_token}/files/{file_id}/download",+ summary="Download a file from a shared chat",+ operation_id="download_shared_chat_file",+ responses={+ 404: {+ "description": (+ "Uniform 404 for every failure mode (unknown token, wrong "+ "file id, file no longer present) — prevents enumeration."+ )+ },+ },+)+async def download_shared_chat_file(+ share_token: Annotated[str, Path(pattern=SHARE_TOKEN_PATTERN)],+ file_id: Annotated[str, Path(pattern=SHARE_TOKEN_PATTERN)],+) -> Response:+ """Download a workspace file allowlisted by a shared chat (no auth).++ Returns uniform 404 for every failure mode to prevent enumeration —+ indistinguishable from "unknown token" or "wrong file id".+ """+ session_id = await share_db.get_shared_chat_file(share_token, file_id)+ if not session_id:+ raise HTTPException(status_code=404, detail="Not found")+ file = await get_workspace_file_by_id(file_id)+ if not file:+ raise HTTPException(status_code=404, detail="Not found")+ return await create_file_download_response(file, inline=True)diff --git a/autogpt_platform/backend/backend/api/features/chat/share_test.py b/autogpt_platform/backend/backend/api/features/chat/share_test.pynew file mode 100644index 0000000000..231fc0fa10--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/chat/share_test.py@@ -0,0 +1,328 @@+"""Route tests for chat-share endpoints (no DB)."""++from datetime import datetime, timezone+from unittest.mock import AsyncMock, patch++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+from starlette.responses import Response++from backend.api.features.chat.share import owner_router, public_router+from backend.copilot.sharing.models import (+ SharedChatMessage,+ SharedChatMessagesPage,+ SharedChatSession,+)+from backend.data.workspace import WorkspaceFile++app = FastAPI()+app.include_router(owner_router, prefix="/api/chat")+app.include_router(public_router, prefix="/api/public/shared/chats")++VALID_TOKEN = "550e8400-e29b-41d4-a716-446655440000"+VALID_FILE_ID = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"+SESSION_ID = "cffea7e0-1111-2222-3333-444444444444"+++def _make_workspace_file(**overrides) -> WorkspaceFile:+ defaults = {+ "id": VALID_FILE_ID,+ "workspace_id": "ws-001",+ "created_at": datetime(2026, 1, 1, tzinfo=timezone.utc),+ "updated_at": datetime(2026, 1, 1, tzinfo=timezone.utc),+ "name": "image.png",+ "path": "/image.png",+ "storage_path": "local://uploads/image.png",+ "mime_type": "image/png",+ "size_bytes": 4,+ "checksum": None,+ "is_deleted": False,+ "deleted_at": None,+ "metadata": {},+ }+ defaults.update(overrides)+ return WorkspaceFile(**defaults)+++def _mock_download_response():+ async def _handler(file, *, inline=False):+ return Response(content=b"\x89PNG", media_type="image/png")++ return _handler++[email protected](autouse=True)+def setup_app_auth(mock_jwt_user):+ """Bypass JWT auth for owner-router tests."""+ from autogpt_libs.auth.jwt_utils import get_jwt_payload++ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]+ yield+ app.dependency_overrides.clear()++[email protected](autouse=True)+def mock_frontend_base_url():+ """Pin ``settings.config.frontend_base_url`` for the share-enable path.++ The route fails fast with 500 when this is unset (it'd otherwise+ return a broken localhost URL in production). CI runs without the+ setting populated, so the route tests need an explicit value.+ """+ from backend.api.features.chat import share as share_module++ original = share_module.settings.config.frontend_base_url+ share_module.settings.config.frontend_base_url = "http://localhost:3000"+ yield+ share_module.settings.config.frontend_base_url = original+++def client():+ return TestClient(app, raise_server_exceptions=False)+++class TestEnableChatSharing:+ def test_enables_share_when_flag_on(self, client):+ with (+ patch(+ "backend.api.features.chat.share.is_feature_enabled",+ new_callable=AsyncMock,+ return_value=True,+ ),+ patch(+ "backend.api.features.chat.share.share_db.enable_chat_session_share",+ new_callable=AsyncMock,+ return_value=VALID_TOKEN,+ ),+ ):+ response = client.post(+ f"/api/chat/sessions/{SESSION_ID}/share",+ json={"auto_share_executions": False},+ )+ assert response.status_code == 200+ body = response.json()+ assert body["share_token"] == VALID_TOKEN+ assert body["share_url"].endswith(f"/share/chat/{VALID_TOKEN}")++ def test_enables_share_with_auto_share_executions(self, client):+ captured: dict = {}++ async def fake_enable(**kwargs):+ captured.update(kwargs)+ return VALID_TOKEN++ with (+ patch(+ "backend.api.features.chat.share.is_feature_enabled",+ new_callable=AsyncMock,+ return_value=True,+ ),+ patch(+ "backend.api.features.chat.share.share_db.enable_chat_session_share",+ side_effect=fake_enable,+ ),+ ):+ response = client.post(+ f"/api/chat/sessions/{SESSION_ID}/share",+ json={"auto_share_executions": True},+ )+ assert response.status_code == 200+ # The route must forward the flag down to the data layer so the+ # backend can auto-link existing + future runs.+ assert captured["auto_share_executions"] is True++ def test_flag_off_refuses_with_403(self, client):+ with patch(+ "backend.api.features.chat.share.is_feature_enabled",+ new_callable=AsyncMock,+ return_value=False,+ ):+ response = client.post(+ f"/api/chat/sessions/{SESSION_ID}/share",+ json={"auto_share_executions": False},+ )+ assert response.status_code == 403++ def test_missing_session_returns_404(self, client):+ with (+ patch(+ "backend.api.features.chat.share.is_feature_enabled",+ new_callable=AsyncMock,+ return_value=True,+ ),+ patch(+ "backend.api.features.chat.share.share_db.enable_chat_session_share",+ new_callable=AsyncMock,+ side_effect=ValueError("Chat session not found"),+ ),+ ):+ response = client.post(+ f"/api/chat/sessions/{SESSION_ID}/share",+ json={"auto_share_executions": False},+ )+ assert response.status_code == 404+++class TestDisableChatSharing:+ def test_disables_share(self, client):+ with patch(+ "backend.api.features.chat.share.share_db.disable_chat_session_share",+ new_callable=AsyncMock,+ return_value=None,+ ):+ response = client.delete(f"/api/chat/sessions/{SESSION_ID}/share")+ assert response.status_code == 204++ def test_unknown_session_returns_404(self, client):+ with patch(+ "backend.api.features.chat.share.share_db.disable_chat_session_share",+ new_callable=AsyncMock,+ side_effect=ValueError("Chat session not found"),+ ):+ response = client.delete(f"/api/chat/sessions/{SESSION_ID}/share")+ assert response.status_code == 404+++class TestGetChatShareState:+ def test_returns_unshared_state(self, client):+ from backend.copilot.sharing.models import ChatShareState++ with patch(+ "backend.api.features.chat.share.share_db.get_chat_share_state",+ new_callable=AsyncMock,+ return_value=ChatShareState(+ is_shared=False, share_token=None, auto_share_executions=False+ ),+ ):+ response = client.get(f"/api/chat/sessions/{SESSION_ID}/share/state")+ assert response.status_code == 200+ body = response.json()+ assert body == {+ "is_shared": False,+ "share_token": None,+ "auto_share_executions": False,+ "message_count": 0,+ "linked_run_count": 0,+ "file_count": 0,+ }++ def test_returns_shared_state_with_token_and_auto_share_flag(self, client):+ from backend.copilot.sharing.models import ChatShareState++ with patch(+ "backend.api.features.chat.share.share_db.get_chat_share_state",+ new_callable=AsyncMock,+ return_value=ChatShareState(+ is_shared=True,+ share_token=VALID_TOKEN,+ auto_share_executions=True,+ ),+ ):+ response = client.get(f"/api/chat/sessions/{SESSION_ID}/share/state")+ assert response.status_code == 200+ body = response.json()+ assert body["is_shared"] is True+ assert body["share_token"] == VALID_TOKEN+ assert body["auto_share_executions"] is True+++class TestPublicChatRead:+ def test_unknown_token_returns_404(self, client):+ with patch(+ "backend.api.features.chat.share.share_db.get_chat_session_by_share_token",+ new_callable=AsyncMock,+ return_value=None,+ ):+ response = client.get(f"/api/public/shared/chats/{VALID_TOKEN}")+ assert response.status_code == 404++ def test_returns_sanitized_session(self, client):+ sess = SharedChatSession(+ id=SESSION_ID,+ title="hello",+ created_at=datetime(2026, 5, 11, tzinfo=timezone.utc),+ updated_at=datetime(2026, 5, 11, tzinfo=timezone.utc),+ shared_at=datetime(2026, 5, 12, tzinfo=timezone.utc),+ linked_executions=[],+ )+ with patch(+ "backend.api.features.chat.share.share_db.get_chat_session_by_share_token",+ new_callable=AsyncMock,+ return_value=sess,+ ):+ response = client.get(f"/api/public/shared/chats/{VALID_TOKEN}")+ assert response.status_code == 200+ body = response.json()+ assert body["id"] == SESSION_ID+ # Critical: credentials/metadata must NOT appear in the public payload.+ assert "credentials" not in body+ assert "metadata" not in body++ def test_messages_endpoint_returns_page(self, client):+ page = SharedChatMessagesPage(+ messages=[+ SharedChatMessage(+ id="m1",+ role="assistant",+ content="hi",+ name=None,+ tool_call_id=None,+ tool_calls=None,+ function_call=None,+ sequence=1,+ created_at=datetime(2026, 5, 11, tzinfo=timezone.utc),+ )+ ],+ has_more=False,+ oldest_sequence=1,+ )+ with patch(+ "backend.api.features.chat.share.share_db.get_shared_chat_messages_paginated",+ new_callable=AsyncMock,+ return_value=page,+ ):+ response = client.get(f"/api/public/shared/chats/{VALID_TOKEN}/messages")+ assert response.status_code == 200+ assert response.json()["messages"][0]["content"] == "hi"++ def test_malformed_token_rejected_by_path_pattern(self, client):+ response = client.get("/api/public/shared/chats/not-a-uuid")+ assert response.status_code == 422+++class TestDownloadSharedChatFile:+ def test_uniform_404_for_unknown_token(self, client):+ with patch(+ "backend.api.features.chat.share.share_db.get_shared_chat_file",+ new_callable=AsyncMock,+ return_value=None,+ ):+ response = client.get(+ f"/api/public/shared/chats/{VALID_TOKEN}/files/{VALID_FILE_ID}/download"+ )+ assert response.status_code == 404++ def test_valid_token_returns_inline(self, client):+ with (+ patch(+ "backend.api.features.chat.share.share_db.get_shared_chat_file",+ new_callable=AsyncMock,+ return_value=SESSION_ID,+ ),+ patch(+ "backend.api.features.chat.share.get_workspace_file_by_id",+ new_callable=AsyncMock,+ return_value=_make_workspace_file(),+ ),+ patch(+ "backend.api.features.chat.share.create_file_download_response",+ side_effect=_mock_download_response(),+ ),+ ):+ response = client.get(+ f"/api/public/shared/chats/{VALID_TOKEN}/files/{VALID_FILE_ID}/download"+ )+ assert response.status_code == 200+ assert response.content == b"\x89PNG"diff --git a/autogpt_platform/backend/backend/api/features/store/db_test.py b/autogpt_platform/backend/backend/api/features/store/db_test.pyindex 2959c304fb..fc619590c1 100644--- a/autogpt_platform/backend/backend/api/features/store/db_test.py+++ b/autogpt_platform/backend/backend/api/features/store/db_test.py@@ -627,7 +627,6 @@ async def test_get_my_agents_default_sort_most_recent(mocker):@pytest.mark.asyncio(loop_scope="session")async def test_get_my_agents_sort_by_name(mocker):"""sort_by=NAME orders by AgentGraph.name asc then updatedAt desc."""- now = datetime.now()mock_library = mocker.patch("prisma.models.LibraryAgent.prisma")mock_library.return_value.find_many = AsyncMock(return_value=[])mock_library.return_value.count = AsyncMock(return_value=0)@@ -651,7 +650,6 @@ async def test_get_my_agents_sort_by_name(mocker):@pytest.mark.asyncio(loop_scope="session")async def test_get_my_agents_pagination_window(mocker):"""skip/take honour the requested page so we hit the right offset."""- now = datetime.now()mock_library = mocker.patch("prisma.models.LibraryAgent.prisma")mock_library.return_value.find_many = AsyncMock(return_value=[])mock_library.return_value.count = AsyncMock(return_value=47)diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex afb98f0b30..9442ea93d2 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -2,7 +2,6 @@ import asyncioimport base64import loggingimport time-import uuidfrom collections import defaultdictfrom datetime import datetime, timezonefrom typing import Annotated, Any, Literal, Sequence, cast, get_args@@ -108,6 +107,7 @@ from backend.data.onboarding import (update_user_onboarding,)from backend.data.redis_client import get_redis_async+from backend.data.sharing.tokens import SHARE_TOKEN_PATTERN, generate_share_tokenfrom backend.data.tally import extract_business_understandingfrom backend.data.understanding import (BusinessUnderstandingInput,@@ -2117,20 +2117,26 @@ async def enable_execution_sharing(raise HTTPException(status_code=404, detail="Execution not found")# Generate a unique share token- share_token = str(uuid.uuid4())+ share_token = generate_share_token()# Remove stale allowlist records before updating the token — prevents a# window where old records + new token could coexist.await execution_db.delete_shared_execution_files(execution_id=graph_exec_id)- # Update the execution with share info- await execution_db.update_graph_execution_share_status(- execution_id=graph_exec_id,- user_id=user_id,- is_shared=True,- share_token=share_token,- shared_at=datetime.now(timezone.utc),- )+ # Update the execution with share info — the underlying update_many+ # also enforces (id, user_id) at the DB layer, so a TOCTOU delete+ # between the pre-check above and this write surfaces as 404 rather+ # than a silent no-op.+ try:+ await execution_db.update_graph_execution_share_status(+ execution_id=graph_exec_id,+ user_id=user_id,+ is_shared=True,+ share_token=share_token,+ shared_at=datetime.now(timezone.utc),+ )+ except NotFoundError as exc:+ raise HTTPException(status_code=404, detail=str(exc))# Create allowlist of workspace files referenced in outputsawait execution_db.create_shared_execution_files(@@ -2168,21 +2174,25 @@ async def disable_execution_sharing(# Remove shared file allowlist recordsawait execution_db.delete_shared_execution_files(execution_id=graph_exec_id)- # Remove share info- await execution_db.update_graph_execution_share_status(- execution_id=graph_exec_id,- user_id=user_id,- is_shared=False,- share_token=None,- shared_at=None,- )+ # Remove share info — owner-gated at the DB layer; TOCTOU delete+ # after the pre-check surfaces as 404.+ try:+ await execution_db.update_graph_execution_share_status(+ execution_id=graph_exec_id,+ user_id=user_id,+ is_shared=False,+ share_token=None,+ shared_at=None,+ )+ except NotFoundError as exc:+ raise HTTPException(status_code=404, detail=str(exc))@v1_router.get("/public/shared/{share_token}")async def get_shared_execution(share_token: Annotated[str,- Path(pattern=r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"),+ Path(pattern=SHARE_TOKEN_PATTERN),],) -> execution_db.SharedExecutionResponse:"""Get a shared graph execution by share token (no auth required)."""@@ -2202,11 +2212,11 @@ async def get_shared_execution(async def download_shared_file(share_token: Annotated[str,- Path(pattern=r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"),+ Path(pattern=SHARE_TOKEN_PATTERN),],file_id: Annotated[str,- Path(pattern=r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"),+ Path(pattern=SHARE_TOKEN_PATTERN),],) -> Response:"""Download a workspace file from a shared execution (no auth required).diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.pyindex 13721c6203..006bb68bf0 100644--- a/autogpt_platform/backend/backend/api/rest_api.py+++ b/autogpt_platform/backend/backend/api/rest_api.py@@ -26,6 +26,7 @@ import backend.api.features.admin.store_admin_routesimport backend.api.features.builderimport backend.api.features.builder.routesimport backend.api.features.chat.routes as chat_routes+import backend.api.features.chat.share as chat_shareimport backend.api.features.executions.review.routesimport backend.api.features.library.dbimport backend.api.features.library.model@@ -392,6 +393,16 @@ app.include_router(tags=["v2", "chat"],prefix="/api/chat",)+app.include_router(+ chat_share.owner_router,+ tags=["v2", "chat", "share"],+ prefix="/api/chat",+)+app.include_router(+ chat_share.public_router,+ tags=["v2", "chat", "share", "public"],+ prefix="/api/public/shared/chats",+)app.include_router(workspace_routes.router,tags=["workspace"],diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.pyindex 42df6a7c16..04bd586680 100644--- a/autogpt_platform/backend/backend/copilot/db.py+++ b/autogpt_platform/backend/backend/copilot/db.py@@ -5,6 +5,7 @@ import loggingfrom datetime import UTC, datetimefrom typing import Any+import sentry_sdkfrom prisma.errors import UniqueViolationErrorfrom prisma.models import ChatMessage as PrismaChatMessagefrom prisma.models import ChatSession as PrismaChatSession@@ -554,6 +555,39 @@ async def delete_chat_session(session_id: str, user_id: str | None = None) -> boTrue if deleted successfully, False otherwise."""try:+ # If the session is currently shared, run the share-cascade+ # FIRST so CHAT_LINK execution shares get revoked + their file+ # allowlists cleared. ``ChatLinkedShare.Session`` has+ # ``onDelete: Cascade`` so a flat ``delete_many`` would erase+ # the linkage rows but leave the per-execution share tokens+ # live with no owner-visible path to revoke them — orphan+ # public shares. Lazy import to avoid the copilot→sharing→+ # copilot import cycle.+ if user_id is not None:+ existing = await PrismaChatSession.prisma().find_first(+ where={"id": session_id, "userId": user_id}+ )+ if existing and existing.isShared:+ from backend.copilot.sharing.db import disable_chat_session_share++ try:+ await disable_chat_session_share(+ session_id=session_id, user_id=user_id+ )+ except Exception as cascade_exc:+ # Cascade failure must not block the deletion path —+ # log + Sentry so an operator can manually clean up+ # the per-execution shares. Better to delete the+ # chat (the user's clear intent) and leave a known+ # orphan to chase than to refuse the delete.+ logger.error(+ "Share cascade failed during chat delete for "+ "session=%s; deletion will proceed",+ session_id,+ exc_info=True,+ )+ sentry_sdk.capture_exception(cascade_exc)+# Build typed where clause with optional user_id validationwhere_clause: ChatSessionWhereInput = {"id": session_id}if user_id is not None:diff --git a/autogpt_platform/backend/backend/copilot/db_test.py b/autogpt_platform/backend/backend/copilot/db_test.pyindex e823113181..83a815c803 100644--- a/autogpt_platform/backend/backend/copilot/db_test.py+++ b/autogpt_platform/backend/backend/copilot/db_test.py@@ -62,6 +62,13 @@ def _make_session(title=None,metadata={},chatStatus="idle",+ # Sharing fields added by the chat-sharing PR — even with+ # ``model_construct`` Pydantic v2 still validates required+ # non-optional columns, so the mock needs them explicitly.+ isShared=False,+ shareToken=None,+ sharedAt=None,+ autoShareExecutions=False,Messages=messages or [],)return session@@ -654,6 +661,10 @@ async def test_list_chat_sessions_by_status_returns_app_models_oldest_first() ->metadata="{}",totalPromptTokens=0,totalCompletionTokens=0,+ isShared=False,+ shareToken=None,+ sharedAt=None,+ autoShareExecutions=False,),PrismaChatSession(id="s2",@@ -667,6 +678,10 @@ async def test_list_chat_sessions_by_status_returns_app_models_oldest_first() ->metadata="{}",totalPromptTokens=0,totalCompletionTokens=0,+ isShared=False,+ shareToken=None,+ sharedAt=None,+ autoShareExecutions=False,),]find_many = AsyncMock(return_value=rows)diff --git a/autogpt_platform/backend/backend/copilot/sharing/__init__.py b/autogpt_platform/backend/backend/copilot/sharing/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/copilot/sharing/db.py b/autogpt_platform/backend/backend/copilot/sharing/db.pynew file mode 100644index 0000000000..102156cc2b--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/sharing/db.py@@ -0,0 +1,876 @@+"""Data layer for chat session sharing.++Mirrors :mod:`backend.data.execution`'s share helpers but for+:class:`prisma.models.ChatSession`. Sharing a chat also opts-in a+caller-selected set of :class:`AgentGraphExecution` rows so the public+viewer can drill into the underlying agent run; the cascade rules are+encoded here (see :func:`disable_chat_session_share`).+"""++import json+import logging+from datetime import UTC, datetime+from typing import Any++import sentry_sdk+from prisma.enums import SharedVia+from prisma.errors import ForeignKeyViolationError, UniqueViolationError+from prisma.models import AgentGraph, AgentGraphExecution, ChatLinkedShare+from prisma.models import ChatMessage as PrismaChatMessage+from prisma.models import ChatSession as PrismaChatSession+from prisma.models import (+ SharedChatFile,+ SharedExecutionFile,+ UserWorkspace,+ UserWorkspaceFile,+)++from backend.blocks import get_block+from backend.blocks._base import BlockType+from backend.copilot.db import get_chat_messages_paginated+from backend.copilot.model import ChatSessionInfo+from backend.copilot.sharing.models import (+ ChatShareState,+ SharedChatLinkedExecution,+ SharedChatMessagesPage,+ SharedChatSession,+ sanitize_chat_message,+ sanitize_chat_session,+)+from backend.data.block import BlockInput, CompletedBlockOutput+from backend.data.db import transaction+from backend.data.sharing.tokens import generate_share_token+from backend.data.sharing.workspace_refs import extract_workspace_file_ids+from backend.util import type as type_utils++logger = logging.getLogger(__name__)++# Linked-execution discovery scans assistant tool responses (role="tool"+# rows) for run_agent tool payloads that reference an execution.+#+# Two response shapes can result from a run_agent invocation:+# * ExecutionStartedResponse — async / still-running / REVIEW;+# ``execution_id`` lives at the top level of the JSON payload.+# * AgentOutputResponse — sync-complete (``wait_for_result``); the+# execution_id lives nested under ``execution.execution_id``.+# * ErrorResponse — failed / terminated actual runs; execution_id is+# optional because generic tool errors do not have a run to link.+# These shapes are emitted by ``backend.copilot.tools.models``.+_EXECUTION_STARTED_TYPE = "execution_started"+_AGENT_OUTPUT_TYPE = "agent_output"+_ERROR_TYPE = "error"+_SCHEDULED_STATUS = "SCHEDULED"+++# ---------- Enable / disable -------------------------------------------------+++async def enable_chat_session_share(+ session_id: str,+ user_id: str,+ auto_share_executions: bool,+) -> str:+ """Enable sharing on a chat session.++ Generates a fresh token, refreshes the file allowlist from the+ session's messages, and — when ``auto_share_executions`` is True —+ auto-links every ``run_agent`` execution referenced by the chat's+ tool messages. The flag is persisted on the session so subsequent+ ``run_agent`` invocations (handled by+ :func:`link_new_execution_to_chat_share`) keep the chat share in+ sync without requiring the owner to revisit the dialog.++ All writes happen inside a single Prisma transaction so a crash+ mid-flow cannot leave the chat publicly readable with a missing+ file allowlist or an execution flipped to ``CHAT_LINK`` shared+ state with no parent chat linkage.++ Returns the share token.++ Raises ValueError if the session does not belong to *user_id*.+ """+ session = await PrismaChatSession.prisma().find_first(+ where={"id": session_id, "userId": user_id},+ )+ if not session:+ raise ValueError(f"Chat session {session_id} not found for user")++ if auto_share_executions:+ execution_ids = list(+ await _collect_execution_ids_from_messages(session_id=session_id)+ )+ # Only auto-link executions the caller still owns. Runs the+ # caller doesn't own (deleted, cross-user) are silently skipped+ # rather than failing the whole share — they shouldn't have+ # been referenced in the chat in the first place, but defending+ # against that here keeps share-enable robust.+ executions_to_link = (+ await AgentGraphExecution.prisma().find_many(+ where={+ "id": {"in": execution_ids},+ "userId": user_id,+ "isDeleted": False,+ },+ )+ if execution_ids+ else []+ )+ else:+ executions_to_link = []++ share_token = generate_share_token()+ now = datetime.now(UTC)++ async with transaction() as tx:+ # Cascade-revoke previously-linked CHAT_LINK executions BEFORE+ # wiping the join table. Otherwise a re-share with a different+ # ``autoShareExecutions`` value (or just a re-share to mint a+ # fresh token) leaves the old per-execution tokens publicly+ # active with no linkage row to reach them via — orphan public+ # shares. Same guard ``disable_chat_session_share`` runs.+ await _cascade_revoke_chat_linked_executions(session_id=session_id, tx=tx)++ # Clear stale allowlist + linkage rows before re-keying the token,+ # so an old token + new linkage never coexist.+ await SharedChatFile.prisma(tx).delete_many(where={"sessionId": session_id})+ await ChatLinkedShare.prisma(tx).delete_many(where={"sessionId": session_id})++ await _build_shared_chat_files(+ session_id=session_id,+ share_token=share_token,+ user_id=user_id,+ tx=tx,+ )++ await _link_executions_to_share(+ session_id=session_id,+ executions=executions_to_link,+ shared_at=now,+ tx=tx,+ )++ # Session update goes LAST inside the transaction so the chat+ # only becomes publicly readable after the allowlist + linkage+ # are committed.+ await PrismaChatSession.prisma(tx).update(+ where={"id": session_id},+ data={+ "isShared": True,+ "shareToken": share_token,+ "sharedAt": now,+ "autoShareExecutions": auto_share_executions,+ },+ )++ return share_token+++async def link_new_execution_to_chat_share(+ session_id: str,+ execution_id: str,+) -> None:+ """Auto-link a freshly-completed execution into an already-shared chat.++ Hook called by the ``run_agent`` tool after the tool result is+ persisted. No-op when the chat is not shared, or shared without+ ``autoShareExecutions=True``. Idempotent — repeated calls for the+ same (session, execution) pair don't double-link.++ ``run_agent`` runs inside the CoPilotExecutor worker process, which+ has a different Prisma client lifecycle than the API server. Any+ Prisma failure (e.g. the worker's client not yet connected) is+ caught and logged: a sharing hook must never crash the tool itself+ — a failure here surfaces as ``ClientNotConnectedError`` inside the+ Claude SDK as an orphan tool_use, which the SDK turns into "The+ model returned an empty response." Skipped links are recovered the+ next time the owner re-shares the chat (enable-time backfill walks+ every existing run via ``_collect_execution_ids_from_messages``).+ """+ try:+ session = await PrismaChatSession.prisma().find_unique(where={"id": session_id})+ if not session or not session.isShared or not session.autoShareExecutions:+ return++ now = datetime.now(UTC)+ async with transaction() as tx:+ # Re-check share state inside the transaction. A concurrent+ # ``disable_chat_session_share`` could have flipped+ # ``isShared`` between the outer check above and the tx+ # start; without this guard we'd create a ChatLinkedShare+ # row pointing at a no-longer-shared session and possibly+ # flip the execution to ``CHAT_LINK`` shared — orphan+ # public state. The pre-fetched ``session`` snapshot is+ # only used for the early-return fast path; the+ # transactional read is the authoritative one.+ session_tx = await PrismaChatSession.prisma(tx).find_unique(+ where={"id": session_id}+ )+ if (+ not session_tx+ or not session_tx.isShared+ or not session_tx.autoShareExecutions+ ):+ return++ execution = await AgentGraphExecution.prisma(tx).find_first(+ where={+ "id": execution_id,+ "userId": session_tx.userId,+ "isDeleted": False,+ },+ )+ if execution is None:+ return++ existing = await ChatLinkedShare.prisma(tx).find_first(+ where={"sessionId": session_id, "executionId": execution_id},+ )+ if existing is not None:+ return++ await _link_executions_to_share(+ session_id=session_id,+ executions=[execution],+ shared_at=now,+ tx=tx,+ )+ except Exception as exc:+ # Best-effort hook: a sharing failure must never break the+ # underlying run_agent tool. See note above on the empty-+ # completion failure mode this guards against. Pair the log+ # with a Sentry capture so the no-crash guarantee doesn't+ # hide real operational regressions (DB outage, schema drift)+ # behind a warn-only signal.+ logger.warning(+ "link_new_execution_to_chat_share failed for session=%s execution=%s; "+ "owner can recover via stop+reshare or an explicit re-enable",+ session_id,+ execution_id,+ exc_info=True,+ )+ sentry_sdk.capture_exception(exc)+++async def disable_chat_session_share(session_id: str, user_id: str) -> None:+ """Revoke sharing on a chat session and cascade-revoke linked executions.++ Cascade rule: an execution share is cleared only when (a) it was+ enabled via a chat share (``sharedVia == CHAT_LINK``) AND (b) no+ other chat session still has a ``ChatLinkedShare`` row referencing+ it. User-initiated execution shares survive untouched, and an+ execution opted-in by multiple chat shares stays shared as long as+ at least one chat share still references it.+ """+ session = await PrismaChatSession.prisma().find_first(+ where={"id": session_id, "userId": user_id},+ )+ if not session:+ raise ValueError(f"Chat session {session_id} not found for user")++ async with transaction() as tx:+ # Flip the session to ``isShared=False`` FIRST so any concurrent+ # ``link_new_execution_to_chat_share`` racing this transaction+ # sees the new state on its own in-tx re-read and bails before+ # creating an orphan ``ChatLinkedShare`` row. The cascade+ # bookkeeping (read linkages → revoke executions → delete+ # rows) all runs inside the same transaction so the window for+ # a phantom row is reduced to the gap between two committed+ # transactions — which the hook's in-tx re-check covers.+ await PrismaChatSession.prisma(tx).update(+ where={"id": session_id},+ data={+ "isShared": False,+ "shareToken": None,+ "sharedAt": None,+ # Reset the auto-share preference so the next time the+ # owner re-shares this chat the modal opens in its+ # default state (toggle off until they flip it).+ "autoShareExecutions": False,+ },+ )++ # Walk the linkage table and disable only the chat-derived shares+ # that aren't still referenced by another chat session's linkage.+ # Reading INSIDE the tx ensures the pre-flip session update is+ # visible and any concurrent linkage commit lands either fully+ # before this read (and gets cascaded) or fully after (and is+ # blocked by the in-tx session re-check).+ await _cascade_revoke_chat_linked_executions(session_id=session_id, tx=tx)++ await ChatLinkedShare.prisma(tx).delete_many(where={"sessionId": session_id})+ await SharedChatFile.prisma(tx).delete_many(where={"sessionId": session_id})+++# ---------- Public read path -------------------------------------------------+++async def get_chat_session_by_share_token(+ share_token: str,+) -> SharedChatSession | None:+ """Look up a shared session header (no messages, no auth)."""+ session = await PrismaChatSession.prisma().find_first(+ where={"shareToken": share_token, "isShared": True},+ )+ if not session:+ return None++ linked = await _resolve_linked_executions(session_id=session.id)+ return sanitize_chat_session(+ ChatSessionInfo.from_db(session),+ linked_executions=linked,+ shared_at=session.sharedAt,+ )+++async def get_shared_chat_messages_paginated(+ share_token: str,+ *,+ limit: int = 50,+ before_sequence: int | None = None,+) -> SharedChatMessagesPage | None:+ """Paginate messages for a shared session.++ Returns ``None`` when the token is unknown or sharing has been+ disabled (uniform with :func:`get_chat_session_by_share_token`).+ """+ session = await PrismaChatSession.prisma().find_first(+ where={"shareToken": share_token, "isShared": True},+ )+ if not session:+ return None++ page = await get_chat_messages_paginated(+ session_id=session.id,+ limit=limit,+ before_sequence=before_sequence,+ # No user scoping — the share token already authorises the read.+ )+ if page is None:+ return None++ return SharedChatMessagesPage(+ messages=[sanitize_chat_message(m) for m in page.messages],+ has_more=page.has_more,+ oldest_sequence=page.oldest_sequence,+ )+++async def get_shared_chat_file(share_token: str, file_id: str) -> str | None:+ """Allowlist lookup for the public file-download endpoint.++ Returns the owning ``session_id`` if the file is allowlisted,+ ``None`` otherwise. Uniform None for every failure mode prevents+ timing-based enumeration of valid file IDs.++ Falls back to a live re-scan of the chat's messages when the+ static allowlist misses — files uploaded AFTER the share was+ enabled (or referenced by later assistant messages) would+ otherwise 404 forever, even though the file is clearly part of+ the shared conversation. The re-scan re-uses the same workspace-+ ownership guard ``_build_shared_chat_files`` enforces at enable+ time, so a malicious tool output trying to reference a foreign+ workspace file still gets rejected. On hit we backfill a+ SharedChatFile row so subsequent downloads short-circuit.+ """+ record = await SharedChatFile.prisma().find_first(+ where={"shareToken": share_token, "fileId": file_id}+ )+ if record is not None:+ return record.sessionId++ # Slow path: chat-share allowlists are built once at enable time,+ # but the chat keeps accumulating messages. Re-derive ownership+ # from the live messages for this token before giving up.+ session = await PrismaChatSession.prisma().find_first(+ where={"shareToken": share_token, "isShared": True},+ )+ if session is None:+ return None+ if not await _file_referenced_in_session(session_id=session.id, file_id=file_id):+ return None+ workspace = await UserWorkspace.prisma().find_unique(+ where={"userId": session.userId}+ )+ if workspace is None:+ return None+ file = await UserWorkspaceFile.prisma().find_first(+ where={"id": file_id, "workspaceId": workspace.id, "isDeleted": False}+ )+ if file is None:+ return None+ # Backfill the allowlist so repeat downloads skip the re-scan.+ try:+ await SharedChatFile.prisma().create(+ data={+ "sessionId": session.id,+ "fileId": file_id,+ "shareToken": share_token,+ }+ )+ except (UniqueViolationError, ForeignKeyViolationError):+ # Concurrent backfill or file deleted between checks — fall+ # through; the file is still ownership-validated above so+ # the download is safe to authorise this once.+ pass+ return session.id+++async def _file_referenced_in_session(*, session_id: str, file_id: str) -> bool:+ """True iff *file_id* appears in any of *session_id*'s messages.++ Scans ``content``, ``toolCalls``, and ``functionCall`` of every+ message using :func:`extract_workspace_file_ids` — same shape the+ enable-time allowlist build uses, so a message that references the+ file via ``workspace://``, ``[Attached files] file_id=``, or JSON+ tool output all qualify.+ """+ candidate_rows = await PrismaChatMessage.prisma().find_many(+ where={"sessionId": session_id, "content": {"contains": file_id}},+ )+ for row in candidate_rows:+ if row.content is not None and file_id in extract_workspace_file_ids(+ row.content+ ):+ return True++ rows = await PrismaChatMessage.prisma().find_many(+ where={"sessionId": session_id},+ )+ for row in rows:+ if row.content is not None:+ if file_id in extract_workspace_file_ids(row.content):+ return True+ if row.toolCalls is not None:+ if file_id in extract_workspace_file_ids(_json_or_none(row.toolCalls)):+ return True+ if row.functionCall is not None:+ if file_id in extract_workspace_file_ids(_json_or_none(row.functionCall)):+ return True+ return False+++# ---------- Linked execution discovery (share-modal helper) ------------------+++async def get_chat_share_state(session_id: str, user_id: str) -> ChatShareState:+ """Return the current share state for *session_id* scoped to *user_id*.++ Returns ``ChatShareState(is_shared=False, ...)`` when the session is+ missing or not owned by the user — the same shape callers see for+ never-shared sessions, so the share modal renders the "enable" path+ without an extra existence check.+ """+ row = await PrismaChatSession.prisma().find_first(+ where={"id": session_id, "userId": user_id},+ )+ if not row:+ return ChatShareState(+ is_shared=False, share_token=None, auto_share_executions=False+ )++ # Counts the modal renders as informed-consent disclosure. Computed+ # at modal-open time (and again on each refetch) so they reflect the+ # live state of the chat — sharing is live, not snapshot-at-enable+ # (see the share-modal warning text), so the numbers under the+ # toggle ARE the numbers that will be visible the moment the+ # owner clicks "Enable sharing".+ message_count = await PrismaChatMessage.prisma().count(+ where={"sessionId": session_id},+ )+ linked_run_count = len(+ await _collect_execution_ids_from_messages(session_id=session_id)+ )+ file_count = await _count_referenced_workspace_files(+ session_id=session_id, user_id=user_id+ )++ return ChatShareState(+ is_shared=row.isShared,+ share_token=row.shareToken,+ auto_share_executions=row.autoShareExecutions,+ message_count=message_count,+ linked_run_count=linked_run_count,+ file_count=file_count,+ )+++async def _count_referenced_workspace_files(*, session_id: str, user_id: str) -> int:+ """How many of the workspace files referenced by this chat's messages+ the owner actually owns (and would land in the public allowlist if+ the share were enabled right now). Mirrors the ownership filter+ ``_build_shared_chat_files`` applies at enable time so the count+ matches what the public viewer can actually download.+ """+ rows = await PrismaChatMessage.prisma().find_many(+ where={"sessionId": session_id},+ )+ file_ids: set[str] = set()+ for row in rows:+ if row.content is not None:+ file_ids |= extract_workspace_file_ids(row.content)+ if row.toolCalls is not None:+ file_ids |= extract_workspace_file_ids(_json_or_none(row.toolCalls))+ if row.functionCall is not None:+ file_ids |= extract_workspace_file_ids(_json_or_none(row.functionCall))+ if not file_ids:+ return 0+ workspace = await UserWorkspace.prisma().find_unique(where={"userId": user_id})+ if not workspace:+ return 0+ owned = await UserWorkspaceFile.prisma().find_many(+ where={+ "id": {"in": list(file_ids)},+ "workspaceId": workspace.id,+ "isDeleted": False,+ }+ )+ return len(owned)+++# ---------- Helpers ----------------------------------------------------------+++async def _build_shared_chat_files(+ session_id: str,+ share_token: str,+ user_id: str,+ *,+ tx: Any | None = None,+) -> int:+ """Scan all messages in the session for workspace://<id> refs + persist allowlist."""+ rows = await PrismaChatMessage.prisma(tx).find_many(+ where={"sessionId": session_id},+ )++ file_ids: set[str] = set()+ for row in rows:+ if row.content is not None:+ file_ids |= extract_workspace_file_ids(row.content)+ if row.toolCalls is not None:+ file_ids |= extract_workspace_file_ids(_json_or_none(row.toolCalls))+ if row.functionCall is not None:+ file_ids |= extract_workspace_file_ids(_json_or_none(row.functionCall))++ if not file_ids:+ return 0++ workspace = await UserWorkspace.prisma(tx).find_unique(where={"userId": user_id})+ if not workspace:+ return 0++ owned_files = await UserWorkspaceFile.prisma(tx).find_many(+ where={+ "id": {"in": list(file_ids)},+ "workspaceId": workspace.id,+ "isDeleted": False,+ }+ )++ created = 0+ for file in owned_files:+ try:+ await SharedChatFile.prisma(tx).create(+ data={+ "sessionId": session_id,+ "fileId": file.id,+ "shareToken": share_token,+ }+ )+ created += 1+ except UniqueViolationError:+ logger.debug("SharedChatFile already exists: %s/%s", session_id, file.id)+ except ForeignKeyViolationError:+ logger.debug("SharedChatFile FK violation for file %s", file.id)+ return created+++async def _cascade_revoke_chat_linked_executions(+ *,+ session_id: str,+ tx: Any | None = None,+) -> None:+ """Revoke each CHAT_LINK execution previously linked to *session_id*+ that isn't still referenced by another chat session's linkage.++ Used by both ``disable_chat_session_share`` and the+ ``enable_chat_session_share`` re-share path — the latter calls this+ BEFORE wiping the join table so the previous generation of linkages+ doesn't strand orphan public per-execution shares.++ User-initiated execution shares (``sharedVia=USER``) are left+ untouched. An execution still referenced by another chat session's+ linkage is left shared so revoking chat A doesn't break chat B's+ drill-in.+ """+ linked = await ChatLinkedShare.prisma(tx).find_many(+ where={"sessionId": session_id},+ include={"Execution": True},+ )+ for row in linked:+ execution = row.Execution+ if execution is None or execution.sharedVia != SharedVia.CHAT_LINK:+ continue+ other_link = await ChatLinkedShare.prisma(tx).find_first(+ where={+ "executionId": execution.id,+ "sessionId": {"not": session_id},+ },+ )+ if other_link is not None:+ continue+ # Drop the execution's file allowlist before clearing the share+ # token. Orphan ``SharedExecutionFile`` rows would still+ # authorise downloads if anyone bookmarked the pre-revoke URL.+ await SharedExecutionFile.prisma(tx).delete_many(+ where={"executionId": execution.id}+ )+ await AgentGraphExecution.prisma(tx).update(+ where={"id": execution.id},+ data={+ "isShared": False,+ "shareToken": None,+ "sharedAt": None,+ "sharedVia": None,+ },+ )+++async def _link_executions_to_share(+ session_id: str,+ executions: list[AgentGraphExecution],+ shared_at: datetime,+ *,+ tx: Any | None = None,+) -> None:+ """Insert ChatLinkedShare rows and cascade-enable share on unshared ones.++ Idempotent against the unique (sessionId, executionId) constraint —+ a concurrent ``run_agent`` for the same execution_id may race the+ runtime hook's pre-insert existence check and both reach this+ function. In that case the second create raises+ ``UniqueViolationError``; we treat it as "already linked, skip"+ rather than a failure, mirroring ``_build_shared_chat_files``.+ """+ for execution in executions:+ try:+ await ChatLinkedShare.prisma(tx).create(+ data={"sessionId": session_id, "executionId": execution.id}+ )+ except UniqueViolationError:+ logger.debug(+ "ChatLinkedShare already exists: %s/%s",+ session_id,+ execution.id,+ )+ continue+ # Conditional update: only flip the execution to ``CHAT_LINK`` when+ # the DB still reports it unshared. Branching on the pre-fetched+ # ``execution.isShared`` in-memory value can race a concurrent+ # transaction that has just shared (or revoked) it — see the+ # disable_chat_session_share cascade for the inverse race. When+ # ``update_many`` matches zero rows we leave the execution's+ # existing share state alone; the ChatLinkedShare row above still+ # records the linkage, so the public viewer keeps drilling into+ # the user-shared token.+ new_token = generate_share_token()+ flipped = await AgentGraphExecution.prisma(tx).update_many(+ where={"id": execution.id, "isShared": False},+ data={+ "isShared": True,+ "shareToken": new_token,+ "sharedAt": shared_at,+ "sharedVia": SharedVia.CHAT_LINK,+ },+ )+ if flipped:+ # Mirror enable_execution_sharing's allowlist build so the+ # public execution viewer can serve the run's workspace files.+ # Without this, the chat viewer renders the run card but+ # every file download 404s — uniform 404 (anti-enumeration)+ # masks the bug, but the artifacts are unreachable.+ await _build_shared_execution_file_allowlist(+ execution_id=execution.id,+ share_token=new_token,+ user_id=execution.userId,+ tx=tx,+ )+++async def _build_shared_execution_file_allowlist(+ *,+ execution_id: str,+ share_token: str,+ user_id: str,+ tx: Any | None = None,+) -> int:+ """Build ``SharedExecutionFile`` rows for a CHAT_LINK-flipped execution.++ Mirrors :func:`backend.data.execution.create_shared_execution_files` but+ is transaction-aware so the allowlist commits with the same atomic+ boundary as the share-state flip. It intentionally scans only the+ public execution outputs rendered by the shared execution viewer, not+ every intermediate node output. That keeps CHAT_LINK shares from+ authorising file downloads the normal execution-share path would not+ expose.+ """+ node_rows = await AgentGraphExecution.prisma(tx).find_unique(+ where={"id": execution_id},+ include={+ "NodeExecutions": {+ "include": {+ "Input": True,+ "Node": {"include": {"AgentBlock": True}},+ }+ }+ },+ )+ if node_rows is None or node_rows.NodeExecutions is None:+ return 0++ outputs = _collect_public_execution_outputs(node_rows)+ file_ids = extract_workspace_file_ids(outputs)+ if not file_ids:+ return 0++ workspace = await UserWorkspace.prisma(tx).find_unique(where={"userId": user_id})+ if workspace is None:+ return 0++ owned_files = await UserWorkspaceFile.prisma(tx).find_many(+ where={+ "id": {"in": list(file_ids)},+ "workspaceId": workspace.id,+ "isDeleted": False,+ }+ )++ created = 0+ for file in owned_files:+ try:+ await SharedExecutionFile.prisma(tx).create(+ data={+ "executionId": execution_id,+ "fileId": file.id,+ "shareToken": share_token,+ }+ )+ created += 1+ except UniqueViolationError:+ logger.debug(+ "SharedExecutionFile already exists: %s/%s", execution_id, file.id+ )+ except ForeignKeyViolationError:+ logger.debug("SharedExecutionFile FK violation for file %s", file.id)+ return created+++async def _resolve_linked_executions(+ session_id: str,+) -> list[SharedChatLinkedExecution]:+ rows = await ChatLinkedShare.prisma().find_many(+ where={"sessionId": session_id},+ include={"Execution": {"include": {"AgentGraph": True}}},+ )+ out: list[SharedChatLinkedExecution] = []+ for row in rows:+ execution = row.Execution+ if execution is None:+ continue+ out.append(+ SharedChatLinkedExecution(+ execution_id=execution.id,+ graph_id=execution.agentGraphId,+ graph_name=_graph_name(execution.AgentGraph),+ share_token=execution.shareToken if execution.isShared else None,+ )+ )+ return out+++async def _collect_execution_ids_from_messages(session_id: str) -> set[str]:+ """Find execution IDs referenced by ``role=tool`` responses in a session.++ Matches both response shapes that ``run_agent`` produces:+ ``ExecutionStartedResponse`` (top-level ``execution_id``) and+ ``AgentOutputResponse`` (nested ``execution.execution_id`` from the+ sync-complete ``wait_for_result`` path).+ """+ rows = await PrismaChatMessage.prisma().find_many(+ where={"sessionId": session_id, "role": "tool"},+ )+ execution_ids: set[str] = set()+ for row in rows:+ if not row.content:+ continue+ payload = _json_or_none(row.content)+ if not isinstance(payload, dict):+ continue+ payload_type = payload.get("type")+ if payload_type == _EXECUTION_STARTED_TYPE:+ if payload.get("status") == _SCHEDULED_STATUS:+ continue+ execution_id = payload.get("execution_id")+ elif payload_type == _AGENT_OUTPUT_TYPE:+ execution = payload.get("execution")+ execution_id = (+ execution.get("execution_id") if isinstance(execution, dict) else None+ )+ elif payload_type == _ERROR_TYPE:+ execution_id = payload.get("execution_id")+ else:+ continue+ if isinstance(execution_id, str) and execution_id:+ execution_ids.add(execution_id)+ return execution_ids+++def _collect_public_execution_outputs(+ execution: AgentGraphExecution,+) -> CompletedBlockOutput:+ outputs: CompletedBlockOutput = {}+ if execution.NodeExecutions is None:+ return outputs++ for node_exec in execution.NodeExecutions:+ node = getattr(node_exec, "Node", None)+ block_id = getattr(node, "agentBlockId", None)+ if not block_id:+ continue+ block = get_block(block_id)+ if block is None or block.block_type != BlockType.OUTPUT:+ continue+ input_data = _node_execution_input_data(node_exec)+ if "name" not in input_data:+ continue+ name = input_data["name"]+ value = input_data.get("value")+ outputs.setdefault(name, []).append(value)+ return outputs+++def _node_execution_input_data(node_exec: Any) -> BlockInput:+ execution_data = getattr(node_exec, "executionData", None)+ if execution_data:+ return type_utils.convert(execution_data, BlockInput)++ input_data: BlockInput = {}+ for data in getattr(node_exec, "Input", None) or []:+ if data.name and data.data is not None:+ input_data[data.name] = type_utils.convert(data.data, Any)+ return input_data+++def _graph_name(graph: "AgentGraph | None") -> str | None:+ if graph is None:+ return None+ return graph.name+++def _json_or_none(value: Any) -> Any:+ """Parse *value* as JSON if it's a string; else return as-is."""+ if isinstance(value, str):+ try:+ return json.loads(value)+ except (json.JSONDecodeError, ValueError):+ return None+ return valuediff --git a/autogpt_platform/backend/backend/copilot/sharing/db_test.py b/autogpt_platform/backend/backend/copilot/sharing/db_test.pynew file mode 100644index 0000000000..3a92842a4a--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/sharing/db_test.py@@ -0,0 +1,912 @@+"""Unit tests for chat-sharing data-layer cascade logic.++These tests pin down the multi-chat cascade behavior — fixed in+PR #13081 round 1. Without coverage here, a future refactor could+silently re-introduce the bug where chat A's revoke breaks chat B's+drill-in into a shared execution.+"""++from __future__ import annotations++from datetime import UTC, datetime+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from prisma.enums import SharedVia+from prisma.models import AgentGraphExecution, ChatLinkedShare+from prisma.models import ChatMessage as PrismaChatMessage+from prisma.models import ChatSession as PrismaChatSession+from prisma.models import (+ SharedChatFile,+ SharedExecutionFile,+ UserWorkspace,+ UserWorkspaceFile,+)++from backend.blocks._base import BlockType+from backend.copilot.sharing.db import (+ _build_shared_execution_file_allowlist,+ _collect_execution_ids_from_messages,+ _file_referenced_in_session,+ disable_chat_session_share,+ enable_chat_session_share,+ get_chat_share_state,+ link_new_execution_to_chat_share,+)++SESSION_ID = "sess-A"+OTHER_SESSION_ID = "sess-B"+USER_ID = "user-1"+EXECUTION_ID = "exec-1"+++def _mock_session(*, auto_share_executions: bool = False) -> PrismaChatSession:+ now = datetime.now(UTC)+ return PrismaChatSession.model_construct(+ id=SESSION_ID,+ createdAt=now,+ updatedAt=now,+ userId=USER_ID,+ credentials={},+ successfulAgentRuns={},+ successfulAgentSchedules={},+ totalPromptTokens=0,+ totalCompletionTokens=0,+ metadata={},+ chatStatus="idle",+ isShared=True,+ shareToken="token-A",+ sharedAt=now,+ autoShareExecutions=auto_share_executions,+ )+++def _mock_execution(+ *, shared_via: SharedVia | None = SharedVia.CHAT_LINK+) -> AgentGraphExecution:+ now = datetime.now(UTC)+ return AgentGraphExecution.model_construct(+ id=EXECUTION_ID,+ createdAt=now,+ agentGraphId="graph-1",+ agentGraphVersion=1,+ executionStatus="COMPLETED",+ userId=USER_ID,+ isDeleted=False,+ isShared=True,+ shareToken="token-exec",+ sharedAt=now,+ sharedVia=shared_via,+ )+++def _mock_linked_share() -> ChatLinkedShare:+ return ChatLinkedShare.model_construct(+ id="link-1",+ createdAt=datetime.now(UTC),+ sessionId=SESSION_ID,+ executionId=EXECUTION_ID,+ Execution=_mock_execution(),+ )+++class _TxStub:+ """Async context-manager that yields a dummy tx token.++ The real Prisma transaction context manager does the same — yields+ a tx handle that gets threaded into ``.prisma(tx)`` calls. For+ these tests we just need a sentinel object the calls can accept.+ """++ def __init__(self) -> None:+ self.tx = MagicMock(name="tx")++ async def __aenter__(self):+ return self.tx++ async def __aexit__(self, *args):+ return None+++def mock_transaction():+ with patch("backend.copilot.sharing.db.transaction", return_value=_TxStub()) as m:+ yield m+++def mock_prisma_calls():+ """Patch every Prisma model call used by disable_chat_session_share.++ Each model's ``.prisma()`` (and ``.prisma(tx)``) returns the same+ mock so we can assert against a single call surface regardless of+ whether the call was inside or outside the transaction.+ """+ with (+ patch.object(PrismaChatSession, "prisma") as session_prisma,+ patch.object(ChatLinkedShare, "prisma") as linked_prisma,+ patch.object(AgentGraphExecution, "prisma") as exec_prisma,+ patch.object(SharedChatFile, "prisma") as file_prisma,+ patch.object(SharedExecutionFile, "prisma") as exec_file_prisma,+ patch.object(PrismaChatMessage, "prisma") as msg_prisma,+ patch.object(UserWorkspace, "prisma") as workspace_prisma,+ patch.object(UserWorkspaceFile, "prisma") as workspace_file_prisma,+ ):+ msg_prisma.return_value.count = AsyncMock(return_value=0)+ msg_prisma.return_value.find_many = AsyncMock(return_value=[])+ workspace_prisma.return_value.find_unique = AsyncMock(return_value=None)+ workspace_file_prisma.return_value.find_many = AsyncMock(return_value=[])+ # Default no-op for the execution-file allowlist so tests that+ # don't exercise the file-build / cascade-cleanup paths still see+ # an awaitable. Tests that DO exercise those paths override.+ exec_file_prisma.return_value.delete_many = AsyncMock(return_value=0)+ exec_file_prisma.return_value.create = AsyncMock()+ # ``_build_shared_execution_file_allowlist`` calls find_unique+ # on AgentGraphExecution to pull NodeExecutions.Output for the+ # workspace-file scan. Default to None so the helper short-+ # circuits unless a test explicitly sets up node-execution data.+ exec_prisma.return_value.find_unique = AsyncMock(return_value=None)+ # The re-share path calls ``_cascade_revoke_chat_linked_executions``+ # which reads ChatLinkedShare.find_many before any other linked+ # ops fire. Default to empty so the cascade is a no-op for+ # tests that don't exercise the previous-generation cleanup.+ linked_prisma.return_value.find_many = AsyncMock(return_value=[])+ yield {+ "session": session_prisma,+ "linked": linked_prisma,+ "execution": exec_prisma,+ "file": file_prisma,+ "exec_file": exec_file_prisma,+ "message": msg_prisma,+ "workspace": workspace_prisma,+ "workspace_file": workspace_file_prisma,+ }+++class TestDisableCascade:+ """Multi-chat cascade rules on disable_chat_session_share."""++ @pytest.mark.asyncio+ async def test_revokes_chat_link_execution_when_no_other_chat_references_it(+ self, mock_prisma_calls, mock_transaction+ ):+ """Execution shared only via this chat → revoke."""+ # Session lookup succeeds.+ mock_prisma_calls["session"].return_value.find_first = AsyncMock(+ return_value=_mock_session()+ )+ # One linked execution for this session.+ mock_prisma_calls["linked"].return_value.find_many = AsyncMock(+ return_value=[_mock_linked_share()]+ )+ # No OTHER chat session has a linkage for this execution.+ mock_prisma_calls["linked"].return_value.find_first = AsyncMock(+ return_value=None+ )+ mock_prisma_calls["linked"].return_value.delete_many = AsyncMock(return_value=1)+ mock_prisma_calls["execution"].return_value.update = AsyncMock()+ mock_prisma_calls["file"].return_value.delete_many = AsyncMock(return_value=0)+ mock_prisma_calls["session"].return_value.update = AsyncMock()++ await disable_chat_session_share(SESSION_ID, USER_ID)++ # Execution was revoked.+ mock_prisma_calls["execution"].return_value.update.assert_called_once()+ update_data = mock_prisma_calls[+ "execution"+ ].return_value.update.call_args.kwargs["data"]+ assert update_data == {+ "isShared": False,+ "shareToken": None,+ "sharedAt": None,+ "sharedVia": None,+ }++ @pytest.mark.asyncio+ async def test_preserves_execution_when_another_chat_still_references_it(+ self, mock_prisma_calls, mock_transaction+ ):+ """Multi-chat reference → leave execution shared. Regression for the+ bug fixed in PR #13081 round 1: chat A's revoke must not silently+ break chat B's drill-in link to the same execution."""+ mock_prisma_calls["session"].return_value.find_first = AsyncMock(+ return_value=_mock_session()+ )+ mock_prisma_calls["linked"].return_value.find_many = AsyncMock(+ return_value=[_mock_linked_share()]+ )+ # ANOTHER chat session's linkage exists for the same execution.+ other_link = ChatLinkedShare.model_construct(+ id="link-2",+ createdAt=datetime.now(UTC),+ sessionId=OTHER_SESSION_ID,+ executionId=EXECUTION_ID,+ )+ mock_prisma_calls["linked"].return_value.find_first = AsyncMock(+ return_value=other_link+ )+ mock_prisma_calls["linked"].return_value.delete_many = AsyncMock(return_value=1)+ mock_prisma_calls["execution"].return_value.update = AsyncMock()+ mock_prisma_calls["file"].return_value.delete_many = AsyncMock(return_value=0)+ mock_prisma_calls["session"].return_value.update = AsyncMock()++ await disable_chat_session_share(SESSION_ID, USER_ID)++ # CRITICAL: execution was NOT revoked because chat B still depends on it.+ mock_prisma_calls["execution"].return_value.update.assert_not_called()+ mock_prisma_calls["linked"].return_value.find_first.assert_awaited_once_with(+ where={+ "executionId": EXECUTION_ID,+ "sessionId": {"not": SESSION_ID},+ },+ )++ @pytest.mark.asyncio+ async def test_preserves_user_shared_execution_even_with_no_other_links(+ self, mock_prisma_calls, mock_transaction+ ):+ """USER-shared execution: cascade must skip regardless of linkage."""+ user_shared_link = ChatLinkedShare.model_construct(+ id="link-1",+ createdAt=datetime.now(UTC),+ sessionId=SESSION_ID,+ executionId=EXECUTION_ID,+ Execution=_mock_execution(shared_via=SharedVia.USER),+ )+ mock_prisma_calls["session"].return_value.find_first = AsyncMock(+ return_value=_mock_session()+ )+ mock_prisma_calls["linked"].return_value.find_many = AsyncMock(+ return_value=[user_shared_link]+ )+ # Even if no other linkage exists, USER-shared execution stays untouched.+ mock_prisma_calls["linked"].return_value.find_first = AsyncMock(+ return_value=None+ )+ mock_prisma_calls["linked"].return_value.delete_many = AsyncMock(return_value=1)+ mock_prisma_calls["execution"].return_value.update = AsyncMock()+ mock_prisma_calls["file"].return_value.delete_many = AsyncMock(return_value=0)+ mock_prisma_calls["session"].return_value.update = AsyncMock()++ await disable_chat_session_share(SESSION_ID, USER_ID)++ mock_prisma_calls["execution"].return_value.update.assert_not_called()++ @pytest.mark.asyncio+ async def test_raises_when_session_not_owned_by_user(+ self, mock_prisma_calls, mock_transaction+ ):+ """Non-owner attempt → ValueError, no writes."""+ mock_prisma_calls["session"].return_value.find_first = AsyncMock(+ return_value=None+ )++ with pytest.raises(ValueError, match="not found for user"):+ await disable_chat_session_share(SESSION_ID, "different-user")++ mock_prisma_calls["linked"].return_value.delete_many.assert_not_called()+ mock_prisma_calls["session"].return_value.update.assert_not_called()++ @pytest.mark.asyncio+ async def test_cascade_revoke_deletes_execution_file_allowlist(+ self, mock_prisma_calls, mock_transaction+ ):+ """Revoking a chat that flipped an execution to CHAT_LINK must+ also drop the execution's ``SharedExecutionFile`` allowlist. A+ stale allowlist row would still authorise public file downloads+ for a leaked pre-revoke URL even though the share token field+ is cleared on the execution."""+ mock_prisma_calls["session"].return_value.find_first = AsyncMock(+ return_value=_mock_session()+ )+ mock_prisma_calls["linked"].return_value.find_many = AsyncMock(+ return_value=[_mock_linked_share()]+ )+ mock_prisma_calls["linked"].return_value.find_first = AsyncMock(+ return_value=None+ )+ mock_prisma_calls["linked"].return_value.delete_many = AsyncMock(return_value=1)+ mock_prisma_calls["execution"].return_value.update = AsyncMock()+ mock_prisma_calls["file"].return_value.delete_many = AsyncMock(return_value=0)+ mock_prisma_calls["session"].return_value.update = AsyncMock()+ exec_file_delete = AsyncMock(return_value=2)+ mock_prisma_calls["exec_file"].return_value.delete_many = exec_file_delete++ await disable_chat_session_share(SESSION_ID, USER_ID)++ exec_file_delete.assert_called_once()+ assert exec_file_delete.call_args.kwargs["where"] == {+ "executionId": EXECUTION_ID+ }++ @pytest.mark.asyncio+ async def test_cascade_skips_exec_file_delete_when_another_chat_references_execution(+ self, mock_prisma_calls, mock_transaction+ ):+ """Multi-chat reference → cascade skips the execution entirely+ (including its file allowlist). Without this the second chat's+ public viewer would break when the first chat is revoked."""+ mock_prisma_calls["session"].return_value.find_first = AsyncMock(+ return_value=_mock_session()+ )+ mock_prisma_calls["linked"].return_value.find_many = AsyncMock(+ return_value=[_mock_linked_share()]+ )+ other_link = ChatLinkedShare.model_construct(+ id="link-2",+ createdAt=datetime.now(UTC),+ sessionId=OTHER_SESSION_ID,+ executionId=EXECUTION_ID,+ )+ mock_prisma_calls["linked"].return_value.find_first = AsyncMock(+ return_value=other_link+ )+ mock_prisma_calls["linked"].return_value.delete_many = AsyncMock(return_value=1)+ mock_prisma_calls["execution"].return_value.update = AsyncMock()+ mock_prisma_calls["file"].return_value.delete_many = AsyncMock(return_value=0)+ mock_prisma_calls["session"].return_value.update = AsyncMock()+ exec_file_delete = AsyncMock(return_value=0)+ mock_prisma_calls["exec_file"].return_value.delete_many = exec_file_delete++ await disable_chat_session_share(SESSION_ID, USER_ID)++ # Same posture as the execution.update assertion: don't touch+ # the allowlist when another chat still references the execution.+ exec_file_delete.assert_not_called()+++class TestEnableChatShareState:+ """Smoke tests for enable_chat_session_share + helpers."""++ @pytest.mark.asyncio+ async def test_raises_value_error_when_session_not_owned_by_user(+ self, mock_prisma_calls+ ):+ """A user can't enable sharing on a chat they don't own — both+ a security guarantee AND the shape callers expect for the 404+ path in the share route."""+ mock_prisma_calls["session"].return_value.find_first = AsyncMock(+ return_value=None+ )++ with pytest.raises(ValueError, match="not found for user"):+ await enable_chat_session_share(+ SESSION_ID, "other-user", auto_share_executions=False+ )++ @pytest.mark.asyncio+ async def test_reshare_cascades_old_chat_link_executions_before_rekey(+ self, mock_prisma_calls, mock_transaction+ ):+ """Re-sharing a chat (e.g. toggling auto-share off without+ Stop-sharing first) must cascade-revoke the previous generation+ of CHAT_LINK execution shares. Without this, the old per-exec+ tokens stay publicly active with no linkage row to reach them,+ leaving orphan public shares.+ """+ prev_link = _mock_linked_share() # CHAT_LINK execution with token-exec+ mock_prisma_calls["session"].return_value.find_first = AsyncMock(+ return_value=_mock_session()+ )+ # First find_many is the cascade pre-cleanup → return the+ # previous generation's linkage. Subsequent calls (none in+ # this enable path) would default to the fixture empty.+ mock_prisma_calls["linked"].return_value.find_many = AsyncMock(+ return_value=[prev_link]+ )+ # No other chat still references the execution.+ mock_prisma_calls["linked"].return_value.find_first = AsyncMock(+ return_value=None+ )+ mock_prisma_calls["linked"].return_value.delete_many = AsyncMock(return_value=1)+ exec_update = AsyncMock()+ mock_prisma_calls["execution"].return_value.update = exec_update+ mock_prisma_calls["execution"].return_value.find_many = AsyncMock(+ return_value=[]+ )+ mock_prisma_calls["file"].return_value.delete_many = AsyncMock(return_value=0)+ with patch("backend.copilot.sharing.db.PrismaChatMessage") as msg_mock:+ msg_mock.prisma.return_value.find_many = AsyncMock(return_value=[])+ mock_prisma_calls["session"].return_value.update = AsyncMock()+ await enable_chat_session_share(+ SESSION_ID, USER_ID, auto_share_executions=False+ )++ # Critical: the previous-generation CHAT_LINK execution was+ # revoked BEFORE the join-table delete that would have orphaned+ # it. Without the cascade the token stays live forever.+ exec_update.assert_called_once()+ update_data = exec_update.call_args.kwargs["data"]+ assert update_data == {+ "isShared": False,+ "shareToken": None,+ "sharedAt": None,+ "sharedVia": None,+ }++ @pytest.mark.asyncio+ async def test_enable_session_update_is_last_inside_transaction(+ self, mock_prisma_calls, mock_transaction+ ):+ """Session update must happen LAST so a crash before it can't+ leave the chat publicly readable with an empty file allowlist."""+ mock_prisma_calls["session"].return_value.find_first = AsyncMock(+ return_value=_mock_session()+ )+ # No executions to validate / link.+ mock_prisma_calls["execution"].return_value.find_many = AsyncMock(+ return_value=[]+ )+ mock_prisma_calls["file"].return_value.delete_many = AsyncMock(return_value=0)+ mock_prisma_calls["linked"].return_value.delete_many = AsyncMock(return_value=0)+ # _build_shared_chat_files needs to find no messages → no files.+ with patch("backend.copilot.sharing.db.PrismaChatMessage") as msg_mock:+ msg_mock.prisma.return_value.find_many = AsyncMock(return_value=[])+ mock_prisma_calls["session"].return_value.update = AsyncMock()++ token = await enable_chat_session_share(+ SESSION_ID, USER_ID, auto_share_executions=False+ )++ # Token returned, session.update called with isShared=True.+ assert isinstance(token, str)+ assert len(token) > 10+ update_call = mock_prisma_calls["session"].return_value.update.call_args+ assert update_call.kwargs["data"]["isShared"] is True+ assert update_call.kwargs["data"]["shareToken"] == token++ @pytest.mark.asyncio+ async def test_get_chat_share_state_returns_default_for_unknown_session(+ self, mock_prisma_calls+ ):+ """Non-existent / non-owned session reports unshared shape uniformly."""+ mock_prisma_calls["session"].return_value.find_first = AsyncMock(+ return_value=None+ )++ state = await get_chat_share_state(SESSION_ID, USER_ID)++ assert state.is_shared is False+ assert state.share_token is None++ @pytest.mark.asyncio+ async def test_get_chat_share_state_returns_token_when_shared(+ self, mock_prisma_calls+ ):+ """Owner of a shared session sees the actual token surfaced."""+ mock_prisma_calls["session"].return_value.find_first = AsyncMock(+ return_value=_mock_session()+ )++ state = await get_chat_share_state(SESSION_ID, USER_ID)++ assert state.is_shared is True+ assert state.share_token == "token-A"+++def _mock_tool_msg(content: str):+ """Build a minimal tool-role ChatMessage row for scanner tests."""+ from prisma.models import ChatMessage as PrismaChatMessage++ return PrismaChatMessage.model_construct(+ id="tm-1",+ createdAt=datetime.now(UTC),+ sessionId=SESSION_ID,+ role="tool",+ content=content,+ sequence=1,+ toolCalls=None,+ functionCall=None,+ name=None,+ toolCallId="call-1",+ refusal=None,+ )+++class TestFileReferencedInSession:+ @pytest.mark.asyncio+ async def test_uses_content_contains_candidate_query_for_workspace_uri(self):+ file_id = "11111111-2222-3333-4444-555555555555"+ msg = _mock_tool_msg(f"")+ with patch("backend.copilot.sharing.db.PrismaChatMessage") as msg_mock:+ find_many = AsyncMock(return_value=[msg])+ msg_mock.prisma.return_value.find_many = find_many++ found = await _file_referenced_in_session(+ session_id=SESSION_ID, file_id=file_id+ )++ assert found is True+ find_many.assert_awaited_once_with(+ where={"sessionId": SESSION_ID, "content": {"contains": file_id}},+ )++ @pytest.mark.asyncio+ async def test_falls_back_to_full_scan_for_json_fields(self):+ file_id = "11111111-2222-3333-4444-555555555555"+ msg = _mock_tool_msg("")+ msg.toolCalls = {"result": f"workspace://{file_id}#text/plain"}+ with patch("backend.copilot.sharing.db.PrismaChatMessage") as msg_mock:+ find_many = AsyncMock(side_effect=[[], [msg]])+ msg_mock.prisma.return_value.find_many = find_many++ found = await _file_referenced_in_session(+ session_id=SESSION_ID, file_id=file_id+ )++ assert found is True+ assert find_many.await_args_list[0].kwargs == {+ "where": {"sessionId": SESSION_ID, "content": {"contains": file_id}},+ }+ assert find_many.await_args_list[1].kwargs == {+ "where": {"sessionId": SESSION_ID},+ }+++class TestCollectExecutionIdsFromMessages:+ """Sub-agent discovery: which executions did this chat spawn?"""++ @pytest.mark.asyncio+ async def test_extracts_execution_id_from_execution_started_tool_response(+ self,+ ):+ """Tool responses with ``type=execution_started`` carry the run id."""+ msg = _mock_tool_msg(+ '{"type":"execution_started","execution_id":"exec-A","graph_id":"g1"}'+ )+ with patch("backend.copilot.sharing.db.PrismaChatMessage") as msg_mock:+ msg_mock.prisma.return_value.find_many = AsyncMock(return_value=[msg])+ ids = await _collect_execution_ids_from_messages(session_id=SESSION_ID)+ assert ids == {"exec-A"}++ @pytest.mark.asyncio+ async def test_dedupes_executions_across_multiple_tool_messages(self):+ """The same execution referenced twice → single entry."""+ m1 = _mock_tool_msg('{"type":"execution_started","execution_id":"exec-A"}')+ m2 = _mock_tool_msg('{"type":"execution_started","execution_id":"exec-A"}')+ m3 = _mock_tool_msg('{"type":"execution_started","execution_id":"exec-B"}')+ with patch("backend.copilot.sharing.db.PrismaChatMessage") as msg_mock:+ msg_mock.prisma.return_value.find_many = AsyncMock(+ return_value=[m1, m2, m3]+ )+ ids = await _collect_execution_ids_from_messages(session_id=SESSION_ID)+ assert ids == {"exec-A", "exec-B"}++ @pytest.mark.asyncio+ async def test_ignores_non_execution_started_tool_responses(self):+ """Other tool types must not contribute to the linked-execs set."""+ msg = _mock_tool_msg(+ '{"type":"web_fetch","url":"https://example.com","status_code":200}'+ )+ with patch("backend.copilot.sharing.db.PrismaChatMessage") as msg_mock:+ msg_mock.prisma.return_value.find_many = AsyncMock(return_value=[msg])+ ids = await _collect_execution_ids_from_messages(session_id=SESSION_ID)+ assert ids == set()++ @pytest.mark.asyncio+ async def test_ignores_malformed_json_tool_content(self):+ """Tool content that isn't valid JSON shouldn't crash the scan."""+ msg = _mock_tool_msg("not-json-at-all {{")+ with patch("backend.copilot.sharing.db.PrismaChatMessage") as msg_mock:+ msg_mock.prisma.return_value.find_many = AsyncMock(return_value=[msg])+ ids = await _collect_execution_ids_from_messages(session_id=SESSION_ID)+ assert ids == set()++ @pytest.mark.asyncio+ async def test_ignores_execution_started_with_missing_id(self):+ """Defense-in-depth — a malformed payload without execution_id."""+ msg = _mock_tool_msg('{"type":"execution_started"}')+ with patch("backend.copilot.sharing.db.PrismaChatMessage") as msg_mock:+ msg_mock.prisma.return_value.find_many = AsyncMock(return_value=[msg])+ ids = await _collect_execution_ids_from_messages(session_id=SESSION_ID)+ assert ids == set()++ @pytest.mark.asyncio+ async def test_extracts_execution_id_from_agent_output_response(self):+ """``wait_for_result`` sync-complete runs persist an AgentOutputResponse+ with ``execution_id`` nested under ``execution`` rather than at the+ top level. Without this branch, sync-complete runs would never be+ auto-linked when the owner re-shares the chat — the exact bug we+ debugged on the QuickThemedGreeter chat."""+ msg = _mock_tool_msg(+ '{"type":"agent_output",'+ '"message":"Agent X completed.",'+ '"execution":{"execution_id":"exec-sync","status":"COMPLETED"}}'+ )+ with patch("backend.copilot.sharing.db.PrismaChatMessage") as msg_mock:+ msg_mock.prisma.return_value.find_many = AsyncMock(return_value=[msg])+ ids = await _collect_execution_ids_from_messages(session_id=SESSION_ID)+ assert ids == {"exec-sync"}++ @pytest.mark.asyncio+ async def test_extracts_execution_id_from_error_response(self):+ """Failed / terminated real executions can be recovered on re-share+ when the runtime hook missed the original link attempt."""+ msg = _mock_tool_msg('{"type":"error","execution_id":"exec-failed"}')+ with patch("backend.copilot.sharing.db.PrismaChatMessage") as msg_mock:+ msg_mock.prisma.return_value.find_many = AsyncMock(return_value=[msg])+ ids = await _collect_execution_ids_from_messages(session_id=SESSION_ID)+ assert ids == {"exec-failed"}++ @pytest.mark.asyncio+ async def test_ignores_scheduled_execution_started_response(self):+ """Schedule setup responses carry a schedule id, not a graph execution id."""+ msg = _mock_tool_msg(+ '{"type":"execution_started","execution_id":"schedule-id","status":"SCHEDULED"}'+ )+ with patch("backend.copilot.sharing.db.PrismaChatMessage") as msg_mock:+ msg_mock.prisma.return_value.find_many = AsyncMock(return_value=[msg])+ ids = await _collect_execution_ids_from_messages(session_id=SESSION_ID)+ assert ids == set()++ @pytest.mark.asyncio+ async def test_ignores_agent_output_with_missing_execution_block(self):+ """An agent_output without a nested execution block is a no-op."""+ msg = _mock_tool_msg('{"type":"agent_output","message":"done"}')+ with patch("backend.copilot.sharing.db.PrismaChatMessage") as msg_mock:+ msg_mock.prisma.return_value.find_many = AsyncMock(return_value=[msg])+ ids = await _collect_execution_ids_from_messages(session_id=SESSION_ID)+ assert ids == set()+++class TestSharedExecutionFileAllowlist:+ @pytest.mark.asyncio+ async def test_uses_public_output_blocks_not_all_node_outputs(+ self, mock_prisma_calls+ ):+ """CHAT_LINK execution shares should expose only files visible in+ the public execution viewer, matching normal execution shares."""+ hidden_file = "11111111-2222-3333-4444-555555555555"+ public_file = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"+ hidden_node = SimpleNamespace(+ Node=SimpleNamespace(agentBlockId="standard-block"),+ executionData={+ "result": f"workspace://{hidden_file}#text/csv",+ },+ Input=None,+ )+ output_node = SimpleNamespace(+ Node=SimpleNamespace(agentBlockId="output-block"),+ executionData={+ "name": "Final report",+ "value": f"workspace://{public_file}#text/markdown",+ },+ Input=None,+ )+ execution = SimpleNamespace(NodeExecutions=[hidden_node, output_node])++ mock_prisma_calls["execution"].return_value.find_unique = AsyncMock(+ return_value=execution+ )+ mock_prisma_calls["workspace"].return_value.find_unique = AsyncMock(+ return_value=SimpleNamespace(id="workspace-1")+ )+ mock_prisma_calls["workspace_file"].return_value.find_many = AsyncMock(+ return_value=[SimpleNamespace(id=public_file)]+ )+ mock_prisma_calls["exec_file"].return_value.create = AsyncMock()++ def get_block(block_id: str):+ block_type = (+ BlockType.OUTPUT if block_id == "output-block" else BlockType.STANDARD+ )+ return SimpleNamespace(block_type=block_type)++ with patch("backend.copilot.sharing.db.get_block", side_effect=get_block):+ created = await _build_shared_execution_file_allowlist(+ execution_id=EXECUTION_ID,+ share_token="share-token",+ user_id=USER_ID,+ )++ assert created == 1+ find_many_call = mock_prisma_calls[+ "workspace_file"+ ].return_value.find_many.call_args.kwargs+ assert find_many_call["where"]["id"] == {"in": [public_file]}+ mock_prisma_calls["exec_file"].return_value.create.assert_awaited_once_with(+ data={+ "executionId": EXECUTION_ID,+ "fileId": public_file,+ "shareToken": "share-token",+ }+ )+++class TestLinkNewExecutionToChatShare:+ """Runtime hook: new run_agent → auto-link if chat has autoShareExecutions=True."""++ @pytest.mark.asyncio+ async def test_no_op_when_chat_not_shared(self, mock_prisma_calls):+ """An execution in an unshared chat is never auto-linked."""+ unshared = _mock_session()+ unshared.isShared = False+ unshared.autoShareExecutions = False+ mock_prisma_calls["session"].return_value.find_unique = AsyncMock(+ return_value=unshared+ )+ link_create = AsyncMock()+ mock_prisma_calls["linked"].return_value.create = link_create++ await link_new_execution_to_chat_share(+ session_id=SESSION_ID, execution_id=EXECUTION_ID+ )++ link_create.assert_not_called()++ @pytest.mark.asyncio+ async def test_no_op_when_auto_share_executions_off(self, mock_prisma_calls):+ """Chat shared but the owner opted out of auto-sharing runs."""+ opted_out = _mock_session(auto_share_executions=False)+ mock_prisma_calls["session"].return_value.find_unique = AsyncMock(+ return_value=opted_out+ )+ link_create = AsyncMock()+ mock_prisma_calls["linked"].return_value.create = link_create++ await link_new_execution_to_chat_share(+ session_id=SESSION_ID, execution_id=EXECUTION_ID+ )++ link_create.assert_not_called()++ @pytest.mark.asyncio+ async def test_idempotent_when_link_already_exists(self, mock_prisma_calls):+ """Repeated calls for the same (session, execution) pair don't double-link."""+ mock_prisma_calls["session"].return_value.find_unique = AsyncMock(+ return_value=_mock_session(auto_share_executions=True)+ )+ mock_prisma_calls["execution"].return_value.find_first = AsyncMock(+ return_value=_mock_execution()+ )+ # Existing ChatLinkedShare row for this (session, execution).+ mock_prisma_calls["linked"].return_value.find_first = AsyncMock(+ return_value=ChatLinkedShare.model_construct(+ sessionId=SESSION_ID, executionId=EXECUTION_ID+ )+ )+ link_create = AsyncMock()+ mock_prisma_calls["linked"].return_value.create = link_create++ await link_new_execution_to_chat_share(+ session_id=SESSION_ID, execution_id=EXECUTION_ID+ )++ link_create.assert_not_called()++ @pytest.mark.asyncio+ async def test_swallows_prisma_failures_without_crashing_caller(+ self, mock_prisma_calls+ ):+ """The hook runs inside the CoPilotExecutor worker; if Prisma is+ unconnected there, the underlying find_unique raises+ ClientNotConnectedError. The hook must NEVER let that escape —+ crashing run_agent surfaces as "The model returned an empty+ response" via the orphan tool_use SDK path. Best-effort: a+ sharing failure must not break the underlying tool.+ """+ from prisma.errors import ClientNotConnectedError++ mock_prisma_calls["session"].return_value.find_unique = AsyncMock(+ side_effect=ClientNotConnectedError()+ )+ # Should NOT raise — the hook catches everything.+ await link_new_execution_to_chat_share(+ session_id=SESSION_ID, execution_id=EXECUTION_ID+ )++ @pytest.mark.asyncio+ async def test_links_new_execution_when_auto_share_on(+ self, mock_prisma_calls, mock_transaction+ ):+ """Chat shared with autoShareExecutions=True → new run gets linked."""+ mock_prisma_calls["session"].return_value.find_unique = AsyncMock(+ return_value=_mock_session(auto_share_executions=True)+ )+ mock_prisma_calls["execution"].return_value.find_first = AsyncMock(+ return_value=_mock_execution()+ )+ mock_prisma_calls["linked"].return_value.find_first = AsyncMock(+ return_value=None+ )+ link_create = AsyncMock()+ mock_prisma_calls["linked"].return_value.create = link_create+ # ``_link_executions_to_share`` uses ``update_many`` with an+ # ``isShared: False`` guard. Mock its return as 0 because the+ # fixture execution is already shared — pinning the DB-conditional+ # behaviour. See ``test_link_skips_already_shared_execution``+ # below for the inverse.+ update_many = AsyncMock(return_value=0)+ mock_prisma_calls["execution"].return_value.update_many = update_many++ await link_new_execution_to_chat_share(+ session_id=SESSION_ID, execution_id=EXECUTION_ID+ )++ link_create.assert_called_once()+ call_data = link_create.call_args.kwargs["data"]+ assert call_data["sessionId"] == SESSION_ID+ assert call_data["executionId"] == EXECUTION_ID+ # Conditional update guards against stale in-memory ``isShared``+ # — the where clause must include ``isShared: False`` so the+ # update is a no-op when the execution was independently shared.+ update_many.assert_called_once()+ where = update_many.call_args.kwargs["where"]+ assert where["id"] == EXECUTION_ID+ assert where["isShared"] is False++ @pytest.mark.asyncio+ async def test_in_tx_recheck_aborts_when_concurrent_disable_unshared_session(+ self, mock_prisma_calls, mock_transaction+ ):+ """Race defense: outside-tx ``session.find_unique`` saw+ ``isShared=True``, but by the time we open the cascade transaction+ a concurrent ``disable_chat_session_share`` has flipped it to+ ``isShared=False``. The in-tx re-read must catch that and bail+ BEFORE we create a ``ChatLinkedShare`` row that would point at a+ no-longer-shared parent.+ """+ shared_outside = _mock_session(auto_share_executions=True)+ unshared_in_tx = _mock_session(auto_share_executions=True)+ unshared_in_tx.isShared = False++ # First call (outside the tx) returns the shared snapshot;+ # second call (inside the tx) returns the unshared snapshot.+ mock_prisma_calls["session"].return_value.find_unique = AsyncMock(+ side_effect=[shared_outside, unshared_in_tx]+ )+ link_create = AsyncMock()+ mock_prisma_calls["linked"].return_value.create = link_create+ update_many = AsyncMock(return_value=0)+ mock_prisma_calls["execution"].return_value.update_many = update_many++ await link_new_execution_to_chat_share(+ session_id=SESSION_ID, execution_id=EXECUTION_ID+ )++ # Critical: no linkage row was created because the in-tx+ # re-check fired the early-return branch.+ link_create.assert_not_called()+ update_many.assert_not_called()++ @pytest.mark.asyncio+ async def test_link_flips_unshared_execution_to_chat_link_provenance(+ self, mock_prisma_calls, mock_transaction+ ):+ """Brand-new execution (isShared=False at insert) → conditional+ update flips it to CHAT_LINK with a freshly minted token. The+ DB-level conditional (``isShared: False`` in the where clause)+ protects against the race where another transaction has just+ shared the execution between the prefetch and the update."""+ unshared_exec = _mock_execution()+ unshared_exec.isShared = False+ unshared_exec.shareToken = None+ unshared_exec.sharedAt = None+ unshared_exec.sharedVia = None++ mock_prisma_calls["session"].return_value.find_unique = AsyncMock(+ return_value=_mock_session(auto_share_executions=True)+ )+ mock_prisma_calls["execution"].return_value.find_first = AsyncMock(+ return_value=unshared_exec+ )+ mock_prisma_calls["linked"].return_value.find_first = AsyncMock(+ return_value=None+ )+ mock_prisma_calls["linked"].return_value.create = AsyncMock()+ # Conditional update succeeds — the DB still reports isShared=False.+ update_many = AsyncMock(return_value=1)+ mock_prisma_calls["execution"].return_value.update_many = update_many++ await link_new_execution_to_chat_share(+ session_id=SESSION_ID, execution_id=EXECUTION_ID+ )++ update_many.assert_called_once()+ call = update_many.call_args.kwargs+ assert call["where"] == {"id": EXECUTION_ID, "isShared": False}+ assert call["data"]["isShared"] is True+ assert call["data"]["sharedVia"] == SharedVia.CHAT_LINK+ assert call["data"]["shareToken"] is not None+ assert call["data"]["sharedAt"] is not Nonediff --git a/autogpt_platform/backend/backend/copilot/sharing/models.py b/autogpt_platform/backend/backend/copilot/sharing/models.pynew file mode 100644index 0000000000..b786f1d4d9--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/sharing/models.py@@ -0,0 +1,256 @@+"""Public response models + sanitizer for shared chat sessions.++A shared chat link is fundamentally a public URL — anyone can read it.+Three classes of data therefore must NEVER leave the backend on this+path:++1. ``ChatSession.credentials`` — provider auth metadata. Dropped wholesale.+2. ``ChatMessage.metadata`` — dispatcher payload (file_ids, model,+ permissions, request_arrival_at). Dropped wholesale.+3. Tool-call arguments / function-call arguments shaped like secrets —+ keys matching :data:`_SECRET_KEY_HINTS`. Redacted in place so the+ conversation still renders coherently, but the values never leak.++The sanitizer also strips server-injected context blocks from user+messages (memory_context / env_context / user_context) via the existing+:func:`strip_injected_context_for_display`. That data is never owned+by the user and would confuse a public reader.+"""++import json+import re+from datetime import datetime+from typing import Any++from pydantic import BaseModel++from backend.copilot.model import ChatMessage as ChatMessageDomain+from backend.copilot.model import ChatSessionInfo+from backend.copilot.service import strip_injected_context_for_display++# Secret-shaped key hints. Each entry is a whole "word" — boundary+# matching is enforced by :data:`_SECRET_KEY_RE` so that ``token`` does+# not false-positive against ``prompt_tokens`` (LLM usage metadata) and+# ``auth`` does not false-positive against ``author`` (attribution).+_SECRET_KEY_HINTS = (+ "api_key",+ "api_keys",+ "api_token",+ "apikey",+ "auth",+ "authorization",+ "bearer",+ "cookie",+ "credential",+ "credentials",+ "oauth",+ "passwd",+ "password",+ "secret",+ "secrets",+ "token",+)+_REDACTED = "[redacted]"++# Boundary-aware matcher. ``(?<![a-z0-9])`` and ``(?![a-z0-9])`` reject+# matches where a letter/digit sits on either side of the hint, so:+#+# - ``access_token`` matches ``token`` (``_`` boundary, end)+# - ``total_tokens`` does NOT match (``s`` letter follows)+# - ``author`` does NOT match (``o`` letter follows ``auth``)+# - ``Authorization`` matches ``authorization`` whole, case-insensitive+#+# Using these lookarounds rather than ``\b`` is deliberate: ``\b`` treats+# underscore as a word character, which would mis-classify the ``_`` →+# letter transition in ``total_tokens`` as a non-boundary and leak.+_SECRET_KEY_RE = re.compile(+ r"(?<![a-z0-9])(?:"+ + "|".join(re.escape(h) for h in _SECRET_KEY_HINTS)+ + r")(?![a-z0-9])",+ re.IGNORECASE,+)+++class SharedChatLinkedExecution(BaseModel):+ """Drill-in pointer for an AgentGraphExecution shared alongside a chat."""++ execution_id: str+ graph_id: str+ graph_name: str | None+ share_token: str | None+ """``None`` when the linked execution was NOT opted-in at share time.++ The viewer can still render the inline tool-call snapshot but cannot+ deep-link into the full execution page."""+++class SharedChatMessage(BaseModel):+ """Public-safe projection of a single chat message."""++ id: str+ role: str+ content: str | None+ name: str | None+ tool_call_id: str | None+ tool_calls: list[dict] | None+ function_call: dict | None+ sequence: int+ created_at: datetime+++class SharedChatSession(BaseModel):+ """Public-safe projection of a chat session (header only)."""++ id: str+ title: str | None+ created_at: datetime+ updated_at: datetime+ shared_at: datetime | None+ """When the owner enabled sharing on this chat. Surfaced so the+ public viewer can render "Shared {date}" against the share-enable+ moment instead of the chat creation date (which can be months+ older for long-lived chats)."""+ linked_executions: list[SharedChatLinkedExecution]+++class SharedChatMessagesPage(BaseModel):+ """Paginated message window for the public viewer."""++ messages: list[SharedChatMessage]+ has_more: bool+ oldest_sequence: int | None+++class ChatShareState(BaseModel):+ """Owner-facing share state for a chat session (not a public model).++ Powers the share modal: ``is_shared`` / ``share_token`` decide the+ share-vs-revoke mode, and the three counts drive the consent-disclosure+ block above the toggle so the owner sees exactly what they're about to+ expose. The counts reflect live state — sharing is live, not+ snapshot-at-enable — so they ARE the numbers visible the moment the+ owner enables sharing.+ """++ is_shared: bool+ share_token: str | None+ auto_share_executions: bool = False+ message_count: int = 0+ linked_run_count: int = 0+ file_count: int = 0+++def sanitize_chat_session(+ session: ChatSessionInfo,+ *,+ linked_executions: list[SharedChatLinkedExecution],+ shared_at: datetime | None = None,+) -> SharedChatSession:+ """Project a session for public consumption.++ Drops credentials and dispatcher metadata; keeps only display fields.+ """+ return SharedChatSession(+ id=session.session_id,+ title=session.title,+ created_at=session.started_at,+ updated_at=session.updated_at,+ shared_at=shared_at,+ linked_executions=linked_executions,+ )+++def sanitize_chat_message(message: ChatMessageDomain) -> SharedChatMessage:+ """Project a message for public consumption.++ - Strips injected context blocks from ``role=user`` string content.+ - Redacts secret-shaped keys inside ``tool_calls`` and ``function_call``.+ - Redacts secret-shaped keys inside ``role=tool`` JSON content when it+ parses as JSON (tool responses carry structured payloads like+ ``agent_output``, ``view_agent_output``, dry-run ``node_executions``+ with block I/O — any of which may contain a secret-shaped field).+ Non-JSON tool content (free-form strings) passes through unchanged,+ same posture as ``role=assistant``.+ - Drops the per-row dispatcher metadata entirely.+ - Drops ``refusal`` (model-internal signal, not user content).++ Plain ``content`` on ``role=user`` / ``role=assistant`` is intentionally+ **not** key-redacted. Tool-call arguments are structured data with+ stable secret-shaped keys (``api_key``, ``auth_token``) that we can+ pattern-match safely, but free-form chat content has no such structure+ -- any regex pass would either miss most real cases or false-positive+ on legitimate text. The share modal's warning banner ("don't share+ if it contains secrets you pasted") makes plain-content exposure an+ explicit user-opt-in decision.+ """+ content = message.content+ if message.role == "user" and isinstance(content, str) and content:+ content = strip_injected_context_for_display(content)+ elif message.role == "tool" and isinstance(content, str) and content:+ content = _redact_secret_keys_in_json_string(content)++ return SharedChatMessage(+ id=message.id or "",+ role=message.role,+ content=content,+ name=message.name,+ tool_call_id=message.tool_call_id,+ tool_calls=_redact_tool_calls(message.tool_calls),+ function_call=_redact_secret_keys(message.function_call),+ sequence=message.sequence or 0,+ created_at=message.created_at or datetime.fromtimestamp(0),+ )+++def _redact_tool_calls(tool_calls: list[dict] | None) -> list[dict] | None:+ if tool_calls is None:+ return None+ return [_redact_secret_keys(tc) for tc in tool_calls]+++def _redact_secret_keys(value: Any) -> Any:+ """Recursively walk *value* and redact secret-shaped subtrees.++ Returns a new structure; never mutates the input. When a dict key+ matches a secret-shaped hint, the ENTIRE subtree under that key is+ replaced with the ``_REDACTED`` sentinel — including lists and+ nested dicts. Pre-fix this only redacted string leaves at the+ immediate level, so payloads like ``{"api_keys": ["sk-1", "sk-2"]}``+ or ``{"auth": {"bearer": "tok"}}`` leaked through because the+ inner leaves had no secret-shaped key wrapping them. Lose the+ (rare, low-value) ability to surface bool/int metadata under a+ secret-shaped key — the sanitizer is the load-bearing security+ boundary for the public viewer.+ """+ if isinstance(value, dict):+ return {+ k: (_REDACTED if _is_secret_key(k) else _redact_secret_keys(v))+ for k, v in value.items()+ }+ if isinstance(value, list):+ return [_redact_secret_keys(item) for item in value]+ return value+++def _is_secret_key(key: str) -> bool:+ return _SECRET_KEY_RE.search(key) is not None+++def _redact_secret_keys_in_json_string(value: str) -> str:+ """Parse *value* as JSON, walk it through :func:`_redact_secret_keys`,+ and re-serialise. Returns *value* unchanged when it isn't valid JSON.++ Tool messages (``role=tool``) persist structured tool responses+ (``agent_output``, ``view_agent_output``, dry-run ``node_executions``+ with block I/O, MCP tool returns) as JSON-serialised strings. The+ public viewer reads these verbatim, so a tool response payload+ containing ``{"api_key": "sk-..."}`` would leak the key. Non-JSON+ content passes through untouched to preserve the posture documented+ on :func:`sanitize_chat_message`.+ """+ try:+ parsed = json.loads(value)+ except (json.JSONDecodeError, ValueError):+ return value+ redacted = _redact_secret_keys(parsed)+ return json.dumps(redacted)diff --git a/autogpt_platform/backend/backend/copilot/sharing/models_test.py b/autogpt_platform/backend/backend/copilot/sharing/models_test.pynew file mode 100644index 0000000000..21d4842ad7--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/sharing/models_test.py@@ -0,0 +1,249 @@+"""Unit tests for the public-share sanitizer.++The sanitizer is the security boundary for public chat sharing — every+test here is checking that data which must NOT cross the public link+genuinely does not.+"""++from datetime import datetime, timezone++from backend.copilot.model import ChatMessage as ChatMessageDomain+from backend.copilot.sharing.models import _redact_secret_keys, sanitize_chat_message+++def _msg(**overrides) -> ChatMessageDomain:+ defaults = dict(+ id="m1",+ role="assistant",+ content=None,+ sequence=0,+ created_at=datetime(2026, 5, 11, tzinfo=timezone.utc),+ )+ defaults.update(overrides)+ return ChatMessageDomain(**defaults)+++class TestRedactSecretKeys:+ def test_redacts_api_key_at_top_level(self):+ result = _redact_secret_keys({"api_key": "sk-xyz", "model": "claude"})+ assert result == {"api_key": "[redacted]", "model": "claude"}++ def test_redacts_nested_secrets_in_arguments(self):+ result = _redact_secret_keys(+ {+ "name": "run_agent",+ "arguments": {+ "auth_token": "eyJ...",+ "input": {"foo": "bar"},+ },+ }+ )+ assert result["arguments"]["auth_token"] == "[redacted]"+ assert result["arguments"]["input"] == {"foo": "bar"}++ def test_passes_through_non_secret_strings(self):+ result = _redact_secret_keys({"prompt": "hello"})+ assert result == {"prompt": "hello"}++ def test_matches_case_insensitively(self):+ result = _redact_secret_keys({"API_KEY": "x", "Cookie": "y"})+ assert result == {"API_KEY": "[redacted]", "Cookie": "[redacted]"}++ def test_redacts_password_variants(self):+ result = _redact_secret_keys({"password": "p", "passwd": "p2"})+ assert result == {"password": "[redacted]", "passwd": "[redacted]"}++ def test_walks_lists(self):+ result = _redact_secret_keys(+ [{"secret": "x"}, {"name": "y"}],+ )+ assert result == [{"secret": "[redacted]"}, {"name": "y"}]++ def test_redacts_secret_shaped_key_regardless_of_value_type(self):+ # Secret-shaped keys redact their ENTIRE subtree — strings,+ # ints, bools, lists, dicts. Trades the (rare) ability to+ # surface bool/int metadata under a secret-shaped key for+ # sealing the leak vectors below.+ assert _redact_secret_keys({"token": 42}) == {"token": "[redacted]"}+ assert _redact_secret_keys({"requires_auth": True}) == {+ "requires_auth": "[redacted]",+ }++ def test_redacts_list_under_secret_shaped_key(self):+ # Regression: pre-fix this leaked because the list is not a+ # string and the inner items had no secret-shaped key wrapping.+ result = _redact_secret_keys({"api_keys": ["sk-prod", "sk-test"]})+ assert result == {"api_keys": "[redacted]"}++ def test_redacts_nested_dict_under_secret_shaped_key(self):+ # Regression: pre-fix this leaked because the dict value+ # recursed and the inner ``bearer`` key didn't match any hint.+ result = _redact_secret_keys({"auth": {"bearer": "tok-xyz"}})+ assert result == {"auth": "[redacted]"}++ def test_redacts_list_of_dicts_under_secret_shaped_key(self):+ # Regression: pre-fix this leaked end-to-end.+ result = _redact_secret_keys(+ {"oauth_tokens": [{"value": "tok-1"}, {"value": "tok-2"}]}+ )+ assert result == {"oauth_tokens": "[redacted]"}++ def test_does_not_mutate_input(self):+ original = {"api_key": "sk-1"}+ _redact_secret_keys(original)+ assert original == {"api_key": "sk-1"}++ def test_does_not_redact_llm_usage_token_counts(self):+ # Cursor regression: substring matching mis-flagged+ # ``prompt_tokens`` / ``completion_tokens`` / ``total_tokens`` as+ # secret-shaped because they contain ``token``. These are+ # legitimate usage-metadata fields and must survive sanitization.+ result = _redact_secret_keys(+ {+ "prompt_tokens": 100,+ "completion_tokens": 50,+ "total_tokens": 150,+ "input_tokens": 80,+ }+ )+ assert result == {+ "prompt_tokens": 100,+ "completion_tokens": 50,+ "total_tokens": 150,+ "input_tokens": 80,+ }++ def test_does_not_redact_author_field(self):+ # Cursor regression: ``auth`` substring used to match ``author``+ # — attribution fields would silently turn into ``[redacted]``.+ result = _redact_secret_keys({"author": "alice", "title": "post"})+ assert result == {"author": "alice", "title": "post"}++ def test_redacts_authorization_header_whole_word(self):+ # ``Authorization`` is a whole word in the hint list — case-+ # insensitive boundary match still catches the HTTP-header form+ # that anything with substring matching used to catch via+ # ``auth``.+ result = _redact_secret_keys({"Authorization": "Bearer xyz"})+ assert result == {"Authorization": "[redacted]"}++ def test_redacts_token_at_underscore_boundaries(self):+ # Tightening the matcher must NOT regress the common+ # ``access_token`` / ``refresh_token`` shapes.+ result = _redact_secret_keys(+ {"access_token": "x", "refresh_token": "y", "id_token": "z"}+ )+ assert result == {+ "access_token": "[redacted]",+ "refresh_token": "[redacted]",+ "id_token": "[redacted]",+ }+++class TestSanitizeChatMessage:+ def test_drops_refusal_and_metadata(self):+ msg = _msg(+ role="assistant",+ content="reply",+ refusal="I cannot do that",+ metadata={"file_ids": ["secret-file"], "model": "claude"},+ )+ sanitized = sanitize_chat_message(msg)+ # SharedChatMessage has no refusal/metadata fields, so they+ # cannot be exposed via the public payload.+ dumped = sanitized.model_dump()+ assert "refusal" not in dumped+ assert "metadata" not in dumped++ def test_redacts_tool_call_arguments(self):+ msg = _msg(+ role="assistant",+ tool_calls=[+ {+ "id": "call_1",+ "function": {+ "name": "fetch",+ "arguments": {+ "url": "https://example.com",+ "api_key": "sk-xyz",+ },+ },+ }+ ],+ )+ sanitized = sanitize_chat_message(msg)+ assert sanitized.tool_calls is not None+ args = sanitized.tool_calls[0]["function"]["arguments"]+ assert args["api_key"] == "[redacted]"+ assert args["url"] == "https://example.com"++ def test_strips_injected_context_from_user_messages(self):+ # Real injected contexts use a ``\n\n`` separator between the+ # closing tag and the user's actual text — the regex in+ # ``strip_injected_context_for_display`` requires that to anchor+ # the leading-block match. This mirrors the production format.+ msg = _msg(+ role="user",+ content="<memory_context>secret</memory_context>\n\nhello",+ )+ sanitized = sanitize_chat_message(msg)+ assert sanitized.content is not None+ assert "secret" not in sanitized.content+ assert "hello" in sanitized.content++ def test_assistant_content_passes_through_unchanged(self):+ # The stripper is intentionally user-only — assistant content+ # may legitimately reference these tags in narrative form.+ msg = _msg(role="assistant", content="see <memory_context> docs")+ sanitized = sanitize_chat_message(msg)+ assert sanitized.content == "see <memory_context> docs"++ def test_no_tool_calls_yields_none(self):+ msg = _msg(role="assistant", content="hi")+ sanitized = sanitize_chat_message(msg)+ assert sanitized.tool_calls is None++ def test_redacts_secret_keys_in_tool_role_json_content(self):+ # Tool messages (``role=tool``) persist tool responses as+ # JSON-serialised strings. A response payload with a secret-+ # shaped key MUST get redacted on the public share path — without+ # this, ``{"api_key": "sk-…"}`` in a tool output leaks verbatim.+ msg = _msg(+ role="tool",+ content=(+ '{"type":"agent_output",'+ '"execution":{"outputs":{"api_key":"sk-leaked",'+ '"public":"ok"}}}'+ ),+ )+ sanitized = sanitize_chat_message(msg)+ assert sanitized.content is not None+ import json as _json++ payload = _json.loads(sanitized.content)+ outputs = payload["execution"]["outputs"]+ assert outputs["api_key"] == "[redacted]"+ assert outputs["public"] == "ok"++ def test_tool_content_passes_through_when_not_json(self):+ # Non-JSON tool content (older / hand-rolled tool returns) must+ # pass through untouched — same posture as plain assistant text.+ msg = _msg(role="tool", content="completed without output")+ sanitized = sanitize_chat_message(msg)+ assert sanitized.content == "completed without output"++ def test_tool_content_redacts_secret_under_nested_list(self):+ # The recursive walk must redact secret-shaped subtrees inside+ # tool JSON arrays too. Failure here would leak when a tool+ # returns ``{"api_keys": ["sk-1", "sk-2"]}``.+ msg = _msg(+ role="tool",+ content='{"api_keys":["sk-1","sk-2"],"count":2}',+ )+ sanitized = sanitize_chat_message(msg)+ assert sanitized.content is not None+ import json as _json++ payload = _json.loads(sanitized.content)+ assert payload["api_keys"] == "[redacted]"+ assert payload["count"] == 2diff --git a/autogpt_platform/backend/backend/copilot/tools/models.py b/autogpt_platform/backend/backend/copilot/tools/models.pyindex 88d9695102..bbe0d23a00 100644--- a/autogpt_platform/backend/backend/copilot/tools/models.py+++ b/autogpt_platform/backend/backend/copilot/tools/models.py@@ -284,6 +284,7 @@ class ErrorResponse(ToolResponseBase):"""Response for errors."""type: ResponseType = ResponseType.ERROR+ execution_id: str | None = Noneerror: str | None = Nonedetails: dict[str, Any] | None = Nonediff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent.py b/autogpt_platform/backend/backend/copilot/tools/run_agent.pyindex c75e68dfca..b5a7f1febc 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent.py@@ -15,7 +15,7 @@ from backend.data.graph import GraphModelfrom backend.data.model import CredentialsMetaInputfrom backend.executor import utils as execution_utilsfrom backend.executor.utils import is_credential_validation_error_message-from backend.util.clients import get_scheduler_client+from backend.util.clients import get_database_manager_async_client, get_scheduler_clientfrom backend.util.exceptions import DatabaseError, GraphValidationError, NotFoundErrorfrom backend.util.timezone_utils import (convert_utc_time_to_user_timezone,@@ -50,9 +50,40 @@ from .utils import (logger = logging.getLogger(__name__)config = ChatConfig()++async def _safe_link_to_chat_share(session_id: str, execution_id: str) -> None:+ """Best-effort client-side wrapper around the chat-share auto-link hook.++ The server-side function ``link_new_execution_to_chat_share`` has its+ own try/except (db.py) so server-raised exceptions never bubble. But+ the call goes over the DatabaseManager RPC boundary, and transport-+ layer failures (``ClientNotConnectedError``, RabbitMQ flap, retry+ exhaustion) raise CLIENT-side — before the wrapped function runs.++ Six callsites in this file dispatch the hook from inside ``run_agent``,+ which must never crash because the wrapper SDK turns an orphan+ ``tool_use`` into "The model returned an empty response." So catch+ everything here and log; the owner can recover by re-toggling share+ (``_collect_execution_ids_from_messages`` backfills at re-enable time).+ """+ try:+ await get_database_manager_async_client().link_new_execution_to_chat_share(+ session_id=session_id, execution_id=execution_id+ )+ except Exception:+ logger.warning(+ "link_new_execution_to_chat_share RPC failed for session=%s "+ "execution=%s; owner can re-share to recover",+ session_id,+ execution_id,+ exc_info=True,+ )++# Constants for response messagesMSG_DO_NOT_RUN_AGAIN = "Do not run again unless explicitly requested."MSG_DO_NOT_SCHEDULE_AGAIN = "Do not schedule again unless explicitly requested."+SCHEDULED_STATUS = "SCHEDULED"MSG_ASK_USER_FOR_VALUES = ("Ask the user what values to use, or call again with use_defaults=true ""to run with default values."@@ -713,6 +744,9 @@ class RunAgentTool(BaseTool):execution.id,exc_info=True,)+ await _safe_link_to_chat_share(+ session_id=session_id, execution_id=execution.id+ )return AgentOutputResponse(message=(f"Agent '{library_agent.name}' completed successfully. "@@ -734,25 +768,44 @@ class RunAgentTool(BaseTool):)elif completed and completed.status == ExecutionStatus.FAILED:error_detail = completed.stats.error if completed.stats else None+ # Auto-share the failed run too — share-modal users may+ # want public viewers to drill into the failure. Without+ # this hook, ``_collect_execution_ids_from_messages`` can't+ # backfill failed runs either (ErrorResponse payload type+ # isn't in the scanned set).+ await _safe_link_to_chat_share(+ session_id=session_id, execution_id=execution.id+ )return ErrorResponse(message=(f"Agent '{library_agent.name}' execution failed. "f"View details at {library_agent_link}."),session_id=session_id,+ execution_id=execution.id,error=error_detail,)elif completed and completed.status == ExecutionStatus.TERMINATED:error_detail = completed.stats.error if completed.stats else None+ # Auto-share terminated runs (cancelled / killed) for the+ # same reason as the FAILED branch — backfill at re-share+ # time won't pick them up.+ await _safe_link_to_chat_share(+ session_id=session_id, execution_id=execution.id+ )return ErrorResponse(message=(f"Agent '{library_agent.name}' execution was terminated. "f"View details at {library_agent_link}."),session_id=session_id,+ execution_id=execution.id,error=error_detail,)elif completed and completed.status == ExecutionStatus.REVIEW:+ await _safe_link_to_chat_share(+ session_id=session_id, execution_id=execution.id+ )return ExecutionStartedResponse(message=(f"Agent '{library_agent.name}' is awaiting human review. "@@ -770,6 +823,9 @@ class RunAgentTool(BaseTool):)else:status = completed.status.value if completed else "unknown"+ await _safe_link_to_chat_share(+ session_id=session_id, execution_id=execution.id+ )return ExecutionStartedResponse(message=(f"Agent '{library_agent.name}' is still {status} after "@@ -786,6 +842,7 @@ class RunAgentTool(BaseTool):status=status,)+ await _safe_link_to_chat_share(session_id=session_id, execution_id=execution.id)return ExecutionStartedResponse(message=(f"Agent '{library_agent.name}' execution started successfully. "@@ -908,4 +965,5 @@ class RunAgentTool(BaseTool):graph_name=library_agent.name,library_agent_id=library_agent.id,library_agent_link=library_agent_link,+ status=SCHEDULED_STATUS,)diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.pyindex 348066af2b..294b2e1c02 100644--- a/autogpt_platform/backend/backend/data/db_manager.py+++ b/autogpt_platform/backend/backend/data/db_manager.py@@ -34,6 +34,7 @@ from backend.api.features.store.embeddings import ()from backend.api.features.store.hybrid_search import unified_hybrid_searchfrom backend.copilot import db as chat_db+from backend.copilot.sharing.db import link_new_execution_to_chat_sharefrom backend.data import dbfrom backend.data.analytics import (get_accuracy_trends_and_alerts,@@ -331,6 +332,13 @@ class DatabaseManager(AppService):# ============ Summary Data ============ #get_user_execution_summary_data = _(get_user_execution_summary_data)+ # ============ Chat Sharing ============ #+ # Exposed so the run_agent tool (running in the CoPilotExecutor+ # worker, which doesn't keep its own connected Prisma client) can+ # auto-link new executions into an already-shared chat without+ # crashing when its local Prisma engine is unconnected.+ link_new_execution_to_chat_share = _(link_new_execution_to_chat_share)+# ============ Workspace ============ #count_workspace_files = _(count_workspace_files)create_workspace_file = _(create_workspace_file)@@ -573,6 +581,9 @@ class DatabaseManagerAsyncClient(AppServiceClient):# ============ Summary Data ============ #get_user_execution_summary_data = d.get_user_execution_summary_data+ # ============ Chat Sharing ============ #+ link_new_execution_to_chat_share = d.link_new_execution_to_chat_share+# ============ Workspace ============ #count_workspace_files = d.count_workspace_filescreate_workspace_file = d.create_workspace_filediff --git a/autogpt_platform/backend/backend/data/execution.py b/autogpt_platform/backend/backend/data/execution.pyindex 846928781d..c173f228df 100644--- a/autogpt_platform/backend/backend/data/execution.py+++ b/autogpt_platform/backend/backend/data/execution.py@@ -18,7 +18,7 @@ from typing import ()from prisma import Json-from prisma.enums import AgentExecutionStatus+from prisma.enums import AgentExecutionStatus, SharedViafrom prisma.errors import ForeignKeyViolationError, UniqueViolationErrorfrom prisma.models import (AgentGraphExecution,@@ -46,7 +46,7 @@ from pydantic.fields import Fieldfrom backend.blocks import get_block, get_io_block_ids, get_webhook_block_idsfrom backend.blocks._base import BlockTypefrom backend.util import type as type_utils-from backend.util.exceptions import DatabaseError+from backend.util.exceptions import DatabaseError, NotFoundErrorfrom backend.util.json import SafeJsonfrom backend.util.models import Paginationfrom backend.util.retry import func_retry@@ -69,6 +69,7 @@ from .model import (GraphInput,NodeExecutionStats,)+from .sharing.workspace_refs import extract_workspace_file_idsT = TypeVar("T")@@ -1620,16 +1621,34 @@ async def update_graph_execution_share_status(is_shared: bool,share_token: str | None,shared_at: datetime | None,+ shared_via: SharedVia | None = None,) -> None:- """Update the sharing status of a graph execution."""- await AgentGraphExecution.prisma().update(- where={"id": execution_id},+ """Update the sharing status of a graph execution.++ ``shared_via`` records the share provenance (USER = explicitly shared+ by the owner; CHAT_LINK = enabled as part of a chat session share)+ and drives cascade-revoke logic. Defaults to ``USER`` when enabling+ a share without specifying, matching pre-chat-sharing behaviour.+ """+ if is_shared and shared_via is None:+ shared_via = SharedVia.USER++ updated = await AgentGraphExecution.prisma().update_many(+ where={"id": execution_id, "userId": user_id},data={"isShared": is_shared,"shareToken": share_token,"sharedAt": shared_at,+ "sharedVia": shared_via if is_shared else None,},)+ if updated != 1:+ # The (id, userId) filter narrows the update to the owner — a+ # zero-row result means either the execution doesn't exist or+ # belongs to another user. Surface as NotFoundError so the+ # route turns it into a uniform 404, matching the rest of the+ # share API's anti-enumeration posture.+ raise NotFoundError(f"Execution {execution_id} not found for user {user_id}")async def get_graph_execution_by_share_token(@@ -1709,38 +1728,6 @@ async def get_graph_execution_by_share_token()-def _extract_workspace_file_ids(outputs: CompletedBlockOutput) -> set[str]:- """Extract workspace file IDs from execution outputs.-- Scans all output values for workspace:// URI strings and extracts- the file IDs. Only matches values that are plain strings starting- with workspace://, not substrings within larger text.- """- file_ids: set[str] = set()-- def _scan(value: Any) -> None:- if isinstance(value, str) and value.startswith("workspace://"):- raw = value.removeprefix("workspace://")- file_ref = raw.split("#", 1)[0] if "#" in raw else raw- if file_ref and not file_ref.startswith("/"):- file_ids.add(file_ref)- elif isinstance(value, list):- for item in value:- _scan(item)- elif isinstance(value, dict):- for v in value.values():- _scan(v)-- for output_values in outputs.values():- if isinstance(output_values, list):- for val in output_values:- _scan(val)- else:- _scan(output_values)-- return file_ids--async def create_shared_execution_files(execution_id: str,share_token: str,@@ -1754,7 +1741,7 @@ async def create_shared_execution_files(Returns the number of records created."""- file_ids = _extract_workspace_file_ids(outputs)+ file_ids = extract_workspace_file_ids(outputs)if not file_ids:return 0diff --git a/autogpt_platform/backend/backend/data/shared_execution_file_test.py b/autogpt_platform/backend/backend/data/shared_execution_file_test.pyindex e9beed280c..ae97f52da3 100644--- a/autogpt_platform/backend/backend/data/shared_execution_file_test.py+++ b/autogpt_platform/backend/backend/data/shared_execution_file_test.py@@ -1,23 +1,23 @@"""Tests for SharedExecutionFile workspace URI extraction logic."""-from backend.data.execution import _extract_workspace_file_ids+from backend.data.sharing.workspace_refs import extract_workspace_file_idsclass TestExtractWorkspaceFileIds:def test_extracts_simple_workspace_uri(self):outputs = {"image": ["workspace://abc123"]}- assert _extract_workspace_file_ids(outputs) == {"abc123"}+ assert extract_workspace_file_ids(outputs) == {"abc123"}def test_extracts_workspace_uri_with_mime_fragment(self):outputs = {"image": ["workspace://abc123#image/png"]}- assert _extract_workspace_file_ids(outputs) == {"abc123"}+ assert extract_workspace_file_ids(outputs) == {"abc123"}def test_extracts_multiple_files_from_multiple_outputs(self):outputs = {"images": ["workspace://file1#image/png", "workspace://file2#image/jpeg"],"video": ["workspace://file3#video/mp4"],}- assert _extract_workspace_file_ids(outputs) == {"file1", "file2", "file3"}+ assert extract_workspace_file_ids(outputs) == {"file1", "file2", "file3"}def test_ignores_non_workspace_strings(self):outputs = {@@ -25,43 +25,55 @@ class TestExtractWorkspaceFileIds:"url": ["https://example.com/image.png"],"data": ["data:image/png;base64,abc"],}- assert _extract_workspace_file_ids(outputs) == set()+ assert extract_workspace_file_ids(outputs) == set()def test_ignores_path_references(self):"""workspace:///path/to/file is a path reference, not a file ID."""outputs = {"file": ["workspace:///path/to/file.txt"]}- assert _extract_workspace_file_ids(outputs) == set()+ assert extract_workspace_file_ids(outputs) == set()def test_handles_nested_dicts_in_output_values(self):outputs = {"result": [{"url": "workspace://nested-file#image/png", "label": "test"}]}- assert _extract_workspace_file_ids(outputs) == {"nested-file"}+ assert extract_workspace_file_ids(outputs) == {"nested-file"}def test_handles_nested_lists_in_output_values(self):outputs = {"result": [["workspace://inner-file"]]}- assert _extract_workspace_file_ids(outputs) == {"inner-file"}+ assert extract_workspace_file_ids(outputs) == {"inner-file"}def test_handles_empty_outputs(self):- assert _extract_workspace_file_ids({}) == set()+ assert extract_workspace_file_ids({}) == set()def test_handles_non_string_values(self):outputs = {"count": [42], "flag": [True], "empty": [None]}- assert _extract_workspace_file_ids(outputs) == set()+ assert extract_workspace_file_ids(outputs) == set()def test_deduplicates_repeated_file_ids(self):outputs = {"a": ["workspace://same-file#image/png"],"b": ["workspace://same-file#image/jpeg"],}- assert _extract_workspace_file_ids(outputs) == {"same-file"}+ assert extract_workspace_file_ids(outputs) == {"same-file"}- def test_does_not_match_workspace_substring_in_text(self):- """Plain text that contains workspace:// as a substring should NOT be extracted- because the value itself must start with workspace://."""+ def test_extracts_workspace_uri_embedded_in_text(self):+ """Assistant messages embed ``workspace://<id>`` URIs inline —+ e.g. ``Here's the chart: ``.++ Previously the prefix-only match missed these, so the public+ viewer's allowlist lookup 404'd on files that the chat clearly+ referenced. The extractor now picks up any embedded URI.+ """outputs = {"text": ["check out workspace://fake-id for details"]}- # The string starts with "check out", not "workspace://", so no match- assert _extract_workspace_file_ids(outputs) == set()+ assert extract_workspace_file_ids(outputs) == {"fake-id"}++ def test_extracts_workspace_uri_from_markdown_image_syntax(self):+ """The motivating case for the embedded-URI extraction:+ markdown image syntax wrapping a workspace:// URI."""+ outputs = {+ "content": "Here's the chart: "+ }+ assert extract_workspace_file_ids(outputs) == {"chart-id"}def test_mixed_workspace_and_non_workspace_outputs(self):outputs = {@@ -69,4 +81,44 @@ class TestExtractWorkspaceFileIds:"text": ["just some text"],"url": ["https://example.com"],}- assert _extract_workspace_file_ids(outputs) == {"real-file"}+ assert extract_workspace_file_ids(outputs) == {"real-file"}++ def test_extracts_file_id_from_attached_files_block(self):+ """``[Attached files]`` blocks in user messages embed+ ``file_id=<uuid>`` tokens — those need to make the allowlist+ too so the public viewer can render them as artifacts."""+ content = (+ "Please review this.\n\n[Attached files]\n"+ "- report.pdf (application/pdf, 191.0 KB), "+ "file_id=550e8400-e29b-41d4-a716-446655440000\n"+ "Use read_workspace_file with the file_id to access file contents."+ )+ assert extract_workspace_file_ids(content) == {+ "550e8400-e29b-41d4-a716-446655440000"+ }++ def test_attached_files_uuid_pattern_rejects_non_uuids(self):+ """``file_id=`` followed by a non-UUID is ignored."""+ content = "see file_id=not-a-uuid here"+ assert extract_workspace_file_ids(content) == set()++ def test_extracts_file_id_from_tool_response_json(self):+ """Tool messages (``role="tool"``) persist their output as a+ JSON blob in ``ChatMessage.content`` — files referenced there+ appear as ``"file_id":"<uuid>"`` not ``file_id=<uuid>``."""+ content = (+ '{"type":"workspace_file_written",'+ '"message":"Wrote FounderStoryCard.tsx",'+ '"file_id":"b5c4f6df-f043-4826-88a2-33c33389c17d",'+ '"name":"FounderStoryCard.tsx"}'+ )+ assert extract_workspace_file_ids(content) == {+ "b5c4f6df-f043-4826-88a2-33c33389c17d"+ }++ def test_extracts_file_id_from_tool_response_json_with_spaces(self):+ """Allow ``"file_id" : "<uuid>"`` with arbitrary whitespace."""+ content = '{"file_id" : "b5c4f6df-f043-4826-88a2-33c33389c17d"}'+ assert extract_workspace_file_ids(content) == {+ "b5c4f6df-f043-4826-88a2-33c33389c17d"+ }diff --git a/autogpt_platform/backend/backend/data/sharing/__init__.py b/autogpt_platform/backend/backend/data/sharing/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/data/sharing/tokens.py b/autogpt_platform/backend/backend/data/sharing/tokens.pynew file mode 100644index 0000000000..db18d18b4f--- /dev/null+++ b/autogpt_platform/backend/backend/data/sharing/tokens.py@@ -0,0 +1,18 @@+"""Shared share-token primitives used by execution + chat sharing.++A share token is a v4 UUID rendered with hyphens. The format is enforced+by ``SHARE_TOKEN_PATTERN`` on every public route that takes a token,+which (a) makes the token un-guessable for callers, and (b) keeps the+404 fast path purely string-shape-based instead of a DB round-trip.+"""++import uuid++# Public route path validators must use this exact pattern so that an+# attacker probing for tokens cannot distinguish "well-formed but not+# shared" from "malformed input" — both 404 immediately.+SHARE_TOKEN_PATTERN = r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"+++def generate_share_token() -> str:+ return str(uuid.uuid4())diff --git a/autogpt_platform/backend/backend/data/sharing/workspace_refs.py b/autogpt_platform/backend/backend/data/sharing/workspace_refs.pynew file mode 100644index 0000000000..0d421f0d3b--- /dev/null+++ b/autogpt_platform/backend/backend/data/sharing/workspace_refs.py@@ -0,0 +1,82 @@+"""Extract workspace file references from arbitrary nested data.++Both execution-output sharing and chat-message sharing need to build an+allowlist of workspace files exposed by a share. Three reference shapes+appear in real payloads:++1. ``workspace://<uuid>`` URI strings — emitted by+ :func:`backend.util.file.store_media_file`, used by blocks and tool+ outputs. Anchored prefix match keeps mid-text occurrences intact.+2. ``file_id=<uuid>`` substrings in ``[Attached files]`` blocks the+ copilot appends to user messages (see+ ``backend/copilot/pending_messages.py``). These show up inside+ ChatMessage.content for user uploads.+3. ``"file_id":"<uuid>"`` JSON tokens in tool-response message content+ (``role="tool"`` rows). Tool outputs like+ ``workspace_file_written`` serialise the file id inside a JSON+ blob persisted as plain text — the JSON shape uses ``":"`` between+ key and value rather than ``=``, so a separate alternation is+ required.++All three forms are handled by a single recursive walker.+"""++import re+from typing import Any++# Match ``workspace://<id>`` anywhere in a string. Assistant messages+# embed these URIs inside markdown (````)+# so a whole-string ``startswith`` check used to miss them — the file+# would render in the chat but 404 in the public viewer because no+# allowlist row existed. ``re.finditer`` over the full content catches+# both the standalone-URI shape AND the embedded-in-markdown shape.+#+# Char class is lowercase alphanumeric + hyphen (the UUID alphabet).+# Stops at ``/`` so ``workspace:///path/to/file`` cannot escape into a+# path reference, and stops at ``#`` so the optional MIME hint fragment+# is excluded from the captured ID.+_WORKSPACE_URI_RE = re.compile(r"workspace://([a-z0-9-]+)")++# Match ``file_id`` followed by either ``=`` (Attached-files block) or+# ``":"`` / ``": "`` (JSON serialised tool output). Anchored on the+# ``file_id`` literal so the UUID alone (e.g. mid-narrative) is never+# pulled out as a reference. The ``\b`` after the UUID prevents+# trailing characters from sneaking in.+_FILE_ID_RE = re.compile(+ r'(?:file_id=|"file_id"\s*:\s*")'+ r"([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\b"+)+++def extract_workspace_file_ids(value: Any) -> set[str]:+ """Walk *value* recursively and collect referenced workspace file IDs.++ Accepts any JSON-shaped value: strings, lists, dicts, primitives.+ Non-string leaves are ignored. Returns the unique set of file IDs+ referenced by either ``workspace://<id>`` URIs or ``file_id=<uuid>``+ tokens (from ``[Attached files]`` blocks).+ """+ file_ids: set[str] = set()+ _scan(value, file_ids)+ return file_ids+++def _scan(value: Any, sink: set[str]) -> None:+ if isinstance(value, str):+ # ``workspace://<uuid>`` anywhere in the string — handles both+ # standalone leaves (``["workspace://abc"]``) and URIs embedded+ # in markdown (````).+ for match in _WORKSPACE_URI_RE.finditer(value):+ sink.add(match.group(1))+ # ``file_id=<uuid>`` tokens from [Attached files] blocks AND+ # ``"file_id":"<uuid>"`` tokens from JSON-serialised tool output.+ for match in _FILE_ID_RE.finditer(value):+ sink.add(match.group(1))+ return+ if isinstance(value, list):+ for item in value:+ _scan(item, sink)+ return+ if isinstance(value, dict):+ for v in value.values():+ _scan(v, sink)diff --git a/autogpt_platform/backend/backend/data/sharing/workspace_refs_test.py b/autogpt_platform/backend/backend/data/sharing/workspace_refs_test.pynew file mode 100644index 0000000000..33c4d0bbf7--- /dev/null+++ b/autogpt_platform/backend/backend/data/sharing/workspace_refs_test.py@@ -0,0 +1,99 @@+"""Unit tests for the workspace-file reference extractor.++The chat-share PR added two alternation branches to ``_FILE_ID_RE``+(``file_id=<uuid>`` from ``[Attached files]`` blocks and+``"file_id":"<uuid>"`` from JSON tool output) on top of the existing+``workspace://<uuid>`` leaf scan. ``shared_execution_file_test.py``+exercises the original ``workspace://`` path; this file pins the two+new patterns and the cross-pattern de-dup behaviour.+"""++from __future__ import annotations++from backend.data.sharing.workspace_refs import extract_workspace_file_ids++UUID_A = "11111111-2222-3333-4444-555555555555"+UUID_B = "66666666-7777-8888-9999-aaaaaaaaaaaa"+++class TestFileIdEqualsPattern:+ """``file_id=<uuid>`` shape — used inside ``[Attached files]`` blocks+ the copilot appends to user messages."""++ def test_extracts_from_attached_files_block(self):+ content = f"[Attached files]\nfile_id={UUID_A} my-image.png"+ assert extract_workspace_file_ids(content) == {UUID_A}++ def test_extracts_multiple_attached_files(self):+ content = (+ "[Attached files]\n"+ f"file_id={UUID_A} image-1.png\n"+ f"file_id={UUID_B} image-2.jpg"+ )+ assert extract_workspace_file_ids(content) == {UUID_A, UUID_B}++ def test_rejects_non_uuid_after_file_id_equals(self):+ # The regex demands the exact UUID layout; "not-a-uuid" must not+ # be admitted to the allowlist.+ content = "[Attached files]\nfile_id=not-a-uuid"+ assert extract_workspace_file_ids(content) == set()++ def test_does_not_match_uuid_without_file_id_prefix(self):+ # Bare UUIDs in narrative prose must not be pulled out as+ # references — only the anchored ``file_id=`` form counts.+ content = f"Here is a uuid in the wild: {UUID_A}"+ assert extract_workspace_file_ids(content) == set()+++class TestFileIdJsonPattern:+ """``"file_id":"<uuid>"`` shape — JSON-serialised tool output."""++ def test_extracts_from_json_blob(self):+ content = (+ '{"type":"workspace_file_written",'+ f'"file_id":"{UUID_A}",'+ '"path":"out.png"}'+ )+ assert extract_workspace_file_ids(content) == {UUID_A}++ def test_extracts_with_whitespace_around_colon(self):+ # The regex tolerates ``"file_id" : "..."`` formatting (per+ # ``\s*:\s*`` in the pattern). Pin the tolerance.+ content = f'{{"file_id" : "{UUID_A}"}}'+ assert extract_workspace_file_ids(content) == {UUID_A}++ def test_rejects_single_quoted_file_id(self):+ # Python repr() / single-quoted forms are not JSON and should+ # not match the JSON-anchored pattern.+ content = f"{{'file_id': '{UUID_A}'}}"+ assert extract_workspace_file_ids(content) == set()+++class TestMixedInput:+ """All three reference shapes coexist in one pass."""++ def test_collects_all_three_shapes_and_dedupes(self):+ # workspace:// leaf (in a list), file_id= substring (in narrative),+ # and "file_id":"" JSON token. Same UUID in two of them must+ # dedupe; distinct UUIDs all surface.+ UUID_C = "cccccccc-dddd-eeee-ffff-000000000000"+ outputs = {+ "image": [f"workspace://{UUID_A}#image/png"],+ "notes": f"[Attached files]\nfile_id={UUID_B} note.txt",+ "tool_response": (+ '{"type":"workspace_file_written",' f'"file_id":"{UUID_C}"}}'+ ),+ # Same UUID via a second shape — must dedupe.+ "duplicate": f"file_id={UUID_A}",+ }+ assert extract_workspace_file_ids(outputs) == {UUID_A, UUID_B, UUID_C}++ def test_ignores_non_string_leaves(self):+ # Numbers, booleans, None shouldn't crash the scan.+ outputs = {+ "count": 3,+ "ok": True,+ "missing": None,+ "ref": [f"workspace://{UUID_A}"],+ }+ assert extract_workspace_file_ids(outputs) == {UUID_A}diff --git a/autogpt_platform/backend/backend/util/feature_flag.py b/autogpt_platform/backend/backend/util/feature_flag.pyindex da7ef011bc..a49832b4a4 100644--- a/autogpt_platform/backend/backend/util/feature_flag.py+++ b/autogpt_platform/backend/backend/util/feature_flag.py@@ -41,6 +41,12 @@ class Flag(str, Enum):ENABLE_PLATFORM_PAYMENT = "enable-platform-payment"CHAT = "chat"CHAT_MODE_OPTION = "chat-mode-option"+ # Gates the "share chat results" feature end-to-end. Backend create+ # routes refuse when off so a stale frontend cannot enable shares;+ # frontend share button hides when off so the UI doesn't tease a+ # feature that won't take. Existing public viewer routes stay on+ # regardless so previously-shared URLs remain valid mid-flight.+ CHAT_SHARING = "chat-sharing"COPILOT_SDK = "copilot-sdk"COPILOT_COST_LIMITS = "copilot-cost-limits"# Self-distilled skills registry (store_skill / read_skill /diff --git a/autogpt_platform/backend/migrations/20260511120000_add_chat_session_sharing/migration.sql b/autogpt_platform/backend/migrations/20260511120000_add_chat_session_sharing/migration.sqlnew file mode 100644index 0000000000..a360fe238b--- /dev/null+++ b/autogpt_platform/backend/migrations/20260511120000_add_chat_session_sharing/migration.sql@@ -0,0 +1,72 @@+-- CreateEnum+CREATE TYPE "SharedVia" AS ENUM ('USER', 'CHAT_LINK');++-- AlterTable: ChatSession sharing columns+ALTER TABLE "ChatSession"+ ADD COLUMN "isShared" BOOLEAN NOT NULL DEFAULT false,+ ADD COLUMN "shareToken" TEXT,+ ADD COLUMN "sharedAt" TIMESTAMP(3);++-- AlterTable: AgentGraphExecution share provenance+ALTER TABLE "AgentGraphExecution"+ ADD COLUMN "sharedVia" "SharedVia";++-- Backfill provenance for already-shared executions. Any pre-existing+-- ``isShared=true`` rows were created via the user-only sharing flow,+-- so they are ``USER``. Leaves new rows with NULL until a share is+-- enabled (the route writes ``sharedVia`` together with ``isShared``).+UPDATE "AgentGraphExecution"+ SET "sharedVia" = 'USER'+ WHERE "isShared" = true+ AND "sharedVia" IS NULL;++-- CreateIndex+CREATE UNIQUE INDEX "ChatSession_shareToken_key" ON "ChatSession"("shareToken");+CREATE INDEX "ChatSession_shareToken_idx" ON "ChatSession"("shareToken");++-- CreateTable+CREATE TABLE "SharedChatFile" (+ "id" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "sessionId" TEXT NOT NULL,+ "fileId" TEXT NOT NULL,+ "shareToken" TEXT NOT NULL,++ CONSTRAINT "SharedChatFile_pkey" PRIMARY KEY ("id")+);++CREATE UNIQUE INDEX "SharedChatFile_shareToken_fileId_key" ON "SharedChatFile"("shareToken", "fileId");+CREATE INDEX "SharedChatFile_shareToken_idx" ON "SharedChatFile"("shareToken");+CREATE INDEX "SharedChatFile_sessionId_idx" ON "SharedChatFile"("sessionId");++ALTER TABLE "SharedChatFile"+ ADD CONSTRAINT "SharedChatFile_sessionId_fkey"+ FOREIGN KEY ("sessionId") REFERENCES "ChatSession"("id")+ ON DELETE CASCADE ON UPDATE CASCADE;+ALTER TABLE "SharedChatFile"+ ADD CONSTRAINT "SharedChatFile_fileId_fkey"+ FOREIGN KEY ("fileId") REFERENCES "UserWorkspaceFile"("id")+ ON DELETE CASCADE ON UPDATE CASCADE;++-- CreateTable+CREATE TABLE "ChatLinkedShare" (+ "id" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "sessionId" TEXT NOT NULL,+ "executionId" TEXT NOT NULL,++ CONSTRAINT "ChatLinkedShare_pkey" PRIMARY KEY ("id")+);++CREATE UNIQUE INDEX "ChatLinkedShare_sessionId_executionId_key" ON "ChatLinkedShare"("sessionId", "executionId");+CREATE INDEX "ChatLinkedShare_sessionId_idx" ON "ChatLinkedShare"("sessionId");+CREATE INDEX "ChatLinkedShare_executionId_idx" ON "ChatLinkedShare"("executionId");++ALTER TABLE "ChatLinkedShare"+ ADD CONSTRAINT "ChatLinkedShare_sessionId_fkey"+ FOREIGN KEY ("sessionId") REFERENCES "ChatSession"("id")+ ON DELETE CASCADE ON UPDATE CASCADE;+ALTER TABLE "ChatLinkedShare"+ ADD CONSTRAINT "ChatLinkedShare_executionId_fkey"+ FOREIGN KEY ("executionId") REFERENCES "AgentGraphExecution"("id")+ ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/autogpt_platform/backend/migrations/20260513120000_add_chat_session_auto_share_executions/migration.sql b/autogpt_platform/backend/migrations/20260513120000_add_chat_session_auto_share_executions/migration.sqlnew file mode 100644index 0000000000..ab74ca18bd--- /dev/null+++ b/autogpt_platform/backend/migrations/20260513120000_add_chat_session_auto_share_executions/migration.sql@@ -0,0 +1,7 @@+-- Adds the global "auto-share executions" toggle to ChatSession.+-- When true, every run_agent execution in this chat (existing at+-- enable-time + any new ones while the share is active) is auto-+-- linked into the chat share via ChatLinkedShare rows. Replaces+-- the previous per-execution checklist model.+ALTER TABLE "ChatSession"+ADD COLUMN "autoShareExecutions" BOOLEAN NOT NULL DEFAULT false;diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex ed7d9462d6..81a4128298 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -206,6 +206,7 @@ model UserWorkspaceFile {metadata Json @default("{}")SharedExecutionFiles SharedExecutionFile[]+ SharedChatFiles SharedChatFile[]@@unique([workspaceId, path])@@index([workspaceId, isDeleted])@@ -282,6 +283,22 @@ model ChatSession {Messages ChatMessage[]+ // Sharing fields — mirrors AgentGraphExecution sharing+ isShared Boolean @default(false)+ shareToken String? @unique+ sharedAt DateTime?++ // When true (set at share-enable time), any run_agent execution in+ // this chat is automatically linked into the share — both the+ // existing history at enable-time and any new runs that land while+ // the share is active. When false, no executions are linked even+ // if the chat itself is shared (cards in the viewer render in their+ // "execution not shared" state).+ autoShareExecutions Boolean @default(false)++ SharedChatFiles SharedChatFile[]+ ChatLinkedShares ChatLinkedShare[]+// Single compound index covers (a) the cap-count (count by userId +// chatStatus), (b) the queue-list ORDER BY updatedAt asc, AND (c) the// sidebar list (find_many WHERE userId ORDER BY updatedAt desc).@@ -291,6 +308,46 @@ model ChatSession {// The migration drops the previously-existing (userId, updatedAt)// index that this one supersedes.@@index([userId, chatStatus, updatedAt], name: "ChatSession_user_status_idx")+ @@index([shareToken])+}++// Tracks which workspace files are exposed via a shared chat session.+// Same allowlist defense as SharedExecutionFile: enumeration-resistant+// downloads via uniform 404 + single allowlist lookup.+model SharedChatFile {+ id String @id @default(uuid())+ createdAt DateTime @default(now())++ sessionId String+ Session ChatSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)++ fileId String+ File UserWorkspaceFile @relation(fields: [fileId], references: [id], onDelete: Cascade)++ shareToken String++ @@unique([shareToken, fileId])+ @@index([shareToken])+ @@index([sessionId])+}++// Links a shared ChatSession to AgentGraphExecution rows that were+// opted-in at share time so the public viewer can resolve drill-ins.+// On chat-share revoke, only executions whose ``sharedVia=CHAT_LINK``+// (no independent user share) get their share state cleared.+model ChatLinkedShare {+ id String @id @default(uuid())+ createdAt DateTime @default(now())++ sessionId String+ Session ChatSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)++ executionId String+ Execution AgentGraphExecution @relation(fields: [executionId], references: [id], onDelete: Cascade)++ @@unique([sessionId, executionId])+ @@index([sessionId])+ @@index([executionId])}model ChatMessage {@@ -657,7 +714,12 @@ model AgentGraphExecution {isShared Boolean @default(false)shareToken String? @uniquesharedAt DateTime?+ // Provenance: USER = explicitly shared by owner, CHAT_LINK = enabled+ // as part of a ChatSession share. Drives cascade-revoke logic so that+ // user-initiated shares survive chat-share revocation.+ sharedVia SharedVia?SharedExecutionFiles SharedExecutionFile[]+ ChatLinkedShares ChatLinkedShare[]@@index([agentGraphId, agentGraphVersion])@@index([userId, isDeleted, createdAt])@@ -667,6 +729,11 @@ model AgentGraphExecution {@@index([parentGraphExecutionId])}+enum SharedVia {+ USER+ CHAT_LINK+}+// This model describes the execution of an AgentNode.model AgentNodeExecution {id String @id @default(uuid())diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/[token]/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/[token]/__tests__/page.test.tsxnew file mode 100644index 0000000000..d114173172--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/[token]/__tests__/page.test.tsx@@ -0,0 +1,91 @@+import { beforeEach, describe, expect, test, vi } from "vitest";+import { http, HttpResponse } from "msw";++import { getGetV1GetSharedExecutionMockHandler200 } from "@/app/api/__generated__/endpoints/default/default.msw";+import type { SharedExecutionResponse } from "@/app/api/__generated__/models/sharedExecutionResponse";+import { server } from "@/mocks/mock-server";+import { render, screen } from "@/tests/integrations/test-utils";+import SharePage from "../page";++const TOKEN = "550e8400-e29b-41d4-a716-446655440000";++vi.mock("next/navigation", () => ({+ useParams: () => ({ token: TOKEN }),+ usePathname: () => `/share/${TOKEN}`,+ useRouter: () => ({+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+ push: vi.fn(),+ refresh: vi.fn(),+ replace: vi.fn(),+ }),+ useSearchParams: () => new URLSearchParams(),+}));++// RunOutputs pulls in heavy library code (output renderers per+// block type); stub it to keep this page test focused on the chrome+// (the wrapper layout + alert + summary card) we actually touched.+vi.mock(+ "@/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/SelectedRunView/components/RunOutputs",+ () => ({+ RunOutputs: () => <div data-testid="run-outputs-stub" />,+ }),+);++beforeEach(() => {+ vi.clearAllMocks();+});++describe("SharePage (execution share viewer)", () => {+ test("renders the AutoGPT logo header + run summary + outputs on the happy path", async () => {+ server.use(+ getGetV1GetSharedExecutionMockHandler200(+ (): SharedExecutionResponse => ({+ id: "exec-1",+ graph_name: "Weather Agent",+ graph_description: "Reports the weather",+ status: "COMPLETED",+ created_at: new Date("2026-05-12T00:00:00Z"),+ outputs: {},+ }),+ ),+ );++ render(<SharePage />);++ // Logo (rendered inside the chrome wrapper at the top of the page).+ // Both light + dark variants ship in the DOM behind dark: class+ // selectors, so we look for at least one match.+ const logos = await screen.findAllByAltText("AutoGPT");+ expect(logos.length).toBeGreaterThan(0);+ // Public-share affordance alert.+ expect(+ await screen.findByText(/publicly shared agent run result/i),+ ).toBeDefined();+ // Run name surfaces from the structured payload (in both header+ // and card-title slots; we just need it to be present).+ const titles = await screen.findAllByText("Weather Agent");+ expect(titles.length).toBeGreaterThan(0);+ // RunOutputs stub is mounted.+ expect(await screen.findByTestId("run-outputs-stub")).toBeDefined();+ });++ test("renders the 'Share Link Not Found' card on a 404 from the backend", async () => {+ server.use(+ http.get(+ "*/api/public/shared/:token",+ () => new HttpResponse(null, { status: 404 }),+ ),+ );++ render(<SharePage />);++ expect(await screen.findByText(/share link not found/i)).toBeDefined();+ expect(+ await screen.findByText(/invalid or has been disabled/i),+ ).toBeDefined();+ // Try again button is the only retry affordance on this view.+ expect(screen.getByRole("button", { name: /try again/i })).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/[token]/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/[token]/page.tsxindex 3db91f411b..4902bf202b 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/share/[token]/page.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/[token]/page.tsx@@ -12,6 +12,28 @@ import {import { Alert, AlertDescription } from "@/components/molecules/Alert/Alert";import { InfoIcon } from "lucide-react";import { useParams } from "next/navigation";+import { ShareActions } from "../components/ShareHeader/ShareActions";+import { ShareHeader } from "../components/ShareHeader/ShareHeader";++// Wraps the page in the shared header + a scrollable container.+// Header is the same component used by the chat share viewer so the+// two routes stay visually consistent.+function ExecutionShareChrome({+ title,+ children,+}: {+ title?: string;+ children: React.ReactNode;+}) {+ return (+ <div className="flex h-screen w-full flex-col bg-background">+ <ShareHeader title={title} actions={<ShareActions />} />+ <div className="min-h-0 flex-1 overflow-y-auto">+ <div className="container mx-auto px-4 py-8">{children}</div>+ </div>+ </div>+ );+}export default function SharePage() {const params = useParams();@@ -27,105 +49,113 @@ export default function SharePage() {if (loading) {return (- <div className="flex min-h-screen items-center justify-center">- <div className="text-center">- <div className="mx-auto mb-4 h-12 w-12 animate-spin rounded-full border-b-2 border-primary"></div>- <p className="text-muted-foreground">Loading shared execution...</p>+ <ExecutionShareChrome>+ <div className="flex items-center justify-center py-16">+ <div className="text-center">+ <div className="mx-auto mb-4 h-12 w-12 animate-spin rounded-full border-b-2 border-primary"></div>+ <p className="text-muted-foreground">Loading shared execution...</p>+ </div></div>- </div>+ </ExecutionShareChrome>);}if (error || is404 || !executionData) {return (- <div className="flex min-h-screen items-center justify-center">- <div className="mx-auto w-full max-w-md p-6">- <Card className="border-dashed">- <CardContent className="pt-6">- <div className="space-y-4 text-center">- <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-muted">- <InfoIcon className="h-6 w-6 text-muted-foreground" />- </div>- <div className="space-y-2">- <h3 className="text-lg font-semibold">- {is404 ? "Share Link Not Found" : "Unable to Load"}- </h3>- <p className="text-sm text-muted-foreground">- {is404- ? "This shared link is invalid or has been disabled by the owner. Please check with the person who shared this link."- : "There was an error loading this shared execution. Please try refreshing the page."}- </p>+ <ExecutionShareChrome>+ <div className="flex items-center justify-center py-16">+ <div className="mx-auto w-full max-w-md p-6">+ <Card className="border-dashed">+ <CardContent className="pt-6">+ <div className="space-y-4 text-center">+ <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-muted">+ <InfoIcon className="h-6 w-6 text-muted-foreground" />+ </div>+ <div className="space-y-2">+ <h3 className="text-lg font-semibold">+ {is404 ? "Share Link Not Found" : "Unable to Load"}+ </h3>+ <p className="text-sm text-muted-foreground">+ {is404+ ? "This shared link is invalid or has been disabled by the owner. Please check with the person who shared this link."+ : "There was an error loading this shared execution. Please try refreshing the page."}+ </p>+ </div>+ <div className="pt-2">+ <button+ onClick={() => window.location.reload()}+ className="text-sm text-primary hover:underline"+ >+ Try again+ </button>+ </div></div>- <div className="pt-2">- <button- onClick={() => window.location.reload()}- className="text-sm text-primary hover:underline"- >- Try again- </button>- </div>- </div>- </CardContent>- </Card>- <div className="mt-8 text-center text-xs text-muted-foreground">- <p>Powered by AutoGPT Platform</p>+ </CardContent>+ </Card>+ <div className="mt-8 text-center text-xs text-muted-foreground">+ <p>Powered by AutoGPT Platform</p>+ </div></div></div>- </div>+ </ExecutionShareChrome>);}return (- <div className="mx-auto max-w-6xl">- <div className="mb-6">- <Alert>- <InfoIcon className="h-4 w-4" />- <AlertDescription>- This is a publicly shared agent run result. The person who shared- this link can disable access at any time.- </AlertDescription>- </Alert>- </div>+ <ExecutionShareChrome title={executionData.graph_name}>+ <div className="mx-auto max-w-6xl">+ <div className="mb-6">+ <Alert>+ <InfoIcon className="h-4 w-4" />+ <AlertDescription>+ This is a publicly shared agent run result. The person who shared+ this link can disable access at any time.+ </AlertDescription>+ </Alert>+ </div>- <Card className="mb-6">- <CardHeader>- <CardTitle className="text-2xl">{executionData.graph_name}</CardTitle>- {executionData.graph_description && (- <p className="mt-2 text-muted-foreground">- {executionData.graph_description}- </p>- )}- </CardHeader>- <CardContent>- <div className="grid grid-cols-2 gap-4 text-sm">- <div>- <span className="font-medium">Status:</span>- <span className="ml-2 capitalize">- {executionData.status.toLowerCase()}- </span>- </div>- <div>- <span className="font-medium">Created:</span>- <span className="ml-2">- {new Date(executionData.created_at).toLocaleString()}- </span>+ <Card className="mb-6">+ <CardHeader>+ <CardTitle className="text-2xl">+ {executionData.graph_name}+ </CardTitle>+ {executionData.graph_description && (+ <p className="mt-2 text-muted-foreground">+ {executionData.graph_description}+ </p>+ )}+ </CardHeader>+ <CardContent>+ <div className="grid grid-cols-2 gap-4 text-sm">+ <div>+ <span className="font-medium">Status:</span>+ <span className="ml-2 capitalize">+ {executionData.status.toLowerCase()}+ </span>+ </div>+ <div>+ <span className="font-medium">Created:</span>+ <span className="ml-2">+ {new Date(executionData.created_at).toLocaleString()}+ </span>+ </div></div>- </div>- </CardContent>- </Card>+ </CardContent>+ </Card>- <Card>- <CardHeader>- <CardTitle>Output</CardTitle>- </CardHeader>- <CardContent>- <RunOutputs outputs={executionData.outputs} shareToken={token} />- </CardContent>- </Card>+ <Card>+ <CardHeader>+ <CardTitle>Output</CardTitle>+ </CardHeader>+ <CardContent>+ <RunOutputs outputs={executionData.outputs} shareToken={token} />+ </CardContent>+ </Card>- <div className="mt-8 text-center text-sm text-muted-foreground">- <p>Powered by AutoGPT Platform</p>+ <div className="mt-8 text-center text-sm text-muted-foreground">+ <p>Powered by AutoGPT Platform</p>+ </div></div>- </div>+ </ExecutionShareChrome>);}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/__tests__/page.test.tsxnew file mode 100644index 0000000000..b4bb4ca662--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/__tests__/page.test.tsx@@ -0,0 +1,367 @@+import { beforeEach, describe, expect, test, vi } from "vitest";+import { waitFor } from "@testing-library/react";+import { http, HttpResponse } from "msw";++import {+ getGetV2GetSharedChatMockHandler200,+ getGetV2GetSharedChatMessagesMockHandler200,+} from "@/app/api/__generated__/endpoints/chat/chat.msw";+import type { SharedChatMessagesPage } from "@/app/api/__generated__/models/sharedChatMessagesPage";+import type { SharedChatSession } from "@/app/api/__generated__/models/sharedChatSession";+import { useCopilotUIStore } from "@/app/(platform)/copilot/store";+import { server } from "@/mocks/mock-server";+import { render, screen } from "@/tests/integrations/test-utils";+import SharedChatPage from "../page";++const mockUseParams = vi.hoisted(() => vi.fn());++vi.mock("next/navigation", () => ({+ useParams: mockUseParams,+ usePathname: () => "/share/chat/test-token",+ useRouter: () => ({+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+ push: vi.fn(),+ refresh: vi.fn(),+ replace: vi.fn(),+ }),+ useSearchParams: () => new URLSearchParams(),+}));++const TOKEN = "550e8400-e29b-41d4-a716-446655440000";++function resetArtifactPanelStore() {+ useCopilotUIStore.setState({+ artifactPanel: {+ isOpen: false,+ isMinimized: false,+ isMaximized: false,+ width: 600,+ activeArtifact: null,+ history: [],+ },+ });+ useCopilotUIStore.getState().resetAutoOpenState();+}++beforeEach(() => {+ vi.clearAllMocks();+ mockUseParams.mockReturnValue({ token: TOKEN });+ resetArtifactPanelStore();+});++describe("SharedChatPage", () => {+ test("renders the read-only viewer with messages on happy path", async () => {+ server.use(+ getGetV2GetSharedChatMockHandler200(+ (): SharedChatSession => ({+ id: "session-123",+ title: "How to deploy",+ created_at: new Date("2026-05-12T00:00:00Z"),+ updated_at: new Date("2026-05-12T00:00:00Z"),+ shared_at: new Date("2026-05-12T00:00:00Z"),+ linked_executions: [],+ }),+ ),+ getGetV2GetSharedChatMessagesMockHandler200(+ (): SharedChatMessagesPage => ({+ messages: [+ {+ id: "m1",+ role: "user",+ content: "How do I deploy?",+ name: null,+ tool_call_id: null,+ tool_calls: null,+ function_call: null,+ sequence: 0,+ created_at: new Date("2026-05-12T00:00:01Z"),+ },+ {+ id: "m2",+ role: "assistant",+ content: "Use docker compose.",+ name: null,+ tool_call_id: null,+ tool_calls: null,+ function_call: null,+ sequence: 1,+ created_at: new Date("2026-05-12T00:00:02Z"),+ },+ ],+ has_more: false,+ oldest_sequence: 0,+ }),+ ),+ );++ render(<SharedChatPage />);++ // Title sits in the ShareHeader's title slot. Logo + actions+ // slots also live in the header but aren't asserted here.+ const heading = await screen.findByRole("heading", { level: 1 });+ expect(heading.textContent).toBe("How to deploy");+ expect(screen.getByText(/^Shared /)).toBeDefined();+ expect(await screen.findByText("How do I deploy?")).toBeDefined();+ expect(await screen.findByText("Use docker compose.")).toBeDefined();+ });++ test("centers the loading state across the shared chat chrome", () => {+ server.use(+ getGetV2GetSharedChatMockHandler200(+ (): SharedChatSession => ({+ id: "session-loading",+ title: "Loading",+ created_at: new Date("2026-05-12T00:00:00Z"),+ updated_at: new Date("2026-05-12T00:00:00Z"),+ shared_at: new Date("2026-05-12T00:00:00Z"),+ linked_executions: [],+ }),+ ),+ );++ render(<SharedChatPage />);++ const loadingState = screen.getByTestId("shared-chat-loading-state");+ expect(loadingState.className).toContain("w-full");+ expect(loadingState.className).toContain("flex-1");+ });++ test("surfaces the has_more notice when the chat is truncated", async () => {+ server.use(+ getGetV2GetSharedChatMockHandler200(+ (): SharedChatSession => ({+ id: "session-123",+ title: "Long chat",+ created_at: new Date("2026-05-12T00:00:00Z"),+ updated_at: new Date("2026-05-12T00:00:00Z"),+ shared_at: new Date("2026-05-12T00:00:00Z"),+ linked_executions: [],+ }),+ ),+ getGetV2GetSharedChatMessagesMockHandler200(+ (): SharedChatMessagesPage => ({+ messages: [+ {+ id: "m1",+ role: "assistant",+ content: "trimmed",+ name: null,+ tool_call_id: null,+ tool_calls: null,+ function_call: null,+ sequence: 999,+ created_at: new Date("2026-05-12T00:00:00Z"),+ },+ ],+ has_more: true,+ oldest_sequence: 999,+ }),+ ),+ );++ render(<SharedChatPage />);++ expect(+ await screen.findByText(/showing the most recent .* messages/i),+ ).toBeDefined();+ expect(+ await screen.findByText(/older history is not visible/i),+ ).toBeDefined();+ });++ test("renders the not-found card when the share token is revoked", async () => {+ // Backend returns 404 for unknown/revoked tokens.+ server.use(+ http.get(+ "*/api/public/shared/chats/:token",+ () => new HttpResponse(null, { status: 404 }),+ ),+ );++ render(<SharedChatPage />);++ expect(await screen.findByText(/share link not found/i)).toBeDefined();+ expect(+ await screen.findByText(/invalid or has been disabled/i),+ ).toBeDefined();+ });++ test("wraps the error state in the branded share header", async () => {+ // Cursor regression: previously the error state returned without+ // ShareHeader, so a revoked link showed a raw card with no logo+ // / no Copy-link / Sign-up CTAs — inconsistent with the execution+ // share viewer. All states (loading, error, success) must share+ // the branded chrome.+ server.use(+ http.get(+ "*/api/public/shared/chats/:token",+ () => new HttpResponse(null, { status: 404 }),+ ),+ );++ render(<SharedChatPage />);++ await screen.findByText(/share link not found/i);+ // Logo image always present in ShareHeader.+ expect(screen.getAllByAltText("AutoGPT").length).toBeGreaterThan(0);+ // Copy-link CTA wired through ShareActions in the chrome.+ expect(screen.getByRole("button", { name: /copy link/i })).toBeDefined();+ });++ test("uses split layout (flex-row) so ArtifactPanel can dock alongside messages", async () => {+ // Owner-side copilot renders messages + ArtifactPanel side-by-side+ // via ``flex-row``. The viewer must match — otherwise opening an+ // artifact covers the chat full-screen instead of splitting.+ server.use(+ getGetV2GetSharedChatMockHandler200(+ (): SharedChatSession => ({+ id: "session-split",+ title: "Layout check",+ created_at: new Date("2026-05-12T00:00:00Z"),+ updated_at: new Date("2026-05-12T00:00:00Z"),+ shared_at: new Date("2026-05-12T00:00:00Z"),+ linked_executions: [],+ }),+ ),+ getGetV2GetSharedChatMessagesMockHandler200(+ (): SharedChatMessagesPage => ({+ messages: [],+ has_more: false,+ oldest_sequence: null,+ }),+ ),+ );++ const { container } = render(<SharedChatPage />);+ // Wait for the page to settle past loading.+ await screen.findByRole("heading", { level: 1 });++ // A flex-row container must sit below the header so the chat+ // column and ArtifactPanel can dock side-by-side on desktop.+ const splitRow = container.querySelector("div.flex-row");+ expect(splitRow).not.toBeNull();+ expect(splitRow?.className).toContain("flex-row");+ expect(+ screen.getByTestId("shared-chat-content-column").className,+ ).toContain("max-w-3xl");+ });++ test("auto-opens the most recent agent artifact in the shared chat", async () => {+ const oldArtifactId = "11111111-1111-4111-8111-111111111111";+ const latestArtifactId = "22222222-2222-4222-8222-222222222222";++ server.use(+ getGetV2GetSharedChatMockHandler200(+ (): SharedChatSession => ({+ id: "session-artifacts",+ title: "Artifacts",+ created_at: new Date("2026-05-12T00:00:00Z"),+ updated_at: new Date("2026-05-12T00:00:00Z"),+ shared_at: new Date("2026-05-12T00:00:00Z"),+ linked_executions: [],+ }),+ ),+ getGetV2GetSharedChatMessagesMockHandler200(+ (): SharedChatMessagesPage => ({+ messages: [+ {+ id: "m1",+ role: "assistant",+ content: `Older artifact [old.md](workspace://${oldArtifactId}#text/markdown)`,+ name: null,+ tool_call_id: null,+ tool_calls: null,+ function_call: null,+ sequence: 0,+ created_at: new Date("2026-05-12T00:00:01Z"),+ },+ {+ id: "m2",+ role: "assistant",+ content: `Latest artifact [latest.md](workspace://${latestArtifactId}#text/markdown)`,+ name: null,+ tool_call_id: null,+ tool_calls: null,+ function_call: null,+ sequence: 1,+ created_at: new Date("2026-05-12T00:00:02Z"),+ },+ ],+ has_more: false,+ oldest_sequence: 0,+ }),+ ),+ http.get(+ "*/api/proxy/api/public/shared/chats/:token/files/:fileId/download",+ () => new HttpResponse("# artifact"),+ ),+ );++ render(<SharedChatPage />);++ await screen.findByText(/Latest artifact/);+ await waitFor(() => {+ const panel = useCopilotUIStore.getState().artifactPanel;+ expect(panel.isOpen).toBe(true);+ expect(panel.activeArtifact?.id).toBe(latestArtifactId);+ expect(panel.activeArtifact?.title).toBe("latest.md");+ });+ expect(+ screen.getByTestId("shared-chat-content-column").className,+ ).not.toContain("max-w-3xl");+ });++ test("falls back to 'Shared chat' when the session has no title", async () => {+ server.use(+ getGetV2GetSharedChatMockHandler200(+ (): SharedChatSession => ({+ id: "session-no-title",+ title: "",+ created_at: new Date("2026-05-12T00:00:00Z"),+ updated_at: new Date("2026-05-12T00:00:00Z"),+ shared_at: new Date("2026-05-12T00:00:00Z"),+ linked_executions: [],+ }),+ ),+ getGetV2GetSharedChatMessagesMockHandler200(+ (): SharedChatMessagesPage => ({+ messages: [],+ has_more: false,+ oldest_sequence: null,+ }),+ ),+ );++ render(<SharedChatPage />);+ const heading = await screen.findByRole("heading", { level: 1 });+ expect(heading.textContent).toBe("Shared chat");+ });++ test("does NOT show the has_more notice when the chat fits in one page", async () => {+ server.use(+ getGetV2GetSharedChatMockHandler200(+ (): SharedChatSession => ({+ id: "session-fits",+ title: "Fits",+ created_at: new Date("2026-05-12T00:00:00Z"),+ updated_at: new Date("2026-05-12T00:00:00Z"),+ shared_at: new Date("2026-05-12T00:00:00Z"),+ linked_executions: [],+ }),+ ),+ getGetV2GetSharedChatMessagesMockHandler200(+ (): SharedChatMessagesPage => ({+ messages: [],+ has_more: false,+ oldest_sequence: null,+ }),+ ),+ );++ render(<SharedChatPage />);+ await screen.findByRole("heading", { level: 1 });+ expect(screen.queryByText(/older history is not visible/i)).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/components/SharedChatErrorState.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/components/SharedChatErrorState.tsxnew file mode 100644index 0000000000..4eed582ca7--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/components/SharedChatErrorState.tsx@@ -0,0 +1,36 @@+import { InfoIcon } from "@phosphor-icons/react";++type Props = {+ reason?: string;+ onRetry: () => void;+};++export function SharedChatErrorState({ onRetry }: Props) {+ return (+ <div className="flex h-full w-full flex-1 items-center justify-center">+ <div className="mx-auto w-full max-w-md p-6">+ <div className="space-y-4 rounded-lg border border-dashed border-zinc-300 p-6 text-center">+ <div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-zinc-100">+ <InfoIcon size={24} className="text-zinc-500" />+ </div>+ <div className="space-y-2">+ <h3 className="text-lg font-semibold">Share link not found</h3>+ <p className="text-sm text-zinc-500">+ This link is invalid or has been disabled by the owner. Ask the+ person who shared it for an updated link.+ </p>+ </div>+ <button+ onClick={onRetry}+ className="text-sm text-zinc-700 underline hover:text-zinc-900"+ >+ Try again+ </button>+ </div>+ <p className="mt-8 text-center text-xs text-zinc-400">+ Powered by AutoGPT Platform+ </p>+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/components/SharedChatLoadingState.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/components/SharedChatLoadingState.tsxnew file mode 100644index 0000000000..27fa4a7370--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/components/SharedChatLoadingState.tsx@@ -0,0 +1,13 @@+export function SharedChatLoadingState() {+ return (+ <div+ data-testid="shared-chat-loading-state"+ className="flex h-full w-full flex-1 items-center justify-center"+ >+ <div className="text-center">+ <div className="mx-auto mb-4 h-12 w-12 animate-spin rounded-full border-b-2 border-primary"></div>+ <p className="text-sm text-zinc-500">Loading shared chat…</p>+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/components/__tests__/SharedChatErrorState.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/components/__tests__/SharedChatErrorState.test.tsxnew file mode 100644index 0000000000..d3934fc749--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/components/__tests__/SharedChatErrorState.test.tsx@@ -0,0 +1,26 @@+import { afterEach, describe, expect, test, vi } from "vitest";++import { cleanup, render, screen } from "@/tests/integrations/test-utils";+import { SharedChatErrorState } from "../SharedChatErrorState";++afterEach(() => {+ cleanup();+});++describe("SharedChatErrorState", () => {+ test("renders the not-found copy", () => {+ render(<SharedChatErrorState onRetry={vi.fn()} />);+ expect(screen.getByText(/share link not found/i)).toBeDefined();+ expect(screen.getByText(/invalid or has been disabled/i)).toBeDefined();+ });++ test("invokes onRetry when the user clicks 'Try again'", () => {+ const onRetry = vi.fn();+ render(<SharedChatErrorState onRetry={onRetry} />);++ const retryButton = screen.getByRole("button", { name: /try again/i });+ retryButton.click();++ expect(onRetry).toHaveBeenCalledTimes(1);+ });+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/components/__tests__/SharedChatLoadingState.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/components/__tests__/SharedChatLoadingState.test.tsxnew file mode 100644index 0000000000..82533f7f4c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/components/__tests__/SharedChatLoadingState.test.tsx@@ -0,0 +1,15 @@+import { afterEach, describe, expect, test } from "vitest";++import { cleanup, render, screen } from "@/tests/integrations/test-utils";+import { SharedChatLoadingState } from "../SharedChatLoadingState";++afterEach(() => {+ cleanup();+});++describe("SharedChatLoadingState", () => {+ test("renders the loading copy", () => {+ render(<SharedChatLoadingState />);+ expect(screen.getByText(/loading shared chat/i)).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/page.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/page.tsxnew file mode 100644index 0000000000..b5d988f33d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/page.tsx@@ -0,0 +1,198 @@+"use client";++import { useCallback, useMemo, type ReactNode } from "react";+import dynamic from "next/dynamic";+import { useParams } from "next/navigation";+import { ChatMessagesContainer } from "@/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer";+import { CopilotChatActionsProvider } from "@/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider";+import { useIsMobile } from "@/app/(platform)/copilot/useIsMobile";+import { sharedChatFilePattern, sharedChatFileUrl } from "@/lib/share/routes";+import { cn } from "@/lib/utils";+import { ShareActions } from "../../components/ShareHeader/ShareActions";+import { ShareHeader } from "../../components/ShareHeader/ShareHeader";+import { useSharedChatPage } from "./useSharedChatPage";+import { SharedChatErrorState } from "./components/SharedChatErrorState";+import { SharedChatLoadingState } from "./components/SharedChatLoadingState";+import { useSharedChatArtifacts } from "./useSharedChatArtifacts";++// Wraps every chat-share state — loading, error, success — in the+// branded shell so a viewer never sees a raw card without the logo+// + CTAs. Matches ``ExecutionShareChrome`` on the execution share+// page so the two routes feel like the same surface.+//+// Uses ``bg-background`` (theme-aware) on the chrome wrappers so dark+// mode renders correctly. Inner success-state wrappers still use the+// owner-side copilot's hardcoded ``#f8f8f9`` so the in-chat surface+// matches the owner experience pixel-for-pixel — see the+// ``CopilotPage`` / ``ChatContainer`` styling.+function SharedChatChrome({+ title,+ subtitle,+ children,+}: {+ title?: string;+ subtitle?: string;+ children: ReactNode;+}) {+ return (+ <div className="flex h-screen w-full flex-col bg-background">+ <ShareHeader+ title={title}+ subtitle={subtitle}+ actions={<ShareActions />}+ />+ <div className="flex min-h-0 w-full flex-1 flex-row overflow-hidden bg-background">+ {children}+ </div>+ </div>+ );+}++// Dynamic import keeps the artifact panel + its viewer dependencies+// out of the initial bundle for public viewers who may never open+// one. Mirrors the owner CopilotPage.+const ArtifactPanel = dynamic(+ () =>+ import(+ "@/app/(platform)/copilot/components/ArtifactPanel/ArtifactPanel"+ ).then((m) => m.ArtifactPanel),+ { ssr: false },+);++// Public viewer has no send capability; this satisfies the actions+// context so tool-call cards render without throwing.+async function noopSend() {}++export default function SharedChatPage() {+ const params = useParams();+ const token = params.token as string;+ const isMobile = useIsMobile();+ const filePattern = useMemo(() => sharedChatFilePattern(token), [token]);+ const fileUrlBuilder = useMemo(+ () => (fileId: string) => sharedChatFileUrl(token, fileId),+ [token],+ );++ const {+ session,+ uiMessages,+ turnStats,+ hasMore,+ isLoading,+ sessionError,+ messagesError,+ error,+ retry,+ } = useSharedChatPage(token);++ const { isArtifactPanelOpen } = useSharedChatArtifacts({+ token,+ uiMessages,+ isLoading,+ filePattern,+ fileUrlBuilder,+ });++ // execution_id → public share_token, so ExecutionStartedCard's+ // "View Execution" CTA routes to /share/{token} instead of the+ // auth-gated /library/agents/... URL.+ const linkedExecutions = session?.linked_executions ?? [];+ const getExecutionShareToken = useCallback(+ (executionId: string) => {+ const match = linkedExecutions.find(+ (link) => link.execution_id === executionId,+ );+ return match?.share_token ?? null;+ },+ [linkedExecutions],+ );++ if (isLoading) {+ return (+ <SharedChatChrome>+ <SharedChatLoadingState />+ </SharedChatChrome>+ );+ }++ // ``sessionError`` (or a missing session payload) means the share+ // link is dead — render the not-found card. ``messagesError`` is+ // transient (mid-deploy 5xx, network blip after retry exhaustion)+ // and should NOT advertise the link as revoked. We still surface+ // the same error card with a Try-again button, but only when the+ // session itself didn't load — otherwise we let the page fall+ // through to render the chrome with an empty message list (an+ // in-place retry would be ideal future work but the current+ // ErrorState card carries the right affordance).+ if (sessionError || !session) {+ return (+ <SharedChatChrome>+ <SharedChatErrorState reason={error} onRetry={retry} />+ </SharedChatChrome>+ );+ }++ const title = session.title || "Shared chat";+ // ``shared_at`` is when the owner enabled sharing — that's what+ // belongs in the "Shared {date}" subtitle. Falling back to+ // ``created_at`` only when ``shared_at`` is missing keeps already-+ // shared chats rendering until the backfill lands, but+ // ``SharedChatSession`` ships ``shared_at`` for every share so the+ // fallback should never fire in practice.+ const sharedOn = new Date(+ session.shared_at || session.created_at,+ ).toLocaleDateString();++ return (+ <SharedChatChrome title={title} subtitle={`Shared ${sharedOn}`}>+ <div className="relative flex min-w-0 flex-1 flex-col overflow-hidden bg-[#f8f8f9]">+ {messagesError && (+ // Session loaded but messages failed — transient 5xx, not a+ // revoked link. Keep the chrome (so the viewer knows the+ // share is real) and show an inline retry instead of the+ // permanent not-found card.+ <div className="flex shrink-0 items-center justify-between gap-3 border-b border-amber-200 bg-amber-50 px-4 py-2 text-xs text-amber-900">+ <span>Couldn't load messages. The share link is valid.</span>+ <button+ onClick={retry}+ className="rounded border border-amber-300 bg-white px-2 py-0.5 font-medium hover:bg-amber-100"+ >+ Try again+ </button>+ </div>+ )}+ {hasMore && (+ <div className="shrink-0 border-b border-zinc-200 bg-zinc-50 px-4 py-2 text-center text-xs text-zinc-600">+ Showing the most recent {uiMessages.length} messages — older history+ is not visible in this shared view.+ </div>+ )}+ <div+ data-testid="shared-chat-content-column"+ className={cn(+ "mx-auto flex min-h-0 w-full flex-1 flex-col bg-[#f8f8f9] px-2 lg:px-0",+ !isArtifactPanelOpen && "max-w-3xl",+ )}+ >+ <CopilotChatActionsProvider+ onSend={noopSend}+ chatSurface="share"+ getExecutionShareToken={getExecutionShareToken}+ >+ <ChatMessagesContainer+ messages={uiMessages}+ status="idle"+ error={undefined}+ isLoading={false}+ turnStats={turnStats}+ readOnly+ filePattern={filePattern}+ fileUrlBuilder={fileUrlBuilder}+ />+ </CopilotChatActionsProvider>+ </div>+ </div>+ {isMobile ? <ArtifactPanel mobile /> : <ArtifactPanel />}+ </SharedChatChrome>+ );+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/useSharedChatArtifacts.ts b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/useSharedChatArtifacts.tsnew file mode 100644index 0000000000..dd15ce8093--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/useSharedChatArtifacts.ts@@ -0,0 +1,52 @@+"use client";++import { useEffect, useMemo, useRef } from "react";+import { UIDataTypes, UIMessage, UITools } from "ai";+import { getMostRecentArtifact } from "@/app/(platform)/copilot/components/ChatMessagesContainer/helpers";+import { useCopilotUIStore } from "@/app/(platform)/copilot/store";++interface Props {+ token: string;+ uiMessages: UIMessage<unknown, UIDataTypes, UITools>[];+ isLoading: boolean;+ filePattern: RegExp;+ fileUrlBuilder: (fileId: string) => string;+}++export function useSharedChatArtifacts({+ token,+ uiMessages,+ isLoading,+ filePattern,+ fileUrlBuilder,+}: Props) {+ const isArtifactPanelOpen = useCopilotUIStore((s) => s.artifactPanel.isOpen);+ const openArtifact = useCopilotUIStore((s) => s.openArtifact);+ const resetArtifactPanel = useCopilotUIStore((s) => s.resetArtifactPanel);+ const autoOpenedArtifactIdRef = useRef<string | null>(null);++ const latestArtifact = useMemo(+ () =>+ getMostRecentArtifact(uiMessages, {+ filePattern,+ fileUrlBuilder,+ origin: "agent",+ }),+ [uiMessages, filePattern, fileUrlBuilder],+ );++ useEffect(() => {+ resetArtifactPanel();+ autoOpenedArtifactIdRef.current = null;+ return () => resetArtifactPanel();+ }, [token, resetArtifactPanel]);++ useEffect(() => {+ if (isLoading || !latestArtifact) return;+ if (autoOpenedArtifactIdRef.current === latestArtifact.id) return;+ autoOpenedArtifactIdRef.current = latestArtifact.id;+ openArtifact(latestArtifact);+ }, [isLoading, latestArtifact, openArtifact]);++ return { isArtifactPanelOpen };+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/useSharedChatPage.ts b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/useSharedChatPage.tsnew file mode 100644index 0000000000..c3d352ec03--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/chat/[token]/useSharedChatPage.ts@@ -0,0 +1,98 @@+import { useMemo } from "react";+import {+ useGetV2GetSharedChat,+ useGetV2GetSharedChatMessages,+} from "@/app/api/__generated__/endpoints/chat/chat";+import { convertChatSessionMessagesToUiMessages } from "@/app/(platform)/copilot/helpers/convertChatSessionToUiMessages";+import { sharedChatFileUrl } from "@/lib/share/routes";++const PAGE_SIZE = 200;++// Retry transient failures, but not real 404s — a missing share is a+// permanent state and looping retries on it would just delay the error+// UI without changing the outcome.+function retryUnlessNotFound(failureCount: number, error: unknown): boolean {+ const status = (error as { status?: number } | null)?.status;+ if (status === 404) return false;+ return failureCount < 3;+}++export function useSharedChatPage(token: string) {+ const sessionQuery = useGetV2GetSharedChat(token, {+ query: {+ retry: retryUnlessNotFound,+ select: (res) => (res.status === 200 ? res.data : undefined),+ },+ });++ const messagesQuery = useGetV2GetSharedChatMessages(+ token,+ { limit: PAGE_SIZE },+ {+ query: {+ enabled: !!sessionQuery.data,+ retry: retryUnlessNotFound,+ select: (res) => (res.status === 200 ? res.data : undefined),+ },+ },+ );++ const isLoading = sessionQuery.isLoading || messagesQuery.isLoading;+ // Distinguish "session not found / revoked" from "messages 5xx'd+ // mid-deploy". The former is permanent (the share link is dead);+ // the latter is transient and should render the chrome + an+ // in-place retry affordance rather than the not-found card. Bucket+ // both errors but expose them separately so the page can switch on+ // intent.+ const sessionError = sessionQuery.isError;+ const messagesError = messagesQuery.isError;+ const rawError = sessionQuery.error || messagesQuery.error;+ const error = rawError instanceof Error ? rawError.message : undefined;++ // Convert the sanitized SharedChatMessage[] into the UIMessage[] shape+ // that the owner-side ChatMessagesContainer expects. ``isComplete``+ // is hard-coded true because public shares are by definition a+ // finished snapshot — there's no live stream, so any tool-call without+ // a paired tool-row should render as completed (no spinner).+ const ui = useMemo(() => {+ if (!sessionQuery.data || !messagesQuery.data) {+ return {+ uiMessages: [],+ turnStats: undefined as+ | ReturnType<typeof convertChatSessionMessagesToUiMessages>["stats"]+ | undefined,+ };+ }+ const converted = convertChatSessionMessagesToUiMessages(+ sessionQuery.data.id,+ messagesQuery.data.messages,+ {+ isComplete: true,+ // Route file URLs through the public allowlist-gated download+ // endpoint so anonymous viewers can render attachments without+ // hitting the auth-protected workspace download. The URL+ // shape and the renderer's matching regex+ // (``sharedChatFilePattern``) live together in+ // ``lib/share/routes.ts`` so they evolve together.+ fileUrlBuilder: (fileId) => sharedChatFileUrl(token, fileId),+ },+ );+ return { uiMessages: converted.messages, turnStats: converted.stats };+ }, [sessionQuery.data, messagesQuery.data, token]);++ return {+ session: sessionQuery.data,+ rawMessages: messagesQuery.data?.messages ?? [],+ uiMessages: ui.uiMessages,+ turnStats: ui.turnStats,+ hasMore: messagesQuery.data?.has_more ?? false,+ isLoading,+ sessionError,+ messagesError,+ error,+ retry: () => {+ sessionQuery.refetch();+ messagesQuery.refetch();+ },+ };+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/components/ShareHeader/ShareActions.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/components/ShareHeader/ShareActions.tsxnew file mode 100644index 0000000000..56b5b55a6f--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/components/ShareHeader/ShareActions.tsx@@ -0,0 +1,67 @@+"use client";++import { useState } from "react";+import { CheckIcon, CopyIcon } from "@phosphor-icons/react";+import { Button } from "@/components/atoms/Button/Button";+import { toast } from "@/components/molecules/Toast/use-toast";+import { useSupabase } from "@/lib/supabase/hooks/useSupabase";++// Renders the right-slot CTAs on every ``/share/...`` viewer:+//+// - **Copy link** — always present. Anonymous viewers want a one-+// click handoff (paste into a chat / email); signed-in viewers+// get the same convenience.+// - **Sign up** — only when the viewer is not authenticated.+// Hidden for signed-in users so the header doesn't nag them to+// re-sign-up.+//+// Lives next to ``ShareHeader`` because both share routes (execution+// and chat) plug into the same header. Keeping the CTAs in one+// component means a future addition lands in one place.+export function ShareActions() {+ const { isLoggedIn, isUserLoading } = useSupabase();+ const [copied, setCopied] = useState(false);++ async function handleCopy() {+ if (typeof window === "undefined") return;+ try {+ await navigator.clipboard.writeText(window.location.href);+ setCopied(true);+ // 2s matches the share dialog's copy-flash so the two flows+ // feel consistent.+ setTimeout(() => setCopied(false), 2000);+ } catch {+ toast({+ title: "Failed to copy link",+ variant: "destructive",+ });+ }+ }++ return (+ <>+ <Button+ size="small"+ variant="secondary"+ onClick={handleCopy}+ leftIcon={+ copied ? (+ <CheckIcon size={14} weight="bold" />+ ) : (+ <CopyIcon size={14} />+ )+ }+ >+ {copied ? "Copied" : "Copy link"}+ </Button>+ {/* While the auth state is still loading we suppress the Sign up+ CTA — flickering it in then out on hydration looks broken to+ signed-in users opening their own share. */}+ {!isUserLoading && !isLoggedIn && (+ <Button size="small" variant="primary" as="NextLink" href="/signup">+ Sign up+ </Button>+ )}+ </>+ );+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/components/ShareHeader/ShareHeader.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/components/ShareHeader/ShareHeader.tsxnew file mode 100644index 0000000000..806e1665b7--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/components/ShareHeader/ShareHeader.tsx@@ -0,0 +1,75 @@+import Image from "next/image";+import Link from "next/link";+import type { ReactNode } from "react";++interface Props {+ /** Page-specific title rendered in the title slot. Truncated on overflow. */+ title?: ReactNode;+ /** Page-specific subtitle below the title (e.g. "Shared May 12, 2026"). */+ subtitle?: ReactNode;+ /** Page-specific CTAs / pills rendered in the actions slot. */+ actions?: ReactNode;+}++// Shared header bar for every ``/share/...`` route.+//+// The same DOM reflows between breakpoints via CSS grid template+// areas — no JS breakpoint hook, no duplicated markup (so only one+// h1 lives in the document regardless of viewport). First paint+// matches final paint, so no hydration flicker.+//+// - Mobile (< sm): two rows — logo spans the top, title + actions+// sit on the bottom row.+// - Desktop (>= sm): one row — title left, logo centre, actions right.+export function ShareHeader({ title, subtitle, actions }: Props) {+ return (+ <header+ className={+ "grid shrink-0 grid-cols-[1fr_auto] grid-rows-[auto_auto] gap-x-4 " ++ "gap-y-2 border-b border-border bg-background px-4 py-3 " ++ "[grid-template-areas:'logo_logo'_'title_actions'] " ++ "sm:grid-cols-[1fr_auto_1fr] sm:grid-rows-1 " ++ "sm:items-center sm:[grid-template-areas:'title_logo_actions']"+ }+ >+ <div className="min-w-0 [grid-area:title]">+ {title && (+ <h1 className="truncate text-sm font-semibold text-zinc-900">+ {title}+ </h1>+ )}+ {subtitle && (+ <p className="truncate text-xs text-zinc-500">{subtitle}</p>+ )}+ </div>+ <div className="flex justify-center [grid-area:logo]">+ <Logo />+ </div>+ <div className="flex shrink-0 items-center justify-end gap-2 [grid-area:actions]">+ {actions}+ </div>+ </header>+ );+}++function Logo() {+ return (+ <Link href="/" className="inline-block">+ <Image+ src="/autogpt-logo-dark-bg.png"+ alt="AutoGPT"+ width={120}+ height={54}+ className="hidden h-7 w-auto dark:block"+ />+ <Image+ src="/autogpt-logo-light-bg.png"+ alt="AutoGPT"+ width={120}+ height={54}+ className="block h-7 w-auto dark:hidden"+ priority+ />+ </Link>+ );+}diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/components/ShareHeader/__tests__/ShareActions.test.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/components/ShareHeader/__tests__/ShareActions.test.tsxnew file mode 100644index 0000000000..b33916ca27--- /dev/null+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/components/ShareHeader/__tests__/ShareActions.test.tsx@@ -0,0 +1,118 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++import {+ cleanup,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import { ShareActions } from "../ShareActions";++const mockUseSupabase = vi.hoisted(() => vi.fn());++vi.mock("@/lib/supabase/hooks/useSupabase", () => ({+ useSupabase: mockUseSupabase,+}));++// Clipboard isn't available in jsdom by default; defineProperty so+// the copy plumbing can be exercised without crashing.+const clipboardWrite = vi.fn(async (_text: string) => {});++beforeEach(() => {+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: { writeText: clipboardWrite },+ });+ Object.defineProperty(window, "location", {+ configurable: true,+ value: new URL("http://localhost/share/chat/some-token"),+ });+ clipboardWrite.mockClear();+ mockUseSupabase.mockReset();+});++afterEach(() => {+ cleanup();+});++describe("ShareActions", () => {+ test("renders Sign up CTA when the viewer is anonymous", () => {+ mockUseSupabase.mockReturnValue({+ isLoggedIn: false,+ isUserLoading: false,+ });+ render(<ShareActions />);++ expect(screen.getByRole("button", { name: /copy link/i })).toBeDefined();+ const signUp = screen.getByRole("link", { name: /sign up/i });+ expect(signUp.getAttribute("href")).toBe("/signup");+ });++ test("hides Sign up CTA when the viewer is signed in", () => {+ mockUseSupabase.mockReturnValue({+ isLoggedIn: true,+ isUserLoading: false,+ });+ render(<ShareActions />);++ expect(screen.getByRole("button", { name: /copy link/i })).toBeDefined();+ expect(screen.queryByRole("link", { name: /sign up/i })).toBeNull();+ });++ test("hides Sign up CTA while auth state is still loading", () => {+ // First paint after navigation: useSupabase hasn't initialised yet.+ // Showing then hiding the CTA on hydration looks broken to a+ // signed-in viewer opening their own share, so we suppress it.+ mockUseSupabase.mockReturnValue({+ isLoggedIn: false,+ isUserLoading: true,+ });+ render(<ShareActions />);++ expect(screen.queryByRole("link", { name: /sign up/i })).toBeNull();+ // Copy link remains available — anonymous and signed-in alike+ // benefit from the one-click handoff.+ expect(screen.getByRole("button", { name: /copy link/i })).toBeDefined();+ });++ test("clicking Copy link writes the current URL to the clipboard", async () => {+ mockUseSupabase.mockReturnValue({+ isLoggedIn: false,+ isUserLoading: false,+ });+ render(<ShareActions />);++ const copy = screen.getByRole("button", { name: /copy link/i });+ copy.click();++ await waitFor(() => {+ expect(clipboardWrite).toHaveBeenCalledTimes(1);+ });+ expect(clipboardWrite.mock.calls[0][0]).toBe(+ "http://localhost/share/chat/some-token",+ );+ // Button briefly flips to "Copied" — pinning the setCopied(true)+ // branch in handleCopy.+ await screen.findByRole("button", { name: /copied/i });+ });++ test("clipboard failure leaves the button on 'Copy link' and does not flash 'Copied'", async () => {+ mockUseSupabase.mockReturnValue({+ isLoggedIn: false,+ isUserLoading: false,+ });+ clipboardWrite.mockRejectedValueOnce(new Error("nope"));+ render(<ShareActions />);++ const copy = screen.getByRole("button", { name: /copy link/i });+ copy.click();++ await waitFor(() => {+ expect(clipboardWrite).toHaveBeenCalled();+ });+ // The catch path swallows the rejection — the "Copied" affordance+ // must NOT appear because setCopied is gated inside the try block.+ expect(screen.queryByRole("button", { name: /copied/i })).toBeNull();+ expect(screen.getByRole("button", { name: /copy link/i })).toBeDefined();+ });+});diff --git a/autogpt_platform/frontend/src/app/(no-navbar)/share/layout.tsx b/autogpt_platform/frontend/src/app/(no-navbar)/share/layout.tsxindex a0d4654ff8..9a9d8921f6 100644--- a/autogpt_platform/frontend/src/app/(no-navbar)/share/layout.tsx+++ b/autogpt_platform/frontend/src/app/(no-navbar)/share/layout.tsx@@ -1,6 +1,4 @@import type { Metadata } from "next";-import Image from "next/image";-import Link from "next/link";export const metadata: Metadata = {title: "Shared Agent Run - AutoGPT",@@ -8,35 +6,15 @@ export const metadata: Metadata = {robots: "noindex, nofollow",};+// Passthrough. Brand chrome lives in ``./components/ShareHeader``+// which both share pages import — consistency comes from the shared+// component, not from this file. Pages own their own viewport/scroll+// behaviour so the chat viewer can be full-bleed while the execution+// viewer scrolls inside its own container.export default function ShareLayout({children,}: {children: React.ReactNode;}) {- return (- <div className="min-h-screen bg-background">- <header className="border-b border-border bg-background">- <div className="container mx-auto flex justify-center px-4 py-4">- <Link href="/" className="inline-block">- <Image- src="/autogpt-logo-dark-bg.png"- alt="AutoGPT"- width={120}- height={54}- className="hidden h-8 w-auto dark:block"- />- <Image- src="/autogpt-logo-light-bg.png"- alt="AutoGPT"- width={120}- height={54}- className="block h-8 w-auto dark:hidden"- priority- />- </Link>- </div>- </header>- <div className="container mx-auto px-4 py-8">{children}</div>- </div>- );+ return <>{children}</>;}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactCard/ArtifactCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactCard/ArtifactCard.tsxindex a79eb5ad0a..6621e099fa 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactCard/ArtifactCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactCard/ArtifactCard.tsx@@ -11,6 +11,17 @@ import { classifyArtifact } from "../ArtifactPanel/helpers";interface Props {artifact: ArtifactRef;+ /** Read-only mode: opt out of the side-effects that only make sense+ * for the owner (auto-registering with the artifact panel so a+ * newly arriving file can pop the panel open).+ *+ * Click behaviour is unchanged from the owner case: an openable+ * artifact still calls ``openArtifact`` and renders inside+ * ``ArtifactPanel`` (the public share viewer mounts the panel too),+ * while a non-openable asset falls back to a direct download. In+ * other words, ``readOnly`` does NOT force every click to download+ * — that's only true for non-openable assets, regardless of mode. */+ readOnly?: boolean;}function formatSize(bytes?: number): string {@@ -20,7 +31,7 @@ function formatSize(bytes?: number): string {return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;}-export function ArtifactCard({ artifact }: Props) {+export function ArtifactCard({ artifact, readOnly }: Props) {const isActive = useCopilotUIStore((s) =>s.artifactPanel.isOpen &&@@ -34,10 +45,13 @@ export function ArtifactCard({ artifact }: Props) {// Register this artifact on mount — the store decides whether to auto-open.// Fires once per artifact ID; subsequent renders with the same ID are no-ops// in the store (knownIds check).+ // Skipped in readOnly mode — the share viewer has no panel for auto-open+ // to target, and registering would just pollute the store.useEffect(() => {+ if (readOnly) return;registerArtifactForAutoOpen(artifact);// eslint-disable-next-line react-hooks/exhaustive-deps -- re-register on ID or MIME change- }, [artifact.id, artifact.mimeType, registerArtifactForAutoOpen]);+ }, [artifact.id, artifact.mimeType, registerArtifactForAutoOpen, readOnly]);const classification = classifyArtifact(artifact.mimeType,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactCard/__tests__/ArtifactCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactCard/__tests__/ArtifactCard.test.tsxnew file mode 100644index 0000000000..c767c5fa9d--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ArtifactCard/__tests__/ArtifactCard.test.tsx@@ -0,0 +1,131 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++import { cleanup, render, screen } from "@/tests/integrations/test-utils";+import type { ArtifactRef } from "../../../store";+import { ArtifactCard } from "../ArtifactCard";++const registerSpy = vi.fn();+const openSpy = vi.fn();++// Mock the copilot UI store — return values per selector so the+// component can call ``useCopilotUIStore(selector)`` and get back+// our spies / static state.+vi.mock("../../../store", () => {+ function useCopilotUIStore<T>(selector: (state: unknown) => T): T {+ const state = {+ artifactPanel: { isOpen: false, activeArtifact: null },+ openArtifact: openSpy,+ registerArtifactForAutoOpen: registerSpy,+ };+ return selector(state);+ }+ return { useCopilotUIStore };+});++// Skip real download wiring — fetch/blob plumbing isn't under test.+// Module-level mock so tests can override implementations per case.+const downloadArtifactMock = vi.fn(() => Promise.resolve());+vi.mock("../../ArtifactPanel/downloadArtifact", () => ({+ downloadArtifact: (...args: unknown[]) =>+ downloadArtifactMock(...(args as [])),+}));++// Toast is invoked from the download-failure path; spy on it so we+// can assert the user-visible "Download failed" surface fires.+const toastSpy = vi.fn();+vi.mock("@/components/molecules/Toast/use-toast", () => ({+ toast: (...args: unknown[]) => toastSpy(...(args as [])),+ useToast: () => ({ toast: toastSpy }),+}));++const ARTIFACT: ArtifactRef = {+ id: "550e8400-e29b-41d4-a716-446655440000",+ title: "report.png",+ mimeType: "image/png",+ origin: "agent",+ sourceUrl: "https://example.com/file/550e8400-e29b-41d4-a716-446655440000",+ sizeBytes: 12_345,+};++beforeEach(() => {+ registerSpy.mockClear();+ openSpy.mockClear();+ downloadArtifactMock.mockReset();+ downloadArtifactMock.mockImplementation(() => Promise.resolve());+ toastSpy.mockClear();+});++afterEach(() => {+ cleanup();+});++describe("ArtifactCard — readOnly", () => {+ test("does NOT register for auto-open in readOnly mode", () => {+ render(<ArtifactCard artifact={ARTIFACT} readOnly />);+ expect(registerSpy).not.toHaveBeenCalled();+ });++ test("registers for auto-open in default (owner) mode", () => {+ render(<ArtifactCard artifact={ARTIFACT} />);+ expect(registerSpy).toHaveBeenCalledTimes(1);+ expect(registerSpy).toHaveBeenCalledWith(ARTIFACT);+ });++ test("openable artifact opens the panel on click in readOnly mode", () => {+ // Click on an openable artifact still calls openArtifact even in readOnly —+ // that's how the share viewer renders previews via ArtifactPanel.+ render(<ArtifactCard artifact={ARTIFACT} readOnly />);+ const button = screen.getByRole("button");+ button.click();+ expect(openSpy).toHaveBeenCalledWith(ARTIFACT);+ });++ test("renders the artifact title", () => {+ render(<ArtifactCard artifact={ARTIFACT} readOnly />);+ expect(screen.getByText("report.png")).toBeDefined();+ });+});++describe("ArtifactCard — non-openable artifact (download-only)", () => {+ // application/zip + .zip extension is classified as download-only,+ // so the card renders the download-only branch instead of the+ // openable click-to-open variant.+ const ZIP_ARTIFACT: ArtifactRef = {+ id: "660e8400-e29b-41d4-a716-446655440000",+ title: "agent-output.zip",+ mimeType: "application/zip",+ origin: "agent",+ sourceUrl: "https://example.com/file/660e8400-e29b-41d4-a716-446655440000",+ };++ test("clicking the card triggers downloadArtifact", () => {+ render(<ArtifactCard artifact={ZIP_ARTIFACT} />);+ const button = screen.getByRole("button");+ button.click();+ expect(downloadArtifactMock).toHaveBeenCalledTimes(1);+ expect(downloadArtifactMock).toHaveBeenCalledWith(ZIP_ARTIFACT);+ // Non-openable artifacts must NOT open the panel — the panel+ // can't preview them.+ expect(openSpy).not.toHaveBeenCalled();+ });++ test("download failure surfaces a destructive toast", async () => {+ downloadArtifactMock.mockImplementation(() =>+ Promise.reject(new Error("network down")),+ );++ render(<ArtifactCard artifact={ZIP_ARTIFACT} />);+ const button = screen.getByRole("button");+ button.click();++ await vi.waitFor(() => {+ expect(toastSpy).toHaveBeenCalledTimes(1);+ });+ const toastArg = toastSpy.mock.calls[0][0] as {+ title: string;+ variant?: string;+ };+ expect(toastArg.title).toMatch(/download failed/i);+ expect(toastArg.variant).toBe("destructive");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsxindex e900a13cec..298899f0e4 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/ChatContainer.tsx@@ -17,6 +17,7 @@ import { CopilotChatActionsProvider } from "../CopilotChatActionsProvider/Copiloimport { EmptySession } from "../EmptySession/EmptySession";import { UsageLimitReachedCard } from "../UsageLimits/UsageLimitReachedCard/UsageLimitReachedCard";import { useIsUsageLimitReached } from "../UsageLimits/useIsUsageLimitReached";+import { SharedChatNotice } from "./components/SharedChatNotice";import { useAutoOpenArtifacts } from "./useAutoOpenArtifacts";export interface ChatContainerProps {@@ -206,6 +207,7 @@ export const ChatContainer = ({</div></div>)}+ <SharedChatNotice sessionId={sessionId} /><Tooltip open={isLimitReached ? undefined : false}><TooltipTrigger asChild><div>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsxindex 92d2d3ce93..6a75cbb8a6 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/__tests__/ChatContainer.test.tsx@@ -1,14 +1,25 @@import React from "react";-import { render, screen, cleanup } from "@/tests/integrations/test-utils";+import { getGetV2GetChatShareStateMockHandler200 } from "@/app/api/__generated__/endpoints/chat/chat.msw";+import type { ChatShareStateResponse } from "@/app/api/__generated__/models/chatShareStateResponse";+import { server } from "@/mocks/mock-server";+import {+ render,+ screen,+ cleanup,+ fireEvent,+ waitFor,+} from "@/tests/integrations/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ChatContainer } from "../ChatContainer";import { useCopilotUIStore } from "../../../store";const mockIsUsageLimitReached = vi.fn();const mockArtifactsEnabled = vi.fn(() => false);+const clipboardWrite = vi.fn(async (_text: string) => {});const ARTIFACT_A_ID = "11111111-0000-0000-0000-000000000000";const ARTIFACT_B_ID = "22222222-0000-0000-0000-000000000000";+const SHARED_TOKEN = "33333333-0000-0000-0000-000000000000";function makeArtifact(id: string, title = `${id}.txt`) {return {@@ -33,6 +44,22 @@ function resetCopilotStore() {});}+function mockShareState(state: Partial<ChatShareStateResponse>) {+ server.use(+ getGetV2GetChatShareStateMockHandler200(+ (): ChatShareStateResponse => ({+ is_shared: false,+ share_token: null,+ auto_share_executions: false,+ message_count: 0,+ linked_run_count: 0,+ file_count: 0,+ ...state,+ }),+ ),+ );+}+vi.mock("framer-motion", () => ({LayoutGroup: ({ children }: { children: React.ReactNode }) => <>{children}</>,motion: {@@ -159,7 +186,13 @@ describe("ChatContainer", () => {beforeEach(() => {mockIsUsageLimitReached.mockReturnValue(false);mockArtifactsEnabled.mockReturnValue(false);+ mockShareState({ is_shared: false });resetCopilotStore();+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: { writeText: clipboardWrite },+ });+ clipboardWrite.mockClear();vi.stubGlobal("ResizeObserver", MockResizeObserver);});@@ -190,6 +223,41 @@ describe("ChatContainer", () => {expect(screen.queryByRole("alert")).toBeNull();});+ it("does not render the shared-chat notice for unshared chats", async () => {+ render(<ChatContainer {...baseProps} />);++ await waitFor(() => {+ expect(screen.queryByText("This chat is shared")).toBeNull();+ });+ });++ it("renders the shared-chat notice for chats the user has shared", async () => {+ mockShareState({ is_shared: true, share_token: SHARED_TOKEN });++ render(<ChatContainer {...baseProps} />);++ expect(await screen.findByText("This chat is shared")).toBeDefined();+ expect(screen.getByRole("button", { name: /copy link/i })).toBeDefined();+ });++ it("copies the shared-chat link from the owner notice", async () => {+ mockShareState({ is_shared: true, share_token: SHARED_TOKEN });++ render(<ChatContainer {...baseProps} />);++ fireEvent.click(await screen.findByRole("button", { name: /copy link/i }));++ await waitFor(() => {+ expect(clipboardWrite).toHaveBeenCalledTimes(1);+ });+ expect(clipboardWrite.mock.calls[0][0]).toMatch(+ new RegExp(`/share/chat/${SHARED_TOKEN}$`),+ );+ expect(+ await screen.findByRole("button", { name: /copied/i }),+ ).toBeDefined();+ });+describe("auto-open artifact panel behavior", () => {it("does not auto-open the artifact panel on initial render", () => {mockArtifactsEnabled.mockReturnValue(true);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/SharedChatNotice.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/SharedChatNotice.tsxnew file mode 100644index 0000000000..27f223c3a6--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatContainer/components/SharedChatNotice.tsx@@ -0,0 +1,60 @@+"use client";++import { useState } from "react";+import { CheckIcon, CopyIcon } from "@phosphor-icons/react";+import { useGetV2GetChatShareState } from "@/app/api/__generated__/endpoints/chat/chat";+import { Button } from "@/components/atoms/Button/Button";+import { useToast } from "@/components/molecules/Toast/use-toast";+import { chatShareUrl } from "@/lib/share/routes";++interface Props {+ sessionId: string;+}++export function SharedChatNotice({ sessionId }: Props) {+ const { toast } = useToast();+ const [copied, setCopied] = useState(false);+ const { data: shareState } = useGetV2GetChatShareState(sessionId, {+ query: {+ enabled: !!sessionId,+ select: (res) => (res.status === 200 ? res.data : undefined),+ },+ });++ if (!shareState?.is_shared || !shareState.share_token) return null;++ const shareUrl = chatShareUrl(shareState.share_token);++ async function copyShareUrl() {+ try {+ await navigator.clipboard.writeText(shareUrl);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ } catch {+ toast({+ title: "Failed to copy link",+ variant: "destructive",+ });+ }+ }++ return (+ <div className="mb-2 flex items-center justify-between gap-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-900">+ <span className="font-medium">This chat is shared</span>+ <Button+ size="small"+ variant="secondary"+ onClick={copyShareUrl}+ leftIcon={+ copied ? (+ <CheckIcon size={14} weight="bold" />+ ) : (+ <CopyIcon size={14} />+ )+ }+ >+ {copied ? "Copied" : "Copy link"}+ </Button>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsxindex 67635a0b57..2cfd5ca236 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/ChatMessagesContainer.tsx@@ -65,13 +65,36 @@ interface Props {* overlays pinned above the input area (e.g. the usage-limit card) can* sit over the last message without permanently obscuring it. */bottomContentPadding?: number;+ /** Public-viewer mode: render messages exactly as the owner sees them,+ * but hide every interactive affordance that depends on auth — feedback+ * buttons, TTS, queue/streaming indicators, load-more, retry, pending-+ * review banners, queued-message strip. Anonymous viewers of a shared+ * chat get the rich renderer without any controls that would 401. */+ readOnly?: boolean;+ /** URL→file-ID matcher used to decide whether a ``FileUIPart`` becomes+ * an ArtifactCard. Owner side defaults to the workspace-file URL+ * shape; the public viewer passes a per-token pattern so its file+ * URLs match without loosening the default. */+ filePattern?: RegExp;+ /** Override the URL emitted when rewriting ``workspace://`` references+ * in markdown prose AND when building inline artifact source URLs.+ * The public viewer passes a token-aware builder. */+ fileUrlBuilder?: (fileId: string) => string;+}++interface RenderSegmentOptions {+ onRetry?: () => void;+ fileUrlBuilder?: (fileId: string) => string;+ forceArtifacts?: boolean;+ readOnly?: boolean;}function renderSegments(segments: RenderSegment[],messageID: string,- onRetry?: () => void,+ options: RenderSegmentOptions = {},): React.ReactNode[] {+ const { onRetry, fileUrlBuilder, forceArtifacts, readOnly } = options;return segments.map((seg, segIdx) => {if (seg.kind === "collapsed-group") {return <CollapsedToolGroup key={`group-${segIdx}`} parts={seg.parts} />;@@ -83,6 +106,9 @@ function renderSegments(messageID={messageID}partIndex={seg.index}onRetry={onRetry}+ fileUrlBuilder={fileUrlBuilder}+ forceArtifacts={forceArtifacts}+ readOnly={readOnly}/>);});@@ -280,6 +306,9 @@ export function ChatMessagesContainer({turnStats,queuedMessages,bottomContentPadding,+ readOnly = false,+ filePattern,+ fileUrlBuilder,}: Props) {// Hide the container for one frame when messages first load so// StickToBottom can scroll to the bottom before the user sees it.@@ -449,7 +478,7 @@ export function ChatMessagesContainer({: undefined}>- {hasMoreMessages && onLoadMore && (+ {!readOnly && hasMoreMessages && onLoadMore && (<LoadMoreSentinelhasMore={hasMoreMessages}isLoading={!!isLoadingMore}@@ -536,15 +565,20 @@ export function ChatMessagesContainer({>{hasReasoning && reasoningSegments && (<StepsCollapse>- {renderSegments(reasoningSegments, message.id)}+ {renderSegments(reasoningSegments, message.id, {+ fileUrlBuilder,+ forceArtifacts: readOnly,+ readOnly,+ })}</StepsCollapse>)}{responseSegments- ? renderSegments(- responseSegments,- message.id,- isLastAssistant ? onRetry : undefined,- )+ ? renderSegments(responseSegments, message.id, {+ onRetry: isLastAssistant ? onRetry : undefined,+ fileUrlBuilder,+ forceArtifacts: readOnly,+ readOnly,+ }): renderableParts.map((part, i) => (<MessagePartRendererkey={`${message.id}-${i}`}@@ -552,6 +586,9 @@ export function ChatMessagesContainer({messageID={message.id}partIndex={i}onRetry={isLastAssistant ? onRetry : undefined}+ fileUrlBuilder={fileUrlBuilder}+ forceArtifacts={readOnly}+ readOnly={readOnly}/>))}{isLastInTurn && !isCurrentlyStreaming && (@@ -567,7 +604,8 @@ export function ChatMessagesContainer({)}{isLastAssistant && showIndicator && indicator}</MessageContent>- {message.role === "user" &&+ {!readOnly &&+ message.role === "user" &&sessionChatStatus === "queued" &&(() => {const stats = turnStats?.get(message.id);@@ -606,25 +644,33 @@ export function ChatMessagesContainer({<MessageAttachmentsfiles={fileParts}isUser={message.role === "user"}+ forceArtifacts={readOnly}+ filePattern={filePattern}+ readOnly={readOnly}/>)}- {showActions && (+ {!readOnly && showActions && (<AssistantMessageActionsmessage={message}sessionID={sessionID ?? null}/>)}+ {readOnly && showActions && (+ <MessageActions className="mt-1 items-center justify-start gap-2 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100">+ <CopyButton text={textParts.map((p) => p.text).join("\n")} />+ </MessageActions>+ )}</Message>);})}- {showIndicator && lastMessage?.role !== "assistant" && (+ {!readOnly && showIndicator && lastMessage?.role !== "assistant" && (<Message from="assistant"><MessageContent className="text-[1rem] leading-relaxed">{indicator}</MessageContent></Message>)}- {isRestoringActiveSession && (+ {!readOnly && isRestoringActiveSession && (<Message from="assistant"><MessageContent className="text-[1rem] leading-relaxed text-slate-900">{showRestoreFallback ? (@@ -649,19 +695,22 @@ export function ChatMessagesContainer({</MessageContent></Message>)}- {graphExecId && <CopilotPendingReviews graphExecId={graphExecId} />}- {queuedMessages?.map((msg, idx) => (- <Message key={idx} from="user">- <MessageContent className="flex flex-col gap-1 rounded-xl border border-dashed border-purple-400 bg-purple-100 px-3 py-2.5 text-[1rem] leading-relaxed text-slate-900 opacity-60 [border-bottom-right-radius:0]">- <span>{msg}</span>- <span className="flex items-center gap-1 text-xs text-slate-500">- <Clock className="size-3" weight="bold" />- Queued- </span>- </MessageContent>- </Message>- ))}- {error && !lastAssistantHasErrorMarker && (+ {!readOnly && graphExecId && (+ <CopilotPendingReviews graphExecId={graphExecId} />+ )}+ {!readOnly &&+ queuedMessages?.map((msg, idx) => (+ <Message key={idx} from="user">+ <MessageContent className="flex flex-col gap-1 rounded-xl border border-dashed border-purple-400 bg-purple-100 px-3 py-2.5 text-[1rem] leading-relaxed text-slate-900 opacity-60 [border-bottom-right-radius:0]">+ <span>{msg}</span>+ <span className="flex items-center gap-1 text-xs text-slate-500">+ <Clock className="size-3" weight="bold" />+ Queued+ </span>+ </MessageContent>+ </Message>+ ))}+ {!readOnly && error && !lastAssistantHasErrorMarker && (<details className="rounded-lg bg-red-50 p-4 text-sm text-red-700"><summary className="cursor-pointer font-medium">The assistant encountered an error. Please try sending yourdiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsxindex de3cd643f6..a5398ed51b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/ChatMessagesContainer.test.tsx@@ -556,7 +556,9 @@ describe("ChatMessagesContainer — queue badges on user messages", () => {{id: userId,role: "user" as const,- parts: [{ type: "text" as const, text: "queue me", state: "done" }],+ parts: [+ { type: "text" as const, text: "queue me", state: "done" as const },+ ],},];render(@@ -622,3 +624,97 @@ describe("ChatMessagesContainer — queue badges on user messages", () => {expect(screen.queryByTestId("queue-badge")).toBeNull();});});++// ── readOnly viewer behaviour ─────────────────────────────────────────────+//+// The shared-chat viewer (``/share/chat/[token]``) renders the same+// ChatMessagesContainer with ``readOnly`` so the public viewer cannot+// trigger any owner-only interactions (load-more, queue badges,+// feedback actions, error banners). These tests pin the gate.++describe("ChatMessagesContainer — readOnly mode", () => {+ beforeEach(() => {+ mockScrollEl.scrollHeight = 100;+ mockScrollEl.scrollTop = 0;+ mockScrollEl.clientHeight = 500;+ MockIntersectionObserver.lastCallback = null;+ vi.stubGlobal("IntersectionObserver", MockIntersectionObserver);+ });++ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ it("hides the load-older-messages sentinel even when more history exists", () => {+ render(+ <ChatMessagesContainer+ {...baseProps}+ hasMoreMessages+ onLoadMore={vi.fn()}+ readOnly+ />,+ );+ expect(+ screen.queryByRole("button", { name: /load older messages/i }),+ ).toBeNull();+ });++ it("hides queued messages even when queuedMessages is non-empty", () => {+ render(+ <ChatMessagesContainer+ {...baseProps}+ queuedMessages={["should not show"]}+ readOnly+ />,+ );+ expect(screen.queryByText("should not show")).toBeNull();+ expect(screen.queryByText("Queued")).toBeNull();+ });++ it("hides the trailing error banner even on error status", () => {+ render(+ <ChatMessagesContainer+ {...baseProps}+ error={new Error("upstream blew up")}+ status="error"+ readOnly+ messages={[+ {+ id: "u-1",+ role: "user",+ parts: [{ type: "text", text: "go" }],+ },+ ]}+ />,+ );+ expect(screen.queryByText(/encountered an error/i)).toBeNull();+ expect(screen.queryByText(/upstream blew up/i)).toBeNull();+ });++ it("hides the queue-badge gate even when the session is queued", () => {+ const userId = "user-q-readonly";+ const turnStats = new Map([+ [userId, { isLatestUserMessage: true, rawMessageId: "uuid-q-ro" }],+ ]);+ const messages = [+ {+ id: userId,+ role: "user" as const,+ parts: [+ { type: "text" as const, text: "queue me", state: "done" as const },+ ],+ },+ ];+ render(+ <ChatMessagesContainer+ {...baseProps}+ messages={messages}+ turnStats={turnStats}+ sessionChatStatus="queued"+ readOnly+ />,+ );+ expect(screen.queryByTestId("queue-badge")).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.tsindex eb94cd2044..3348be6017 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/helpers.test.ts@@ -1,11 +1,14 @@import { describe, expect, it } from "vitest";import {+ WORKSPACE_FILE_PATTERN,extractWorkspaceArtifacts,filePartToArtifactRef,isReasoningToolPart,+ resolveWorkspaceUrls,splitReasoningAndResponse,} from "../helpers";import type { MessagePart } from "../helpers";+import type { FileUIPart } from "ai";function textPart(text: string): MessagePart {return { type: "text", text } as MessagePart;@@ -374,3 +377,93 @@ describe("splitReasoningAndResponse", () => {);});});++// ----- Custom fileUrlBuilder threading -----------------------------------+// The public-share viewer threads a token-aware URL builder through+// these helpers so anonymous readers can render file references that+// hit the public allowlist-gated download endpoint instead of the+// auth'd workspace one. These tests pin the contract.++describe("extractWorkspaceArtifacts with custom fileUrlBuilder", () => {+ const FILE_ID = "550e8400-e29b-41d4-a716-446655440000";++ it("routes sourceUrl through the supplied builder", () => {+ const text = `See [report](workspace://${FILE_ID}) for details.`;+ const builder = (id: string) => `/share/files/${id}.dl`;+ const out = extractWorkspaceArtifacts(text, builder);+ expect(out).toHaveLength(1);+ expect(out[0].sourceUrl).toBe(`/share/files/${FILE_ID}.dl`);+ });++ it("default builder produces the workspace-file URL", () => {+ const text = `[report](workspace://${FILE_ID})`;+ const out = extractWorkspaceArtifacts(text);+ expect(out[0].sourceUrl).toContain(`/files/${FILE_ID}/download`);+ });+});++describe("resolveWorkspaceUrls with custom fileUrlBuilder", () => {+ const FILE_ID = "550e8400-e29b-41d4-a716-446655440000";++ it("rewrites image syntax using the supplied builder", () => {+ const text = ``;+ const builder = (id: string) => `/share/files/${id}.png`;+ const out = resolveWorkspaceUrls(text, builder);+ expect(out).toBe(``);+ });++ it("rewrites link syntax to absolute URL with origin prefix", () => {+ const text = `Open [the file](workspace://${FILE_ID}) here.`;+ const builder = (id: string) => `/share/files/${id}.dl`;+ const out = resolveWorkspaceUrls(text, builder);+ // jsdom's window.location.origin is "http://localhost:3000".+ expect(out).toContain(`(http://localhost:3000/share/files/${FILE_ID}.dl)`);+ });++ it("default builder rewrites workspace:// to the workspace endpoint", () => {+ const text = ``;+ const out = resolveWorkspaceUrls(text);+ expect(out).toMatch(/api\/workspace\/files\/.*\/download/);+ });++ it("video MIME hint produces video: alt prefix", () => {+ const text = ``;+ const builder = (id: string) => `/share/files/${id}.mp4`;+ const out = resolveWorkspaceUrls(text, builder);+ expect(out).toBe(``);+ });+});++describe("filePartToArtifactRef with custom pattern", () => {+ const FILE_ID = "550e8400-e29b-41d4-a716-446655440000";+ const file: FileUIPart = {+ type: "file",+ filename: "report.png",+ mediaType: "image/png",+ url: `/api/proxy/api/public/shared/chats/some-token/files/${FILE_ID}/download`,+ };++ it("default pattern (workspace-file) rejects public-share URL", () => {+ expect(filePartToArtifactRef(file)).toBeNull();+ });++ it("custom pattern matching the public-share URL extracts the file ID", () => {+ const pattern =+ /\/api\/proxy\/api\/public\/shared\/chats\/[^/]+\/files\/([a-f0-9-]+)\/download/;+ const ref = filePartToArtifactRef(file, "agent", pattern);+ expect(ref?.id).toBe(FILE_ID);+ expect(ref?.title).toBe("report.png");+ expect(ref?.mimeType).toBe("image/png");+ });++ it("returns null when url has no file", () => {+ expect(+ filePartToArtifactRef({ ...file, url: "" } as FileUIPart),+ ).toBeNull();+ });++ it("WORKSPACE_FILE_PATTERN matches a workspace-file URL", () => {+ const url = `/api/proxy/api/workspace/files/${FILE_ID}/download`;+ expect(url.match(WORKSPACE_FILE_PATTERN)?.[1]).toBe(FILE_ID);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageAttachments.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageAttachments.tsxindex 43ad4c4208..3682a27dc3 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageAttachments.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessageAttachments.tsx@@ -21,6 +21,18 @@ import { filePartToArtifactRef } from "../helpers";interface Props {files: FileUIPart[];isUser?: boolean;+ /** Force the artifact-card rendering path regardless of the+ * ``ARTIFACTS`` flag. The public share viewer passes this so+ * anonymous readers always get the rich treatment — the flag+ * defaults off and we don't want it to gate the viewer UX. */+ forceArtifacts?: boolean;+ /** URL→file-ID pattern used by ``filePartToArtifactRef``. Owner+ * side defaults to the workspace-file URL shape; the public viewer+ * passes a per-token pattern from ``lib/share/routes.ts``. */+ filePattern?: RegExp;+ /** Read-only mode — forwarded to ``ArtifactCard`` so clicks+ * download instead of trying to open a panel that isn't mounted. */+ readOnly?: boolean;}function renderFileContent(file: FileUIPart): React.ReactNode | null {@@ -41,8 +53,15 @@ function renderFileContent(file: FileUIPart): React.ReactNode | null {);}-export function MessageAttachments({ files, isUser }: Props) {- const isArtifactsEnabled = useGetFlag(Flag.ARTIFACTS);+export function MessageAttachments({+ files,+ isUser,+ forceArtifacts,+ filePattern,+ readOnly,+}: Props) {+ const isArtifactsFlagEnabled = useGetFlag(Flag.ARTIFACTS);+ const isArtifactsEnabled = forceArtifacts || isArtifactsFlagEnabled;if (files.length === 0) return null;return (@@ -52,12 +71,14 @@ export function MessageAttachments({ files, isUser }: Props) {const artifactRef = filePartToArtifactRef(file,isUser ? "user-upload" : "agent",+ filePattern,);if (artifactRef) {return (<ArtifactCardkey={`artifact-${artifactRef.id}-${i}`}artifact={artifactRef}+ readOnly={readOnly}/>);}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsxindex 503aafb009..8219e06f8b 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/MessagePartRenderer.tsx@@ -68,17 +68,32 @@ function WorkspaceMediaImage(props: React.JSX.IntrinsicElements["img"]) {/** Stable components override for Streamdown (avoids re-creating on every render). */const STREAMDOWN_COMPONENTS = { img: WorkspaceMediaImage };-function TextWithArtifactCards({ text }: { text: string }) {- const isArtifactsEnabled = useGetFlag(Flag.ARTIFACTS);- const artifacts = extractWorkspaceArtifacts(text);- const resolved = resolveWorkspaceUrls(text);+function TextWithArtifactCards({+ text,+ fileUrlBuilder,+ forceArtifacts,+ readOnly,+}: {+ text: string;+ fileUrlBuilder?: (fileId: string) => string;+ forceArtifacts?: boolean;+ readOnly?: boolean;+}) {+ const isArtifactsFlagEnabled = useGetFlag(Flag.ARTIFACTS);+ const isArtifactsEnabled = forceArtifacts || isArtifactsFlagEnabled;+ const artifacts = extractWorkspaceArtifacts(text, fileUrlBuilder);+ const resolved = resolveWorkspaceUrls(text, fileUrlBuilder);return (<>{isArtifactsEnabled && artifacts.length > 0 && (<div className="mb-2 flex flex-col gap-1">{artifacts.map((artifact) => (- <ArtifactCard key={artifact.id} artifact={artifact} />+ <ArtifactCard+ key={artifact.id}+ artifact={artifact}+ readOnly={readOnly}+ />))}</div>)}@@ -94,6 +109,17 @@ interface Props {messageID: string;partIndex: number;onRetry?: () => void;+ /** Override the URL emitted when rewriting workspace:// references+ * in markdown. Owner side defaults to the workspace-file endpoint;+ * the public share viewer passes a token-aware builder so anonymous+ * readers can download via the public allowlist-gated route. */+ fileUrlBuilder?: (fileId: string) => string;+ /** Force inline artifact-card rendering for workspace:// URIs in+ * prose, regardless of the ``ARTIFACTS`` LD flag. */+ forceArtifacts?: boolean;+ /** Read-only mode — forwarded so embedded ``ArtifactCard``s+ * download on click instead of opening a panel. */+ readOnly?: boolean;}export function MessagePartRenderer({@@ -101,6 +127,9 @@ export function MessagePartRenderer({messageID,partIndex,onRetry,+ fileUrlBuilder,+ forceArtifacts,+ readOnly,}: Props) {const key = `${messageID}-${partIndex}`;@@ -157,7 +186,15 @@ export function MessagePartRenderer({);}- return <TextWithArtifactCards key={key} text={cleanText} />;+ return (+ <TextWithArtifactCards+ key={key}+ text={cleanText}+ fileUrlBuilder={fileUrlBuilder}+ forceArtifacts={forceArtifacts}+ readOnly={readOnly}+ />+ );}case "tool-ask_question":return <AskQuestionTool key={key} part={part as ToolUIPart} />;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.tsindex f2fb7b2d67..9fd4a7011f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/helpers.ts@@ -47,8 +47,17 @@ export function isReasoningToolPart(part: MessagePart): boolean {return REASONING_TOOL_TYPES.has(part.type);}-const WORKSPACE_FILE_PATTERN =- /\/api\/proxy\/api\/workspace\/files\/([a-f0-9-]+)\/download/;+// Default workspace-file URL shape: ``/api/proxy/api/workspace/files/<uuid>/download``.+// Other surfaces (e.g. public share viewer) pass their own pattern into+// ``filePartToArtifactRef`` rather than loosen this one — keeping the+// match anchored to a known prefix per surface prevents an unrelated+// future ``FileUIPart`` source from accidentally rendering as an+// artifact. ``^`` and ``$`` are required — without them, the pattern+// matches as a substring inside longer URLs (e.g. an attacker-controlled+// file URL prefixed with the proxy path) and surfaces the embedded UUID+// as a renderable artifact id.+export const WORKSPACE_FILE_PATTERN =+ /^\/api\/proxy\/api\/workspace\/files\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\/download$/;const WORKSPACE_URI_PATTERN = /workspace:\/\/([a-f0-9-]+)(?:#([^\s)\]]+))?/g;const INTERACTIVE_RESPONSE_TYPES: ReadonlySet<string> = new Set([@@ -263,9 +272,14 @@ export function parseSpecialMarkers(text: string): {export function filePartToArtifactRef(file: FileUIPart,origin: ArtifactRef["origin"] = "user-upload",+ /** Pattern that extracts the file UUID from ``file.url``. Defaults+ * to the workspace-file shape; the public share viewer passes a+ * per-token pattern from ``lib/share/routes.ts`` so its file URLs+ * match without loosening the default. */+ pattern: RegExp = WORKSPACE_FILE_PATTERN,): ArtifactRef | null {if (!file.url) return null;- const match = file.url.match(WORKSPACE_FILE_PATTERN);+ const match = file.url.match(pattern);if (!match) return null;return {id: match[1],@@ -279,7 +293,17 @@ export function filePartToArtifactRef(const FULL_UUID =/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;-export function extractWorkspaceArtifacts(text: string): ArtifactRef[] {+/** Build the default workspace-file URL — used wherever a caller+ * doesn't supply its own ``fileUrlBuilder``. Centralising it here+ * keeps the owner-side default in one place. */+function defaultWorkspaceFileUrl(fileId: string): string {+ return `/api/proxy${getGetWorkspaceDownloadFileByIdUrl(fileId)}`;+}++export function extractWorkspaceArtifacts(+ text: string,+ fileUrlBuilder: (fileId: string) => string = defaultWorkspaceFileUrl,+): ArtifactRef[] {const seen = new Set<string>();const artifacts: ArtifactRef[] = [];@@ -311,7 +335,7 @@ export function extractWorkspaceArtifacts(text: string): ArtifactRef[] {id: parsed.fileID,title,mimeType: parsed.mimeType,- sourceUrl: `/api/proxy${getGetWorkspaceDownloadFileByIdUrl(parsed.fileID)}`,+ sourceUrl: fileUrlBuilder(parsed.fileID),origin: "agent",});}@@ -321,6 +345,10 @@ export function extractWorkspaceArtifacts(text: string): ArtifactRef[] {export function getMessageArtifacts(message: UIMessage<unknown, UIDataTypes, UITools>,+ options: {+ filePattern?: RegExp;+ fileUrlBuilder?: (fileId: string) => string;+ } = {},): ArtifactRef[] {const byId = new Map<string, ArtifactRef>();@@ -330,7 +358,7 @@ export function getMessageArtifacts(for (const part of message.parts) {if (part.type === "file") {const origin = message.role === "user" ? "user-upload" : "agent";- const artifact = filePartToArtifactRef(part, origin);+ const artifact = filePartToArtifactRef(part, origin, options.filePattern);if (artifact) {byId.set(artifact.id, artifact);}@@ -339,7 +367,10 @@ export function getMessageArtifacts(for (const part of message.parts) {if (part.type === "text") {- for (const artifact of extractWorkspaceArtifacts(part.text)) {+ for (const artifact of extractWorkspaceArtifacts(+ part.text,+ options.fileUrlBuilder,+ )) {if (!byId.has(artifact.id)) {byId.set(artifact.id, artifact);}@@ -350,6 +381,61 @@ export function getMessageArtifacts(return Array.from(byId.values());}+export function getMostRecentArtifact(+ messages: UIMessage<unknown, UIDataTypes, UITools>[],+ options: {+ filePattern?: RegExp;+ fileUrlBuilder?: (fileId: string) => string;+ origin?: ArtifactRef["origin"];+ } = {},+): ArtifactRef | null {+ for (+ let messageIndex = messages.length - 1;+ messageIndex >= 0;+ messageIndex--+ ) {+ const message = messages[messageIndex];+ for (+ let partIndex = message.parts.length - 1;+ partIndex >= 0;+ partIndex--+ ) {+ const part = message.parts[partIndex];+ if (part.type === "file") {+ const origin = message.role === "user" ? "user-upload" : "agent";+ const artifact = filePartToArtifactRef(+ part,+ origin,+ options.filePattern,+ );+ if (+ artifact &&+ (!options.origin || artifact.origin === options.origin)+ ) {+ return artifact;+ }+ }+ if (part.type === "text") {+ const artifacts = extractWorkspaceArtifacts(+ part.text,+ options.fileUrlBuilder,+ );+ for (+ let artifactIndex = artifacts.length - 1;+ artifactIndex >= 0;+ artifactIndex--+ ) {+ const artifact = artifacts[artifactIndex];+ if (!options.origin || artifact.origin === options.origin) {+ return artifact;+ }+ }+ }+ }+ }+ return null;+}+/*** Resolve workspace:// URLs in markdown text to proxy download URLs.*@@ -358,13 +444,15 @@ export function getMessageArtifacts(* inspected so that videos can be rendered with a `<video>` element via the* custom img component.*/-export function resolveWorkspaceUrls(text: string): string {+export function resolveWorkspaceUrls(+ text: string,+ fileUrlBuilder: (fileId: string) => string = defaultWorkspaceFileUrl,+): string {// Handle image links: let resolved = text.replace(/!\[([^\]]*)\]\(workspace:\/\/([^)#\s]+)(?:#([^)#\s]*))?\)/g,(_match, alt: string, fileId: string, mimeHint?: string) => {- const apiPath = getGetWorkspaceDownloadFileByIdUrl(fileId);- const url = `/api/proxy${apiPath}`;+ const url = fileUrlBuilder(fileId);if (mimeHint?.startsWith("video/")) {return ``;}@@ -381,11 +469,11 @@ export function resolveWorkspaceUrls(text: string): string {resolved = resolved.replace(/(?<!!)\[([^\]]*)\]\(workspace:\/\/([^)#\s]+)(?:#[^)#\s]*)?\)/g,(_match, linkText: string, fileId: string) => {- const apiPath = getGetWorkspaceDownloadFileByIdUrl(fileId);+ const url = fileUrlBuilder(fileId);const origin =typeof window !== "undefined" ? window.location.origin : "";- const url = `${origin}/api/proxy${apiPath}`;- return `[${linkText || "Download file"}](${url})`;+ const absoluteUrl = url.startsWith("/") ? `${origin}${url}` : url;+ return `[${linkText || "Download file"}](${absoluteUrl})`;},);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsxindex c1a038d04c..f53bbe2327 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatSidebar/ChatSidebar.tsx@@ -31,8 +31,10 @@ import {PencilSimpleIcon,PlusCircleIcon,PlusIcon,+ ShareNetworkIcon,TrashIcon,} from "@phosphor-icons/react";+import { ShareChatDialog } from "../../sharing/ShareChatDialog";import { useQueryClient } from "@tanstack/react-query";import { AnimatePresence, motion } from "framer-motion";import { parseAsString, useQueryState } from "nuqs";@@ -84,8 +86,10 @@ export function ChatSidebar() {const [exportingSessionIds, setExportingSessionIds] = useState<Set<string>>(new Set(),);+ const [sharingSessionId, setSharingSessionId] = useState<string | null>(null);const renameInputRef = useRef<HTMLInputElement>(null);const renameCancelledRef = useRef(false);+ const chatSharingEnabled = useGetFlag(Flag.CHAT_SHARING);const { mutate: renameSession } = usePatchV2UpdateSessionTitle({mutation: {@@ -464,6 +468,17 @@ export function ChatSidebar() {? "Exporting…": "Export chat"}</DropdownMenuItem>+ {chatSharingEnabled && (+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ setSharingSessionId(session.id);+ }}+ >+ <ShareNetworkIcon className="mr-2 h-4 w-4" />+ Share chat+ </DropdownMenuItem>+ )}<DropdownMenuItemonClick={(e) =>handleDeleteClick(e, session.id, session.title)@@ -503,6 +518,17 @@ export function ChatSidebar() {onConfirm={confirmDelete}onCancel={cancelDelete}/>++ {sharingSessionId && (+ <ShareChatDialog+ sessionId={sharingSessionId}+ open={true}+ onOpenChange={(next) => {+ if (!next) setSharingSessionId(null);+ }}+ />+ )}+{isChatSearchEnabled ? (<ChatSearchModalsessions={sessions}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsxindex abecdf6e9a..e84b795730 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/CopilotChatActionsProvider.tsx@@ -9,16 +9,20 @@ interface Props {onSend: (message: string) => void | Promise<void>;/** Defaults to "copilot" — the standalone page. */chatSurface?: CopilotChatSurface;+ getExecutionShareToken?: (executionId: string) => string | null | undefined;children: React.ReactNode;}export function CopilotChatActionsProvider({onSend,chatSurface = "copilot",+ getExecutionShareToken,children,}: Props) {return (- <CopilotChatActionsContext.Provider value={{ onSend, chatSurface }}>+ <CopilotChatActionsContext.Provider+ value={{ onSend, chatSurface, getExecutionShareToken }}+ >{children}</CopilotChatActionsContext.Provider>);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/useCopilotChatActions.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/useCopilotChatActions.tsindex b417f28bcd..e36a47d5c2 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/useCopilotChatActions.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotChatActionsProvider/useCopilotChatActions.ts@@ -12,12 +12,23 @@ import { createContext, useContext } from "react";* is already looking at the builder and the panel auto-switches URL on* edit_agent / run_agent completion, so the navigation CTAs are* redundant and open duplicate tabs.+ * `"share"` — the public ``/share/chat/[token]`` viewer; navigation CTAs+ * point at auth-gated /library /build routes that anonymous viewers+ * can't reach, so hide them.*/-export type CopilotChatSurface = "copilot" | "builder";+export type CopilotChatSurface = "copilot" | "builder" | "share";interface CopilotChatActions {onSend: (message: string) => void | Promise<void>;chatSurface: CopilotChatSurface;+ /**+ * Optional: maps execution_id → public share_token for the executions+ * linked to the current chat. Only populated on the ``"share"``+ * surface, where ``ExecutionStartedCard`` uses it to rewrite the+ * "View Execution" CTA to ``/share/{token}`` instead of the+ * auth-gated ``/library/agents/...`` link.+ */+ getExecutionShareToken?: (executionId: string) => string | null | undefined;}const CopilotChatActionsContext = createContext<CopilotChatActions | null>(diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.tsindex e29c27c8bd..dc7031afe5 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts@@ -83,7 +83,17 @@ const ATTACHED_FILES_RE =/\n?\n?\[Attached files\]\n([\s\S]*?)Use read_workspace_file with the file_id to access file contents\./;const FILE_LINE_RE = /^- (.+) \(([^,]+),\s*[\d.]+ KB\), file_id=([0-9a-f-]+)$/;-function extractFileParts(content: string): {+/** Default file URL builder — routes through the authed workspace+ * download endpoint. Public viewers override this via the+ * ``fileUrlBuilder`` option on the conversion helper. */+function defaultWorkspaceFileUrl(fileId: string): string {+ return `/api/proxy${getGetWorkspaceDownloadFileByIdUrl(fileId)}`;+}++function extractFileParts(+ content: string,+ fileUrlBuilder: (fileId: string) => string,+): {cleanText: string;fileParts: FileUIPart[];} {@@ -98,12 +108,11 @@ function extractFileParts(content: string): {const m = line.trim().match(FILE_LINE_RE);if (!m) continue;const [, filename, mimeType, fileId] = m;- const apiPath = getGetWorkspaceDownloadFileByIdUrl(fileId);fileParts.push({type: "file",filename,mediaType: mimeType,- url: `/api/proxy${apiPath}`,+ url: fileUrlBuilder(fileId),});}@@ -217,11 +226,18 @@ export function convertChatSessionMessagesToUiMessages(isComplete?: boolean;/** Tool outputs from adjacent pages, for cross-page tool_call matching. */extraToolOutputs?: Map<string, unknown>;+ /** Override the URL emitted for attached-file ``FileUIPart``s.+ * The default routes through the authed workspace download+ * endpoint; public-share viewers pass a token-aware builder that+ * hits ``/api/public/shared/chats/<token>/files/<id>/download``+ * so anonymous readers can render attachments. */+ fileUrlBuilder?: (fileId: string) => string;},): {messages: UIMessage<unknown, UIDataTypes, UITools>[];stats: TurnStatsMap;} {+ const fileUrlBuilder = options?.fileUrlBuilder ?? defaultWorkspaceFileUrl;const messages = coerceSessionChatMessages(rawMessages);// Find the most-recent user message — when the session is queued, this// is the message that's waiting and renders the "Queued" badge.@@ -284,7 +300,10 @@ export function convertChatSessionMessagesToUiMessages(state: "done",} as UIMessage<unknown, UIDataTypes, UITools>["parts"][number]);} else if (msg.role === "user") {- const { cleanText, fileParts } = extractFileParts(msg.content);+ const { cleanText, fileParts } = extractFileParts(+ msg.content,+ fileUrlBuilder,+ );if (cleanText) {parts.push({ type: "text", text: cleanText, state: "done" });}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/sharing/ShareChatDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/sharing/ShareChatDialog.tsxnew file mode 100644index 0000000000..ce12bc9843--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/sharing/ShareChatDialog.tsx@@ -0,0 +1,154 @@+"use client";++import { CheckIcon, CopyIcon, ShareNetworkIcon } from "@phosphor-icons/react";+import { Button } from "@/components/atoms/Button/Button";+import { Switch } from "@/components/atoms/Switch/Switch";+import { Text } from "@/components/atoms/Text/Text";+import { Dialog } from "@/components/molecules/Dialog/Dialog";+import { useShareChatDialog } from "./useShareChatDialog";++type Props = {+ sessionId: string;+ open: boolean;+ onOpenChange: (open: boolean) => void;+};++export function ShareChatDialog({ sessionId, open, onOpenChange }: Props) {+ const state = useShareChatDialog({ sessionId, open });++ return (+ <Dialog+ title="Share this chat"+ controlled={{ isOpen: open, set: onOpenChange }}+ >+ <Dialog.Content>+ <div className="space-y-4">+ <div className="space-y-2 rounded-md border border-amber-200 bg-amber-50 p-3">+ <Text variant="small" className="text-amber-900">+ Anyone with the link will see this conversation. Don't share+ if it contains secrets you pasted, personal details, or+ credentials you wouldn't want public.+ </Text>+ <Text variant="small" className="text-amber-900">+ Sharing is <strong>live</strong>: new messages, agent runs, and+ files added after you enable sharing become visible too. Stop+ sharing to revoke access.+ </Text>+ </div>++ {!state.isLoadingState && (+ // Consent disclosure — exact numbers from the server's+ // share-state snapshot. Shown both before enable (so the+ // owner knows what they're about to expose) and after+ // enable (so they can audit what the public viewer sees+ // right now).+ <div className="rounded-md border border-zinc-200 bg-zinc-50 p-3">+ <Text variant="small" className="font-medium text-zinc-900">+ {state.isShared ? "Currently sharing" : "About to share"}+ </Text>+ <ul className="mt-1 list-disc pl-5 text-xs text-zinc-700">+ <li>+ {state.messageCount}{" "}+ {state.messageCount === 1 ? "message" : "messages"}+ </li>+ {state.autoShareExecutions && (+ <li>+ {state.linkedRunCount} agent{" "}+ {state.linkedRunCount === 1 ? "run" : "runs"}+ </li>+ )}+ <li>+ {state.fileCount} workspace{" "}+ {state.fileCount === 1 ? "file" : "files"}+ </li>+ </ul>+ </div>+ )}++ {/* Global execution-sharing toggle. When ON, every agent+ run in this chat — past and future — is included in the+ share automatically. Locked while shared so the toggle+ state always matches what the viewer sees. */}+ <div className="flex items-center justify-between gap-3 rounded border border-zinc-200 px-3 py-2.5">+ <div className="min-w-0">+ <Text variant="body" className="font-medium">+ Share agent runs in this chat+ </Text>+ <Text variant="small" className="text-zinc-500">+ Includes every run from this conversation, including ones that+ happen after you share.+ </Text>+ </div>+ <Switch+ checked={state.autoShareExecutions}+ onCheckedChange={state.setAutoShareExecutions}+ disabled={state.isShared || state.isLoadingState}+ aria-label="Share agent runs from this chat"+ />+ </div>++ {state.isShared && state.shareUrl && (+ <div className="space-y-2">+ <Text variant="small" className="font-medium">+ Share link+ </Text>+ <div className="flex items-center gap-2">+ <input+ readOnly+ value={state.shareUrl}+ className="flex-1 rounded border border-zinc-200 bg-zinc-50 px-2 py-1.5 font-mono text-xs"+ />+ <Button+ size="small"+ variant="secondary"+ onClick={state.copyShareUrl}+ leftIcon={+ state.copied ? (+ <CheckIcon size={14} weight="bold" />+ ) : (+ <CopyIcon size={14} />+ )+ }+ >+ {state.copied ? "Copied" : "Copy"}+ </Button>+ </div>+ </div>+ )}+ </div>+ <Dialog.Footer>+ {state.isShared ? (+ // Two-step destructive confirmation. First click flips+ // confirmingStop so the button copy reads "Confirm stop";+ // second click fires the DELETE. A "Cancel" affordance+ // appears alongside the confirm so a misclick is recoverable.+ <>+ {state.confirmingStop && (+ <Button variant="secondary" onClick={state.cancelStop}>+ Cancel+ </Button>+ )}+ <Button+ variant="destructive"+ onClick={state.requestStop}+ loading={state.isDisabling}+ >+ {state.confirmingStop ? "Confirm stop sharing" : "Stop sharing"}+ </Button>+ </>+ ) : (+ <Button+ variant="primary"+ onClick={state.enable}+ loading={state.isEnabling}+ disabled={state.isLoadingState}+ leftIcon={<ShareNetworkIcon size={14} />}+ >+ Enable sharing+ </Button>+ )}+ </Dialog.Footer>+ </Dialog.Content>+ </Dialog>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/sharing/__tests__/ShareChatDialog.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/sharing/__tests__/ShareChatDialog.test.tsxnew file mode 100644index 0000000000..7d3c13ffc3--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/sharing/__tests__/ShareChatDialog.test.tsx@@ -0,0 +1,281 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++import {+ getDeleteV2DisableChatSharingMockHandler204,+ getGetV2GetChatShareStateMockHandler200,+} from "@/app/api/__generated__/endpoints/chat/chat.msw";+import type { ChatShareStateResponse } from "@/app/api/__generated__/models/chatShareStateResponse";+import { server } from "@/mocks/mock-server";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import { ShareChatDialog } from "../ShareChatDialog";++const SESSION_ID = "550e8400-e29b-41d4-a716-446655440000";++vi.mock("next/navigation", () => ({+ usePathname: () => "/copilot",+ useRouter: () => ({+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+ push: vi.fn(),+ refresh: vi.fn(),+ replace: vi.fn(),+ }),+ useSearchParams: () => new URLSearchParams(),+}));++// Clipboard isn't available in jsdom by default; defineProperty so+// the copyShareUrl plumbing can be exercised without crashing. The+// explicit (text: string) typing keeps mock.calls[0][0] usable in+// assertions without TS complaining about tuple length.+const clipboardWrite = vi.fn(async (_text: string) => {});+beforeEach(() => {+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: { writeText: clipboardWrite },+ });+ clipboardWrite.mockClear();+});++afterEach(() => {+ cleanup();+});++function mockShareState(state: Partial<ChatShareStateResponse>) {+ server.use(+ getGetV2GetChatShareStateMockHandler200(+ (): ChatShareStateResponse => ({+ is_shared: false,+ share_token: null,+ auto_share_executions: false,+ ...state,+ }),+ ),+ );+}++describe("ShareChatDialog", () => {+ test("opens in 'Enable sharing' mode for an unshared chat", async () => {+ mockShareState({ is_shared: false });+ render(+ <ShareChatDialog sessionId={SESSION_ID} open onOpenChange={vi.fn()} />,+ );++ expect(+ await screen.findByRole("button", { name: /enable sharing/i }),+ ).toBeDefined();+ // Read-only warning always visible.+ expect(+ screen.getByText(/anyone with the link will see this conversation/i),+ ).toBeDefined();+ // The auto-share toggle is present and labelled — the always-show+ // box the user asked for, regardless of run count.+ expect(+ screen.getByLabelText(/share agent runs from this chat/i),+ ).toBeDefined();+ });++ test("opens in 'Stop sharing' mode and shows the share URL for an already-shared chat", async () => {+ const TOKEN = "11111111-2222-3333-4444-555555555555";+ mockShareState({+ is_shared: true,+ share_token: TOKEN,+ auto_share_executions: true,+ });+ render(+ <ShareChatDialog sessionId={SESSION_ID} open onOpenChange={vi.fn()} />,+ );++ expect(+ await screen.findByRole("button", { name: /stop sharing/i }),+ ).toBeDefined();+ // Share URL surfaces inside the dialog so the owner can copy it.+ const urlInput = await screen.findByDisplayValue(+ new RegExp(`/share/chat/${TOKEN}$`),+ );+ expect(urlInput).toBeDefined();+ expect(screen.getByRole("button", { name: /copy/i })).toBeDefined();+ });++ test("renders the auto-share toggle when chat is already shared", async () => {+ mockShareState({+ is_shared: true,+ share_token: "11111111-2222-3333-4444-555555555555",+ auto_share_executions: true,+ });+ render(+ <ShareChatDialog sessionId={SESSION_ID} open onOpenChange={vi.fn()} />,+ );++ // Wait for the share-state query to resolve and hydrate the dialog.+ await screen.findByRole("button", { name: /stop sharing/i });++ // The toggle is still rendered (always-visible by design) and+ // labelled — its visual checked-state is owned by the Switch+ // component implementation; we just pin that it exists and is+ // reachable via its accessible label.+ expect(+ screen.getByLabelText(/share agent runs from this chat/i),+ ).toBeDefined();+ });++ test("does not render dialog content when open=false", () => {+ mockShareState({ is_shared: false });+ render(+ <ShareChatDialog+ sessionId={SESSION_ID}+ open={false}+ onOpenChange={vi.fn()}+ />,+ );+ expect(+ screen.queryByRole("button", { name: /enable sharing/i }),+ ).toBeNull();+ expect(screen.queryByRole("button", { name: /stop sharing/i })).toBeNull();+ });++ test("Stop sharing requires a confirmation step before firing the DELETE", async () => {+ const TOKEN = "33333333-dddd-eeee-ffff-444444444444";+ mockShareState({+ is_shared: true,+ share_token: TOKEN,+ auto_share_executions: true,+ });+ server.use(getDeleteV2DisableChatSharingMockHandler204());++ render(+ <ShareChatDialog sessionId={SESSION_ID} open onOpenChange={vi.fn()} />,+ );++ const stopButton = await screen.findByRole("button", {+ name: /^stop sharing$/i,+ });+ fireEvent.click(stopButton);++ // After the first click the button copy switches to "Confirm+ // stop sharing" and a Cancel button appears. The DELETE has NOT+ // fired yet — accidental click is recoverable.+ const confirmButton = await screen.findByRole("button", {+ name: /confirm stop sharing/i,+ });+ expect(screen.getByRole("button", { name: /^cancel$/i })).toBeDefined();+ // Still in shared state — Enable hasn't appeared.+ expect(+ screen.queryByRole("button", { name: /enable sharing/i }),+ ).toBeNull();++ fireEvent.click(confirmButton);++ // Second click is the authoritative DELETE; share-state flips+ // and Enable comes back.+ await screen.findByRole("button", { name: /enable sharing/i });+ });++ test("clicking Cancel during stop-confirmation returns to the share view", async () => {+ const TOKEN = "44444444-eeee-ffff-aaaa-555555555555";+ mockShareState({+ is_shared: true,+ share_token: TOKEN,+ auto_share_executions: true,+ });++ render(+ <ShareChatDialog sessionId={SESSION_ID} open onOpenChange={vi.fn()} />,+ );++ const stopButton = await screen.findByRole("button", {+ name: /^stop sharing$/i,+ });+ fireEvent.click(stopButton);+ fireEvent.click(await screen.findByRole("button", { name: /^cancel$/i }));++ // The confirm-stop UI collapses back to the primary "Stop+ // sharing" button — the share is still active.+ await screen.findByRole("button", { name: /^stop sharing$/i });+ expect(+ screen.queryByRole("button", { name: /confirm stop sharing/i }),+ ).toBeNull();+ });++ test("clicking Copy writes the share URL to the clipboard", async () => {+ const TOKEN = "55555555-aaaa-bbbb-cccc-666666666666";+ mockShareState({+ is_shared: true,+ share_token: TOKEN,+ auto_share_executions: true,+ });++ render(+ <ShareChatDialog sessionId={SESSION_ID} open onOpenChange={vi.fn()} />,+ );++ const copyButton = await screen.findByRole("button", { name: /copy/i });+ fireEvent.click(copyButton);++ await waitFor(() => {+ expect(clipboardWrite).toHaveBeenCalledTimes(1);+ });+ expect(clipboardWrite.mock.calls[0][0]).toMatch(+ new RegExp(`/share/chat/${TOKEN}$`),+ );+ // Button briefly flips to the "Copied" affordance — pinning the+ // setCopied / setTimeout(2000) loop in useShareChatDialog.+ await screen.findByRole("button", { name: /copied/i });+ });++ test("clipboard failure surfaces a destructive toast and skips the copied flash", async () => {+ // navigator.clipboard.writeText can reject when the browser refuses+ // (insecure context, missing permission). Production must surface a+ // toast and NOT flip the button to "Copied".+ const TOKEN = "99999999-aaaa-bbbb-cccc-aaaaaaaaaaaa";+ mockShareState({+ is_shared: true,+ share_token: TOKEN,+ auto_share_executions: true,+ });+ clipboardWrite.mockRejectedValueOnce(new Error("nope"));++ render(+ <ShareChatDialog sessionId={SESSION_ID} open onOpenChange={vi.fn()} />,+ );++ const copyButton = await screen.findByRole("button", { name: /copy/i });+ fireEvent.click(copyButton);++ await waitFor(() => {+ expect(clipboardWrite).toHaveBeenCalled();+ });+ // After the rejection settles, the button must stay on "Copy" and+ // never flip to "Copied" (the setCopied(true) branch is skipped+ // inside the catch).+ expect(screen.queryByRole("button", { name: /copied/i })).toBeNull();+ expect(screen.getByRole("button", { name: /copy/i })).toBeDefined();+ });++ test("auto-share toggle is locked once the chat is shared", async () => {+ // The share-state drives what viewers see, so flipping the toggle+ // mid-share would lie. Production guards this with+ // ``disabled={state.isShared || state.isLoadingState}``.+ mockShareState({+ is_shared: true,+ share_token: "77777777-aaaa-bbbb-cccc-888888888888",+ auto_share_executions: true,+ });+ render(+ <ShareChatDialog sessionId={SESSION_ID} open onOpenChange={vi.fn()} />,+ );++ // Wait for the share-state query to hydrate (the Stop sharing button+ // only appears once isLoadingState flips false), then assert the+ // toggle is in Radix's data-disabled state.+ await screen.findByRole("button", { name: /stop sharing/i });+ const toggle = screen.getByLabelText(/share agent runs from this chat/i);+ expect(toggle.getAttribute("data-disabled")).not.toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/sharing/useShareChatDialog.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/sharing/useShareChatDialog.tsnew file mode 100644index 0000000000..92c665b322--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/sharing/useShareChatDialog.ts@@ -0,0 +1,173 @@+import { useEffect, useState } from "react";+import { useQueryClient } from "@tanstack/react-query";+import {+ getGetV2GetChatShareStateQueryKey,+ useDeleteV2DisableChatSharing,+ useGetV2GetChatShareState,+ usePostV2EnableChatSharing,+} from "@/app/api/__generated__/endpoints/chat/chat";+import { useToast } from "@/components/molecules/Toast/use-toast";+import { chatShareUrl } from "@/lib/share/routes";++type Props = {+ sessionId: string;+ open: boolean;+};++export function useShareChatDialog({ sessionId, open }: Props) {+ const { toast } = useToast();+ const queryClient = useQueryClient();++ const [isShared, setIsShared] = useState(false);+ const [shareToken, setShareToken] = useState<string | null>(null);+ // Default ON so the common case ("share this chat and the runs it+ // produced") works without the owner having to think about it.+ // Server state overrides this once the share-state query resolves.+ const [autoShareExecutions, setAutoShareExecutions] = useState(true);+ const [copied, setCopied] = useState(false);+ // Two-step confirmation for "Stop sharing". A share may have been+ // posted to social / email / Slack — an accidental click would dead-+ // letter every external reference with no undo (the next re-enable+ // mints a new token). Flipped on first click; second click is the+ // authoritative DELETE.+ const [confirmingStop, setConfirmingStop] = useState(false);++ const { data: stateResponse, isLoading: isLoadingState } =+ useGetV2GetChatShareState(sessionId, {+ query: {+ enabled: open,+ select: (res) => (res.status === 200 ? res.data : undefined),+ },+ });++ // Hydrate local state from the backend payload so the modal opens+ // in the right mode after a reload.+ useEffect(() => {+ if (stateResponse) {+ setIsShared(stateResponse.is_shared ?? false);+ setShareToken(stateResponse.share_token ?? null);+ if (stateResponse.is_shared) {+ setAutoShareExecutions(stateResponse.auto_share_executions ?? false);+ }+ }+ }, [stateResponse]);++ const invalidateState = () =>+ queryClient.invalidateQueries({+ queryKey: getGetV2GetChatShareStateQueryKey(sessionId),+ });++ const { mutate: enable, isPending: isEnabling } = usePostV2EnableChatSharing({+ mutation: {+ onSuccess: (res) => {+ if (res.status !== 200) {+ toast({+ title: "Failed to enable sharing",+ description: "Please try again.",+ variant: "destructive",+ });+ return;+ }+ setIsShared(true);+ setShareToken(res.data.share_token);+ invalidateState();+ toast({+ title: "Chat sharing enabled",+ description:+ "Anyone with the link can now view this conversation. Revoke any time.",+ });+ },+ onError: () => {+ toast({+ title: "Failed to enable sharing",+ description: "Please try again.",+ variant: "destructive",+ });+ },+ },+ });++ const { mutate: disable, isPending: isDisabling } =+ useDeleteV2DisableChatSharing({+ mutation: {+ onSuccess: () => {+ setIsShared(false);+ setShareToken(null);+ setConfirmingStop(false);+ invalidateState();+ toast({+ title: "Chat sharing disabled",+ description: "The share link is no longer accessible.",+ });+ },+ onError: () => {+ toast({+ title: "Failed to disable sharing",+ description: "Please try again.",+ variant: "destructive",+ });+ },+ },+ });++ const shareUrl = shareToken ? chatShareUrl(shareToken) : "";++ async function copyShareUrl() {+ if (!shareUrl) return;+ try {+ await navigator.clipboard.writeText(shareUrl);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ } catch {+ toast({+ title: "Failed to copy link",+ variant: "destructive",+ });+ }+ }++ // Disclosure counts surfaced to the modal so the owner sees what+ // they're about to expose. Defaults to 0 while the share-state+ // query is loading. Values from the latest server snapshot.+ const messageCount = stateResponse?.message_count ?? 0;+ const linkedRunCount = stateResponse?.linked_run_count ?? 0;+ const fileCount = stateResponse?.file_count ?? 0;++ function requestStop() {+ if (!confirmingStop) {+ setConfirmingStop(true);+ return;+ }+ disable({ sessionId });+ }++ function cancelStop() {+ setConfirmingStop(false);+ }++ return {+ isShared,+ shareToken,+ shareUrl,+ copied,+ autoShareExecutions,+ setAutoShareExecutions,+ isLoadingState,+ enable: () =>+ enable({+ sessionId,+ data: { auto_share_executions: autoShareExecutions },+ }),+ isEnabling,+ requestStop,+ cancelStop,+ confirmingStop,+ isDisabling,+ copyShareUrl,+ messageCount,+ linkedRunCount,+ fileCount,+ };+}++export type ShareChatDialogState = ReturnType<typeof useShareChatDialog>;diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/ExecutionStartedCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/ExecutionStartedCard.tsxindex c0283380b1..201d4f2c9f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/ExecutionStartedCard.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/ExecutionStartedCard.tsx@@ -2,6 +2,7 @@import type { ExecutionStartedResponse } from "@/app/api/__generated__/models/executionStartedResponse";import { Button } from "@/components/atoms/Button/Button";+import { executionSharePath } from "@/lib/share/routes";import { useRouter } from "next/navigation";import {ContentCard,@@ -29,6 +30,7 @@ export function titleForStatus(status: string | undefined): string {return "Execution stopped";if (s === "TIMED_OUT" || s === "INCOMPLETE") return "Execution incomplete";if (s === "RUNNING") return "Execution running";+ if (s === "SCHEDULED") return "Execution scheduled";return "Execution started";}@@ -38,8 +40,20 @@ export function ExecutionStartedCard({ output }: Props) {// onto the URL so the builder's in-place execution UI opens — the// "View Execution" button here would navigate the user away from the// page they're editing, so hide it.- const { chatSurface } = useCopilotChatActions();- const hideViewExecution = chatSurface === "builder";+ //+ // On the public share viewer, route the CTA to the linked execution's+ // own share page (``/share/{token}``) when a linked share exists.+ // If it doesn't (chat shared without opting in to share this run),+ // hide the button — the auth-gated /library URL is unreachable.+ const { chatSurface, getExecutionShareToken } = useCopilotChatActions();+ const linkedShareToken = getExecutionShareToken?.(output.execution_id);+ const hideViewExecution =+ chatSurface === "builder" || (chatSurface === "share" && !linkedShareToken);++ const href = linkedShareToken+ ? executionSharePath(linkedShareToken)+ : (output.library_agent_link ??+ `/library/agents/${output.graph_id}?activeTab=runs&activeItem=${output.execution_id}`);return (<ContentGrid>@@ -51,12 +65,7 @@ export function ExecutionStartedCard({ output }: Props) {<Buttonsize="small"className="mt-3"- onClick={() =>- router.push(- output.library_agent_link ??- `/library/agents/${output.graph_id}?activeTab=runs&activeItem=${output.execution_id}`,- )- }+ onClick={() => router.push(href)}>View Execution</Button>diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/__tests__/titleForStatus.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/__tests__/titleForStatus.test.tsindex daaa21c1ed..4f47dcf7bc 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/__tests__/titleForStatus.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/tools/RunAgent/components/ExecutionStartedCard/__tests__/titleForStatus.test.ts@@ -11,6 +11,7 @@ describe("titleForStatus", () => {["TIMED_OUT", "Execution incomplete"],["INCOMPLETE", "Execution incomplete"],["RUNNING", "Execution running"],+ ["SCHEDULED", "Execution scheduled"],["QUEUED", "Execution started"],["", "Execution started"],])("maps %s -> %s", (input, expected) => {diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/ShareRunButton/useShareRunButton.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/ShareRunButton/useShareRunButton.tsindex 2a07f9bee6..f39dd56b26 100644--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/ShareRunButton/useShareRunButton.ts+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/selected-views/ShareRunButton/useShareRunButton.ts@@ -4,6 +4,7 @@ import {useDeleteV1DisableExecutionSharing,} from "@/app/api/__generated__/endpoints/default/default";import { useToast } from "@/components/molecules/Toast/use-toast";+import { executionShareUrl } from "@/lib/share/routes";interface UseShareRunButtonProps {graphId: string;@@ -29,11 +30,7 @@ export function useShareRunButton({setShareToken(initialShareToken || null);}, [initialIsShared, initialShareToken]);- // Generate the share URL from the token- const baseUrl =- process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || window.location.origin;-- const shareUrl = shareToken ? `${baseUrl}/share/${shareToken}` : "";+ const shareUrl = shareToken ? executionShareUrl(shareToken) : "";const { mutateAsync: enableSharing, isPending: isEnabling } =usePostV1EnableExecutionSharing();diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 12f44a55ff..bba37fb9cd 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -2580,6 +2580,124 @@}}},+ "/api/chat/sessions/{session_id}/share": {+ "delete": {+ "tags": ["v2", "chat", "share", "chat", "share"],+ "summary": "Disable Chat Sharing",+ "description": "Revoke sharing for a chat session.\n\nCascade-revokes linked executions whose share originated here\n(``sharedVia == CHAT_LINK``). User-initiated execution shares\nsurvive — see :func:`backend.copilot.sharing.db.disable_chat_session_share`.",+ "operationId": "deleteV2DisableChatSharing",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Session Id" }+ }+ ],+ "responses": {+ "204": { "description": "Successful Response" },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ },+ "post": {+ "tags": ["v2", "chat", "share", "chat", "share"],+ "summary": "Enable Chat Sharing",+ "description": "Enable sharing for a chat session.\n\nFlag-gated: refuses with 403 when ``chat-sharing`` is off so a stale\nfrontend cannot enable shares post-rollback.",+ "operationId": "postV2EnableChatSharing",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Session Id" }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/EnableShareRequest" }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/backend__api__features__chat__share__ShareResponse"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "403": { "description": "Chat sharing is not enabled for this user" },+ "404": { "description": "Chat session not found for user" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },+ "/api/chat/sessions/{session_id}/share/state": {+ "get": {+ "tags": ["v2", "chat", "share", "chat", "share"],+ "summary": "Get Chat Share State",+ "description": "Return the chat's current share state.\n\nThe share modal calls this on open so it can render in the right\nmode (share-vs-revoke) and pre-select the auto-share toggle.",+ "operationId": "getV2GetChatShareState",+ "security": [{ "HTTPBearerJWT": [] }],+ "parameters": [+ {+ "name": "session_id",+ "in": "path",+ "required": true,+ "schema": { "type": "string", "title": "Session Id" }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChatShareStateResponse"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },"/api/chat/sessions/{session_id}/stream": {"delete": {"tags": ["v2", "chat", "chat"],@@ -4592,7 +4710,9 @@"description": "Successful Response","content": {"application/json": {- "schema": { "$ref": "#/components/schemas/ShareResponse" }+ "schema": {+ "$ref": "#/components/schemas/backend__api__features__v1__ShareResponse"+ }}}},@@ -7731,6 +7851,147 @@}}},+ "/api/public/shared/chats/{share_token}": {+ "get": {+ "tags": ["v2", "chat", "share", "public", "chat", "share", "public"],+ "summary": "Get Shared Chat",+ "operationId": "getV2GetSharedChat",+ "parameters": [+ {+ "name": "share_token",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",+ "title": "Share Token"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/SharedChatSession" }+ }+ }+ },+ "404": { "description": "Shared chat not found" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },+ "/api/public/shared/chats/{share_token}/files/{file_id}/download": {+ "get": {+ "tags": ["v2", "chat", "share", "public", "chat", "share", "public"],+ "summary": "Download a file from a shared chat",+ "description": "Download a workspace file allowlisted by a shared chat (no auth).\n\nReturns uniform 404 for every failure mode to prevent enumeration —\nindistinguishable from \"unknown token\" or \"wrong file id\".",+ "operationId": "download_shared_chat_file",+ "parameters": [+ {+ "name": "share_token",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",+ "title": "Share Token"+ }+ },+ {+ "name": "file_id",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",+ "title": "File Id"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": { "application/json": { "schema": {} } }+ },+ "404": {+ "description": "Uniform 404 for every failure mode (unknown token, wrong file id, file no longer present) — prevents enumeration."+ },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },+ "/api/public/shared/chats/{share_token}/messages": {+ "get": {+ "tags": ["v2", "chat", "share", "public", "chat", "share", "public"],+ "summary": "Get Shared Chat Messages",+ "operationId": "getV2GetSharedChatMessages",+ "parameters": [+ {+ "name": "share_token",+ "in": "path",+ "required": true,+ "schema": {+ "type": "string",+ "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",+ "title": "Share Token"+ }+ },+ {+ "name": "limit",+ "in": "query",+ "required": false,+ "schema": { "type": "integer", "default": 50, "title": "Limit" }+ },+ {+ "name": "before_sequence",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [{ "type": "integer" }, { "type": "null" }],+ "title": "Before Sequence"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SharedChatMessagesPage"+ }+ }+ }+ },+ "400": { "description": "Invalid limit (must be 1..200)" },+ "404": { "description": "Shared chat not found" },+ "422": {+ "description": "Validation Error",+ "content": {+ "application/json": {+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }+ }+ }+ }+ }+ }+ },"/api/public/shared/{share_token}": {"get": {"tags": ["v1"],@@ -11113,6 +11374,42 @@"title": "ChatSessionMetadata","description": "Typed metadata stored in the ``metadata`` JSON column of ChatSession.\n\nAdd new session-level flags here instead of adding DB columns —\nno migration required for new fields as long as a default is provided."},+ "ChatShareStateResponse": {+ "properties": {+ "is_shared": {+ "type": "boolean",+ "title": "Is Shared",+ "default": false+ },+ "share_token": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Share Token"+ },+ "auto_share_executions": {+ "type": "boolean",+ "title": "Auto Share Executions",+ "default": false+ },+ "message_count": {+ "type": "integer",+ "title": "Message Count",+ "default": 0+ },+ "linked_run_count": {+ "type": "integer",+ "title": "Linked Run Count",+ "default": 0+ },+ "file_count": {+ "type": "integer",+ "title": "File Count",+ "default": 0+ }+ },+ "type": "object",+ "title": "ChatShareStateResponse",+ "description": "Surfaces the chat's current share state so the modal can open\nin the right mode (share-vs-revoke) without an extra round-trip.\n\nThe three counts power the consent-disclosure block above the\ntoggle so the owner sees exactly what they're about to expose.\nThey reflect live state — sharing is live (not snapshot-at-enable),\nso these numbers are also a lower bound for what subsequent\nviewers will see if more messages / runs / files land before\nrevocation."+ },"ClarificationNeededResponse": {"properties": {"type": {@@ -11881,6 +12178,18 @@"required": ["url", "relevance_score"],"title": "Document"},+ "EnableShareRequest": {+ "properties": {+ "auto_share_executions": {+ "type": "boolean",+ "title": "Auto Share Executions",+ "default": false+ }+ },+ "type": "object",+ "title": "EnableShareRequest",+ "description": "Whether to auto-link every ``run_agent`` execution in this chat.\n\nWhen true, the backend creates ``ChatLinkedShare`` rows for every\nexisting agent run AND auto-links any new runs that land while the\nshare is active. When false, only the chat messages are shared\n(cards in the viewer render in their \"execution not shared\" state)."+ },"ErrorResponse": {"properties": {"type": {@@ -11892,6 +12201,10 @@"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Session Id"},+ "execution_id": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Execution Id"+ },"error": {"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Error"@@ -16457,15 +16770,140 @@"title": "ShareRequest","description": "Optional request body for share endpoint."},- "ShareResponse": {+ "SharedChatLinkedExecution": {"properties": {- "share_url": { "type": "string", "title": "Share Url" },- "share_token": { "type": "string", "title": "Share Token" }+ "execution_id": { "type": "string", "title": "Execution Id" },+ "graph_id": { "type": "string", "title": "Graph Id" },+ "graph_name": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Graph Name"+ },+ "share_token": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Share Token"+ }},"type": "object",- "required": ["share_url", "share_token"],- "title": "ShareResponse",- "description": "Response from share endpoints."+ "required": ["execution_id", "graph_id", "graph_name", "share_token"],+ "title": "SharedChatLinkedExecution",+ "description": "Drill-in pointer for an AgentGraphExecution shared alongside a chat."+ },+ "SharedChatMessage": {+ "properties": {+ "id": { "type": "string", "title": "Id" },+ "role": { "type": "string", "title": "Role" },+ "content": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Content"+ },+ "name": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Name"+ },+ "tool_call_id": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Tool Call Id"+ },+ "tool_calls": {+ "anyOf": [+ {+ "items": { "additionalProperties": true, "type": "object" },+ "type": "array"+ },+ { "type": "null" }+ ],+ "title": "Tool Calls"+ },+ "function_call": {+ "anyOf": [+ { "additionalProperties": true, "type": "object" },+ { "type": "null" }+ ],+ "title": "Function Call"+ },+ "sequence": { "type": "integer", "title": "Sequence" },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "title": "Created At"+ }+ },+ "type": "object",+ "required": [+ "id",+ "role",+ "content",+ "name",+ "tool_call_id",+ "tool_calls",+ "function_call",+ "sequence",+ "created_at"+ ],+ "title": "SharedChatMessage",+ "description": "Public-safe projection of a single chat message."+ },+ "SharedChatMessagesPage": {+ "properties": {+ "messages": {+ "items": { "$ref": "#/components/schemas/SharedChatMessage" },+ "type": "array",+ "title": "Messages"+ },+ "has_more": { "type": "boolean", "title": "Has More" },+ "oldest_sequence": {+ "anyOf": [{ "type": "integer" }, { "type": "null" }],+ "title": "Oldest Sequence"+ }+ },+ "type": "object",+ "required": ["messages", "has_more", "oldest_sequence"],+ "title": "SharedChatMessagesPage",+ "description": "Paginated message window for the public viewer."+ },+ "SharedChatSession": {+ "properties": {+ "id": { "type": "string", "title": "Id" },+ "title": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Title"+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "title": "Created At"+ },+ "updated_at": {+ "type": "string",+ "format": "date-time",+ "title": "Updated At"+ },+ "shared_at": {+ "anyOf": [+ { "type": "string", "format": "date-time" },+ { "type": "null" }+ ],+ "title": "Shared At"+ },+ "linked_executions": {+ "items": {+ "$ref": "#/components/schemas/SharedChatLinkedExecution"+ },+ "type": "array",+ "title": "Linked Executions"+ }+ },+ "type": "object",+ "required": [+ "id",+ "title",+ "created_at",+ "updated_at",+ "shared_at",+ "linked_executions"+ ],+ "title": "SharedChatSession",+ "description": "Public-safe projection of a chat session (header only)."},"SharedExecutionResponse": {"properties": {@@ -19653,6 +20091,25 @@],"title": "WorkspaceFileItem"},+ "backend__api__features__chat__share__ShareResponse": {+ "properties": {+ "share_url": { "type": "string", "title": "Share Url" },+ "share_token": { "type": "string", "title": "Share Token" }+ },+ "type": "object",+ "required": ["share_url", "share_token"],+ "title": "ShareResponse"+ },+ "backend__api__features__v1__ShareResponse": {+ "properties": {+ "share_url": { "type": "string", "title": "Share Url" },+ "share_token": { "type": "string", "title": "Share Token" }+ },+ "type": "object",+ "required": ["share_url", "share_token"],+ "title": "ShareResponse",+ "description": "Response from share endpoints."+ },"backend__api__features__workspace__routes__UploadFileResponse": {"properties": {"file_id": { "type": "string", "title": "File Id" },diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.helpers.test.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.helpers.test.tsindex 3590de8ca7..172efb4c86 100644--- a/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.helpers.test.ts+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/__tests__/route.helpers.test.ts@@ -78,6 +78,21 @@ describe("isWorkspaceDownloadRequest", () => {).toBe(true);});+ it("matches api/public/shared/chats/{uuid}/files/{uuid}/download pattern", () => {+ expect(+ isWorkspaceDownloadRequest([+ "api",+ "public",+ "shared",+ "chats",+ VALID_UUID,+ "files",+ VALID_UUID_2,+ "download",+ ]),+ ).toBe(true);+ });+it("rejects public shared paths not ending with download", () => {expect(isWorkspaceDownloadRequest([@@ -92,6 +107,21 @@ describe("isWorkspaceDownloadRequest", () => {).toBe(false);});+ it("rejects public shared chat paths not ending with download", () => {+ expect(+ isWorkspaceDownloadRequest([+ "api",+ "public",+ "shared",+ "chats",+ VALID_UUID,+ "files",+ VALID_UUID_2,+ "metadata",+ ]),+ ).toBe(false);+ });+it("rejects non-UUID file ID in workspace path", () => {expect(isWorkspaceDownloadRequest([@@ -132,6 +162,36 @@ describe("isWorkspaceDownloadRequest", () => {).toBe(false);});+ it("rejects non-UUID token in public shared chat path", () => {+ expect(+ isWorkspaceDownloadRequest([+ "api",+ "public",+ "shared",+ "chats",+ "not-a-uuid",+ "files",+ VALID_UUID,+ "download",+ ]),+ ).toBe(false);+ });++ it("rejects non-UUID file ID in public shared chat path", () => {+ expect(+ isWorkspaceDownloadRequest([+ "api",+ "public",+ "shared",+ "chats",+ VALID_UUID,+ "files",+ "not-a-uuid",+ "download",+ ]),+ ).toBe(false);+ });+it("accepts uppercase hex in UUIDs", () => {expect(isWorkspaceDownloadRequest([diff --git a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.ts b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.tsindex 3e258f5a57..8e46f12225 100644--- a/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.ts+++ b/autogpt_platform/frontend/src/app/api/proxy/[...path]/route.helpers.ts@@ -28,6 +28,21 @@ export function isWorkspaceDownloadRequest(path: string[]): boolean {return true;}+ // api/public/shared/chats/{token}/files/{id}/download+ if (+ path.length === 8 &&+ path[0] === "api" &&+ path[1] === "public" &&+ path[2] === "shared" &&+ path[3] === "chats" &&+ UUID_RE.test(path[4]) &&+ path[5] === "files" &&+ UUID_RE.test(path[6]) &&+ path[7] === "download"+ ) {+ return true;+ }+return false;}diff --git a/autogpt_platform/frontend/src/lib/share/__tests__/routes.test.ts b/autogpt_platform/frontend/src/lib/share/__tests__/routes.test.tsnew file mode 100644index 0000000000..f16095ef1f--- /dev/null+++ b/autogpt_platform/frontend/src/lib/share/__tests__/routes.test.ts@@ -0,0 +1,120 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++import {+ chatSharePath,+ chatShareUrl,+ executionSharePath,+ executionShareUrl,+ sharedChatFilePattern,+ sharedChatFileUrl,+} from "../routes";++describe("share viewer path builders", () => {+ test("chatSharePath returns the canonical viewer route", () => {+ expect(chatSharePath("abc-123")).toBe("/share/chat/abc-123");+ });++ test("executionSharePath returns the canonical viewer route", () => {+ expect(executionSharePath("abc-123")).toBe("/share/abc-123");+ });+});++describe("share viewer absolute URL builders", () => {+ const ORIGINAL_ENV = process.env.NEXT_PUBLIC_FRONTEND_BASE_URL;++ beforeEach(() => {+ delete process.env.NEXT_PUBLIC_FRONTEND_BASE_URL;+ });++ afterEach(() => {+ if (ORIGINAL_ENV === undefined) {+ delete process.env.NEXT_PUBLIC_FRONTEND_BASE_URL;+ } else {+ process.env.NEXT_PUBLIC_FRONTEND_BASE_URL = ORIGINAL_ENV;+ }+ vi.unstubAllGlobals();+ });++ test("chatShareUrl uses window.location.origin when env var is unset", () => {+ vi.stubGlobal("window", {+ location: { origin: "https://app.example.com" },+ });+ expect(chatShareUrl("abc-123")).toBe(+ "https://app.example.com/share/chat/abc-123",+ );+ });++ test("executionShareUrl uses NEXT_PUBLIC_FRONTEND_BASE_URL when set", () => {+ process.env.NEXT_PUBLIC_FRONTEND_BASE_URL = "https://shared.example.com";+ vi.stubGlobal("window", {+ location: { origin: "https://app.example.com" },+ });+ expect(executionShareUrl("abc-123")).toBe(+ "https://shared.example.com/share/abc-123",+ );+ });++ test("chatShareUrl prefers env var over window.location", () => {+ process.env.NEXT_PUBLIC_FRONTEND_BASE_URL = "https://shared.example.com";+ vi.stubGlobal("window", {+ location: { origin: "https://app.example.com" },+ });+ expect(chatShareUrl("abc-123")).toBe(+ "https://shared.example.com/share/chat/abc-123",+ );+ });+});++describe("sharedChatFileUrl", () => {+ test("returns the public allowlist-gated download path", () => {+ const url = sharedChatFileUrl(+ "550e8400-e29b-41d4-a716-446655440000",+ "6ba7b810-9dad-11d1-80b4-00c04fd430c8",+ );+ expect(url).toBe(+ "/api/proxy/api/public/shared/chats/550e8400-e29b-41d4-a716-446655440000/files/6ba7b810-9dad-11d1-80b4-00c04fd430c8/download",+ );+ });+});++describe("sharedChatFilePattern", () => {+ const SHARE_TOKEN = "550e8400-e29b-41d4-a716-446655440000";+ const FILE_ID = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";++ test("matches the URL built by sharedChatFileUrl for the same token", () => {+ const pattern = sharedChatFilePattern(SHARE_TOKEN);+ const url = sharedChatFileUrl(SHARE_TOKEN, FILE_ID);+ const match = url.match(pattern);+ expect(match?.[1]).toBe(FILE_ID);+ });++ test("rejects URLs built for a different token (no cross-share match)", () => {+ const pattern = sharedChatFilePattern(SHARE_TOKEN);+ const otherToken = "00000000-0000-0000-0000-000000000000";+ const url = sharedChatFileUrl(otherToken, FILE_ID);+ expect(url.match(pattern)).toBeNull();+ });++ test("rejects non-UUID file IDs", () => {+ const pattern = sharedChatFilePattern(SHARE_TOKEN);+ const badUrl = `/api/proxy/api/public/shared/chats/${SHARE_TOKEN}/files/not-a-uuid/download`;+ expect(badUrl.match(pattern)).toBeNull();+ });++ test("rejects workspace-file URLs (anchored on share prefix)", () => {+ const pattern = sharedChatFilePattern(SHARE_TOKEN);+ const workspaceUrl = `/api/proxy/api/workspace/files/${FILE_ID}/download`;+ expect(workspaceUrl.match(pattern)).toBeNull();+ });++ test("escapes regex metacharacters in token (defensive)", () => {+ // Tokens are UUIDs in production, but the helper must still be+ // safe against a caller passing a token with regex special chars.+ const pattern = sharedChatFilePattern("token.with*special?chars");+ const url = `/api/proxy/api/public/shared/chats/token.with*special?chars/files/${FILE_ID}/download`;+ expect(url.match(pattern)?.[1]).toBe(FILE_ID);+ // And a similar URL with different escaping is rejected.+ const evilUrl = `/api/proxy/api/public/shared/chats/tokenXwithYspecialZchars/files/${FILE_ID}/download`;+ expect(evilUrl.match(pattern)).toBeNull();+ });+});diff --git a/autogpt_platform/frontend/src/lib/share/routes.ts b/autogpt_platform/frontend/src/lib/share/routes.tsnew file mode 100644index 0000000000..b858d6bdd2--- /dev/null+++ b/autogpt_platform/frontend/src/lib/share/routes.ts@@ -0,0 +1,67 @@+// Single source of truth for every share-related path: the viewer+// route that ends up on a user's clipboard, and the API path the+// frontend hits when toggling shares. When the next shareable type+// joins the platform, add functions here and grep won't find anything+// else to touch.++function getBaseUrl(): string {+ // ``NEXT_PUBLIC_FRONTEND_BASE_URL`` lets the backend's share URL and+ // the frontend's share URL match in environments where Next.js is+ // proxied behind a different host than its window.location. Falls+ // back to the current origin in dev.+ if (typeof window === "undefined") {+ return process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || "";+ }+ return process.env.NEXT_PUBLIC_FRONTEND_BASE_URL || window.location.origin;+}++export function executionSharePath(token: string): string {+ return `/share/${token}`;+}++export function chatSharePath(token: string): string {+ return `/share/chat/${token}`;+}++export function executionShareUrl(token: string): string {+ return `${getBaseUrl()}${executionSharePath(token)}`;+}++export function chatShareUrl(token: string): string {+ return `${getBaseUrl()}${chatSharePath(token)}`;+}++// ---------- Per-share file download URL + matcher --------------------------+//+// The renderer extracts a file ID from a ``FileUIPart.url`` to decide+// whether to render an ArtifactCard. Keeping the URL builder and the+// matching regex in the same module guarantees they evolve together —+// if the public-share file route ever changes, both update here and+// nowhere else needs to be touched.++const FILE_UUID_GROUP =+ "([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})";++function escapeRegex(value: string): string {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++export function sharedChatFileUrl(shareToken: string, fileId: string): string {+ return `/api/proxy/api/public/shared/chats/${shareToken}/files/${fileId}/download`;+}++export function sharedChatFilePattern(shareToken: string): RegExp {+ // Anchor on the literal share-chat prefix for THIS token so only+ // URLs we constructed for this specific share match. Per-token+ // patterns prevent cross-share contamination when multiple viewers+ // are mounted side-by-side (storybook / tests).+ //+ // ``^`` and ``$`` enforce full-string match — without them the regex+ // could pull a file UUID out of a longer/malformed URL (e.g.+ // ``https://attacker.example/api/proxy/.../files/<id>/download?x=…``)+ // and surface it as an artifact for this share token even though we+ // never constructed that URL.+ return new RegExp(+ `^/api/proxy/api/public/shared/chats/${escapeRegex(shareToken)}/files/${FILE_UUID_GROUP}/download$`,+ );+}diff --git a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.tsindex 463ec98cbb..bb297d5e34 100644--- a/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts+++ b/autogpt_platform/frontend/src/services/feature-flags/use-get-flag.ts@@ -14,6 +14,7 @@ export enum Flag {AGENT_BRIEFING = "agent-briefing",GENERIC_TRIGGER_AGENTS = "generic-trigger-agents",CHAT_SEARCH = "chat-search",+ CHAT_SHARING = "chat-sharing",}const isPwMockEnabled = process.env.NEXT_PUBLIC_PW_TEST === "true";@@ -28,6 +29,7 @@ const defaultFlags = {[Flag.AGENT_BRIEFING]: false,[Flag.GENERIC_TRIGGER_AGENTS]: false,[Flag.CHAT_SEARCH]: false,+ [Flag.CHAT_SHARING]: false,};type FlagValues = typeof defaultFlags;