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): day-one kickoff after hire (#14039)
Abhimanyu Yadav23cbdce533e0
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex 8895630fd6..fb3d2be261 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -4,7 +4,7 @@ import asyncioimport loggingfrom collections.abc import AsyncGeneratorfrom datetime import datetime, timezone-from typing import Annotated+from typing import Annotated, Anyfrom uuid import uuid4from autogpt_libs import auth@@ -28,8 +28,16 @@ from backend.copilot.config import (CopilotLLMModel,CopilotMode,)-from backend.copilot.db import get_chat_messages_paginated+from backend.copilot.db import (+ chat_message_has_assistant_reply,+ get_chat_messages_paginated,+)from backend.copilot.executor.utils import enqueue_cancel_task, schedule_chat_turn+from backend.copilot.expert_kickoff import (+ expert_kickoff_message_id,+ expert_kickoff_metadata,+ scoped_client_message_id,+)from backend.copilot.model import (CHAT_STATUS_IDLE,CHAT_STATUS_RUNNING,@@ -39,6 +47,7 @@ from backend.copilot.model import (delete_chat_session,get_chat_session_metadata,get_or_create_builder_session,+ get_or_create_expert_kickoff_session,get_user_sessions,update_session_pinned,update_session_title,@@ -241,17 +250,25 @@ class StreamChatRequest(BaseModel):default=None,max_length=64,description=(- "Optional per-click UUID generated by the frontend. Becomes "- "the persisted ``ChatMessage.id`` (PK). Frontend / network / "- "RMQ-redelivery retransmits of the same logical send reuse "- "the id, so the Postgres unique-constraint on the PK is the "- "atomic dedup primitive: a duplicate INSERT returns a "- "subscribe-only response without creating a parallel turn. "+ "Optional per-click UUID generated by the frontend. The server "+ "scopes it to the authenticated user and session before using "+ "the result as ``ChatMessage.id``. Frontend / network / "+ "RMQ-redelivery retransmits of the same logical send reuse the "+ "key, so the Postgres unique-constraint on the resulting PK is "+ "the atomic dedup primitive. A duplicate INSERT returns a "+ "subscribe-only response without creating a parallel turn. ""Distinct user clicks (even with identical text) MUST send ""different ids — the frontend's per-click ``crypto.randomUUID()`` ""guarantees that."),)+ expert_kickoff: bool = Field(+ default=False,+ description=(+ "Marks the hidden, once-per-expert day-one kickoff. The server "+ "derives its owner-scoped message ID and persistence metadata."+ ),+ )class QueuePendingMessageRequest(BaseModel):@@ -300,6 +317,10 @@ class CreateSessionRequest(BaseModel):with ``builder_graph_id`` (422) — builder-bound sessions are neverexpert-scoped.+ ``expert_kickoff`` switches expert creation to an atomic create-or-adopt+ mode keyed by the authenticated user and expert. It is invalid without+ ``expert_id``.+Extra/unknown fields are rejected (422) to prevent silent mis-use."""@@ -310,6 +331,7 @@ class CreateSessionRequest(BaseModel):llm_auth_provider: CopilotLlmAuthProvider = "platform"llm_credential_id: str | None = Field(default=None, max_length=128)expert_id: str | None = Field(default=None, max_length=128)+ expert_kickoff: bool = Falseclass CreateSessionResponse(BaseModel):@@ -425,6 +447,13 @@ async def list_sessions(limit: int = Query(default=50, ge=1, le=100),offset: int = Query(default=0, ge=0),expert_id: str | None = Query(default=None, max_length=128),+ pinned_first: bool = Query(+ default=True,+ description=(+ "Keep pinned sessions before recent sessions. Set false for "+ "strict recency when adopting the latest expert thread."+ ),+ ),) -> ListSessionsResponse:"""List chat sessions for the authenticated user.@@ -437,12 +466,18 @@ async def list_sessions(limit: Maximum number of sessions to return (1-100).offset: Number of sessions to skip for pagination.expert_id: Restrict the listing to sessions scoped to this expert.+ pinned_first: Whether pinned sessions precede strict recency ordering.Returns:ListSessionsResponse: List of session summaries and total count."""sessions, total_count = await get_user_sessions(- user_id, limit, offset, organization_id=ctx.org_id, expert_id=expert_id+ user_id,+ limit,+ offset,+ organization_id=ctx.org_id,+ expert_id=expert_id,+ pinned_first=pinned_first,)# Batch-check Redis for active stream status on each session@@ -654,6 +689,8 @@ async def create_session((``edit_agent`` / ``run_agent`` reject any ``agent_id`` other thanthe bound graph) and a small blacklist hides tools that conflictwith the panel's scope (see :data:`BUILDER_BLOCKED_TOOLS`).+ - Expert kickoff: atomically create or adopt the canonical first session+ for ``(user_id, expert_id)``.Args:user_id: The authenticated user ID parsed from the JWT (required).@@ -666,6 +703,13 @@ async def create_session(dry_run = request.dry_run if request else Falsebuilder_graph_id = request.builder_graph_id if request else Noneexpert_id = request.expert_id if request else None+ expert_kickoff = request.expert_kickoff if request else False++ if expert_kickoff and expert_id is None:+ raise HTTPException(+ status_code=422,+ detail="expert_kickoff requires expert_id",+ )# The builder branch below ignores expert_id, so accepting both would# validate the expert and then silently drop the scoping. Reject upfront.@@ -693,6 +737,7 @@ async def create_session(f"{', dry_run=True' if dry_run else ''}"f"{f', builder_graph_id={builder_graph_id}' if builder_graph_id else ''}"f"{f', expert_id={expert_id}' if expert_id else ''}"+ f"{', expert_kickoff=True' if expert_kickoff else ''}")if builder_graph_id:@@ -707,6 +752,16 @@ async def create_session(organization_id=ctx.org_id,team_id=ctx.team_id,)+ elif expert_kickoff and expert_id is not None:+ session = await get_or_create_expert_kickoff_session(+ user_id,+ expert_id,+ dry_run=dry_run,+ organization_id=ctx.org_id,+ team_id=ctx.team_id,+ llm_auth_provider=llm_auth_provider,+ llm_credential_id=llm_credential_id,+ )else:session = await create_chat_session(user_id,@@ -1391,6 +1446,37 @@ async def stream_chat_post(elif session.metadata.llm_auth_provider == "codex":await enforce_codex_access_http(user_id)+ message = request.message+ message_id = (+ scoped_client_message_id(user_id, session_id, request.message_id)+ if request.message_id+ else None+ )+ message_metadata: dict[str, Any] | None = None+ persisted_kickoff_has_reply: bool | None = None+ resume_persisted_kickoff = False+ if request.expert_kickoff:+ if not request.is_user_message or not message.strip():+ raise HTTPException(+ status_code=422,+ detail="expert_kickoff requires a non-empty user message",+ )+ if session.expert_id is None:+ raise HTTPException(+ status_code=422,+ detail="expert_kickoff requires an expert-scoped session",+ )+ message_id = expert_kickoff_message_id(+ user_id,+ session_id,+ session.expert_id,+ )+ message_metadata = expert_kickoff_metadata(session.expert_id)+ persisted_kickoff_has_reply = await chat_message_has_assistant_reply(+ message_id,+ session_id,+ )+# Session-anchored tenancy: the ChatSession row is the authoritative# org/team for every turn in it — a user whose active header org# differs still charges/attributes turns to the session's org.@@ -1400,9 +1486,7 @@ async def stream_chat_post(try:turn_in_flight = (- request.is_user_message- and request.message- and await is_turn_in_flight(session_id)+ request.is_user_message and message and await is_turn_in_flight(session_id))except StreamRegistryUnavailable as exc:# Same fail-closed mapping as the RateLimitUnavailable branch below:@@ -1416,11 +1500,18 @@ async def stream_chat_post() from excif turn_in_flight:+ if request.expert_kickoff:+ if persisted_kickoff_has_reply is not None:+ return _empty_ui_message_stream_response()+ raise HTTPException(+ status_code=409,+ detail="expert kickoff requires an idle session",+ )try:await queue_pending_for_http(session_id=session_id,user_id=user_id,- message=request.message,+ message=message,context=request.context,file_ids=request.file_ids,)@@ -1429,6 +1520,11 @@ async def stream_chat_post(if exc.status_code != 409:raise+ if request.expert_kickoff and persisted_kickoff_has_reply is not None:+ if persisted_kickoff_has_reply:+ return _empty_ui_message_stream_response()+ resume_persisted_kickoff = True+# Permission resolution is only needed below for the actual turn — keep# it after the queue-fall-through so a queued mid-turn request returns# without paying the work.@@ -1480,7 +1576,7 @@ async def stream_chat_post(if request.file_ids:files = await resolve_workspace_files(user_id, request.file_ids)sanitized_file_ids = [wf.id for wf in files] or None- request.message += build_files_block(files)+ message += build_files_block(files)# Atomically append user message to session BEFORE creating task to avoid# race condition where GET_SESSION sees task as "running" but message isn't@@ -1500,8 +1596,10 @@ async def stream_chat_post(turn_id = await schedule_chat_turn(session_id=session_id,user_id=user_id,- message=request.message,- message_id=request.message_id,+ message=message,+ message_id=message_id,+ message_metadata=message_metadata,+ message_already_persisted=resume_persisted_kickoff,is_user_message=request.is_user_message,context=request.context,file_ids=sanitized_file_ids,@@ -1514,7 +1612,9 @@ async def stream_chat_post(permissions=builder_permissions,request_arrival_at=request_arrival_at,)- except ConcurrentTurnLimitError:+ except ConcurrentTurnLimitError as exc:+ if resume_persisted_kickoff:+ raise HTTPException(status_code=429, detail=str(exc)) from exc# Soft running cap (default 5) hit. Fall through to the queue:# if total in-flight (running + queued) is still under the hard# cap (default 15), persist the user's message and flip the@@ -1526,8 +1626,9 @@ async def stream_chat_post(user_id=user_id,inflight_cap=inflight_cap,session_id=session_id,- message=request.message,- message_id=request.message_id,+ message=message,+ message_id=message_id,+ message_metadata=message_metadata,is_user_message=request.is_user_message,context=request.context,file_ids=sanitized_file_ids,diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.pyindex 30a47e65dc..84b5b2939d 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py@@ -270,7 +270,11 @@ def _mock_stream_internals(# The route anchors turn tenancy on the session row# (session.organization_id / session.team_id), so the stub must carry# both — None exercises the legacy ctx-fallback path.- mock_session = mocker.MagicMock(organization_id=None, team_id=None)+ mock_session = mocker.MagicMock(+ organization_id=None,+ team_id=None,+ expert_id=None,+ )mock_session.metadata.llm_auth_provider = llm_auth_providermock_session.metadata.llm_credential_id = ("cred-codex" if llm_auth_provider == "codex" else None@@ -284,6 +288,11 @@ def _mock_stream_internals(new_callable=AsyncMock,return_value=False,)+ mocker.patch(+ "backend.api.features.chat.routes.chat_message_has_assistant_reply",+ new_callable=AsyncMock,+ return_value=None,+ )mock_paywall = mocker.patch("backend.api.features.chat.routes.enforce_payment_paywall",new_callable=AsyncMock,@@ -305,7 +314,11 @@ def _mock_stream_internals(new_callable=AsyncMock,return_value=None,)- return types.SimpleNamespace(enqueue=mock_schedule, paywall=mock_paywall)+ return types.SimpleNamespace(+ enqueue=mock_schedule,+ paywall=mock_paywall,+ session=mock_session,+ )def test_stream_chat_accepts_20_file_ids(mocker: pytest_mock.MockerFixture):@@ -359,6 +372,210 @@ def test_stream_chat_skips_enqueue_for_duplicate_message(mocks.enqueue.assert_called_once()+def test_stream_chat_canonicalizes_expert_kickoff(+ mocker: pytest_mock.MockerFixture,+ test_user_id: str,+) -> None:+ expert_id = "3f8b0f7e-9f30-4a3b-a6a1-000000000001"+ mocks = _mock_stream_internals(mocker)+ mocks.session.expert_id = expert_id++ response = client.post(+ "/sessions/sess-1/stream",+ json={+ "message": "You were just hired.",+ "message_id": "attacker-controlled-id",+ "expert_kickoff": True,+ },+ )++ assert response.status_code == 200+ call = mocks.enqueue.await_args.kwargs+ assert call["message_id"] == chat_routes.expert_kickoff_message_id(+ test_user_id,+ "sess-1",+ expert_id,+ )+ assert call["message_metadata"] == {+ "hidden": True,+ "kind": "expert_kickoff",+ "expert_id": expert_id,+ }+++def test_stream_chat_short_circuits_completed_expert_kickoff(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocks = _mock_stream_internals(mocker)+ mocks.session.expert_id = "3f8b0f7e-9f30-4a3b-a6a1-000000000001"+ mocker.patch(+ "backend.api.features.chat.routes.chat_message_has_assistant_reply",+ new_callable=AsyncMock,+ return_value=True,+ )++ response = client.post(+ "/sessions/sess-1/stream",+ json={"message": "You were just hired.", "expert_kickoff": True},+ )++ assert response.status_code == 200+ mocks.enqueue.assert_not_awaited()+++def test_stream_chat_redispatches_orphaned_expert_kickoff(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocks = _mock_stream_internals(mocker)+ mocks.session.expert_id = "3f8b0f7e-9f30-4a3b-a6a1-000000000001"+ mocker.patch(+ "backend.api.features.chat.routes.chat_message_has_assistant_reply",+ new_callable=AsyncMock,+ return_value=False,+ )++ response = client.post(+ "/sessions/sess-1/stream",+ json={"message": "You were just hired.", "expert_kickoff": True},+ )++ assert response.status_code == 200+ assert mocks.enqueue.await_args.kwargs["message_already_persisted"] is True+++def test_stream_chat_returns_retryable_limit_for_orphaned_expert_kickoff(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocks = _mock_stream_internals(mocker)+ mocks.session.expert_id = "3f8b0f7e-9f30-4a3b-a6a1-000000000001"+ mocker.patch(+ "backend.api.features.chat.routes.chat_message_has_assistant_reply",+ new_callable=AsyncMock,+ return_value=False,+ )+ mocks.enqueue.side_effect = chat_routes.ConcurrentTurnLimitError("try again")++ response = client.post(+ "/sessions/sess-1/stream",+ json={"message": "You were just hired.", "expert_kickoff": True},+ )++ assert response.status_code == 429+ assert response.json() == {"detail": "try again"}+++def test_stream_chat_does_not_redispatch_running_persisted_kickoff(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocks = _mock_stream_internals(mocker)+ mocks.session.expert_id = "3f8b0f7e-9f30-4a3b-a6a1-000000000001"+ mocker.patch(+ "backend.api.features.chat.routes.chat_message_has_assistant_reply",+ new_callable=AsyncMock,+ return_value=False,+ )+ mocker.patch(+ "backend.api.features.chat.routes.is_turn_in_flight",+ new_callable=AsyncMock,+ return_value=True,+ )++ response = client.post(+ "/sessions/sess-1/stream",+ json={"message": "You were just hired.", "expert_kickoff": True},+ )++ assert response.status_code == 200+ mocks.enqueue.assert_not_awaited()+++def test_stream_chat_does_not_queue_kickoff_behind_an_unrelated_turn(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocks = _mock_stream_internals(mocker)+ mocks.session.expert_id = "3f8b0f7e-9f30-4a3b-a6a1-000000000001"+ mocker.patch(+ "backend.api.features.chat.routes.is_turn_in_flight",+ new_callable=AsyncMock,+ return_value=True,+ )+ queue_pending = mocker.patch(+ "backend.api.features.chat.routes.queue_pending_for_http",+ new_callable=AsyncMock,+ )++ response = client.post(+ "/sessions/sess-1/stream",+ json={"message": "You were just hired.", "expert_kickoff": True},+ )++ assert response.status_code == 409+ queue_pending.assert_not_awaited()+ mocks.enqueue.assert_not_awaited()+++def test_stream_chat_rejects_kickoff_for_plain_session(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mocks = _mock_stream_internals(mocker)++ response = client.post(+ "/sessions/sess-1/stream",+ json={"message": "You were just hired.", "expert_kickoff": True},+ )++ assert response.status_code == 422+ mocks.enqueue.assert_not_awaited()+++ "payload",+ [+ {"message": "", "expert_kickoff": True},+ {+ "message": "You were just hired.",+ "is_user_message": False,+ "expert_kickoff": True,+ },+ ],+)+def test_stream_chat_rejects_invalid_kickoff_message_shape(+ mocker: pytest_mock.MockerFixture,+ payload: dict,+) -> None:+ mocks = _mock_stream_internals(mocker)+ mocks.session.expert_id = "3f8b0f7e-9f30-4a3b-a6a1-000000000001"++ response = client.post("/sessions/sess-1/stream", json=payload)++ assert response.status_code == 422+ assert response.json()["detail"] == (+ "expert_kickoff requires a non-empty user message"+ )+ mocks.enqueue.assert_not_awaited()+++def test_stream_chat_scopes_client_message_id_to_owner_and_session(+ mocker: pytest_mock.MockerFixture,+ test_user_id: str,+) -> None:+ mocks = _mock_stream_internals(mocker)++ response = client.post(+ "/sessions/sess-1/stream",+ json={"message": "hello", "message_id": "client-click-id"},+ )++ assert response.status_code == 200+ assert mocks.enqueue.await_args.kwargs[+ "message_id"+ ] == chat_routes.scoped_client_message_id(+ test_user_id,+ "sess-1",+ "client-click-id",+ )++# ─── UUID format filtering ─────────────────────────────────────────────@@ -1403,6 +1620,47 @@ def test_create_session_with_expert_id_persists_it(assert mock_create.call_args.kwargs["expert_id"] == "expert-1"+def test_create_expert_kickoff_session_uses_atomic_get_or_create(+ mocker: pytest_mock.MockerFixture,+ test_user_id: str,+) -> None:+ from backend.copilot.model import ChatSession++ expert_id = "3f8b0f7e-9f30-4a3b-a6a1-000000000001"+ mock_get = _mock_get_expert(mocker, _make_expert(expert_id))+ mock_create = _mock_create_chat_session(mocker)+ existing = ChatSession.new(test_user_id, dry_run=False, expert_id=expert_id)+ mock_get_or_create = mocker.patch.object(+ chat_routes,+ "get_or_create_expert_kickoff_session",+ new=AsyncMock(return_value=existing),+ )++ response = client.post(+ "/sessions",+ json={"expert_id": expert_id, "expert_kickoff": True},+ )++ assert response.status_code == 200+ assert response.json()["id"] == existing.session_id+ mock_get.assert_awaited_once_with(test_user_id, expert_id)+ mock_get_or_create.assert_awaited_once()+ assert mock_get_or_create.await_args.args[:2] == (test_user_id, expert_id)+ mock_create.assert_not_awaited()+++def test_create_expert_kickoff_session_requires_expert_id(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mock_create = _mock_create_chat_session(mocker)++ response = client.post("/sessions", json={"expert_kickoff": True})++ assert response.status_code == 422+ assert response.json()["detail"] == "expert_kickoff requires expert_id"+ mock_create.assert_not_awaited()++def test_create_session_with_other_users_expert_returns_404(mocker: pytest_mock.MockerFixture,test_user_id: str,@@ -2066,6 +2324,21 @@ def test_list_sessions_filters_by_expert_id(assert mock_get.call_args.kwargs["expert_id"] == "expert-1"+def test_list_sessions_can_request_strict_recency(+ mocker: pytest_mock.MockerFixture,+) -> None:+ mock_get = mocker.patch(+ "backend.api.features.chat.routes.get_user_sessions",+ new_callable=AsyncMock,+ return_value=([], 0),+ )++ response = client.get("/sessions?pinned_first=false")++ assert response.status_code == 200+ assert mock_get.await_args.kwargs["pinned_first"] is False++def test_list_sessions_marks_running_as_processing(mocker: pytest_mock.MockerFixture,) -> None:diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.pyindex 6c2d60982f..aa6bb6850e 100644--- a/autogpt_platform/backend/backend/copilot/db.py+++ b/autogpt_platform/backend/backend/copilot/db.py@@ -74,6 +74,32 @@ async def get_chat_session_metadata(session_id: str) -> ChatSessionInfo | None:return ChatSessionInfo.from_db(session) if session else None+async def chat_message_has_assistant_reply(+ message_id: str,+ session_id: str,+) -> bool | None:+ """Whether a persisted user message already has an assistant reply after it.++ ``None`` means the message does not exist, ``False`` means no assistant row+ follows it, and ``True`` means an assistant reply was persisted after it in+ the same session.+ """+ messages = PrismaChatMessage.prisma()+ existing = await messages.find_first(+ where={"id": message_id, "sessionId": session_id},+ )+ if existing is None:+ return None+ assistant_reply = await messages.find_first(+ where={+ "sessionId": session_id,+ "role": "assistant",+ "sequence": {"gt": existing.sequence},+ },+ )+ return assistant_reply is not None++def _own_org_scope(organization_id: str | None) -> list[ChatSessionWhereInput]:"""AND-clause scoping a user's own sessions to the active org.@@ -670,6 +696,7 @@ async def get_user_chat_sessions(organization_id: str | None = None,title_contains: str | None = None,expert_id: str | None = None,+ pinned_first: bool = True,) -> list[ChatSessionInfo]:"""Get chat sessions for a user, ordered by most recent.@@ -684,6 +711,8 @@ async def get_user_chat_sessions(without waiting on async embedding.``expert_id`` restricts the listing to sessions scoped to that expert.+ ``pinned_first=False`` provides strict recency ordering for internal+ adoption flows; the user-facing sidebar keeps pinned sessions first."""params: list[Any] = [user_id]conditions = ['"userId" = $1', _EXCLUDE_DREAM_SESSIONS_SQL]@@ -699,10 +728,13 @@ async def get_user_chat_sessions(params.append(expert_id)conditions.append(f'"expertId" = ${len(params)}')params.extend((limit, offset))+ ordering = (+ '"isPinned" DESC, "updatedAt" DESC' if pinned_first else '"updatedAt" DESC'+ )query = ('SELECT * FROM {schema_prefix}"ChatSession" WHERE '+ " AND ".join(conditions)- + ' ORDER BY "isPinned" DESC, "updatedAt" DESC '+ + f" ORDER BY {ordering} "+ f"LIMIT ${len(params) - 1} OFFSET ${len(params)}")sessions = await db.query_raw_with_schema(query, *params, model=PrismaChatSession)diff --git a/autogpt_platform/backend/backend/copilot/db_test.py b/autogpt_platform/backend/backend/copilot/db_test.pyindex 086928f9b6..bbd981ffc7 100644--- a/autogpt_platform/backend/backend/copilot/db_test.py+++ b/autogpt_platform/backend/backend/copilot/db_test.py@@ -13,6 +13,7 @@ from prisma.models import ChatSession as PrismaChatSessionfrom backend.copilot.db import (PaginatedMessages,+ chat_message_has_assistant_reply,get_chat_messages_paginated,get_user_chat_sessions,set_turn_duration,@@ -79,6 +80,47 @@ def _make_session(return session+async def test_chat_message_has_assistant_reply_distinguishes_delivery_state():+ kickoff = _make_msg(3, role="user", content="kickoff")+ assistant = _make_msg(4, role="assistant", content="ready")+ find_first = AsyncMock(side_effect=[kickoff, assistant])++ with patch.object(+ PrismaChatMessage,+ "prisma",+ return_value=AsyncMock(find_first=find_first),+ ):+ result = await chat_message_has_assistant_reply("msg-3", "sess-1")++ assert result is True+ assert find_first.await_args_list[1].kwargs["where"] == {+ "sessionId": "sess-1",+ "role": "assistant",+ "sequence": {"gt": 3},+ }+++async def test_chat_message_has_assistant_reply_reports_missing_and_orphaned():+ missing = AsyncMock(return_value=None)+ with patch.object(+ PrismaChatMessage,+ "prisma",+ return_value=AsyncMock(find_first=missing),+ ):+ assert await chat_message_has_assistant_reply("missing", "sess-1") is None++ kickoff = _make_msg(3, role="user", content="kickoff")+ orphaned = AsyncMock(side_effect=[kickoff, None])+ with patch.object(+ PrismaChatMessage,+ "prisma",+ return_value=AsyncMock(find_first=orphaned),+ ):+ assert await chat_message_has_assistant_reply("msg-3", "sess-1") is False++SESSION_ID = "sess-1"@@ -673,6 +715,21 @@ async def test_get_user_chat_sessions_orders_pinned_first():assert 'ORDER BY "isPinned" DESC, "updatedAt" DESC' in query+async def test_get_user_chat_sessions_can_order_by_strict_recency():+ raw = AsyncMock(return_value=[])+ with patch("backend.copilot.db.db.query_raw_with_schema", raw):+ await get_user_chat_sessions(+ "user-abc",+ limit=1,+ pinned_first=False,+ )++ query = raw.call_args.args[0]+ assert 'ORDER BY "updatedAt" DESC' in query+ assert 'ORDER BY "isPinned"' not in query++# NOTE: previously this file had a separate suite for ``db.get_chat_session``# (windowed eager-load). That function was removed in favour of going through# ``get_chat_messages_paginated`` directly — see ``model._get_session_from_db``.diff --git a/autogpt_platform/backend/backend/copilot/executor/utils.py b/autogpt_platform/backend/backend/copilot/executor/utils.pyindex 6962e8fbc8..62a9355467 100644--- a/autogpt_platform/backend/backend/copilot/executor/utils.py+++ b/autogpt_platform/backend/backend/copilot/executor/utils.py@@ -6,6 +6,7 @@ Defines two exchanges and queues following the graph executor pattern:"""import logging+from typing import Anyfrom pydantic import BaseModel@@ -485,6 +486,8 @@ async def schedule_chat_turn(user_id: str,message: str,message_id: str | None = None,+ message_metadata: dict[str, Any] | None = None,+ message_already_persisted: bool = False,is_user_message: bool = True,context: dict[str, str] | None = None,file_ids: list[str] | None = None,@@ -504,7 +507,8 @@ async def schedule_chat_turn(Returns the new ``turn_id`` on a fresh dispatch, or ``None`` if theinbound message was a duplicate of one already saved (caller shouldsubscribe to the existing in-flight turn's stream instead of opening- a new one).+ a new one). ``message_already_persisted`` re-dispatches an orphaned+ kickoff row only when this caller atomically admits the idle session.Raises :class:`backend.copilot.active_turns.ConcurrentTurnLimitError`when the user is at the configured cap. Caller maps that to HTTP 429.@@ -524,12 +528,15 @@ async def schedule_chat_turn(from backend.copilot.tracking import track_user_messageasync with acquire_turn_slot(user_id, session_id) as slot:+ if message_already_persisted and not slot.admitted:+ return Noneis_duplicate = False- if message:+ if message and not message_already_persisted:chat_message = ChatMessage(id=message_id,role="user" if is_user_message else "assistant",content=message,+ metadata=message_metadata,)is_duplicate = (await append_and_save_message(session_id, chat_message)diff --git a/autogpt_platform/backend/backend/copilot/executor/utils_test.py b/autogpt_platform/backend/backend/copilot/executor/utils_test.pyindex 47602551ba..0e675a799a 100644--- a/autogpt_platform/backend/backend/copilot/executor/utils_test.py+++ b/autogpt_platform/backend/backend/copilot/executor/utils_test.py@@ -1,5 +1,11 @@"""Tests for CoPilot executor utils (queue config, message models, logging)."""+from contextlib import asynccontextmanager+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from backend.copilot.executor import utilsfrom backend.copilot.executor.utils import (COPILOT_EXECUTION_EXCHANGE,COPILOT_EXECUTION_QUEUE_NAME,@@ -11,6 +17,57 @@ from backend.copilot.executor.utils import ()+async def test_schedule_chat_turn_redispatches_admitted_persisted_message() -> None:+ slot = MagicMock(admitted=True)++ @asynccontextmanager+ async def acquire(*_args, **_kwargs):+ yield slot++ append = AsyncMock()+ dispatch = AsyncMock()+ with (+ patch.object(utils, "acquire_turn_slot", new=acquire),+ patch("backend.copilot.model.append_and_save_message", new=append),+ patch.object(utils, "dispatch_turn", new=dispatch),+ ):+ turn_id = await utils.schedule_chat_turn(+ session_id="s1",+ user_id="u1",+ message="kickoff",+ message_already_persisted=True,+ )++ assert turn_id is not None+ append.assert_not_awaited()+ dispatch.assert_awaited_once()+++async def test_schedule_chat_turn_skips_concurrent_persisted_redispatch() -> None:+ slot = MagicMock(admitted=False)++ @asynccontextmanager+ async def acquire(*_args, **_kwargs):+ yield slot++ dispatch = AsyncMock()+ with (+ patch.object(utils, "acquire_turn_slot", new=acquire),+ patch.object(utils, "dispatch_turn", new=dispatch),+ ):+ turn_id = await utils.schedule_chat_turn(+ session_id="s1",+ user_id="u1",+ message="kickoff",+ message_already_persisted=True,+ )++ assert turn_id is None+ dispatch.assert_not_awaited()++class TestCoPilotExecutionEntry:def test_basic_fields(self):entry = CoPilotExecutionEntry(diff --git a/autogpt_platform/backend/backend/copilot/expert_kickoff.py b/autogpt_platform/backend/backend/copilot/expert_kickoff.pynew file mode 100644index 0000000000..31fe3c7333--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/expert_kickoff.py@@ -0,0 +1,56 @@+"""Server-owned identity and metadata for an expert's first kickoff turn."""++import uuid+from collections.abc import Mapping+from typing import Any++EXPERT_KICKOFF_KIND = "expert_kickoff"++_MESSAGE_NAMESPACE = uuid.UUID("d0890fe0-26eb-5ee4-91b4-42a930ce29ac")+_CLIENT_MESSAGE_NAMESPACE = uuid.UUID("d70473da-722b-55cb-963f-4729e64d7b06")+++def scoped_client_message_id(+ user_id: str,+ session_id: str,+ client_message_id: str,+) -> str:+ """Scope a client idempotency key to its authenticated session owner.++ Clients can choose ``client_message_id``. They cannot use it to claim an+ arbitrary global ``ChatMessage`` primary key belonging to another user.+ """+ return str(+ uuid.uuid5(+ _CLIENT_MESSAGE_NAMESPACE,+ f"{user_id}:{session_id}:{client_message_id}",+ )+ )+++def expert_kickoff_message_id(+ user_id: str,+ session_id: str,+ expert_id: str,+) -> str:+ """Return the canonical message PK for one expert session's kickoff."""+ return str(+ uuid.uuid5(+ _MESSAGE_NAMESPACE,+ f"{user_id}:{session_id}:{expert_id}",+ )+ )+++def expert_kickoff_metadata(expert_id: str) -> dict[str, Any]:+ """Metadata that keeps the persisted control turn off user surfaces."""+ return {+ "hidden": True,+ "kind": EXPERT_KICKOFF_KIND,+ "expert_id": expert_id,+ }+++def is_hidden_chat_message(metadata: Mapping[str, Any] | None) -> bool:+ """Whether message metadata marks a row as hidden from user surfaces."""+ return metadata is not None and metadata.get("hidden") is Truediff --git a/autogpt_platform/backend/backend/copilot/expert_kickoff_test.py b/autogpt_platform/backend/backend/copilot/expert_kickoff_test.pynew file mode 100644index 0000000000..9aa1872ceb--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/expert_kickoff_test.py@@ -0,0 +1,49 @@+from backend.copilot.expert_kickoff import (+ expert_kickoff_message_id,+ expert_kickoff_metadata,+ is_hidden_chat_message,+ scoped_client_message_id,+)+++def test_message_id_is_stable_and_scoped_to_owner_and_expert() -> None:+ message_id = expert_kickoff_message_id("user-a", "session-a", "expert-a")++ assert message_id == expert_kickoff_message_id("user-a", "session-a", "expert-a")+ assert message_id != expert_kickoff_message_id("user-b", "session-a", "expert-a")+ assert message_id != expert_kickoff_message_id("user-a", "session-b", "expert-a")+ assert message_id != expert_kickoff_message_id("user-a", "session-a", "expert-b")+ assert len(message_id) == 36+++def test_client_message_ids_are_stable_and_tenant_scoped() -> None:+ message_id = scoped_client_message_id("user-a", "session-a", "click-a")++ assert message_id == scoped_client_message_id("user-a", "session-a", "click-a")+ assert message_id != scoped_client_message_id("user-b", "session-a", "click-a")+ assert message_id != scoped_client_message_id("user-a", "session-b", "click-a")+ assert message_id != scoped_client_message_id("user-a", "session-a", "click-b")+++def test_client_cannot_preclaim_an_expert_kickoff_primary_key() -> None:+ kickoff_id = expert_kickoff_message_id(+ "target-user", "target-session", "target-expert"+ )++ assert (+ scoped_client_message_id("attacker", "attacker-session", kickoff_id)+ != kickoff_id+ )+++def test_metadata_marks_kickoff_hidden_without_hiding_other_messages() -> None:+ metadata = expert_kickoff_metadata("expert-a")++ assert metadata == {+ "hidden": True,+ "kind": "expert_kickoff",+ "expert_id": "expert-a",+ }+ assert is_hidden_chat_message(metadata)+ assert not is_hidden_chat_message(None)+ assert not is_hidden_chat_message({"hidden": False})diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.pyindex 45be6ef569..e4c155bcae 100644--- a/autogpt_platform/backend/backend/copilot/model.py+++ b/autogpt_platform/backend/backend/copilot/model.py@@ -54,6 +54,7 @@ RoutingSource = Literal[# Redis cache key prefix for chat sessionsCHAT_SESSION_CACHE_PREFIX = "chat:session:"+_EXPERT_KICKOFF_SESSION_NAMESPACE = uuid.UUID("3fd5434f-225a-53e8-b248-1a749a925892")def _get_session_cache_key(session_id: str) -> str:@@ -381,6 +382,7 @@ class ChatSession(ChatSessionInfo):user_id: str,*,dry_run: bool,+ session_id: str | None = None,builder_graph_id: str | None = None,source_platform: str | None = None,organization_id: str | None = None,@@ -390,7 +392,7 @@ class ChatSession(ChatSessionInfo):expert_id: str | None = None,) -> Self:return cls(- session_id=str(uuid.uuid4()),+ session_id=session_id or str(uuid.uuid4()),user_id=user_id,title=None,messages=[],@@ -1163,6 +1165,7 @@ async def create_chat_session(user_id: str,*,dry_run: bool,+ session_id: str | None = None,builder_graph_id: str | None = None,organization_id: str | None = None,team_id: str | None = None,@@ -1193,6 +1196,7 @@ async def create_chat_session(session = ChatSession.new(user_id,dry_run=dry_run,+ session_id=session_id,builder_graph_id=builder_graph_id,source_platform=source_platform,organization_id=organization_id,@@ -1228,6 +1232,66 @@ async def create_chat_session(return session+def expert_kickoff_session_id(+ user_id: str,+ expert_id: str,+ organization_id: str | None = None,+) -> str:+ """Return the canonical first-session ID for one user's expert."""+ return str(+ uuid.uuid5(+ _EXPERT_KICKOFF_SESSION_NAMESPACE,+ f"{user_id}:{organization_id or 'personal'}:{expert_id}",+ )+ )+++async def get_or_create_expert_kickoff_session(+ user_id: str,+ expert_id: str,+ *,+ dry_run: bool,+ organization_id: str | None = None,+ team_id: str | None = None,+ llm_auth_provider: CopilotLlmAuthProvider = "platform",+ llm_credential_id: str | None = None,+) -> ChatSession:+ """Atomically create or adopt the canonical expert kickoff session."""+ sessions, _ = await get_user_sessions(+ user_id,+ limit=1,+ organization_id=organization_id,+ expert_id=expert_id,+ pinned_first=False,+ )+ if sessions:+ existing = await get_chat_session(sessions[0].session_id, user_id)+ if existing is not None:+ return existing++ session_id = expert_kickoff_session_id(user_id, expert_id, organization_id)+ existing = await get_chat_session(session_id, user_id)+ if existing is not None:+ return existing++ try:+ return await create_chat_session(+ user_id,+ dry_run=dry_run,+ session_id=session_id,+ organization_id=organization_id,+ team_id=team_id,+ llm_auth_provider=llm_auth_provider,+ llm_credential_id=llm_credential_id,+ expert_id=expert_id,+ )+ except DatabaseError:+ existing = await get_chat_session(session_id, user_id)+ if existing is not None and existing.expert_id == expert_id:+ return existing+ raise++async def get_or_create_builder_session(user_id: str,graph_id: str,@@ -1291,6 +1355,7 @@ async def get_user_sessions(organization_id: str | None = None,title_contains: str | None = None,expert_id: str | None = None,+ pinned_first: bool = True,) -> tuple[list[ChatSessionInfo], int]:"""Get chat sessions for a user from the database with total count.@@ -1312,6 +1377,7 @@ async def get_user_sessions(organization_id=organization_id,title_contains=title_contains,expert_id=expert_id,+ pinned_first=pinned_first,)total_count = await db.get_user_session_count(user_id, organization_id=organization_id, expert_id=expert_iddiff --git a/autogpt_platform/backend/backend/copilot/model_test.py b/autogpt_platform/backend/backend/copilot/model_test.pyindex d74e5d6579..1b2d8bcaa7 100644--- a/autogpt_platform/backend/backend/copilot/model_test.py+++ b/autogpt_platform/backend/backend/copilot/model_test.py@@ -1217,6 +1217,120 @@ async def test_get_session_from_db_returns_none_when_missing(# ─── get_or_create_builder_session ─────────────────────────────────────+def test_expert_kickoff_session_id_is_stable_and_owner_scoped() -> None:+ from .model import expert_kickoff_session_id++ first = expert_kickoff_session_id("user-a", "expert-a")++ assert first == expert_kickoff_session_id("user-a", "expert-a")+ assert first != expert_kickoff_session_id("user-b", "expert-a")+ assert first != expert_kickoff_session_id("user-a", "expert-b")+ assert first != expert_kickoff_session_id("user-a", "expert-a", "organization-a")+++async def test_get_or_create_expert_kickoff_session_recovers_create_race(+ mocker: MockerFixture,+) -> None:+ from backend.util.exceptions import DatabaseError++ from .model import expert_kickoff_session_id, get_or_create_expert_kickoff_session++ existing = ChatSession.new("user-a", dry_run=False, expert_id="expert-a")+ existing.session_id = expert_kickoff_session_id("user-a", "expert-a")+ get_session = mocker.patch(+ "backend.copilot.model.get_chat_session",+ new_callable=mocker.AsyncMock,+ side_effect=[None, existing],+ )+ mocker.patch(+ "backend.copilot.model.get_user_sessions",+ new_callable=mocker.AsyncMock,+ return_value=([], 0),+ )+ create_session = mocker.patch(+ "backend.copilot.model.create_chat_session",+ new_callable=mocker.AsyncMock,+ side_effect=DatabaseError("duplicate session id"),+ )++ result = await get_or_create_expert_kickoff_session(+ "user-a",+ "expert-a",+ dry_run=False,+ )++ assert result is existing+ assert get_session.await_count == 2+ assert create_session.await_args.kwargs["session_id"] == existing.session_id+++async def test_get_or_create_expert_kickoff_session_reraises_real_db_failure(+ mocker: MockerFixture,+) -> None:+ from backend.util.exceptions import DatabaseError++ from .model import get_or_create_expert_kickoff_session++ mocker.patch(+ "backend.copilot.model.get_user_sessions",+ new_callable=mocker.AsyncMock,+ return_value=([], 0),+ )+ mocker.patch(+ "backend.copilot.model.get_chat_session",+ new_callable=mocker.AsyncMock,+ return_value=None,+ )+ mocker.patch(+ "backend.copilot.model.create_chat_session",+ new_callable=mocker.AsyncMock,+ side_effect=DatabaseError("database unavailable"),+ )++ with pytest.raises(DatabaseError, match="database unavailable"):+ await get_or_create_expert_kickoff_session(+ "user-a",+ "expert-a",+ dry_run=False,+ )+++async def test_get_or_create_expert_kickoff_session_adopts_latest_thread(+ mocker: MockerFixture,+) -> None:+ from .model import get_or_create_expert_kickoff_session++ existing = ChatSession.new("user-a", dry_run=False, expert_id="expert-a")+ get_sessions = mocker.patch(+ "backend.copilot.model.get_user_sessions",+ new_callable=mocker.AsyncMock,+ return_value=([existing], 1),+ )+ get_session = mocker.patch(+ "backend.copilot.model.get_chat_session",+ new_callable=mocker.AsyncMock,+ return_value=existing,+ )+ create_session = mocker.patch(+ "backend.copilot.model.create_chat_session",+ new_callable=mocker.AsyncMock,+ )++ result = await get_or_create_expert_kickoff_session(+ "user-a",+ "expert-a",+ dry_run=False,+ )++ assert result is existing+ assert get_sessions.await_args.kwargs["pinned_first"] is False+ get_session.assert_awaited_once_with(existing.session_id, "user-a")+ create_session.assert_not_awaited()++@pytest.mark.asyncioasync def test_get_or_create_builder_session_raises_when_graph_not_owned(mocker: MockerFixture,diff --git a/autogpt_platform/backend/backend/copilot/sharing/db.py b/autogpt_platform/backend/backend/copilot/sharing/db.pyindex 102156cc2b..53ac9bde4e 100644--- a/autogpt_platform/backend/backend/copilot/sharing/db.py+++ b/autogpt_platform/backend/backend/copilot/sharing/db.py@@ -28,6 +28,7 @@ from prisma.models import (from backend.blocks import get_blockfrom backend.blocks._base import BlockTypefrom backend.copilot.db import get_chat_messages_paginated+from backend.copilot.expert_kickoff import is_hidden_chat_messagefrom backend.copilot.model import ChatSessionInfofrom backend.copilot.sharing.models import (ChatShareState,@@ -349,7 +350,11 @@ async def get_shared_chat_messages_paginated(return Nonereturn SharedChatMessagesPage(- messages=[sanitize_chat_message(m) for m in page.messages],+ messages=[+ sanitize_chat_message(message)+ for message in page.messages+ if not is_hidden_chat_message(message.metadata)+ ],has_more=page.has_more,oldest_sequence=page.oldest_sequence,)diff --git a/autogpt_platform/backend/backend/copilot/sharing/db_test.py b/autogpt_platform/backend/backend/copilot/sharing/db_test.pyindex 6db19c55d0..86d335e7ea 100644--- a/autogpt_platform/backend/backend/copilot/sharing/db_test.py+++ b/autogpt_platform/backend/backend/copilot/sharing/db_test.py@@ -25,6 +25,7 @@ from prisma.models import ()from backend.blocks._base import BlockType+from backend.copilot.model import ChatMessagefrom backend.copilot.sharing.db import (_build_shared_execution_file_allowlist,_collect_execution_ids_from_messages,@@ -32,6 +33,7 @@ from backend.copilot.sharing.db import (disable_chat_session_share,enable_chat_session_share,get_chat_share_state,+ get_shared_chat_messages_paginated,link_new_execution_to_chat_share,)@@ -110,6 +112,45 @@ class _TxStub:return None+async def test_shared_transcript_omits_hidden_kickoff_messages(+ mock_prisma_calls,+) -> None:+ mock_prisma_calls["session"].return_value.find_first = AsyncMock(+ return_value=_mock_session()+ )+ page = SimpleNamespace(+ messages=[+ ChatMessage(+ id="hidden",+ role="user",+ content="private kickoff prompt",+ sequence=0,+ metadata={"hidden": True, "kind": "expert_kickoff"},+ ),+ ChatMessage(+ id="visible",+ role="assistant",+ content="Hello from your expert",+ sequence=1,+ ),+ ],+ has_more=False,+ oldest_sequence=0,+ )++ with patch(+ "backend.copilot.sharing.db.get_chat_messages_paginated",+ new=AsyncMock(return_value=page),+ ):+ result = await get_shared_chat_messages_paginated("token-A")++ assert result is not None+ assert [message.content for message in result.messages] == [+ "Hello from your expert"+ ]++@pytest.fixture()def mock_transaction():with patch("backend.copilot.sharing.db.transaction", return_value=_TxStub()) as m:diff --git a/autogpt_platform/backend/backend/copilot/turn_queue.py b/autogpt_platform/backend/backend/copilot/turn_queue.pyindex 46af2f6982..fc068e207e 100644--- a/autogpt_platform/backend/backend/copilot/turn_queue.py+++ b/autogpt_platform/backend/backend/copilot/turn_queue.py@@ -32,8 +32,11 @@ import loggingimport uuidfrom typing import Any, Mapping+from prisma.errors import UniqueViolationError+from backend.copilot.active_turns import TurnSlot, count_running_turnsfrom backend.copilot.config import ChatConfig, CopilotLlmAuthProvider+from backend.copilot.db import is_duplicate_chat_message_id_errorfrom backend.copilot.model import (CHAT_STATUS_IDLE,CHAT_STATUS_QUEUED,@@ -97,6 +100,7 @@ async def try_enqueue_turn(session_id: str,message: str,message_id: str | None = None,+ message_metadata: Mapping[str, Any] | None = None,is_user_message: bool = True,context: Mapping[str, str] | None = None,file_ids: list[str] | None = None,@@ -106,7 +110,7 @@ async def try_enqueue_turn(llm_credential_id: str | None = None,permissions: Mapping[str, Any] | None = None,request_arrival_at: float = 0.0,-) -> ChatMessage:+) -> ChatMessage | None:"""Admit a queued turn against the user's hard cap.Non-locked count-then-insert: under burst, two concurrent submits@@ -122,6 +126,7 @@ async def try_enqueue_turn(session_id=session_id,message=message,message_id=message_id,+ message_metadata=message_metadata,is_user_message=is_user_message,context=context,file_ids=file_ids,@@ -140,6 +145,7 @@ async def enqueue_turn(session_id: str,message: str,message_id: str | None = None,+ message_metadata: Mapping[str, Any] | None = None,is_user_message: bool = True,context: Mapping[str, str] | None = None,file_ids: list[str] | None = None,@@ -149,7 +155,7 @@ async def enqueue_turn(llm_credential_id: str | None = None,permissions: Mapping[str, Any] | None = None,request_arrival_at: float = 0.0,-) -> ChatMessage:+) -> ChatMessage | None:"""Persist the user's pending message and flip the session to``"queued"``. Caller is responsible for the in-flight cap checkAND session-ownership check upstream — once the row is committed@@ -159,7 +165,7 @@ async def enqueue_turn(The dispatcher's submit-time payload is stashed in the row's``metadata`` JSONB so a later promotion replays the turn faithfully."""- metadata: dict[str, Any] = {}+ metadata = dict(message_metadata or {})if context is not None:metadata["context"] = dict(context)if file_ids is not None:@@ -182,14 +188,19 @@ async def enqueue_turn(db = chat_db()async with _get_session_lock(session_id):live_sequence = await db.get_next_sequence(session_id)- row = await db.add_chat_message(- message_id=message_id or str(uuid.uuid4()),- session_id=session_id,- role="user" if is_user_message else "assistant",- content=message,- sequence=live_sequence,- metadata=metadata or None,- )+ try:+ row = await db.add_chat_message(+ message_id=message_id or str(uuid.uuid4()),+ session_id=session_id,+ role="user" if is_user_message else "assistant",+ content=message,+ sequence=live_sequence,+ metadata=metadata or None,+ )+ except UniqueViolationError as exc:+ if message_id and is_duplicate_chat_message_id_error(exc):+ return None+ raise# Flip the session to ``"queued"``. CAS-gated on ``"idle"`` so a# double-submit (session already queued/running) leaves the state# alone; the second pending message persists as a normal ChatMessagediff --git a/autogpt_platform/backend/backend/copilot/turn_queue_test.py b/autogpt_platform/backend/backend/copilot/turn_queue_test.pyindex d4ca89c6fb..369f01a981 100644--- a/autogpt_platform/backend/backend/copilot/turn_queue_test.py+++ b/autogpt_platform/backend/backend/copilot/turn_queue_test.py@@ -11,6 +11,7 @@ from datetime import datetime, timezonefrom unittest.mock import AsyncMock, MagicMock, patchimport pytest+from prisma.errors import UniqueViolationErrorfrom backend.copilot import turn_queuefrom backend.copilot.model import ChatMessage as PydanticChatMessage@@ -75,6 +76,7 @@ async def test_enqueue_turn_packs_metadata_into_metadata_payload() -> None:session_id="s1",message="hello",message_id="msg-1",+ message_metadata={"hidden": True, "kind": "expert_kickoff"},context={"url": "https://example.com"},file_ids=["f1", "f2"],mode="extended_thinking",@@ -93,6 +95,8 @@ async def test_enqueue_turn_packs_metadata_into_metadata_payload() -> None:assert metadata["llm_auth_provider"] == "platform"assert metadata["permissions"] == {"tool_filter": "allow"}assert metadata["request_arrival_at"] == 123.45+ assert metadata["hidden"] is True+ assert metadata["kind"] == "expert_kickoff"# Session is flipped idle → queued.db.update_chat_session_status.assert_awaited_once_with(session_id="s1", expect_status="idle", status="queued", user_id="u1"@@ -119,6 +123,34 @@ async def test_enqueue_turn_only_includes_default_transport_without_extra_params}+async def test_enqueue_turn_treats_duplicate_message_pk_as_already_queued() -> None:+ db = MagicMock()+ db.get_next_sequence = AsyncMock(return_value=1)+ db.add_chat_message = AsyncMock(+ side_effect=UniqueViolationError(+ {"user_facing_error": {"message": "ChatMessage_pkey"}}+ )+ )+ db.update_chat_session_status = AsyncMock()+ invalidate = AsyncMock()+ with (+ patch.object(turn_queue, "chat_db", return_value=db),+ patch.object(turn_queue, "_get_session_lock", return_value=_NoopAsyncCM()),+ patch.object(turn_queue, "invalidate_session_cache", new=invalidate),+ ):+ result = await turn_queue.enqueue_turn(+ user_id="u1",+ session_id="s1",+ message="kickoff",+ message_id="same-id",+ )++ assert result is None+ db.update_chat_session_status.assert_not_awaited()+ invalidate.assert_not_awaited()++# ── cancel_queued_turn ─────────────────────────────────────────────────diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsxindex ae19cdd418..cd58e950b1 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx@@ -48,6 +48,7 @@ export function CopilotChatHost({sessionChatStatus,expertIdentity,isAdoptingExpertSession,+ isKickoffStarting,} = useCopilotPage();return (@@ -90,6 +91,7 @@ export function CopilotChatHost({turnStats={turnStats}expertIdentity={expertIdentity}isAdoptingExpertSession={isAdoptingExpertSession}+ isKickoffStarting={isKickoffStarting}/></div><RateLimitGatediff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsxindex cfdc68df27..ce965ce4d8 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-errors.test.tsx@@ -5,8 +5,12 @@ import {} from "@/tests/integrations/copilot-sse";import { screen, waitFor } from "@testing-library/react";import type { UIMessageChunk } from "ai";+import { http, HttpResponse } from "msw";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { resetCopilotChatRegistry } from "../copilotChatRegistry";+import { useCopilotStreamStore } from "../copilotStreamStore";+import { getKickoffStatus, kickoffStorageKey } from "../expertKickoff";+import { useCopilotUIStore } from "../store";import {renderHost,TEST_BACKEND_BASE_URL,@@ -34,24 +38,40 @@ vi.mock("../helpers", async (importActual) => {});vi.mock("@/lib/auth/hooks/useAuth", () => ({- useAuth: () => ({ isUserLoading: false, isLoggedIn: true }),+ useAuth: () => ({+ user: { id: "test-user" },+ isUserLoading: false,+ isLoggedIn: true,+ }),}));+const flagState = vi.hoisted(() => ({ experts: false }));+vi.mock("@/services/feature-flags/use-get-flag", () => ({Flag: {ARTIFACTS: "ARTIFACTS",CHAT_MODE_OPTION: "CHAT_MODE_OPTION",ENABLE_PLATFORM_PAYMENT: "ENABLE_PLATFORM_PAYMENT",+ HIRE_EXPERTS: "HIRE_EXPERTS",},- useGetFlag: () => false,+ useGetFlag: (flag: string) =>+ flag === "HIRE_EXPERTS" ? flagState.experts : false,}));beforeEach(() => {resetCopilotChatRegistry();+ useCopilotStreamStore.getState().resetAll();+ useCopilotUIStore.setState({ initialPrompt: null });+ window.localStorage.clear();+ flagState.experts = false;});afterEach(() => {resetCopilotChatRegistry();+ useCopilotStreamStore.getState().resetAll();+ useCopilotUIStore.setState({ initialPrompt: null });+ window.localStorage.clear();+ flagState.experts = false;});describe("AutoPilot streaming — error paths", () => {@@ -101,6 +121,58 @@ describe("AutoPilot streaming — error paths", () => {).toBeDefined();});+ it("clears kickoff recovery state after an HTTP 429", async () => {+ const expertId = "3f8b0f7e-9f30-4a3b-a6a1-000000000001";+ flagState.experts = true;+ server.use(+ http.get("*/api/experts", () =>+ HttpResponse.json([+ {+ id: expertId,+ name: "Maria",+ avatar_url: null,+ role: "Operations expert",+ },+ ]),+ ),+ copilotStreamErrorHandler({+ baseUrl: TEST_BACKEND_BASE_URL,+ sessionId: TEST_SESSION_ID,+ status: 429,+ body: { detail: "You've reached your usage limit. Try again later." },+ }),+ );++ renderHost({+ searchParams: `?sessionId=${TEST_SESSION_ID}&expertId=${expertId}&kickoff=1`,+ sessionOverride: { expert_id: expertId },+ });++ expect(+ await screen.findByText(/daily autopilot limit reached/i, undefined, {+ timeout: 5000,+ }),+ ).toBeDefined();+ await waitFor(() =>+ expect(getKickoffStatus("test-user", expertId)).toBe("idle"),+ );+ expect(+ window.localStorage.getItem(kickoffStorageKey("test-user", expertId)),+ ).toBeNull();+ expect(useCopilotStreamStore.getState().getCoord(TEST_SESSION_ID)).toEqual({+ lastSubmittedMessageText: null,+ lastSubmittedKickoffExpertId: null,+ lastSubmittedKickoffAttemptToken: null,+ });+ expect(useCopilotUIStore.getState().initialPrompt).toBeNull();+ expect(+ useCopilotStreamStore+ .getState()+ .getMessageSnapshot(TEST_SESSION_ID)+ .filter((message) => message.role === "user"),+ ).toHaveLength(0);+ });+it("surfaces an HTTP 500 response as a visible error", async () => {server.use(copilotStreamErrorHandler({diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamStore.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamStore.test.tsindex 2fa3c9eac5..abd6648c82 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamStore.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamStore.test.ts@@ -58,6 +58,32 @@ describe("copilotStreamStore pending first send persistence", () => {).toEqual({ send: null, parts: [] });});+ it("restores expert kickoff metadata across the session-creation remount", async () => {+ const firstModule = await importFreshStore();+ const metadata = {+ kind: "expert_kickoff" as const,+ expertId: "3f8b0f7e-9f30-4a3b-a6a1-000000000001",+ attemptToken: "attempt-1",+ };+ const firstStore = firstModule.useCopilotStreamStore.getState();+ firstStore.setPendingFirstSend({+ text: "private kickoff prompt",+ files: [],+ metadata,+ });+ firstStore.bindPendingFirstSendToSession("expert-session");++ const secondModule = await importFreshStore();+ expect(+ secondModule.useCopilotStreamStore+ .getState()+ .takePendingFirstSend("expert-session"),+ ).toEqual({+ send: { text: "private kickoff prompt", files: [], metadata },+ parts: [],+ });+ });+it("does not consume a pending send for a different session", async () => {const firstModule = await importFreshStore();const firstStore = firstModule.useCopilotStreamStore.getState();diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.tsindex 9ed6b01bb8..df8140647a 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/copilotStreamTransport.test.ts@@ -11,6 +11,7 @@ vi.mock("../helpers", () => ({}));import { createCopilotTransport } from "../copilotStreamTransport";+import { buildKickoffMessage } from "../expertKickoff";const UUID_RE =/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;@@ -22,12 +23,13 @@ function makeRefs() {};}-function lastMessage(text: string) {+function lastMessage(text: string, metadata?: unknown) {return [{id: "ai-sdk-generated-id",role: "user" as const,parts: [{ type: "text" as const, text }],+ metadata,},];}@@ -135,3 +137,58 @@ describe("copilotStreamTransport.prepareSendMessagesRequest", () => {},);});++describe("copilotStreamTransport — expert kickoff routing", () => {+ const EXPERT_ID = "3f8b0f7e-9f30-4a3b-a6a1-000000000001";++ function prep(transport: ReturnType<typeof createCopilotTransport>) {+ return (+ transport as unknown as {+ prepareSendMessagesRequest: (args: {+ messages: Array<{+ id: string;+ role: "user" | "assistant";+ parts: Array<{ type: "text"; text: string }>;+ metadata?: unknown;+ }>;+ }) => Promise<{+ body: { message_id?: string; expert_kickoff?: boolean };+ }>;+ }+ ).prepareSendMessagesRequest;+ }++ it("marks kickoff requests while leaving the canonical id to the server", async () => {+ const transport = createCopilotTransport({+ sessionId: "sess-1",+ ...makeRefs(),+ });+ const kickoff = buildKickoffMessage(EXPERT_ID);++ const tabA = await prep(transport)({+ messages: lastMessage(kickoff.text, kickoff.metadata),+ });+ const tabB = await prep(transport)({+ messages: lastMessage(kickoff.text, kickoff.metadata),+ });++ expect(tabA.body.expert_kickoff).toBe(true);+ expect(tabA.body.message_id).toMatch(UUID_RE);+ expect(tabB.body.message_id).toMatch(UUID_RE);+ expect(tabB.body.message_id).not.toBe(tabA.body.message_id);+ });++ it("keeps random UUIDs for ordinary messages", async () => {+ const transport = createCopilotTransport({+ sessionId: "sess-1",+ ...makeRefs(),+ });++ const out = await prep(transport)({+ messages: lastMessage("You were just hired."),+ });++ expect(out.body.message_id).toMatch(UUID_RE);+ expect(out.body.expert_kickoff).toBe(false);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-kickoff.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-kickoff.test.tsxnew file mode 100644index 0000000000..287c1d974c--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expert-kickoff.test.tsx@@ -0,0 +1,463 @@+import { server } from "@/mocks/mock-server";+import { CredentialsProvidersContext } from "@/providers/agent-credentials/credentials-provider";+import {+ fireEvent,+ render,+ screen,+ waitFor,+} from "@/tests/integrations/test-utils";+import type { UIMessage } from "ai";+import { http, HttpResponse } from "msw";+import { parseAsString, useQueryState } from "nuqs";+import { withNuqsTestingAdapter } from "nuqs/adapters/testing";+import { useState } from "react";+import { afterEach, describe, expect, it, vi } from "vitest";+import { useCopilotStreamStore } from "../copilotStreamStore";+import {+ buildKickoffMessage,+ getKickoffAttemptToken,+ getKickoffStatus,+ isKickoffMessage,+ kickoffStorageKey,+ markKickoffDone,+ markKickoffPending,+} from "../expertKickoff";+import { useCopilotUIStore } from "../store";+import { useChatSession } from "../useChatSession";+import { useExpertKickoff } from "../useExpertKickoff";+import { useSendMessage } from "../useSendMessage";++const flagState = vi.hoisted(() => ({+ values: { "hire-experts": true } as Record<string, boolean>,+}));++vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {+ const actual =+ await importOriginal<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return {+ ...actual,+ useGetFlag: (flag: string) => flagState.values[flag] ?? false,+ };+});++const sendSpy = vi.hoisted(() => vi.fn());++const USER_ID = "user-1";+const EXPERT_ID = "3f8b0f7e-9f30-4a3b-a6a1-000000000001";+const KICKOFF_SESSION_ID = "4f8b0f7e-9f30-4a3b-a6a1-000000000001";+const EXISTING_SESSION_ID = "4f8b0f7e-9f30-4a3b-a6a1-000000000002";+const ORPHAN_SESSION_ID = "4f8b0f7e-9f30-4a3b-a6a1-000000000003";++function latestKickoffAttemptToken(messages: UIMessage[]) {+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ const attemptToken = getKickoffAttemptToken(messages[index]);+ if (attemptToken) return attemptToken;+ }+ return null;+}++afterEach(() => {+ server.resetHandlers();+ sendSpy.mockReset();+ flagState.values = { "hire-experts": true };+ window.localStorage.clear();+ useCopilotUIStore.setState({ adoptedExpertThreads: new Set<string>() });+ useCopilotStreamStore.getState().resetAll();+});++function KickoffHarness() {+ const [expertId] = useQueryState("expertId", parseAsString);+ const [kickoff] = useQueryState("kickoff", parseAsString);+ const [clientMessages, setClientMessages] = useState<UIMessage[]>([]);+ const [settledCount, setSettledCount] = useState(0);+ const {+ sessionId,+ setSessionId,+ sessionExpertId,+ hydratedMessages,+ createSession,+ refetchSession,+ } = useChatSession({ expertId });+ const isUserStoppingRef = { current: false };++ async function sendMessage(input: {+ text?: string;+ metadata?: UIMessage["metadata"];+ }) {+ sendSpy(input);+ setClientMessages((messages) => [+ ...messages,+ {+ id: `client-${messages.length + 1}`,+ role: "user",+ parts: [{ type: "text", text: input.text ?? "" }],+ metadata: input.metadata,+ },+ ]);+ }++ const { onSend } = useSendMessage({+ sessionId,+ sendMessage: sendMessage as never,+ createSession,+ isUserStoppingRef,+ });++ const { isKickoffStarting } = useExpertKickoff({+ userId: USER_ID,+ expertId,+ kickoff: kickoff === "1",+ sessionId,+ sessionExpertId,+ hasPersistedExpertHistory:+ sessionId && hydratedMessages !== undefined+ ? hydratedMessages.some((message) => !isKickoffMessage(message))+ : null,+ kickoffAttemptToken: latestKickoffAttemptToken(clientMessages),+ isClientThreadEmpty: clientMessages.every(isKickoffMessage),+ onAdoptSession: setSessionId,+ async onKickoff(id, attemptToken) {+ const message = buildKickoffMessage(id, attemptToken);+ await onSend(message.text, undefined, undefined, message.metadata);+ },+ onSettled() {+ setSettledCount((count) => count + 1);+ },+ });++ return (+ <div>+ <div data-testid="session-id">{sessionId ?? "none"}</div>+ <div data-testid="kickoff-param">{kickoff ?? "none"}</div>+ <div data-testid="settled-count">{settledCount}</div>+ <div data-testid="kickoff-starting">{String(isKickoffStarting)}</div>+ <div data-testid="client-message-count">{clientMessages.length}</div>+ <button type="button" onClick={() => void refetchSession()}>+ Refresh session+ </button>+ </div>+ );+}++function renderKickoff(searchParams: string) {+ const Wrapper = withNuqsTestingAdapter({ searchParams, hasMemory: true });+ return render(+ <CredentialsProvidersContext.Provider value={{}}>+ <Wrapper>+ <KickoffHarness />+ </Wrapper>+ </CredentialsProvidersContext.Provider>,+ );+}++function stubTransports() {+ return http.get("*/api/chat/transports", () =>+ HttpResponse.json({+ transports: [+ {+ auth_provider: "platform",+ credential_id: null,+ label: "AutoGPT Platform",+ available: true,+ default: true,+ },+ ],+ }),+ );+}++function makeSessionPayload(id: string, messages: unknown[] = []) {+ return {+ id,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-02T00:00:00Z",+ user_id: USER_ID,+ expert_id: EXPERT_ID,+ messages,+ };+}++function persistedKickoffMessage() {+ const kickoff = buildKickoffMessage(EXPERT_ID);+ return {+ id: "5f8b0f7e-9f30-4a3b-a6a1-000000000001",+ role: "user",+ content: kickoff.text,+ metadata: {+ hidden: true,+ kind: "expert_kickoff",+ expert_id: EXPERT_ID,+ },+ created_at: "2026-01-01T00:00:00Z",+ };+}++function persistedAssistantMessage() {+ return {+ id: "5f8b0f7e-9f30-4a3b-a6a1-000000000002",+ role: "assistant",+ content: "I am ready to help.",+ created_at: "2026-01-01T00:00:01Z",+ };+}++describe("useExpertKickoff", () => {+ it("creates atomically and waits for server persistence before consuming kickoff", async () => {+ let createBody: unknown = null;+ let createCount = 0;+ let persistedMessages: unknown[] = [];+ server.use(+ stubTransports(),+ http.get("*/api/chat/sessions", () =>+ HttpResponse.json({ sessions: [], total: 0 }),+ ),+ http.post("*/api/chat/sessions", async ({ request }) => {+ createCount += 1;+ createBody = await request.json();+ return HttpResponse.json({+ id: KICKOFF_SESSION_ID,+ created_at: "2026-01-01T00:00:00Z",+ user_id: USER_ID,+ expert_id: EXPERT_ID,+ });+ }),+ http.get(`*/api/chat/sessions/${KICKOFF_SESSION_ID}`, () =>+ HttpResponse.json(+ makeSessionPayload(KICKOFF_SESSION_ID, persistedMessages),+ ),+ ),+ );++ renderKickoff(`?expertId=${EXPERT_ID}&kickoff=1`);++ await waitFor(() => expect(createCount).toBe(1));+ expect(createBody).toEqual({+ expert_id: EXPERT_ID,+ expert_kickoff: true,+ llm_auth_provider: "platform",+ });++ await waitFor(() => expect(sendSpy).toHaveBeenCalledTimes(1));+ expect(sendSpy).toHaveBeenCalledWith({+ text: buildKickoffMessage(EXPERT_ID).text,+ files: undefined,+ metadata: {+ kind: "expert_kickoff",+ expertId: EXPERT_ID,+ attemptToken: expect.any(String),+ },+ });+ expect(screen.getByTestId("client-message-count").textContent).toBe("1");+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("pending");+ expect(screen.getByTestId("kickoff-param").textContent).toBe("1");+ expect(screen.getByTestId("kickoff-starting").textContent).toBe("true");++ persistedMessages = [+ persistedKickoffMessage(),+ persistedAssistantMessage(),+ ];+ fireEvent.click(screen.getByRole("button", { name: "Refresh session" }));++ await waitFor(() =>+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("done"),+ );+ await waitFor(() =>+ expect(screen.getByTestId("settled-count").textContent).toBe("1"),+ );+ expect(screen.getByTestId("kickoff-starting").textContent).toBe("false");+ expect(sendSpy).toHaveBeenCalledTimes(1);+ expect(createCount).toBe(1);+ });++ it("does nothing on a second visit after persisted completion", async () => {+ const attemptToken = markKickoffPending(USER_ID, EXPERT_ID);+ markKickoffDone(USER_ID, EXPERT_ID, attemptToken);+ let listCount = 0;+ let createCount = 0;+ server.use(+ stubTransports(),+ http.get("*/api/chat/sessions", () => {+ listCount += 1;+ return HttpResponse.json({ sessions: [], total: 0 });+ }),+ http.post("*/api/chat/sessions", () => {+ createCount += 1;+ return HttpResponse.json({ id: "should-not-happen" });+ }),+ );++ renderKickoff(`?expertId=${EXPERT_ID}&kickoff=1`);++ await waitFor(() => expect(listCount).toBeGreaterThan(0));+ await waitFor(() =>+ expect(screen.getByTestId("settled-count").textContent).toBe("1"),+ );+ expect(sendSpy).not.toHaveBeenCalled();+ expect(createCount).toBe(0);+ expect(screen.getByTestId("session-id").textContent).toBe("none");+ });++ it("stands down while another tab holds a fresh pending latch", async () => {+ markKickoffPending(USER_ID, EXPERT_ID);+ let listCount = 0;+ let createCount = 0;+ server.use(+ stubTransports(),+ http.get("*/api/chat/sessions", () => {+ listCount += 1;+ return HttpResponse.json({ sessions: [], total: 0 });+ }),+ http.post("*/api/chat/sessions", () => {+ createCount += 1;+ return HttpResponse.json({ id: "should-not-happen" });+ }),+ );++ renderKickoff(`?expertId=${EXPERT_ID}&kickoff=1`);++ await waitFor(() => expect(listCount).toBeGreaterThan(0));+ expect(sendSpy).not.toHaveBeenCalled();+ expect(createCount).toBe(0);+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("pending");+ });++ it("releases pending state when atomic session creation fails", async () => {+ let createCount = 0;+ server.use(+ stubTransports(),+ http.get("*/api/chat/sessions", () =>+ HttpResponse.json({ sessions: [], total: 0 }),+ ),+ http.post("*/api/chat/sessions", () => {+ createCount += 1;+ return new HttpResponse(null, { status: 500 });+ }),+ );++ renderKickoff(`?expertId=${EXPERT_ID}&kickoff=1`);++ await waitFor(() => expect(createCount).toBe(1));+ await waitFor(() =>+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("idle"),+ );+ expect(sendSpy).not.toHaveBeenCalled();+ expect(+ window.localStorage.getItem(kickoffStorageKey(USER_ID, EXPERT_ID)),+ ).toBeNull();+ expect(screen.getByTestId("kickoff-starting").textContent).toBe("false");+ expect(screen.getByTestId("settled-count").textContent).toBe("1");+ });++ it("adopts a thread with history and retires kickoff without sending", async () => {+ let createCount = 0;+ let requestedExpertId: string | null = null;+ let requestedPinnedFirst: string | null = null;+ server.use(+ stubTransports(),+ http.get("*/api/chat/sessions", ({ request }) => {+ const url = new URL(request.url);+ requestedExpertId = url.searchParams.get("expert_id");+ requestedPinnedFirst = url.searchParams.get("pinned_first");+ return HttpResponse.json({+ sessions: [+ {+ id: EXISTING_SESSION_ID,+ title: "Maria thread",+ expert_id: EXPERT_ID,+ is_processing: false,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-02T00:00:00Z",+ },+ ],+ total: 1,+ });+ }),+ http.get(`*/api/chat/sessions/${EXISTING_SESSION_ID}`, () =>+ HttpResponse.json(+ makeSessionPayload(EXISTING_SESSION_ID, [+ {+ id: "5f8b0f7e-9f30-4a3b-a6a1-000000000002",+ role: "user",+ content: "Plan my week",+ created_at: "2026-01-01T00:00:00Z",+ },+ ]),+ ),+ ),+ http.post("*/api/chat/sessions", () => {+ createCount += 1;+ return HttpResponse.json({ id: "should-not-happen" });+ }),+ );++ renderKickoff(`?expertId=${EXPERT_ID}&kickoff=1`);++ await waitFor(() =>+ expect(screen.getByTestId("session-id").textContent).toBe(+ EXISTING_SESSION_ID,+ ),+ );+ await waitFor(() =>+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("done"),+ );+ expect(screen.getByTestId("kickoff-starting").textContent).toBe("false");+ expect(requestedExpertId).toBe(EXPERT_ID);+ expect(requestedPinnedFirst).toBe("false");+ expect(sendSpy).not.toHaveBeenCalled();+ expect(createCount).toBe(0);+ });++ it("recovers an adopted empty expert session without duplicate creation", async () => {+ let createCount = 0;+ server.use(+ stubTransports(),+ http.get("*/api/chat/sessions", () =>+ HttpResponse.json({+ sessions: [+ {+ id: ORPHAN_SESSION_ID,+ title: "New chat",+ expert_id: EXPERT_ID,+ is_processing: false,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ },+ ],+ total: 1,+ }),+ ),+ http.get(`*/api/chat/sessions/${ORPHAN_SESSION_ID}`, () =>+ HttpResponse.json(+ makeSessionPayload(ORPHAN_SESSION_ID, [persistedKickoffMessage()]),+ ),+ ),+ http.post("*/api/chat/sessions", () => {+ createCount += 1;+ return HttpResponse.json({ id: "should-not-happen" });+ }),+ );++ renderKickoff(`?expertId=${EXPERT_ID}&kickoff=1`);++ await waitFor(() =>+ expect(screen.getByTestId("session-id").textContent).toBe(+ ORPHAN_SESSION_ID,+ ),+ );+ await waitFor(() => expect(sendSpy).toHaveBeenCalledTimes(1));+ expect(sendSpy).toHaveBeenCalledWith({+ text: buildKickoffMessage(EXPERT_ID).text,+ files: undefined,+ metadata: {+ kind: "expert_kickoff",+ expertId: EXPERT_ID,+ attemptToken: expect.any(String),+ },+ });+ expect(createCount).toBe(0);+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("pending");+ expect(screen.getByTestId("kickoff-starting").textContent).toBe("true");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expertKickoff.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expertKickoff.test.tsnew file mode 100644index 0000000000..64396f08e0--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/expertKickoff.test.ts@@ -0,0 +1,248 @@+import type { UIMessage } from "ai";+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ buildKickoffMessage,+ clearKickoffPending,+ getKickoffAttemptTokenFromMetadata,+ getKickoffExpertId,+ getKickoffExpertIdFromMetadata,+ getKickoffStatus,+ isKickoffMessage,+ isKickoffText,+ kickoffStorageKey,+ markKickoffDone,+ markKickoffPending,+ parseLegacyKickoffExpertId,+ shouldClearKickoffParam,+ stripKickoffMessages,+ stripLegacyKickoffMarker,+ withKickoffLock,+} from "../expertKickoff";++const EXPERT_ID = "3f8b0f7e-9f30-4a3b-a6a1-000000000001";+const USER_ID = "user-1";++function userMessage(+ id: string,+ text: string,+ metadata?: UIMessage["metadata"],+): UIMessage {+ return {+ id,+ role: "user",+ parts: [{ type: "text", text }],+ metadata,+ } as UIMessage;+}++function assistantMessage(+ id: string,+ text: string,+ metadata?: UIMessage["metadata"],+): UIMessage {+ return {+ id,+ role: "assistant",+ parts: [{ type: "text", text }],+ metadata,+ } as UIMessage;+}++describe("buildKickoffMessage", () => {+ it("keeps routing data in metadata and sends a clean day-one prompt", () => {+ const message = buildKickoffMessage(EXPERT_ID, "attempt-1");++ expect(message.metadata).toEqual({+ kind: "expert_kickoff",+ expertId: EXPERT_ID,+ attemptToken: "attempt-1",+ });+ expect(getKickoffAttemptTokenFromMetadata(message.metadata)).toBe(+ "attempt-1",+ );+ expect(message.text).toContain("You were just hired.");+ expect(message.text).toContain("Introduce yourself in 2-3 sentences");+ expect(message.text).toContain("run_agent");+ expect(message.text).toContain("If no workflow is installed");+ expect(message.text).toContain("Never pretend a run succeeded.");+ expect(message.text).not.toContain("EXPERT_KICKOFF");+ expect(message.text).not.toContain(EXPERT_ID);+ });+});++describe("shouldClearKickoffParam", () => {+ it("preserves kickoff through a retryable expert-map error and recovery", () => {+ expect(shouldClearKickoffParam(true, false, null)).toBe(false);+ expect(shouldClearKickoffParam(true, true, EXPERT_ID)).toBe(false);+ });++ it("clears kickoff only when experts are disabled or a loaded map misses it", () => {+ expect(shouldClearKickoffParam(false, false, null)).toBe(true);+ expect(shouldClearKickoffParam(true, true, null)).toBe(true);+ });+});++describe("kickoff message identification", () => {+ it("uses first-class metadata without matching ordinary prose", () => {+ const kickoff = buildKickoffMessage(EXPERT_ID);++ expect(+ isKickoffMessage(userMessage("m1", kickoff.text, kickoff.metadata)),+ ).toBe(true);+ expect(+ isKickoffMessage(+ userMessage(+ "m2",+ "You were just hired. Introduce yourself in 2-3 sentences in your voice",+ ),+ ),+ ).toBe(false);+ expect(+ isKickoffMessage(assistantMessage("m3", kickoff.text, kickoff.metadata)),+ ).toBe(false);+ });++ it("accepts persisted snake-case metadata and rejects malformed metadata", () => {+ expect(+ getKickoffExpertIdFromMetadata({+ kind: "expert_kickoff",+ expert_id: EXPERT_ID,+ }),+ ).toBe(EXPERT_ID);+ expect(+ getKickoffExpertIdFromMetadata({+ kind: "expert_kickoff",+ expert_id: "not-a-uuid",+ }),+ ).toBeNull();+ expect(+ getKickoffExpertIdFromMetadata({ kind: "ordinary", expertId: EXPERT_ID }),+ ).toBeNull();+ });++ it("removes only kickoff messages from the transcript", () => {+ const kickoff = buildKickoffMessage(EXPERT_ID);+ const messages = [+ userMessage("m1", kickoff.text, kickoff.metadata),+ assistantMessage("m2", "Hi, I'm Maria. Here's my day-one plan."),+ userMessage("m3", "Sounds good, go ahead."),+ ];++ expect(stripKickoffMessages(messages).map((message) => message.id)).toEqual(+ ["m2", "m3"],+ );+ });++ it("strictly recognizes legacy markers for backward compatibility", () => {+ const legacy = `[[EXPERT_KICKOFF:${EXPERT_ID}]]\n\nLegacy prompt`;++ expect(parseLegacyKickoffExpertId(legacy)).toBe(EXPERT_ID);+ expect(isKickoffText(legacy)).toBe(true);+ expect(stripLegacyKickoffMarker(legacy)).toBe("Legacy prompt");+ expect(getKickoffExpertId(userMessage("legacy", legacy))).toBe(EXPERT_ID);+ expect(+ parseLegacyKickoffExpertId(`[[EXPERT_KICKOFF:${EXPERT_ID}] Legacy`),+ ).toBeNull();+ expect(+ parseLegacyKickoffExpertId("[[EXPERT_KICKOFF:not-a-uuid]]"),+ ).toBeNull();+ expect(+ parseLegacyKickoffExpertId(`prefix [[EXPERT_KICKOFF:${EXPERT_ID}]]`),+ ).toBeNull();+ });+});++describe("kickoff status state machine", () => {+ afterEach(() => {+ window.localStorage.clear();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it("uses a distinct, user-and-expert-scoped storage namespace", () => {+ expect(kickoffStorageKey(USER_ID, EXPERT_ID)).toBe(+ `expert-kickoff-status:${USER_ID}:${EXPERT_ID}`,+ );+ });++ it("walks idle → pending → done independently per user and expert", () => {+ const otherExpert = "3f8b0f7e-9f30-4a3b-a6a1-000000000002";+ const otherUser = "user-2";++ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("idle");+ const attemptToken = markKickoffPending(USER_ID, EXPERT_ID);+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("pending");+ markKickoffDone(USER_ID, EXPERT_ID, attemptToken);+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("done");+ expect(getKickoffStatus(USER_ID, otherExpert)).toBe("idle");+ expect(getKickoffStatus(otherUser, EXPERT_ID)).toBe("idle");+ });++ it("clearKickoffPending releases pending but never done", () => {+ const abandonedAttempt = markKickoffPending(USER_ID, EXPERT_ID);+ clearKickoffPending(USER_ID, EXPERT_ID, abandonedAttempt);+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("idle");++ const completedAttempt = markKickoffPending(USER_ID, EXPERT_ID);+ markKickoffDone(USER_ID, EXPERT_ID, completedAttempt);+ clearKickoffPending(USER_ID, EXPERT_ID, completedAttempt);+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("done");+ });++ it("expires stale pending state so a crashed tab cannot consume kickoff", () => {+ window.localStorage.setItem(+ kickoffStorageKey(USER_ID, EXPERT_ID),+ `pending:${Date.now() - 10 * 60 * 1000}:expired-attempt`,+ );+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("idle");+ });++ it("does not let an expired attempt overwrite or clear its retry", () => {+ const now = Date.now();+ const dateNow = vi.spyOn(Date, "now");+ dateNow.mockReturnValue(now - 10 * 60 * 1000);+ const expiredAttempt = markKickoffPending(USER_ID, EXPERT_ID);++ dateNow.mockReturnValue(now);+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("idle");+ const retryAttempt = markKickoffPending(USER_ID, EXPERT_ID);++ expect(markKickoffDone(USER_ID, EXPERT_ID, expiredAttempt)).toBe(false);+ clearKickoffPending(USER_ID, EXPERT_ID, expiredAttempt);+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("pending");++ expect(markKickoffDone(USER_ID, EXPERT_ID, retryAttempt)).toBe(true);+ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("done");+ });++ it("ignores unscoped legacy state so it cannot leak between accounts", () => {+ window.localStorage.setItem(`expert-kickoff-${EXPERT_ID}`, "1");+ window.localStorage.setItem(`expert-kickoff-status:${EXPERT_ID}`, "done");++ expect(getKickoffStatus(USER_ID, EXPERT_ID)).toBe("idle");+ });++ it("serializes cross-tab work with the Web Locks API", async () => {+ const request = vi.fn(+ async (_name: string, action: () => Promise<string>) => action(),+ );+ vi.stubGlobal("navigator", { locks: { request } });++ await expect(+ withKickoffLock(USER_ID, EXPERT_ID, async () => "started"),+ ).resolves.toBe("started");+ await expect(+ withKickoffLock("user-2", EXPERT_ID, async () => "also-started"),+ ).resolves.toBe("also-started");+ expect(request).toHaveBeenNthCalledWith(+ 1,+ `expert-kickoff-status:${USER_ID}:${EXPERT_ID}`,+ expect.any(Function),+ );+ expect(request).toHaveBeenNthCalledWith(+ 2,+ `expert-kickoff-status:user-2:${EXPERT_ID}`,+ expect.any(Function),+ );+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsxindex cce9a1dc4c..27ff21adde 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sse-helpers.tsx@@ -28,6 +28,7 @@ export interface SessionOverride {messages?: SessionDetailResponse["messages"];has_more_messages?: boolean;chat_status?: string;+ expert_id?: string | null;}/**@@ -47,6 +48,7 @@ export function sessionHandler(opts: SessionOverride = {}) {oldest_sequence: null,active_stream: opts.active_stream ?? null,metadata: { dry_run: false, builder_graph_id: null },+ expert_id: opts.expert_id ?? null,});}@@ -106,7 +108,9 @@ function Wrapper({* messages). The default Orval mocks return random faker data that flips the* input into "limit reached" or injects ghost queued chips, so we pin them.*/-export function renderHost(opts: { sessionOverride?: SessionOverride } = {}) {+export function renderHost(+ opts: { sessionOverride?: SessionOverride; searchParams?: string } = {},+) {server.use(sessionHandler(opts.sessionOverride),getGetV2GetCopilotUsageMockHandler200({@@ -139,7 +143,9 @@ export function renderHost(opts: { sessionOverride?: SessionOverride } = {}) {<CopilotChatHost droppedFiles={[]} onDroppedFilesConsumed={() => {}} />,{wrapper: ({ children }) => (- <Wrapper searchParams={`?sessionId=${TEST_SESSION_ID}`}>+ <Wrapper+ searchParams={opts.searchParams ?? `?sessionId=${TEST_SESSION_ID}`}+ >{children}</Wrapper>),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 79bcde0a6d..6841a03e3c 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@@ -21,6 +21,12 @@ import { getLatestTaskList } from "../TaskProgressBar/helpers";import { SharedChatNotice } from "./components/SharedChatNotice";import { useAutoOpenArtifacts } from "./useAutoOpenArtifacts";import type { ExpertIdentity } from "../../useExpertMap";+import {+ getKickoffAttemptToken,+ getKickoffExpertId,+ stripLegacyKickoffMarker,+ type ExpertKickoffMetadata,+} from "../../expertKickoff";export interface ChatContainerProps {messages: UIMessage<unknown, UIDataTypes, UITools>[];@@ -48,6 +54,7 @@ export interface ChatContainerProps {message: string,files?: File[],workspaceFiles?: WorkspaceAttachment[],+ metadata?: ExpertKickoffMetadata,) => void | Promise<void>;onStop: () => void;/** Called to enqueue a message while streaming (bypasses normal send flow). */@@ -71,6 +78,8 @@ export interface ChatContainerProps {* expert's latest thread — the composer stays locked so a draft can't be* lost to that navigation. */isAdoptingExpertSession?: boolean;+ /** True until a newly hired expert's first kickoff has been handed off. */+ isKickoffStarting?: boolean;}export const ChatContainer = ({messages,@@ -100,6 +109,7 @@ export const ChatContainer = ({turnStats,expertIdentity,isAdoptingExpertSession,+ isKickoffStarting,}: ChatContainerProps) => {const isArtifactsEnabled = useGetFlag(Flag.ARTIFACTS);const isTaskBarEnabled = useGetFlag(Flag.TASK_PROGRESS_BAR);@@ -125,7 +135,8 @@ export const ChatContainer = ({const isSessionUnavailable =!!isReconnecting || isLoadingSession || !!isSessionError;const isLimitReached = useIsUsageLimitReached();- const isInputDisabled = isSessionUnavailable || isLimitReached;+ const isInputDisabled =+ isSessionUnavailable || isLimitReached || !!isKickoffStarting;const inputLayoutId = "copilot-2-chat-input";// Measure the usage-limit overlay so the messages scroll area can pad its@@ -160,7 +171,26 @@ export const ChatContainer = ({.map((p) => p.text).join("");if (lastText) {- onSend(lastText);+ const kickoffExpertId = lastUserMsg+ ? getKickoffExpertId(lastUserMsg)+ : null;+ const kickoffAttemptToken = lastUserMsg+ ? getKickoffAttemptToken(lastUserMsg)+ : null;+ onSend(+ kickoffExpertId ? stripLegacyKickoffMarker(lastText) : lastText,+ undefined,+ undefined,+ kickoffExpertId+ ? {+ kind: "expert_kickoff",+ expertId: kickoffExpertId,+ ...(kickoffAttemptToken+ ? { attemptToken: kickoffAttemptToken }+ : {}),+ }+ : undefined,+ );}}, [messages, onSend]);@@ -257,6 +287,8 @@ export const ChatContainer = ({droppedFiles={droppedFiles}onDroppedFilesConsumed={onDroppedFilesConsumed}isAdoptingExpertSession={isAdoptingExpertSession}+ isKickoffStarting={isKickoffStarting}+ expertName={expertIdentity?.name}/>)}</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 1b6a5e06ba..dcc99ed4a5 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@@ -101,7 +101,9 @@ vi.mock("framer-motion", () => {});vi.mock("@/app/(platform)/copilot/components/ChatInput/ChatInput", () => ({- ChatInput: () => <div data-testid="chat-input" />,+ ChatInput: ({ disabled }: { disabled?: boolean }) => (+ <input data-testid="chat-input" disabled={disabled} />+ ),}));vi.mock("@/components/atoms/Tooltip/BaseTooltip", () => ({@@ -127,13 +129,19 @@ vi.mock("@/services/feature-flags/use-get-flag", () => ({vi.mock("../../ChatMessagesContainer/ChatMessagesContainer", () => ({ChatMessagesContainer: ({bottomContentPadding,+ onRetry,}: {bottomContentPadding?: number;+ onRetry?: () => void;}) => (<divdata-testid="chat-messages-container"data-bottom-padding={bottomContentPadding ?? 0}- />+ >+ <button type="button" onClick={onRetry}>+ Retry message+ </button>+ </div>),}));@@ -233,6 +241,43 @@ describe("ChatContainer", () => {expect(screen.queryByRole("alert")).toBeNull();});+ it("keeps the session composer disabled while expert kickoff is starting", () => {+ render(<ChatContainer {...baseProps} isKickoffStarting />);++ expect(+ (screen.getByTestId("chat-input") as HTMLInputElement).disabled,+ ).toBe(true);+ });++ it("preserves expert kickoff metadata when retrying its hidden prompt", () => {+ const onSend = vi.fn();+ const expertId = "3f8b0f7e-9f30-4a3b-a6a1-000000000001";+ const attemptToken = "attempt-1";+ render(+ <ChatContainer+ {...baseProps}+ onSend={onSend}+ messages={[+ {+ id: "kickoff",+ role: "user",+ parts: [{ type: "text", text: "private kickoff prompt" }],+ metadata: { kind: "expert_kickoff", expertId, attemptToken },+ },+ ]}+ />,+ );++ fireEvent.click(screen.getByRole("button", { name: "Retry message" }));++ expect(onSend).toHaveBeenCalledWith(+ "private kickoff prompt",+ undefined,+ undefined,+ { kind: "expert_kickoff", expertId, attemptToken },+ );+ });+it("does not render the shared-chat notice for unshared chats", async () => {render(<ChatContainer {...baseProps} />);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 70de1f03ca..fae4d00951 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@@ -20,6 +20,7 @@ import { TurnStatsBar } from "../JobStatsBar/TurnStatsBar";import { useElapsedTimer } from "../JobStatsBar/useElapsedTimer";import { CopilotPendingReviews } from "../CopilotPendingReviews/CopilotPendingReviews";import type { TurnStatsMap } from "../../helpers/convertChatSessionToUiMessages";+import { stripKickoffMessages } from "../../expertKickoff";import {buildRenderSegments,getTurnMessages,@@ -310,7 +311,7 @@ export function LoadMoreSentinel({}export function ChatMessagesContainer({- messages,+ messages: allMessages,status,error,isLoading,@@ -331,6 +332,12 @@ export function ChatMessagesContainer({fileUrlBuilder,expertIdentity,}: Props) {+ // The expert-kickoff control prompt is filtered at the transcript renderer+ // only so lifecycle, dedup and metadata-preserving retry logic still see it.+ const messages = useMemo(+ () => stripKickoffMessages(allMessages),+ [allMessages],+ );// The in-chat "progress in the sidebar" notice only applies to the old// sidebar surface — hide it entirely when the task bar is on.const isTaskBarEnabled = useGetFlag(Flag.TASK_PROGRESS_BAR);diff --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 e1badf79dc..b7992d7bd7 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@@ -2,6 +2,7 @@ import { act } from "@testing-library/react";import { render, screen, cleanup } from "@/tests/integrations/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { ChatMessagesContainer } from "../ChatMessagesContainer";+import { buildKickoffMessage } from "../../../expertKickoff";const mockScrollEl = {scrollHeight: 100,@@ -713,3 +714,62 @@ describe("ChatMessagesContainer — readOnly mode", () => {expect(screen.queryByTestId("queue-badge")).toBeNull();});});++// ── expert-kickoff hiding ─────────────────────────────────────────────────++describe("ChatMessagesContainer — expert kickoff hiding", () => {+ afterEach(() => {+ cleanup();+ });++ it("hides the marked kickoff user message but renders the reply", () => {+ const kickoff = buildKickoffMessage("3f8b0f7e-9f30-4a3b-a6a1-000000000001");+ render(+ <ChatMessagesContainer+ {...baseProps}+ hasMoreMessages={false}+ messages={[+ {+ id: "m1",+ role: "user",+ parts: [{ type: "text", text: kickoff.text }],+ metadata: kickoff.metadata,+ },+ {+ id: "m2",+ role: "assistant",+ parts: [{ type: "text", text: "Hi, I'm Maria." }],+ },+ ]}+ />,+ );++ expect(screen.queryAllByTestId("message-user")).toHaveLength(0);+ expect(screen.getAllByTestId("message-assistant").length).toBeGreaterThan(+ 0,+ );+ });++ it("keeps a user message that merely repeats the kickoff wording", () => {+ render(+ <ChatMessagesContainer+ {...baseProps}+ hasMoreMessages={false}+ messages={[+ {+ id: "m1",+ role: "user",+ parts: [+ {+ type: "text",+ text: "You were just hired. Introduce yourself in 2-3 sentences in your voice",+ },+ ],+ },+ ]}+ />,+ );++ expect(screen.getAllByTestId("message-user")).toHaveLength(1);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/__tests__/main.test.tsxindex a9d4d10da8..5036b68e7c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/__tests__/main.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/__tests__/main.test.tsx@@ -61,6 +61,15 @@ test("renders greeting and composer", async () => {expect(await screen.findByPlaceholderText(/./)).toBeDefined();});+test("shows a named kickoff status and withholds the empty composer", () => {+ render(<EmptySession {...baseProps} isKickoffStarting expertName="Maria" />);++ expect(screen.getByRole("status").textContent).toContain(+ "Opening Maria's workspace",+ );+ expect(screen.queryByPlaceholderText(/./)).toBeNull();+});+test("falls back to pulse strip when there is no briefing", async () => {mockPulseStripAgent();server.use(getGetBriefingsGetLatestBriefingMockHandler200(null));diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsxindex a1b5ac39cd..19cc75d693 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx@@ -23,6 +23,7 @@ import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import type { WorkspaceAttachment } from "../../helpers/workspaceAttachments";import { EmptyHero } from "./components/EmptyHero";import { GreetingLoader } from "./components/GreetingLoader";+import { ExpertKickoffLoader } from "./components/ExpertKickoffLoader/ExpertKickoffLoader";import { CopilotHome } from "../CopilotHome/CopilotHome";import { RecipientChip } from "../ChatInput/components/RecipientChip";import { useRecipientPicker } from "./useRecipientPicker";@@ -40,6 +41,8 @@ interface Props {droppedFiles?: File[];onDroppedFilesConsumed?: () => void;isAdoptingExpertSession?: boolean;+ isKickoffStarting?: boolean;+ expertName?: string;}export function EmptySession({@@ -50,6 +53,8 @@ export function EmptySession({droppedFiles,onDroppedFilesConsumed,isAdoptingExpertSession,+ isKickoffStarting,+ expertName,}: Props) {const { user } = useAuth();const greetingName = getGreetingName(user);@@ -91,6 +96,10 @@ export function EmptySession({};}, []);+ if (isKickoffStarting) {+ return <ExpertKickoffLoader expertName={expertName} />;+ }+return (<div className="relative flex h-full flex-1 items-start justify-center overflow-y-auto px-0 py-5 md:px-6 md:py-10">{!isBrainDumpEnabled && (diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/components/ExpertKickoffLoader/ExpertKickoffLoader.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/components/ExpertKickoffLoader/ExpertKickoffLoader.tsxnew file mode 100644index 0000000000..2279997aea--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/components/ExpertKickoffLoader/ExpertKickoffLoader.tsx@@ -0,0 +1,27 @@+import { OrbitLoader } from "../../../OrbitLoader/OrbitLoader";++interface Props {+ expertName?: string;+}++export function ExpertKickoffLoader({ expertName }: Props) {+ return (+ <div+ role="status"+ aria-live="polite"+ className="flex h-full flex-1 flex-col items-center justify-center gap-4 text-center"+ >+ <OrbitLoader size={32} />+ <div>+ <p className="text-base font-medium text-neutral-900">+ {expertName+ ? `Opening ${expertName}'s workspace`+ : "Opening workspace"}+ </p>+ <p className="mt-1 text-sm text-neutral-500">+ Your expert is getting ready to start.+ </p>+ </div>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.tsindex dc350ac078..796f6a6413 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamStore.ts@@ -1,6 +1,7 @@import type { FileUIPart, UIMessage } from "ai";import { create } from "zustand";import { createJSONStorage, persist } from "zustand/middleware";+import type { ExpertKickoffMetadata } from "./expertKickoff";/*** Per-session state. Zustand (not React refs) so it can survive events we@@ -24,10 +25,14 @@ import { createJSONStorage, persist } from "zustand/middleware";*/export interface SessionCoord {lastSubmittedMessageText: string | null;+ lastSubmittedKickoffExpertId: string | null;+ lastSubmittedKickoffAttemptToken: string | null;}const defaultCoord: SessionCoord = {lastSubmittedMessageText: null,+ lastSubmittedKickoffExpertId: null,+ lastSubmittedKickoffAttemptToken: null,};/**@@ -49,11 +54,12 @@ const defaultCoord: SessionCoord = {export interface PendingFirstSend {text: string;files: File[];+ metadata?: ExpertKickoffMetadata;}interface PersistedCopilotStreamState {sessions: Record<string, SessionCoord>;- pendingFirstSend: Pick<PendingFirstSend, "text"> | null;+ pendingFirstSend: Pick<PendingFirstSend, "text" | "metadata"> | null;pendingFirstSendSessionId: string | null;pendingFileParts: FileUIPart[];}@@ -103,7 +109,7 @@ export const useCopilotStreamStore = create<CopilotStreamStore>()(isStreaming: false,getCoord(sessionId) {- return get().sessions[sessionId] ?? defaultCoord;+ return { ...defaultCoord, ...get().sessions[sessionId] };},updateCoord(sessionId, patch) {set((state) => ({@@ -212,7 +218,10 @@ export const useCopilotStreamStore = create<CopilotStreamStore>()(return {sessions: state.sessions,pendingFirstSend: canRestorePending- ? { text: state.pendingFirstSend!.text }+ ? {+ text: state.pendingFirstSend!.text,+ metadata: state.pendingFirstSend!.metadata,+ }: null,pendingFirstSendSessionId: canRestorePending? state.pendingFirstSendSessionId@@ -227,7 +236,11 @@ export const useCopilotStreamStore = create<CopilotStreamStore>()(persisted.pendingFirstSend &&typeof persisted.pendingFirstSendSessionId === "string"? {- send: { text: persisted.pendingFirstSend.text, files: [] },+ send: {+ text: persisted.pendingFirstSend.text,+ files: [],+ metadata: persisted.pendingFirstSend.metadata,+ },sessionId: persisted.pendingFirstSendSessionId,parts: persisted.pendingFileParts ?? [],}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.tsindex 99803cae2f..9a517103f3 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/copilotStreamTransport.ts@@ -4,6 +4,7 @@ import type { ChatTransport, FileUIPart, UIMessage } from "ai";import { v4 as uuidv4 } from "uuid";import { createSmoothingTransform } from "./copilotStreamSmoothing";+import { getKickoffExpertIdFromMetadata } from "./expertKickoff";import { getCopilotAuthHeaders } from "./helpers";import type { CopilotLlmModel, CopilotMode } from "./store";@@ -64,6 +65,7 @@ export function createCopilotTransport({api: baseUrl,prepareSendMessagesRequest: async ({ messages }) => {const last = messages[messages.length - 1];+ const kickoffExpertId = getKickoffExpertIdFromMetadata(last.metadata);// Extract file_ids from FileUIPart entries on the messageconst fileIds = last.parts?.filter((p): p is FileUIPart => p.type === "file")@@ -73,11 +75,10 @@ export function createCopilotTransport({return match?.[1];}).filter(Boolean) as string[] | undefined;- // ``message_id`` becomes the persisted ``ChatMessage.id`` (PK) —- // Postgres' uniqueness constraint then makes the INSERT itself- // the atomic dedup primitive: a retransmit (SDK-internal retry,- // browser auto-retry, RMQ redelivery) lands on a duplicate PK- // and the backend short-circuits to subscribe-only.+ // ``message_id`` is the client idempotency key. The backend scopes it+ // to the authenticated user + session before using the result as the+ // persisted PK, so retransmits collide atomically without letting one+ // tenant preclaim another tenant's global ChatMessage id.//// Generated here (rather than in ``useSendMessage``) for two// reasons: (1) AI SDK's ``messageId`` arg on ``sendMessage`` is@@ -97,10 +98,12 @@ export function createCopilotTransport({file_ids: fileIds && fileIds.length > 0 ? fileIds : null,mode: copilotModeRef.current ?? null,model: copilotModelRef.current ?? null,- // Supplying options forces uuid's getRandomValues path. Unlike- // crypto.randomUUID, getRandomValues is available on plain-HTTP LAN- // origins used by the local single-container appliance.+ // Supplying options forces uuid's+ // getRandomValues path. Unlike crypto.randomUUID,+ // getRandomValues is available on plain-HTTP LAN origins used+ // by the local single-container appliance.message_id: uuidv4({}),+ expert_kickoff: kickoffExpertId !== null,},headers: await getCopilotAuthHeaders(),};diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/expertKickoff.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/expertKickoff.tsnew file mode 100644index 0000000000..08e4ca883e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/expertKickoff.ts@@ -0,0 +1,211 @@+import { isValidUUID } from "@/lib/utils";+import type { UIMessage } from "ai";++const EXPERT_KICKOFF_KIND = "expert_kickoff";+const KICKOFF_STORAGE_PREFIX = "expert-kickoff-status:";+const LEGACY_MARKER_PATTERN =+ /^\[\[EXPERT_KICKOFF:([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\]\](?:\n\n)?/i;+const PENDING_TTL_MS = 2 * 60 * 1000;++const KICKOFF_PROMPT =+ "You were just hired. Introduce yourself in 2-3 sentences in your voice. " ++ "If you have installed workflows, state the day-one job they support and " ++ "start the first bundled workflow with run_agent. If no workflow is " ++ "installed, explain the outcomes you can help with and ask which one to " ++ "start. If required access or credentials are missing, ask for exactly the " ++ "one connection the next job needs and why. Never pretend a run succeeded.";++export interface ExpertKickoffMetadata {+ kind: typeof EXPERT_KICKOFF_KIND;+ expertId: string;+ attemptToken?: KickoffAttemptToken;+}++export interface ExpertKickoffSend {+ text: string;+ metadata: ExpertKickoffMetadata;+}++export type KickoffStatus = "idle" | "pending" | "done";+export type KickoffAttemptToken = string;++export function buildKickoffMessage(+ expertId: string,+ attemptToken?: KickoffAttemptToken,+): ExpertKickoffSend {+ return {+ text: KICKOFF_PROMPT,+ metadata: {+ kind: EXPERT_KICKOFF_KIND,+ expertId,+ ...(attemptToken ? { attemptToken } : {}),+ },+ };+}++export function getKickoffExpertIdFromMetadata(+ metadata: unknown,+): string | null {+ if (!metadata || typeof metadata !== "object") return null;+ const value = metadata as Record<string, unknown>;+ if (value.kind !== EXPERT_KICKOFF_KIND) return null;+ const expertId = value.expertId ?? value.expert_id;+ return typeof expertId === "string" && isValidUUID(expertId)+ ? expertId+ : null;+}++export function getKickoffAttemptTokenFromMetadata(+ metadata: unknown,+): KickoffAttemptToken | null {+ if (!metadata || typeof metadata !== "object") return null;+ const value = metadata as Record<string, unknown>;+ if (value.kind !== EXPERT_KICKOFF_KIND) return null;+ const attemptToken = value.attemptToken;+ return typeof attemptToken === "string" &&+ attemptToken.length > 0 &&+ attemptToken.length <= 128+ ? attemptToken+ : null;+}++export function parseLegacyKickoffExpertId(text: string): string | null {+ const match = text.match(LEGACY_MARKER_PATTERN);+ return match?.[1] ?? null;+}++export function isKickoffText(text: string): boolean {+ return parseLegacyKickoffExpertId(text) !== null;+}++export function stripLegacyKickoffMarker(text: string): string {+ return text.replace(LEGACY_MARKER_PATTERN, "");+}++function firstTextPart(message: UIMessage): string | null {+ const part = message.parts.find(+ (candidate): candidate is Extract<typeof candidate, { type: "text" }> =>+ candidate.type === "text",+ );+ return part?.text ?? null;+}++export function getKickoffExpertId(message: UIMessage): string | null {+ if (message.role !== "user") return null;+ const metadataExpertId = getKickoffExpertIdFromMetadata(message.metadata);+ if (metadataExpertId) return metadataExpertId;+ const text = firstTextPart(message);+ return text ? parseLegacyKickoffExpertId(text) : null;+}++export function getKickoffAttemptToken(+ message: UIMessage,+): KickoffAttemptToken | null {+ if (message.role !== "user") return null;+ return getKickoffAttemptTokenFromMetadata(message.metadata);+}++export function isKickoffMessage(message: UIMessage): boolean {+ return getKickoffExpertId(message) !== null;+}++export function shouldClearKickoffParam(+ isExpertsEnabled: boolean,+ hasLoadedExperts: boolean,+ expertId: string | null,+): boolean {+ return !isExpertsEnabled || (hasLoadedExperts && expertId === null);+}++export function stripKickoffMessages<T extends UIMessage>(messages: T[]): T[] {+ return messages.filter((message) => !isKickoffMessage(message));+}++export function kickoffStorageKey(userId: string, expertId: string): string {+ return `${KICKOFF_STORAGE_PREFIX}${userId}:${expertId}`;+}++function readKickoffStorage(userId: string, expertId: string): string | null {+ return window.localStorage.getItem(kickoffStorageKey(userId, expertId));+}++export function getKickoffStatus(+ userId: string,+ expertId: string,+): KickoffStatus {+ if (typeof window === "undefined") return "idle";+ try {+ const value = readKickoffStorage(userId, expertId);+ if (value === null) return "idle";+ if (value === "done" || value === "1" || value.startsWith("done:")) {+ return "done";+ }+ if (!value.startsWith("pending:")) return "idle";+ const startedAt = Number(value.split(":", 2)[1]);+ return Number.isFinite(startedAt) && Date.now() - startedAt < PENDING_TTL_MS+ ? "pending"+ : "idle";+ } catch {+ return "idle";+ }+}++export function markKickoffPending(+ userId: string,+ expertId: string,+): KickoffAttemptToken {+ const attemptToken = `${Date.now()}:${crypto.randomUUID()}`;+ if (typeof window === "undefined") return attemptToken;+ try {+ window.localStorage.setItem(+ kickoffStorageKey(userId, expertId),+ `pending:${attemptToken}`,+ );+ } catch {+ return attemptToken;+ }+ return attemptToken;+}++export function markKickoffDone(+ userId: string,+ expertId: string,+ attemptToken: KickoffAttemptToken,+): boolean {+ if (typeof window === "undefined") return false;+ try {+ const current = readKickoffStorage(userId, expertId);+ const completed = `done:${attemptToken}`;+ if (current === completed) return true;+ if (current !== `pending:${attemptToken}`) return false;+ window.localStorage.setItem(kickoffStorageKey(userId, expertId), completed);+ return true;+ } catch {+ return false;+ }+}++export function clearKickoffPending(+ userId: string,+ expertId: string,+ attemptToken: KickoffAttemptToken,+): void {+ if (typeof window === "undefined") return;+ try {+ const value = readKickoffStorage(userId, expertId);+ if (value === `pending:${attemptToken}`) {+ window.localStorage.removeItem(kickoffStorageKey(userId, expertId));+ }+ } catch {+ return;+ }+}++export async function withKickoffLock<T>(+ userId: string,+ expertId: string,+ action: () => Promise<T>,+): Promise<T | undefined> {+ if (typeof navigator === "undefined" || !navigator.locks) return action();+ return navigator.locks.request(kickoffStorageKey(userId, expertId), action);+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/expertSessionQuery.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/expertSessionQuery.tsnew file mode 100644index 0000000000..4cf87bfab1--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/expertSessionQuery.ts@@ -0,0 +1,13 @@+import type { GetV2ListSessionsParams } from "@/app/api/__generated__/models/getV2ListSessionsParams";++const LATEST_EXPERT_SESSION_LIMIT = 1;++export function latestExpertSessionParams(+ expertId: string | null,+): GetV2ListSessionsParams {+ return {+ expert_id: expertId ?? undefined,+ limit: LATEST_EXPERT_SESSION_LIMIT,+ pinned_first: false,+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.tsindex 860043d907..eed06184f2 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/__tests__/convertChatSessionToUiMessages.test.ts@@ -61,6 +61,21 @@ describe("convertChatSessionMessagesToUiMessages", () => {expect(result.messages[0].role).toBe("user");});+ it("preserves persisted kickoff metadata on the hydrated UI message", () => {+ const metadata = {+ hidden: true,+ kind: "expert_kickoff",+ expert_id: "3f8b0f7e-9f30-4a3b-a6a1-000000000001",+ };+ const result = convertChatSessionMessagesToUiMessages(+ SESSION_ID,+ [{ role: "user", content: "kickoff", sequence: 0, metadata }],+ { isComplete: true },+ );++ expect(result.messages[0].metadata).toEqual(metadata);+ });+it("attaches a reasoning row between user/assistant to the surrounding assistant bubble", () => {const result = convertChatSessionMessagesToUiMessages(SESSION_ID,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.tsindex f35f4658eb..824c64a4ed 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/helpers/convertChatSessionToUiMessages.ts@@ -23,6 +23,7 @@ interface SessionChatMessage {sequence: number | null;duration_ms: number | null;created_at: string | null;+ metadata: unknown;}function coerceSessionChatMessages(@@ -63,6 +64,7 @@ function coerceSessionChatMessages(: msg.created_at instanceof Date? msg.created_at.toISOString(): null,+ metadata: msg.metadata,};}).filter((m): m is SessionChatMessage => m !== null);@@ -487,6 +489,7 @@ export function convertChatSessionMessagesToUiMessages(id: msgId,role: uiRole,parts,+ metadata: msg.metadata,});const patch: Partial<TurnStats> = {};diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.tsindex f37856ee0b..9fc844f5d5 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts@@ -23,6 +23,7 @@ import {resolveCopilotLLMAuthSelection,} from "./helpers/copilotLlmAuth";import { useCopilotStreamStore } from "./copilotStreamStore";+import { latestExpertSessionParams } from "./expertSessionQuery";interface UseChatSessionOptions {dryRun?: boolean;@@ -118,7 +119,7 @@ export function useChatSession({!adoptedExpertThreads.has(expertId);const latestExpertSessionQuery = useGetV2ListSessions(- { expert_id: expertId ?? undefined, limit: 1 },+ latestExpertSessionParams(expertId),{query: {enabled: canAdoptExpertSession,@@ -207,7 +208,7 @@ export function useChatSession({const { mutateAsync: createSessionMutation, isPending: isCreatingSession } =usePostV2CreateSession();- async function createSession() {+ async function createSession(options?: { expertKickoff?: boolean }) {if (sessionId) return sessionId;// Latched for the life of this mount, including on failure: once the user// has asked for a new thread, auto-navigating them into an old one is@@ -272,6 +273,7 @@ export function useChatSession({}if (dryRun) sessionData.dry_run = true;if (expertId) sessionData.expert_id = expertId;+ if (options?.expertKickoff) sessionData.expert_kickoff = true;const body =Object.keys(sessionData).length > 0? { data: sessionData }diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.tsindex 354ab1f114..79dda47e1c 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts@@ -1,9 +1,10 @@import { toast } from "@/components/molecules/Toast/use-toast";import { useAuth } from "@/lib/auth/hooks/useAuth";+import { isValidUUID } from "@/lib/utils";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import type { UIMessage } from "ai";import { parseAsString, useQueryState } from "nuqs";-import { useMemo, useRef } from "react";+import { useEffect, useMemo, useRef } from "react";import { concatWithAssistantMerge } from "./helpers/convertChatSessionToUiMessages";import { getLatestAssistantStatusMessage } from "./helpers";import type { WorkspaceAttachment } from "./helpers/workspaceAttachments";@@ -13,6 +14,14 @@ import { useCopilotStreamStore } from "./copilotStreamStore";import { useCopilotPendingChips } from "./useCopilotPendingChips";import { useCopilotUIStore } from "./store";import { useChatSession } from "./useChatSession";+import {+ buildKickoffMessage,+ getKickoffAttemptToken,+ isKickoffMessage,+ shouldClearKickoffParam,+ type ExpertKickoffMetadata,+} from "./expertKickoff";+import { useExpertKickoff } from "./useExpertKickoff";import { useCopilotNotifications } from "./useCopilotNotifications";import { useCopilotStream } from "./useCopilotStream";import { useExpertMap } from "./useExpertMap";@@ -45,20 +54,59 @@ function hasAssistantTail(messages: UIMessage[]) {return lastUserIndex !== -1 && lastUserIndex < messages.length - 1;}+function getLatestKickoffAttemptToken(messages: UIMessage[]) {+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ const attemptToken = getKickoffAttemptToken(messages[index]);+ if (attemptToken) return attemptToken;+ }+ return null;+}+export function useCopilotPage() {const { user, isUserLoading, isLoggedIn } = useAuth();const isModeToggleEnabled = useGetFlag(Flag.CHAT_MODE_OPTION);const isExpertsEnabled = useGetFlag(Flag.HIRE_EXPERTS);const isBrainDumpEnabled = useGetFlag(Flag.ONBOARDING_BRAIN_DUMP);const [expertIdParam] = useQueryState("expertId", parseAsString);- const expertId = isExpertsEnabled ? expertIdParam : null;- const { expertsById } = useExpertMap();+ const [kickoffParam, setKickoffParam] = useQueryState(+ "kickoff",+ parseAsString,+ );+ const { expertsById, isLoadingExperts, hasLoadedExperts } = useExpertMap();+ const validExpertIdParam =+ expertIdParam && isValidUUID(expertIdParam) ? expertIdParam : null;+ const expertId =+ isExpertsEnabled &&+ hasLoadedExperts &&+ validExpertIdParam &&+ expertsById.has(validExpertIdParam)+ ? validExpertIdParam+ : null;+ const isKickoffResolving =+ isExpertsEnabled &&+ kickoffParam === "1" &&+ validExpertIdParam !== null &&+ isLoadingExperts;++ useEffect(() => {+ if (kickoffParam !== "1") return;+ if (!shouldClearKickoffParam(isExpertsEnabled, hasLoadedExperts, expertId))+ return;+ void setKickoffParam(null, { history: "replace" });+ }, [+ expertId,+ hasLoadedExperts,+ isExpertsEnabled,+ kickoffParam,+ setKickoffParam,+ ]);const { copilotChatMode, copilotLlmModel, isDryRun } = useCopilotUIStore();const { mutate: completeGreeting } = useCompleteBrainDumpGreeting();const {sessionId,+ setSessionId,sessionExpertId,isAdoptingExpertSession,hydratedMessages,@@ -100,6 +148,7 @@ export function useCopilotPage() {rateLimitMessage,dismissRateLimit,} = useCopilotStream({+ userId: user?.id ?? null,sessionId,hydratedMessages,hasActiveStream,@@ -107,6 +156,7 @@ export function useCopilotPage() {copilotMode: isModeToggleEnabled ? copilotChatMode : undefined,copilotModel: isModeToggleEnabled ? copilotLlmModel : undefined,});+ const kickoffAttemptToken = getLatestKickoffAttemptToken(currentMessages);const { pagedMessages, pagedTurnStats, hasMore, isLoadingMore, loadMore } =useLoadMoreMessages({@@ -202,6 +252,7 @@ export function useCopilotPage() {message: string,files?: File[],workspaceFiles?: WorkspaceAttachment[],+ metadata?: ExpertKickoffMetadata,) {const trimmed = message.trim();const hasAttachments =@@ -245,7 +296,7 @@ export function useCopilotPage() {err instanceof Error &&err.name === "QueueFollowUpNotActiveError") {- await sendNewMessage(message, files, workspaceFiles);+ await sendNewMessage(message, files, workspaceFiles, metadata);return;}toast({@@ -264,11 +315,38 @@ export function useCopilotPage() {if (sessionId) {isInflightRef.current = true;}- await sendNewMessage(message, files, workspaceFiles);+ await sendNewMessage(message, files, workspaceFiles, metadata);}useWorkflowImportAutoSubmit({ onSend, setPendingFileParts });+ const { isKickoffStarting } = useExpertKickoff({+ userId: user?.id ?? null,+ expertId,+ kickoff: isExpertsEnabled && kickoffParam === "1",+ sessionId,+ sessionExpertId,+ hasPersistedExpertHistory:+ sessionId && hydratedMessages !== undefined+ ? hydratedMessages.some((message) => !isKickoffMessage(message))+ : null,+ kickoffAttemptToken,+ isClientThreadEmpty: messages.every(isKickoffMessage),+ onAdoptSession: setSessionId,+ async onKickoff(id, attemptToken) {+ const kickoffMessage = buildKickoffMessage(id, attemptToken);+ await sendNewMessage(+ kickoffMessage.text,+ undefined,+ undefined,+ kickoffMessage.metadata,+ );+ },+ onSettled() {+ void setKickoffParam(null, { history: "replace" });+ },+ });+useSessionTitlePoll({ sessionId, status, isReconnecting });return {@@ -307,5 +385,6 @@ export function useCopilotPage() {sessionChatStatus,expertIdentity,isAdoptingExpertSession,+ isKickoffStarting: isKickoffResolving || isKickoffStarting,};}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.tsindex ef632aab28..6c19950e6f 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotStream.ts@@ -16,6 +16,13 @@ import {} from "./copilotChatRegistry";import { handleStreamError } from "./copilotStreamErrorHandlers";import { useCopilotStreamStore } from "./copilotStreamStore";+import {+ clearKickoffPending,+ getKickoffAttemptTokenFromMetadata,+ getKickoffExpertId,+ getKickoffExpertIdFromMetadata,+ withKickoffLock,+} from "./expertKickoff";import {deduplicateMessages,extractSendMessageText,@@ -60,6 +67,7 @@ const FINISH_REFETCH_ATTEMPTS_PENDING_SWITCH = 8;const STREAM_RENDER_THROTTLE_MS = 30;interface UseCopilotStreamArgs {+ userId?: string | null;sessionId: string | null;hydratedMessages: UIMessage[] | undefined;hasActiveStream: boolean;@@ -71,6 +79,7 @@ interface UseCopilotStreamArgs {}export function useCopilotStream({+ userId = null,sessionId,hydratedMessages,hasActiveStream,@@ -192,6 +201,15 @@ export function useCopilotStream({function handleError(error: Error) {if (!sessionId) return;+ const coord = useCopilotStreamStore.getState().getCoord(sessionId);+ const kickoffExpertId = coord.lastSubmittedKickoffExpertId;+ const kickoffAttemptToken = coord.lastSubmittedKickoffAttemptToken;+ function releaseKickoffPending() {+ if (!userId || !kickoffExpertId || !kickoffAttemptToken) return;+ void withKickoffLock(userId, kickoffExpertId, async () => {+ clearKickoffPending(userId, kickoffExpertId, kickoffAttemptToken);+ }).catch(() => undefined);+ }handleStreamError({error,onRateLimit: (message) => {@@ -199,29 +217,45 @@ export function useCopilotStream({// optimistic user bubble added by useChat is a lie. Restore the text// into the composer (via the same store slot URL pre-fills use) and// drop the unsent bubble so the user can edit/resend after reset.- const unsentText =- useCopilotStreamStore.getState().getCoord(sessionId)- .lastSubmittedMessageText ?? null;+ const coord = useCopilotStreamStore.getState().getCoord(sessionId);+ const unsentText = coord.lastSubmittedMessageText;if (unsentText) {- // The 429 callback fires async — by the time it lands, the user- // may have started typing a new draft. Only restore + clear the- // recovery slot when the composer is empty; otherwise leave the- // unsent text in the per-session store so a reload / resume can- // surface it later instead of silently dropping it.- const composer = document.getElementById(- "chat-input",- ) as HTMLTextAreaElement | null;- const composerEmpty = !composer || composer.value.length === 0;- if (composerEmpty) {- setInitialPrompt(unsentText);- useCopilotStreamStore- .getState()- .updateCoord(sessionId, { lastSubmittedMessageText: null });+ // The expert-kickoff control prompt must never surface in the+ // user's composer — drop the recovery slot instead of restoring+ // it. Its bubble below is dropped too; the once-per-expert+ // pending latch expires so a later visit can retry the kickoff.+ if (kickoffExpertId) {+ useCopilotStreamStore.getState().updateCoord(sessionId, {+ lastSubmittedMessageText: null,+ lastSubmittedKickoffExpertId: null,+ lastSubmittedKickoffAttemptToken: null,+ });+ } else {+ // The 429 callback fires async — by the time it lands, the user+ // may have started typing a new draft. Only restore + clear the+ // recovery slot when the composer is empty; otherwise leave the+ // unsent text in the per-session store so a reload / resume can+ // surface it later instead of silently dropping it.+ const composer = document.getElementById(+ "chat-input",+ ) as HTMLTextAreaElement | null;+ const composerEmpty = !composer || composer.value.length === 0;+ if (composerEmpty) {+ setInitialPrompt(unsentText);+ useCopilotStreamStore.getState().updateCoord(sessionId, {+ lastSubmittedMessageText: null,+ lastSubmittedKickoffExpertId: null,+ lastSubmittedKickoffAttemptToken: null,+ });+ }}setMessages((prev) => {const last = prev[prev.length - 1];- if (last?.role === "user") return prev.slice(0, -1);- return prev;+ const next = last?.role === "user" ? prev.slice(0, -1) : prev;+ useCopilotStreamStore+ .getState()+ .setMessageSnapshot(sessionId, next);+ return next;});}setRateLimitMessage(message);@@ -229,6 +263,20 @@ export function useCopilotStream({onReconnect: () => handleReconnectRef.current(),isUserStoppingRef,});+ if (kickoffExpertId) {+ releaseKickoffPending();+ useCopilotStreamStore.getState().updateCoord(sessionId, {+ lastSubmittedMessageText: null,+ lastSubmittedKickoffExpertId: null,+ lastSubmittedKickoffAttemptToken: null,+ });+ setMessages((prev) => {+ const last = prev[prev.length - 1];+ const next = last?.role === "user" ? prev.slice(0, -1) : prev;+ useCopilotStreamStore.getState().setMessageSnapshot(sessionId, next);+ return next;+ });+ }}function handleData(dataPart: { type: string; data?: unknown }) {@@ -259,7 +307,14 @@ export function useCopilotStream({chatRuntime.onError = undefined;}};- }, [chatRuntime, sessionId, refetchSession]);+ }, [+ chatRuntime,+ sessionId,+ refetchSession,+ setInitialPrompt,+ setMessages,+ userId,+ ]);// Flipped to ``true`` the first time the user actually hits Send on this// mount. Lets the ``hasConnectedThisMountRef`` latch below distinguish@@ -337,6 +392,12 @@ export function useCopilotStream({...args: Parameters<typeof sdkSendMessage>): ReturnType<typeof sdkSendMessage> {const text = extractSendMessageText(args[0]);+ const metadata =+ args[0] && typeof args[0] === "object" && "metadata" in args[0]+ ? args[0].metadata+ : undefined;+ const kickoffExpertId = getKickoffExpertIdFromMetadata(metadata);+ const kickoffAttemptToken = getKickoffAttemptTokenFromMetadata(metadata);const sid = sessionId;const coord = sid ? useCopilotStreamStore.getState().getCoord(sid) : null;@@ -362,9 +423,11 @@ export function useCopilotStream({if (sid) {markCopilotChatRuntimeHealthy(sid);- useCopilotStreamStore- .getState()- .updateCoord(sid, { lastSubmittedMessageText: text });+ useCopilotStreamStore.getState().updateCoord(sid, {+ lastSubmittedMessageText: text,+ lastSubmittedKickoffExpertId: kickoffExpertId,+ lastSubmittedKickoffAttemptToken: kickoffAttemptToken,+ });}hasSentThisMountRef.current = true;if (isUserStoppingRef.current) {@@ -385,6 +448,25 @@ export function useCopilotStream({useCopilotStreamStore.getState().setMessageSnapshot(sessionId, messages);}, [sessionId, messages]);+ useEffect(() => {+ if (!sessionId || !hydratedMessages) return;+ const coord = useCopilotStreamStore.getState().getCoord(sessionId);+ const kickoffExpertId = coord.lastSubmittedKickoffExpertId;+ if (!kickoffExpertId) return;+ if (+ !hydratedMessages.some(+ (message) => getKickoffExpertId(message) === kickoffExpertId,+ )+ ) {+ return;+ }+ useCopilotStreamStore.getState().updateCoord(sessionId, {+ lastSubmittedMessageText: null,+ lastSubmittedKickoffExpertId: null,+ lastSubmittedKickoffAttemptToken: null,+ });+ }, [hydratedMessages, sessionId]);+// Cheap signal that changes on any stream activity — drives the stall// watchdog. Counts messages, the last message's parts, and the total// text length on the last message so in-place part updates (tokendiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertKickoff.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertKickoff.tsnew file mode 100644index 0000000000..ee22ae18d1--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertKickoff.ts@@ -0,0 +1,219 @@+import {+ useGetV2ListChatTransports,+ useGetV2ListSessions,+} from "@/app/api/__generated__/endpoints/chat/chat";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";+import { useEffect, useRef, useState } from "react";+import {+ clearKickoffPending,+ getKickoffStatus,+ markKickoffDone,+ markKickoffPending,+ type KickoffAttemptToken,+ withKickoffLock,+} from "./expertKickoff";+import { latestExpertSessionParams } from "./expertSessionQuery";++interface Args {+ userId: string | null;+ expertId: string | null;+ kickoff: boolean;+ sessionId: string | null;+ sessionExpertId: string | null;+ hasPersistedExpertHistory: boolean | null;+ kickoffAttemptToken: KickoffAttemptToken | null;+ isClientThreadEmpty: boolean;+ onAdoptSession: (sessionId: string) => void;+ onKickoff: (+ expertId: string,+ attemptToken: KickoffAttemptToken,+ ) => Promise<void>;+ onSettled: () => void;+}++export function useExpertKickoff({+ userId,+ expertId,+ kickoff,+ sessionId,+ sessionExpertId,+ hasPersistedExpertHistory,+ kickoffAttemptToken,+ isClientThreadEmpty,+ onAdoptSession,+ onKickoff,+ onSettled,+}: Args) {+ const isExpertsEnabled = useGetFlag(Flag.HIRE_EXPERTS);+ const firedRef = useRef(false);+ const settledRef = useRef(false);+ const attemptTokenRef = useRef<KickoffAttemptToken | null>(null);+ const [failedKickoff, setFailedKickoff] = useState<{+ userId: string;+ expertId: string;+ } | null>(null);+ const isArmed = isExpertsEnabled && kickoff && !!userId && !!expertId;+ const wantsSession = isArmed && !sessionId && !!expertId;+ const wantsCreatePath =+ wantsSession &&+ !!userId &&+ !!expertId &&+ getKickoffStatus(userId, expertId) === "idle";++ const sessionsQuery = useGetV2ListSessions(+ latestExpertSessionParams(expertId),+ {+ query: {+ enabled: wantsSession,+ refetchOnWindowFocus: false,+ refetchInterval:+ wantsSession &&+ userId &&+ expertId &&+ getKickoffStatus(userId, expertId) === "pending"+ ? 1_000+ : false,+ },+ },+ );+ const transportsQuery = useGetV2ListChatTransports({+ query: { enabled: wantsCreatePath },+ });++ const onKickoffRef = useRef(onKickoff);+ const onAdoptSessionRef = useRef(onAdoptSession);+ const onSettledRef = useRef(onSettled);++ useEffect(() => {+ onKickoffRef.current = onKickoff;+ onAdoptSessionRef.current = onAdoptSession;+ onSettledRef.current = onSettled;+ }, [onAdoptSession, onKickoff, onSettled]);++ useEffect(() => {+ firedRef.current = false;+ settledRef.current = false;+ attemptTokenRef.current = null;+ }, [expertId, userId]);++ useEffect(() => {+ if (kickoffAttemptToken) attemptTokenRef.current = kickoffAttemptToken;+ }, [kickoffAttemptToken]);++ const settleKickoff = useRef(() => {+ if (settledRef.current) return;+ settledRef.current = true;+ onSettledRef.current();+ }).current;++ const fireKickoff = useRef(+ async (ownerId: string, id: string, attemptToken: KickoffAttemptToken) => {+ try {+ await onKickoffRef.current(id, attemptToken);+ } catch {+ clearKickoffPending(ownerId, id, attemptToken);+ firedRef.current = false;+ setFailedKickoff({ userId: ownerId, expertId: id });+ settleKickoff();+ }+ },+ ).current;++ const beginKickoff = useRef((ownerId: string, id: string) => {+ if (firedRef.current) return;+ firedRef.current = true;+ void withKickoffLock(ownerId, id, async () => {+ if (getKickoffStatus(ownerId, id) !== "idle") {+ firedRef.current = false;+ return;+ }+ const attemptToken = markKickoffPending(ownerId, id);+ attemptTokenRef.current = attemptToken;+ await fireKickoff(ownerId, id, attemptToken);+ }).catch(() => {+ firedRef.current = false;+ setFailedKickoff({ userId: ownerId, expertId: id });+ settleKickoff();+ });+ }).current;++ useEffect(() => {+ if (!isArmed || !userId || !expertId) return;+ if (getKickoffStatus(userId, expertId) !== "done") return;+ settleKickoff();+ }, [expertId, isArmed, settleKickoff, userId]);++ useEffect(() => {+ if (!isArmed || !userId || !expertId || sessionId) return;+ const sessions =+ sessionsQuery.data?.status === 200+ ? sessionsQuery.data.data.sessions+ : null;+ if (sessions !== null && sessions.length > 0) {+ onAdoptSessionRef.current(sessions[0].id);+ return;+ }+ if (sessions === null && !sessionsQuery.isError) return;+ if (getKickoffStatus(userId, expertId) !== "idle") return;+ if (transportsQuery.data?.status !== 200) return;+ beginKickoff(userId, expertId);+ }, [+ beginKickoff,+ expertId,+ isArmed,+ sessionId,+ sessionsQuery.data,+ sessionsQuery.isError,+ transportsQuery.data,+ userId,+ ]);++ useEffect(() => {+ if (!isArmed || !userId || !expertId || !sessionId) return;+ if (sessionExpertId !== expertId || hasPersistedExpertHistory === null)+ return;++ if (hasPersistedExpertHistory) {+ const attemptToken = attemptTokenRef.current;+ if (attemptToken) {+ void withKickoffLock(userId, expertId, async () => {+ markKickoffDone(userId, expertId, attemptToken);+ }).catch(() => undefined);+ } else {+ void withKickoffLock(userId, expertId, async () => {+ if (getKickoffStatus(userId, expertId) !== "idle") return;+ const historyAttempt = markKickoffPending(userId, expertId);+ markKickoffDone(userId, expertId, historyAttempt);+ }).catch(() => undefined);+ }+ settleKickoff();+ return;+ }++ if (!isClientThreadEmpty) return;+ if (getKickoffStatus(userId, expertId) !== "idle") return;+ beginKickoff(userId, expertId);+ }, [+ beginKickoff,+ expertId,+ hasPersistedExpertHistory,+ isArmed,+ isClientThreadEmpty,+ sessionExpertId,+ sessionId,+ settleKickoff,+ userId,+ ]);++ return {+ isKickoffStarting:+ isExpertsEnabled &&+ kickoff &&+ !!userId &&+ !!expertId &&+ !(+ failedKickoff?.userId === userId && failedKickoff.expertId === expertId+ ) &&+ getKickoffStatus(userId, expertId) !== "done",+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.tsindex 18db149cf6..37db4e8847 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useSendMessage.ts@@ -4,6 +4,7 @@ import type { UseChatHelpers } from "@ai-sdk/react";import type { FileUIPart, UIMessage } from "ai";import { useEffect, useRef, useState } from "react";import { useCopilotStreamStore } from "./copilotStreamStore";+import type { ExpertKickoffMetadata } from "./expertKickoff";import {buildWorkspaceFilePart,workspaceFileDownloadUrl,@@ -24,7 +25,9 @@ type SendMessageFn = UseChatHelpers<UIMessage>["sendMessage"];interface Args {sessionId: string | null;sendMessage: SendMessageFn;- createSession: () => Promise<string | undefined>;+ createSession: (options?: {+ expertKickoff?: boolean;+ }) => Promise<string | undefined>;isUserStoppingRef: React.MutableRefObject<boolean>;}@@ -101,6 +104,7 @@ export function useSendMessage({text: string,files: File[],prebuiltParts: FileUIPart[],+ metadata?: ExpertKickoffMetadata,) {// The per-click UUID that becomes the backend's ``ChatMessage.id``// is generated inside the transport's ``prepareSendMessagesRequest``@@ -111,9 +115,10 @@ export function useSendMessage({// target and break the optimistic-render path that pushes the user// bubble into ``messages`` synchronously.if (files.length === 0) {- sendMessage({+ await sendMessage({text,files: prebuiltParts.length > 0 ? prebuiltParts : undefined,+ metadata,});return;}@@ -129,7 +134,7 @@ export function useSendMessage({// The workspace references didn't fail to upload (they need no upload),// so don't discard them just because the local uploads failed.if (prebuiltParts.length > 0) {- sendMessage({ text, files: prebuiltParts });+ await sendMessage({ text, files: prebuiltParts, metadata });return;}throw new Error("All file uploads failed");@@ -137,9 +142,10 @@ export function useSendMessage({// Merge already-stored workspace parts with the freshly uploaded ones so// a single message can mix both kinds of attachment.const allParts = [...prebuiltParts, ...buildFileParts(uploaded)];- sendMessage({+ await sendMessage({text,files: allParts.length > 0 ? allParts : undefined,+ metadata,});} finally {setIsUploadingFiles(false);@@ -159,13 +165,20 @@ export function useSendMessage({.getState().takePendingFirstSend(sessionId);if (!send) return;- void dispatchRef.current(sessionId, send.text, send.files, parts);+ void dispatchRef.current(+ sessionId,+ send.text,+ send.files,+ parts,+ send.metadata,+ );}, [sessionId]);async function onSend(message: string,files?: File[],workspaceFiles?: WorkspaceAttachment[],+ metadata?: ExpertKickoffMetadata,) {const trimmed = message.trim();const hasWorkspaceFiles = !!workspaceFiles && workspaceFiles.length > 0;@@ -200,10 +213,13 @@ export function useSendMessage({const { pendingFileParts, setPendingFileParts } =useCopilotStreamStore.getState();setPendingFileParts([]);- await dispatchToSession(sessionId, trimmed, files ?? [], [- ...pendingFileParts,- ...workspaceParts,- ]);+ await dispatchToSession(+ sessionId,+ trimmed,+ files ?? [],+ [...pendingFileParts, ...workspaceParts],+ metadata,+ );return;}@@ -218,9 +234,11 @@ export function useSendMessage({}useCopilotStreamStore.getState()- .setPendingFirstSend({ text: trimmed, files: files ?? [] });+ .setPendingFirstSend({ text: trimmed, files: files ?? [], metadata });try {- await createSession();+ await createSession({+ expertKickoff: metadata?.kind === "expert_kickoff",+ });} catch (err) {const { setPendingFirstSend, setPendingFileParts } =useCopilotStreamStore.getState();diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-section.test.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-section.test.tsxindex 128a071200..28da36cadb 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-section.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/__tests__/experts-section.test.tsx@@ -14,6 +14,21 @@ import { beforeEach, describe, expect, test, vi } from "vitest";import { MainMarkeplacePage } from "../components/MainMarketplacePage/MainMarketplacePage";const mockUseAuth = vi.hoisted(() => vi.fn());+const mockRouterPush = vi.hoisted(() => vi.fn());++vi.mock("next/navigation", () => ({+ useRouter: () => ({+ back: vi.fn(),+ forward: vi.fn(),+ prefetch: vi.fn(),+ push: mockRouterPush,+ refresh: vi.fn(),+ replace: vi.fn(),+ }),+ usePathname: () => "/marketplace",+ useSearchParams: () => new URLSearchParams(),+ useParams: () => ({}),+}));vi.mock("@/lib/auth/hooks/useAuth", () => ({useAuth: mockUseAuth,@@ -81,6 +96,7 @@ function renderMarketplace() {describe("Marketplace ExpertsSection", () => {beforeEach(() => {+ mockRouterPush.mockReset();mockUseAuth.mockReturnValue({user: { id: "user-1" },isLoggedIn: true,@@ -103,7 +119,11 @@ describe("Marketplace ExpertsSection", () => {);expect(await screen.findByText("Maria joined your team")).toBeDefined();- expect(await screen.findByText("Chat with Maria")).toBeDefined();+ expect(await screen.findByText("View team")).toBeDefined();+ expect(screen.queryByText("Chat with Maria")).toBeNull();+ expect(mockRouterPush).toHaveBeenCalledWith(+ `/copilot?expertId=${hiredMaria.id}&kickoff=1`,+ );});test("stays hidden and fetches nothing for signed-out visitors", async () => {diff --git a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/components/ExpertProfileSheet/useExpertProfileSheet.tsx b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/components/ExpertProfileSheet/useExpertProfileSheet.tsxindex be965a4fe0..815e90542c 100644--- a/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/components/ExpertProfileSheet/useExpertProfileSheet.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/marketplace/components/ExpertsSection/components/ExpertProfileSheet/useExpertProfileSheet.tsx@@ -14,6 +14,7 @@ import {type VoicePickResult,} from "@/components/organisms/VoicePicker/helpers";import { useQueryClient } from "@tanstack/react-query";+import { useRouter } from "next/navigation";import { useRef, useState } from "react";function celebrate(result: HireResult) {@@ -24,20 +25,9 @@ function celebrate(result: HireResult) {: undefined,variant: "success",action: (- <div className="flex gap-2">- <Button- as="NextLink"- href={`/copilot?expertId=${result.expert.id}`}- variant="secondary"- size="small"- unmask={false}- >- {`Chat with ${result.expert.name}`}- </Button>- <Button as="NextLink" href="/team" variant="ghost" size="small">- View team- </Button>- </div>+ <Button as="NextLink" href="/team" variant="ghost" size="small">+ View team+ </Button>),});}@@ -47,6 +37,7 @@ export function useExpertProfileSheet(onClose: () => void,) {const queryClient = useQueryClient();+ const router = useRouter();// Set once a hire succeeds for a persona that ships writing samples: it// swaps the sheet to the voice pick before the hire is celebrated.const [hireResult, setHireResult] = useState<HireResult | null>(null);@@ -71,7 +62,12 @@ export function useExpertProfileSheet(const completedHire = pendingCelebrationRef.current;pendingCelebrationRef.current = null;setHireResult(null);- if (completedHire) celebrate(completedHire);+ if (completedHire) {+ celebrate(completedHire);+ // Hiring isn't installing: hand the user straight to the expert's thread+ // with kickoff=1 so it introduces itself and starts its day-one job.+ router.push(`/copilot?expertId=${completedHire.expert.id}&kickoff=1`);+ }onClose();}@@ -83,14 +79,13 @@ export function useExpertProfileSheet(await queryClient.invalidateQueries({queryKey: getListExpertsQueryKey(),});+ pendingCelebrationRef.current = result;// Offer the voice pick when the persona ships writing samples; otherwise// finish with the classic celebration toast.if ((expert.voice_samples ?? []).length > 0) {- pendingCelebrationRef.current = result;setHireResult(result);return;}- celebrate(result);handleClose();} catch {toast({diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex 9f218ae935..a8415d3e96 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -3368,7 +3368,7 @@"get": {"tags": ["v2", "chat", "chat"],"summary": "List Sessions",- "description": "List chat sessions for the authenticated user.\n\nReturns a paginated list of chat sessions belonging to the current user,\nwith pinned sessions first and most-recently-updated as the tiebreaker.\n\nArgs:\n user_id: The authenticated user's ID.\n limit: Maximum number of sessions to return (1-100).\n offset: Number of sessions to skip for pagination.\n expert_id: Restrict the listing to sessions scoped to this expert.\n\nReturns:\n ListSessionsResponse: List of session summaries and total count.",+ "description": "List chat sessions for the authenticated user.\n\nReturns a paginated list of chat sessions belonging to the current user,\nwith pinned sessions first and most-recently-updated as the tiebreaker.\n\nArgs:\n user_id: The authenticated user's ID.\n limit: Maximum number of sessions to return (1-100).\n offset: Number of sessions to skip for pagination.\n expert_id: Restrict the listing to sessions scoped to this expert.\n pinned_first: Whether pinned sessions precede strict recency ordering.\n\nReturns:\n ListSessionsResponse: List of session summaries and total count.","operationId": "getV2ListSessions","security": [{ "HTTPBearerJWT": [] }],"parameters": [@@ -3406,6 +3406,18 @@],"title": "Expert Id"}+ },+ {+ "name": "pinned_first",+ "in": "query",+ "required": false,+ "schema": {+ "type": "boolean",+ "description": "Keep pinned sessions before recent sessions. Set false for strict recency when adopting the latest expert thread.",+ "default": true,+ "title": "Pinned First"+ },+ "description": "Keep pinned sessions before recent sessions. Set false for strict recency when adopting the latest expert thread."}],"responses": {@@ -3435,7 +3447,7 @@"post": {"tags": ["v2", "chat", "chat"],"summary": "Create Session",- "description": "Create (or get-or-create) a chat session.\n\nTwo modes, selected by the request body:\n\n- Default: create a fresh session for the user. ``dry_run=True`` forces\n run_block and run_agent calls to use dry-run simulation.\n- Builder-bound: when ``builder_graph_id`` is set, get-or-create keyed\n on ``(user_id, builder_graph_id)``. Returns the existing session for\n that graph or creates one locked to it. Graph ownership is validated\n inside :func:`get_or_create_builder_session`; raises 404 on\n unauthorized access. Write-side scope is enforced per-tool\n (``edit_agent`` / ``run_agent`` reject any ``agent_id`` other than\n the bound graph) and a small blacklist hides tools that conflict\n with the panel's scope (see :data:`BUILDER_BLOCKED_TOOLS`).\n\nArgs:\n user_id: The authenticated user ID parsed from the JWT (required).\n request: Optional request body with ``dry_run``,\n ``builder_graph_id`` and/or ``expert_id``.\n\nReturns:\n CreateSessionResponse: Details of the resulting session.",+ "description": "Create (or get-or-create) a chat session.\n\nTwo modes, selected by the request body:\n\n- Default: create a fresh session for the user. ``dry_run=True`` forces\n run_block and run_agent calls to use dry-run simulation.\n- Builder-bound: when ``builder_graph_id`` is set, get-or-create keyed\n on ``(user_id, builder_graph_id)``. Returns the existing session for\n that graph or creates one locked to it. Graph ownership is validated\n inside :func:`get_or_create_builder_session`; raises 404 on\n unauthorized access. Write-side scope is enforced per-tool\n (``edit_agent`` / ``run_agent`` reject any ``agent_id`` other than\n the bound graph) and a small blacklist hides tools that conflict\n with the panel's scope (see :data:`BUILDER_BLOCKED_TOOLS`).\n- Expert kickoff: atomically create or adopt the canonical first session\n for ``(user_id, expert_id)``.\n\nArgs:\n user_id: The authenticated user ID parsed from the JWT (required).\n request: Optional request body with ``dry_run``,\n ``builder_graph_id`` and/or ``expert_id``.\n\nReturns:\n CreateSessionResponse: Details of the resulting session.","operationId": "postV2CreateSession","security": [{ "HTTPBearerJWT": [] }],"requestBody": {@@ -16462,12 +16474,17 @@{ "type": "null" }],"title": "Expert Id"+ },+ "expert_kickoff": {+ "type": "boolean",+ "title": "Expert Kickoff",+ "default": false}},"additionalProperties": false,"type": "object","title": "CreateSessionRequest",- "description": "Request model for creating (or get-or-creating) a chat session.\n\nTwo modes, selected by the body:\n\n- Default: create a fresh session. ``dry_run`` is a **top-level**\n field — do not nest it inside ``metadata``.\n- Builder-bound: when ``builder_graph_id`` is set, the endpoint\n switches to **get-or-create** keyed on\n ``(user_id, builder_graph_id)``. The builder panel calls this on\n mount so the chat persists across refreshes. Graph ownership is\n validated inside :func:`get_or_create_builder_session`. Write-side\n scope is enforced per-tool (``edit_agent`` / ``run_agent`` reject\n any ``agent_id`` other than the bound graph) and a small blacklist\n hides tools that conflict with the panel's scope\n (``create_agent`` / ``customize_agent`` / ``get_agent_building_guide``\n — see :data:`BUILDER_BLOCKED_TOOLS`). Read-side lookups\n (``find_block``, ``find_agent``, ``search_docs``, …) stay open.\n\n``expert_id`` scopes the session to a hired expert. It must reference\nan expert owned by the caller that is neither a template nor archived,\notherwise the request is rejected with 404. It is mutually exclusive\nwith ``builder_graph_id`` (422) — builder-bound sessions are never\nexpert-scoped.\n\nExtra/unknown fields are rejected (422) to prevent silent mis-use."+ "description": "Request model for creating (or get-or-creating) a chat session.\n\nTwo modes, selected by the body:\n\n- Default: create a fresh session. ``dry_run`` is a **top-level**\n field — do not nest it inside ``metadata``.\n- Builder-bound: when ``builder_graph_id`` is set, the endpoint\n switches to **get-or-create** keyed on\n ``(user_id, builder_graph_id)``. The builder panel calls this on\n mount so the chat persists across refreshes. Graph ownership is\n validated inside :func:`get_or_create_builder_session`. Write-side\n scope is enforced per-tool (``edit_agent`` / ``run_agent`` reject\n any ``agent_id`` other than the bound graph) and a small blacklist\n hides tools that conflict with the panel's scope\n (``create_agent`` / ``customize_agent`` / ``get_agent_building_guide``\n — see :data:`BUILDER_BLOCKED_TOOLS`). Read-side lookups\n (``find_block``, ``find_agent``, ``search_docs``, …) stay open.\n\n``expert_id`` scopes the session to a hired expert. It must reference\nan expert owned by the caller that is neither a template nor archived,\notherwise the request is rejected with 404. It is mutually exclusive\nwith ``builder_graph_id`` (422) — builder-bound sessions are never\nexpert-scoped.\n\n``expert_kickoff`` switches expert creation to an atomic create-or-adopt\nmode keyed by the authenticated user and expert. It is invalid without\n``expert_id``.\n\nExtra/unknown fields are rejected (422) to prevent silent mis-use."},"CreateSessionResponse": {"properties": {@@ -24544,7 +24561,13 @@{ "type": "null" }],"title": "Message Id",- "description": "Optional per-click UUID generated by the frontend. Becomes the persisted ``ChatMessage.id`` (PK). Frontend / network / RMQ-redelivery retransmits of the same logical send reuse the id, so the Postgres unique-constraint on the PK is the atomic dedup primitive: a duplicate INSERT returns a subscribe-only response without creating a parallel turn. Distinct user clicks (even with identical text) MUST send different ids — the frontend's per-click ``crypto.randomUUID()`` guarantees that."+ "description": "Optional per-click UUID generated by the frontend. The server scopes it to the authenticated user and session before using the result as ``ChatMessage.id``. Frontend / network / RMQ-redelivery retransmits of the same logical send reuse the key, so the Postgres unique-constraint on the resulting PK is the atomic dedup primitive. A duplicate INSERT returns a subscribe-only response without creating a parallel turn. Distinct user clicks (even with identical text) MUST send different ids — the frontend's per-click ``crypto.randomUUID()`` guarantees that."+ },+ "expert_kickoff": {+ "type": "boolean",+ "title": "Expert Kickoff",+ "description": "Marks the hidden, once-per-expert day-one kickoff. The server derives its owner-scoped message ID and persistence metadata.",+ "default": false}},"type": "object",