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): show "Sent from" badge on delegated copilot messages (#14758)
Abhimanyu Yadav3727f0f75241
diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.pyindex 3a1a6b6e9e..66c069f8ea 100644--- a/autogpt_platform/backend/backend/copilot/baseline/service.py+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py@@ -1710,6 +1710,7 @@ async def stream_chat_completion_baseline(request_arrival_at: float = 0.0,organization_id: str | None = None,team_id: str | None = None,+ message_metadata: dict[str, Any] | None = None,**_kwargs: Any,) -> AsyncGenerator[StreamBaseResponse, None]:"""Baseline LLM with tool calling via OpenAI-compatible API.@@ -1758,7 +1759,7 @@ async def stream_chat_completion_baseline(if is_user_message and message and message.strip():await clear_pending_question(session)- if maybe_append_user_message(session, message, is_user_message):+ if maybe_append_user_message(session, message, is_user_message, message_metadata):if is_user_message:track_user_message(user_id=user_id,diff --git a/autogpt_platform/backend/backend/copilot/executor/processor.py b/autogpt_platform/backend/backend/copilot/executor/processor.pyindex 849e23b361..04caef6456 100644--- a/autogpt_platform/backend/backend/copilot/executor/processor.py+++ b/autogpt_platform/backend/backend/copilot/executor/processor.py@@ -698,6 +698,7 @@ class CoPilotProcessor:user_id=entry.user_id,context=entry.context,file_ids=entry.file_ids,+ message_metadata=entry.message_metadata,model=entry.model,permissions=entry.permissions,envelope=envelope,diff --git a/autogpt_platform/backend/backend/copilot/executor/utils.py b/autogpt_platform/backend/backend/copilot/executor/utils.pyindex 2ecf1a737c..68136d5a7e 100644--- a/autogpt_platform/backend/backend/copilot/executor/utils.py+++ b/autogpt_platform/backend/backend/copilot/executor/utils.py@@ -285,6 +285,11 @@ class CoPilotExecutionEntry(BaseModel):file_ids: list[str] | None = None"""Workspace file IDs attached to the user's message"""+ message_metadata: dict[str, Any] | None = None+ """Persisted on the user message row (e.g. ``from_session_id`` /+ ``from_expert_id`` provenance for a delegated or handed-off task) so the+ thread can render where the message came from."""+organization_id: str | None = None"""Active organization for tenant-scoped execution"""@@ -345,6 +350,7 @@ async def enqueue_copilot_turn(llm_credential_id: str | None = None,permissions: CopilotPermissions | None = None,request_arrival_at: float = 0.0,+ message_metadata: dict[str, Any] | None = None,*,envelope: TurnEnvelope,) -> None:@@ -388,6 +394,7 @@ async def enqueue_copilot_turn(llm_credential_id=llm_credential_id,permissions=permissions,request_arrival_at=request_arrival_at,+ message_metadata=message_metadata,envelope=envelope,)@@ -418,6 +425,7 @@ async def schedule_turn(permissions: CopilotPermissions | None = None,request_arrival_at: float = 0.0,spawn: SpawnRequest | None = None,+ message_metadata: dict[str, Any] | None = None,) -> None:"""End-to-end "start a copilot turn": reserve a per-user concurrencyslot, register the session in the stream registry, then publish the@@ -484,6 +492,7 @@ async def schedule_turn(permissions=permissions,request_arrival_at=request_arrival_at,spawn=spawn,+ message_metadata=message_metadata,)@@ -507,6 +516,7 @@ async def dispatch_turn(permissions: CopilotPermissions | None = None,request_arrival_at: float = 0.0,spawn: SpawnRequest | None = None,+ message_metadata: dict[str, Any] | None = None,) -> None:"""Within an already-held turn slot, register the session in thestream registry, publish the work to the executor queue, and@@ -574,6 +584,7 @@ async def dispatch_turn(llm_credential_id=llm_credential_id,permissions=permissions,request_arrival_at=request_arrival_at,+ message_metadata=message_metadata,envelope=envelope,)slot.keep()diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.pyindex db2d9971f8..3ed325fa8b 100644--- a/autogpt_platform/backend/backend/copilot/model.py+++ b/autogpt_platform/backend/backend/copilot/model.py@@ -337,6 +337,7 @@ def maybe_append_user_message(session: "ChatSession",message: str | None,is_user_message: bool,+ metadata: dict[str, Any] | None = None,) -> bool:"""Append a user/assistant message to the session if not already present.@@ -351,7 +352,9 @@ def maybe_append_user_message(role = "user" if is_user_message else "assistant"if is_message_duplicate(session.messages, role, message):return False- session.messages.append(ChatMessage(role=role, content=message))+ session.messages.append(+ ChatMessage(role=role, content=message, metadata=metadata or None)+ )return Truediff --git a/autogpt_platform/backend/backend/copilot/pending_message_helpers.py b/autogpt_platform/backend/backend/copilot/pending_message_helpers.pyindex 16ab4cb6f3..a25631359e 100644--- a/autogpt_platform/backend/backend/copilot/pending_message_helpers.py+++ b/autogpt_platform/backend/backend/copilot/pending_message_helpers.py@@ -8,7 +8,7 @@ routes.py stays free of Redis/Lua details."""import logging-from typing import TYPE_CHECKING, Callable+from typing import TYPE_CHECKING, Any, Callablefrom fastapi import HTTPExceptionfrom pydantic import BaseModel@@ -141,6 +141,7 @@ async def queue_user_message(context: PendingMessageContext | None = None,file_ids: list[str] | None = None,require_turn_in_flight: bool = False,+ metadata: dict[str, Any] | None = None,) -> QueuePendingMessageResponse:"""Push *message* into the per-session pending buffer.@@ -148,11 +149,16 @@ async def queue_user_message(called from the HTTP pending-message path and the autopilot block.Call-frequency rate limiting is the caller's responsibility (HTTP pathenforces it; internal block callers skip it).++ ``metadata`` lands on the user row the message is persisted as. It is+ for internal senders only (a session messaging another session); the+ HTTP path never passes it."""pending = PendingMessage(content=message,file_ids=file_ids or [],context=context,+ metadata=metadata or None,)if require_turn_in_flight:new_len = await push_pending_message_if_session_running(@@ -461,7 +467,9 @@ async def persist_pending_as_user_rows(for pm in pending:content = content_of(pm)- session.messages.append(ChatMessage(role="user", content=content))+ session.messages.append(+ ChatMessage(role="user", content=content, metadata=pm.metadata or None)+ )if transcript_builder is not None:transcript_builder.append_user(content=content)diff --git a/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.py b/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.pyindex 3e48f3272d..0835a062d0 100644--- a/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.py+++ b/autogpt_platform/backend/backend/copilot/pending_message_helpers_test.py@@ -511,9 +511,12 @@ def _make_chat_message_class("""Return a simple ChatMessage stand-in that tracks sequence."""class _Msg:- def __init__(self, role: str, content: str) -> None:+ def __init__(+ self, role: str, content: str, metadata: dict[str, Any] | None = None+ ) -> None:self.role = roleself.content = content+ self.metadata = metadataself.sequence: int | None = Nonemonkeypatch.setattr(helpers_module, "ChatMessage", _Msg)@@ -570,6 +573,77 @@ async def test_persist_pending_happy_path_appends_and_returns_true(push_mock.assert_not_awaited()+async def test_persist_pending_copies_metadata_onto_the_user_row(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A session-to-session message keeps its sender on the persisted row;+ a human follow-up gets no metadata at all."""+ from backend.copilot.pending_message_helpers import persist_pending_as_user_rows+ from backend.copilot.pending_messages import PendingMessage as PM++ _make_chat_message_class(monkeypatch)+ session = MagicMock()+ session.session_id = "sess"+ session.messages = []++ async def _fake_upsert(sess: Any) -> Any:+ for i, m in enumerate(sess.messages):+ m.sequence = i+ return sess++ monkeypatch.setattr(helpers_module, "upsert_chat_session", _fake_upsert)+ monkeypatch.setattr(helpers_module, "push_pending_message", AsyncMock())++ provenance = {"from_session_id": "sess-parent", "from_expert_id": "expert-a"}+ pending = [PM(content="from a teammate", metadata=provenance), PM(content="me")]+ ok = await persist_pending_as_user_rows(session, None, pending, log_prefix="[T]")+ assert ok is True+ assert [m.metadata for m in session.messages] == [provenance, None]+++async def test_queue_user_message_stamps_metadata_on_the_pending_message(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from backend.copilot.pending_message_helpers import queue_user_message++ push_mock = AsyncMock(return_value=1)+ monkeypatch.setattr(helpers_module, "push_pending_message", push_mock)+ monkeypatch.setattr(+ helpers_module, "is_turn_in_flight", AsyncMock(return_value=False)+ )++ provenance = {"from_session_id": "sess-parent", "from_expert_id": None}+ await queue_user_message(session_id="sess", message="hi", metadata=provenance)+ assert push_mock.await_args.args[1].metadata == provenance++ await queue_user_message(session_id="sess", message="typed")+ assert push_mock.await_args.args[1].metadata is None+++async def test_queue_user_message_in_flight_gate_keeps_metadata(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from backend.copilot.pending_message_helpers import queue_user_message++ gated_push = AsyncMock(return_value=2)+ monkeypatch.setattr(+ helpers_module, "push_pending_message_if_session_running", gated_push+ )++ provenance = {"from_session_id": "sess-parent", "from_expert_id": None}+ state = await queue_user_message(+ session_id="sess",+ message="hi",+ require_turn_in_flight=True,+ metadata=provenance,+ )+ assert state.turn_in_flight is True+ assert gated_push.await_args.args[1].metadata == provenance++@pytest.mark.asyncioasync def test_persist_pending_no_transcript_path_skips_transcript(monkeypatch: pytest.MonkeyPatch,diff --git a/autogpt_platform/backend/backend/copilot/pending_messages.py b/autogpt_platform/backend/backend/copilot/pending_messages.pyindex 296dac9896..4064aec6b9 100644--- a/autogpt_platform/backend/backend/copilot/pending_messages.py+++ b/autogpt_platform/backend/backend/copilot/pending_messages.py@@ -81,6 +81,11 @@ class PendingMessage(BaseModel):# Enqueue time (unix seconds) so the turn-start drain can order pending# messages relative to the turn's ``current`` message.enqueued_at: float = Field(default_factory=time.time)+ # Persisted onto the user row this message becomes (e.g. the+ # ``from_session_id`` / ``from_expert_id`` provenance of a message another+ # session sent). Set only by internal callers; the HTTP pending route+ # never forwards it, so a human message stays metadata-free.+ metadata: dict[str, Any] | None = Nonedef _buffer_key(session_id: str) -> str:diff --git a/autogpt_platform/backend/backend/copilot/pending_messages_test.py b/autogpt_platform/backend/backend/copilot/pending_messages_test.pyindex b97f7a4bc7..a90f8fba91 100644--- a/autogpt_platform/backend/backend/copilot/pending_messages_test.py+++ b/autogpt_platform/backend/backend/copilot/pending_messages_test.py@@ -189,6 +189,29 @@ async def test_push_and_drain_single_message(fake_redis: _FakeRedis) -> None:assert await peek_pending_count("sess1") == 0+async def test_push_and_drain_round_trips_metadata(fake_redis: _FakeRedis) -> None:+ """Sender provenance rides the Redis payload so the row persisted at the+ other end can say where the message came from."""+ provenance = {"from_session_id": "sess-parent", "from_expert_id": None}+ await push_pending_message(+ "sess-meta", PendingMessage(content="hello", metadata=provenance)+ )+ await push_pending_message("sess-meta", PendingMessage(content="typed"))++ drained = await drain_pending_messages("sess-meta")+ assert [m.metadata for m in drained] == [provenance, None]+++def test_pending_message_metadata_survives_json() -> None:+ provenance = {"from_session_id": "sess-parent", "from_expert_id": "expert-a"}+ payload = PendingMessage(content="hi", metadata=provenance).model_dump_json()+ assert PendingMessage.model_validate_json(payload).metadata == provenance+ # A human message carries none, and a pre-metadata payload still parses.+ assert PendingMessage(content="hi").metadata is None+ assert PendingMessage.model_validate_json('{"content": "old"}').metadata is None++@pytest.mark.asyncioasync def test_push_and_drain_preserves_order(fake_redis: _FakeRedis) -> None:for i in range(3):diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex c17ef7481f..663992f7a3 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -4528,6 +4528,7 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuesorganization_id: str | None = None,team_id: str | None = None,credential_lease: CredentialLease | CodexCredentialLease | None = None,+ message_metadata: dict[str, Any] | None = None,**_kwargs: Any,) -> AsyncGenerator[StreamBaseResponse, None]:# Pyright's complexity heuristic bails on this ~1500 LoC function (retry@@ -4620,7 +4621,7 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuesawait clear_pending_question(session)_user_message_appended = maybe_append_user_message(- session, message, is_user_message+ session, message, is_user_message, message_metadata)if _user_message_appended and is_user_message:track_user_message(diff --git a/autogpt_platform/backend/backend/copilot/sdk/session_waiter.py b/autogpt_platform/backend/backend/copilot/sdk/session_waiter.pyindex 8ceb5dc0c2..b071e0c906 100644--- a/autogpt_platform/backend/backend/copilot/sdk/session_waiter.py+++ b/autogpt_platform/backend/backend/copilot/sdk/session_waiter.py@@ -21,7 +21,7 @@ import asyncioimport loggingimport uuidfrom dataclasses import dataclass, field-from typing import TYPE_CHECKING, Literal+from typing import TYPE_CHECKING, Any, Literalfrom backend.copilot import stream_registryfrom backend.copilot.active_turns import ConcurrentTurnLimitError@@ -144,6 +144,7 @@ async def run_copilot_turn_via_queue(tool_name: str,spawn: SpawnRequest | None = None,allow_queue: bool = True,+ message_metadata: dict[str, Any] | None = None,) -> tuple[SessionOutcome, SessionResult]:"""Dispatch a copilot turn onto the queue and wait for its result.@@ -211,7 +212,9 @@ async def run_copilot_turn_via_queue(session_id[:12],tool_name,)- state = await queue_user_message(session_id=session_id, message=message)+ state = await queue_user_message(+ session_id=session_id, message=message, metadata=message_metadata+ )if timeout <= 0:# Fire-and-forget: caller explicitly asked not to wait.return "queued", SessionResult(@@ -251,6 +254,7 @@ async def run_copilot_turn_via_queue(llm_credential_id=session.metadata.llm_credential_id,permissions=permissions,spawn=spawn,+ message_metadata=message_metadata,)except TreeRefusal as refused:return "refused", SessionResult(refusal=refused.message)diff --git a/autogpt_platform/backend/backend/copilot/sdk/session_waiter_test.py b/autogpt_platform/backend/backend/copilot/sdk/session_waiter_test.pyindex 9c1e4d7ddb..99db61cee0 100644--- a/autogpt_platform/backend/backend/copilot/sdk/session_waiter_test.py+++ b/autogpt_platform/backend/backend/copilot/sdk/session_waiter_test.py@@ -83,7 +83,44 @@ async def test_queue_branch_timeout_zero_returns_immediately():create_session.assert_not_awaited()enqueue.assert_not_awaited()wait_result.assert_not_awaited()- queue_mock.assert_awaited_once_with(session_id="sess-busy", message="follow-up")+ queue_mock.assert_awaited_once_with(+ session_id="sess-busy", message="follow-up", metadata=None+ )+++async def test_queue_branch_keeps_the_callers_message_metadata():+ """A spawn tool's sender provenance must survive the in-flight fallback:+ the pending message is what becomes the persisted user row."""+ queue_mock = AsyncMock(return_value=_QR())+ provenance = {"from_session_id": "sess-parent", "from_expert_id": "expert-a"}++ with (+ patch(+ "backend.copilot.sdk.session_waiter.is_turn_in_flight",+ new=AsyncMock(return_value=True),+ ),+ patch(+ "backend.copilot.sdk.session_waiter.queue_user_message",+ new=queue_mock,+ ),+ patch(+ "backend.copilot.sdk.session_waiter.wait_for_session_result",+ new=AsyncMock(),+ ),+ ):+ outcome, _ = await run_copilot_turn_via_queue(+ session_id="sess-busy",+ user_id="u1",+ message="follow-up",+ timeout=0,+ tool_call_id="sub:parent",+ tool_name="run_sub_session",+ message_metadata=provenance,+ )++ assert outcome == "queued"+ assert queue_mock.await_args.kwargs["metadata"] == provenance@pytest.mark.asynciodiff --git a/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert.py b/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert.pyindex aaf4c4640a..21568bff08 100644--- a/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert.py+++ b/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert.py@@ -50,6 +50,7 @@ from .expert_delegation import (chain_refusal,resolve_target_expert,safe_caller_name,+ sent_from_metadata,unknown_target_message,)from .models import DelegatedExpertInfo, ErrorResponse, ToolResponseBase@@ -199,6 +200,7 @@ class DelegateToExpertTool(BaseTool):# A teammate keeps their own teammates; depth still bounds the chain.spawn=SpawnRequest(may_spawn=True),allow_queue=False,+ message_metadata=sent_from_metadata(session, caller),)elapsed = time.monotonic() - started_atdiscarded = (diff --git a/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert_test.py b/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert_test.pyindex 9f80e4ae47..df4adaf1f2 100644--- a/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert_test.py@@ -442,6 +442,25 @@ class TestDelegation:assert "Otto" in mock_turn.await_args.kwargs["message"]assert mock_sessions[0].metadata.delegated_by_expert_id is None+ @pytest.mark.asyncio+ async def test_delegated_message_carries_sender_provenance(+ self, roster, mock_turn, mock_sessions+ ):+ """The teammate's thread renders a "Sent from" badge off the message+ row, so the delegating session and expert ride its metadata."""+ await DelegateToExpertTool()._execute(+ user_id="alice",+ session=_session(session_id="s-parent", expert_id="expert-a"),+ expert_id="expert-b",+ prompt="hi",+ wait_for_result=0,+ )+ assert mock_turn.await_args.kwargs["message_metadata"] == {+ "from_session_id": "s-parent",+ "from_expert_id": "expert-a",+ "from_expert_name": "Ari",+ }+@pytest.mark.asyncioasync def test_response_carries_target_identity(self, roster, mock_turn, mock_sessionsdiff --git a/autogpt_platform/backend/backend/copilot/tools/delegation_preamble_cases.json b/autogpt_platform/backend/backend/copilot/tools/delegation_preamble_cases.jsonnew file mode 100644index 0000000000..59def1087e--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/delegation_preamble_cases.json@@ -0,0 +1,47 @@+{+ "$comment": [+ "Shared contract for the preamble delegate_to_expert and handoff_to_expert",+ "prepend to a teammate's task, asserted by both",+ "backend/copilot/tools/delegation_preamble_cases_test.py and",+ "frontend/.../ChatMessagesContainer/__tests__/userMessageParts.contract.test.ts.",+ "message: what the backend sends the receiving session (the stored user row).",+ "visible: what the frontend shows and copies for that row once the preamble",+ "is stripped. Rewording a backend preamble fails the backend test until this",+ "file is updated, and the updated file fails the frontend test until the",+ "frontend regex is updated to match."+ ],+ "cases": [+ {+ "kind": "delegation",+ "caller": "Avery",+ "context": "",+ "prompt": "Draft the launch update.",+ "message": "[Delegated task from Avery, a teammate on this user's team — not the user. They cannot see your thread, so report the outcome in your final message. If the task needs something only the user can provide, say what is missing instead of guessing.]\n\nDraft the launch update.",+ "visible": "Draft the launch update."+ },+ {+ "kind": "delegation",+ "caller": "Avery",+ "context": "Launch on Friday.",+ "prompt": "Review **all** links.\n\n- [ ] Footer",+ "message": "[Delegated task from Avery, a teammate on this user's team — not the user. They cannot see your thread, so report the outcome in your final message. If the task needs something only the user can provide, say what is missing instead of guessing.]\n\n[Context: Launch on Friday.]\n\nReview **all** links.\n\n- [ ] Footer",+ "visible": "[Context: Launch on Friday.]\n\nReview **all** links.\n\n- [ ] Footer"+ },+ {+ "kind": "handoff",+ "caller": "Avery",+ "context": "",+ "prompt": "Draft the launch update.",+ "message": "[Task handed to you by Avery, a teammate on this user's team. It is yours now: they are not waiting on a report and cannot answer follow-ups. Take it to completion and tell the user the outcome yourself. If something only the user can provide is missing, ask them.]\n\nDraft the launch update.",+ "visible": "Draft the launch update."+ },+ {+ "kind": "handoff",+ "caller": "Avery",+ "context": "Launch on Friday.",+ "prompt": "Review **all** links.\n\n- [ ] Footer",+ "message": "[Task handed to you by Avery, a teammate on this user's team. It is yours now: they are not waiting on a report and cannot answer follow-ups. Take it to completion and tell the user the outcome yourself. If something only the user can provide is missing, ask them.]\n\n[Context: Launch on Friday.]\n\nReview **all** links.\n\n- [ ] Footer",+ "visible": "[Context: Launch on Friday.]\n\nReview **all** links.\n\n- [ ] Footer"+ }+ ]+}diff --git a/autogpt_platform/backend/backend/copilot/tools/delegation_preamble_cases_test.py b/autogpt_platform/backend/backend/copilot/tools/delegation_preamble_cases_test.pynew file mode 100644index 0000000000..dfead507a7--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/tools/delegation_preamble_cases_test.py@@ -0,0 +1,33 @@+"""The delegation/handoff preamble is a contract with the frontend.++``ChatMessagesContainer`` hides the generated ``[Delegated task from …]`` /+``[Task handed to you by …]`` framing from user bubbles by matching its+wording. These cases are the one place both sides agree on that wording:+reword a preamble here and this test fails until+``delegation_preamble_cases.json`` is updated, after which the frontend+contract test fails until its matcher follows.+"""++import json+import pathlib++import pytest++from .delegate_to_expert import _handoff_message+from .handoff_to_expert import _transfer_message++_CASES = json.loads(+ (pathlib.Path(__file__).parent / "delegation_preamble_cases.json").read_text()+)["cases"]++_BUILDERS = {"delegation": _handoff_message, "handoff": _transfer_message}++[email protected]("case", _CASES, ids=[c["kind"] for c in _CASES])+def test_preamble_matches_the_shared_frontend_contract(case: dict[str, str]):+ build = _BUILDERS[case["kind"]]+ assert build(case["caller"], case["context"], case["prompt"]) == case["message"]+++def test_every_builder_has_a_case():+ assert {c["kind"] for c in _CASES} == set(_BUILDERS)diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_delegation.py b/autogpt_platform/backend/backend/copilot/tools/expert_delegation.pyindex a2c0069d81..e26d3c1bbe 100644--- a/autogpt_platform/backend/backend/copilot/tools/expert_delegation.py+++ b/autogpt_platform/backend/backend/copilot/tools/expert_delegation.py@@ -13,6 +13,7 @@ just passes the task on with the other tool."""import logging+from typing import Anyfrom backend.api.features.experts.models import Expertfrom backend.copilot.model import ChatSession, get_chat_session@@ -35,6 +36,25 @@ MAX_DELEGATION_DEPTH = MAX_DEPTH_FRAMING_DELIMITERS = str.maketrans("", "", "[]")+def sent_from_metadata(+ session: ChatSession, expert_name: str | None = None+) -> dict[str, Any]:+ """Provenance stamped on the message a spawn tool sends to another thread.++ The receiving thread renders it as a "Sent from <expert>" badge that links+ back to the session the work came from. ``from_expert_id`` is ``None``+ for a plain Otto session; the name is a display hint only, the frontend+ falls back to its expert roster (or "Otto") when it is absent.+ """+ metadata: dict[str, Any] = {+ "from_session_id": session.session_id,+ "from_expert_id": session.expert_id,+ }+ if expert_name:+ metadata["from_expert_name"] = expert_name+ return metadata++def safe_caller_name(caller: str) -> str:"""Collapse *caller* to a single bracket-free line, capped and non-empty.diff --git a/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert.py b/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert.pyindex fb12a8cce2..3f15d76beb 100644--- a/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert.py+++ b/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert.py@@ -47,6 +47,7 @@ from .expert_delegation import (chain_refusal,resolve_target_expert,safe_caller_name,+ sent_from_metadata,unknown_target_message,)from .models import (@@ -239,6 +240,7 @@ class HandoffToExpertTool(BaseTool):tool_name="handoff_to_expert",spawn=SpawnRequest(may_spawn=True),allow_queue=False,+ message_metadata=sent_from_metadata(session, caller),)def _error(self, message: str, session: ChatSession) -> ErrorResponse:diff --git a/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert_test.py b/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert_test.pyindex 4cbf2a159d..680403dfa5 100644--- a/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert_test.py@@ -460,6 +460,22 @@ class TestTransfer:)assert mock_turn.await_args.kwargs["timeout"] == 0+ @pytest.mark.asyncio+ async def test_handed_off_message_carries_sender_provenance(+ self, roster, mock_turn, mock_sessions+ ):+ await HandoffToExpertTool()._execute(+ user_id="alice",+ session=_session(session_id="s-parent", expert_id="expert-a"),+ expert_id="expert-b",+ prompt="own the weekly summary",+ )+ assert mock_turn.await_args.kwargs["message_metadata"] == {+ "from_session_id": "s-parent",+ "from_expert_id": "expert-a",+ "from_expert_name": "Ari",+ }+@pytest.mark.asyncioasync def test_framing_transfers_ownership(self, roster, mock_turn, mock_sessions):await HandoffToExpertTool()._execute(diff --git a/autogpt_platform/backend/backend/copilot/tools/message_session.py b/autogpt_platform/backend/backend/copilot/tools/message_session.pyindex a8441e34a6..bf95357696 100644--- a/autogpt_platform/backend/backend/copilot/tools/message_session.py+++ b/autogpt_platform/backend/backend/copilot/tools/message_session.py@@ -32,6 +32,7 @@ from backend.copilot.session_permissions import resolve_session_permissionsfrom backend.copilot.turn_queue import InflightCapExceeded, try_enqueue_turnfrom .base import BaseTool+from .expert_delegation import sent_from_metadatafrom .models import ErrorResponse, SessionMessageResponse, ToolResponseBaselogger = logging.getLogger(__name__)@@ -128,10 +129,14 @@ class MessageSessionTool(BaseTool):)payload = _render(session, body)+ # Every delivery path stamps the sender: the row this message becomes+ # is what the target's thread renders as "Sent from".+ provenance = sent_from_metadata(session)queued = await queue_user_message(session_id=target_id,message=payload,require_turn_in_flight=True,+ metadata=provenance,)if queued.turn_in_flight:return SessionMessageResponse(@@ -146,14 +151,16 @@ class MessageSessionTool(BaseTool):# such row — so the user's own submit-time payload (their attachments,# page context and model choice) would be replaced by this message's.if await get_chat_session_status(target.session_id) != CHAT_STATUS_IDLE:- await queue_user_message(session_id=target.session_id, message=payload)+ await queue_user_message(+ session_id=target.session_id, message=payload, metadata=provenance+ )return SessionMessageResponse(message=f"Queued for session {target.session_id}'s next turn.",delivery="queued",target_session_id=target.session_id,)- return await self._wake(user_id, session, target, payload)+ return await self._wake(user_id, session, target, payload, provenance)def _error(self, message: str, session: ChatSession) -> ErrorResponse:return ErrorResponse(message=message, session_id=session.session_id)@@ -164,6 +171,7 @@ class MessageSessionTool(BaseTool):session: ChatSession,target: ChatSessionInfo,payload: str,+ provenance: dict[str, Any],) -> ToolResponseBase:"""Start a turn on an idle session so the message is actually read.@@ -181,7 +189,7 @@ class MessageSessionTool(BaseTool):inflight_cap=get_inflight_turn_limit(),session_id=target_id,message=payload,- message_metadata={"from_session_id": session.session_id},+ message_metadata=provenance,llm_auth_provider=target.metadata.llm_auth_provider,llm_credential_id=target.metadata.llm_credential_id,permissions=(diff --git a/autogpt_platform/backend/backend/copilot/tools/run_sub_session.py b/autogpt_platform/backend/backend/copilot/tools/run_sub_session.pyindex bac1380ab6..93f53f47bc 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_sub_session.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_sub_session.py@@ -47,6 +47,7 @@ from backend.copilot.sdk.stream_accumulator import ToolCallEntryfrom backend.copilot.tree import SpawnRequestfrom .base import BaseTool+from .expert_delegation import sent_from_metadatafrom .models import (DelegatedExpertInfo,ErrorResponse,@@ -270,6 +271,7 @@ class RunSubSessionTool(BaseTool):# write to it; depth bounds how far it may spawn onward.spawn=SpawnRequest(may_spawn=True, shares_memory=True),allow_queue=False,+ message_metadata=sent_from_metadata(session),)elapsed = time.monotonic() - started_atdiscarded = opened_here and await discard_unused_sub_session(diff --git a/autogpt_platform/backend/backend/copilot/tools/session_messaging_test.py b/autogpt_platform/backend/backend/copilot/tools/session_messaging_test.pyindex 83d9c35393..dbf23e53eb 100644--- a/autogpt_platform/backend/backend/copilot/tools/session_messaging_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/session_messaging_test.py@@ -281,6 +281,102 @@ class TestMessageSessionDelivery:assert meta["from_session_id"] == CALLER_SESSION+class TestEveryDeliveryCarriesTheSender:+ """The target's thread renders "Sent from" off the persisted user row,+ so the provenance must ride every delivery path — not only the wake.+ An injected or queued message goes through the pending buffer, whose+ ``PendingMessage`` becomes that row."""++ EXPECTED = {"from_session_id": CALLER_SESSION, "from_expert_id": None}++ async def test_injected_into_a_running_turn(self) -> None:+ queued = QueuePendingMessageResponse(+ buffer_length=1, max_buffer_length=10, turn_in_flight=True+ )+ with patch(+ f"{_MSG}.get_chat_session_metadata",+ new=AsyncMock(return_value=_info(TARGET_SESSION, status="running")),+ ):+ with patch(+ f"{_MSG}.queue_user_message", new=AsyncMock(return_value=queued)+ ) as deliver:+ result = await MessageSessionTool()._execute(+ OWNER, _session(), session_id=TARGET_SESSION, message="hi"+ )+ assert isinstance(result, SessionMessageResponse)+ assert result.delivery == "injected"+ assert deliver.await_args.kwargs["metadata"] == self.EXPECTED++ async def test_queued_for_a_waiting_turn(self) -> None:+ queued = QueuePendingMessageResponse(+ buffer_length=0, max_buffer_length=10, turn_in_flight=False+ )+ with patch(+ f"{_MSG}.get_chat_session_metadata",+ new=AsyncMock(return_value=_info(TARGET_SESSION, status="queued")),+ ):+ with patch(+ f"{_MSG}.queue_user_message", new=AsyncMock(return_value=queued)+ ) as deliver:+ with patch(+ f"{_MSG}.get_chat_session_status",+ new=AsyncMock(return_value="queued"),+ ):+ result = await MessageSessionTool()._execute(+ OWNER, _session(), session_id=TARGET_SESSION, message="hi"+ )+ assert isinstance(result, SessionMessageResponse)+ assert result.delivery == "queued"+ assert all(+ call.kwargs["metadata"] == self.EXPECTED for call in deliver.await_args_list+ )++ async def test_woken_from_idle(self) -> None:+ queued = QueuePendingMessageResponse(+ buffer_length=0, max_buffer_length=10, turn_in_flight=False+ )+ with patch(+ f"{_MSG}.get_chat_session_metadata",+ new=AsyncMock(return_value=_info(TARGET_SESSION)),+ ):+ with patch(+ f"{_MSG}.queue_user_message", new=AsyncMock(return_value=queued)+ ):+ with patch(+ f"{_MSG}.get_chat_session_status",+ new=AsyncMock(return_value="idle"),+ ), patch(+ f"{_MSG}.try_enqueue_turn", new=AsyncMock(return_value=object())+ ) as enqueue:+ result = await MessageSessionTool()._execute(+ OWNER, _session(), session_id=TARGET_SESSION, message="hi"+ )+ assert isinstance(result, SessionMessageResponse)+ assert result.delivery == "woke"+ assert enqueue.await_args.kwargs["message_metadata"] == self.EXPECTED++ async def test_an_expert_sender_is_named_by_id(self) -> None:+ queued = QueuePendingMessageResponse(+ buffer_length=1, max_buffer_length=10, turn_in_flight=True+ )+ sender = _session()+ sender.expert_id = "expert-a"+ with patch(+ f"{_MSG}.get_chat_session_metadata",+ new=AsyncMock(return_value=_info(TARGET_SESSION, status="running")),+ ):+ with patch(+ f"{_MSG}.queue_user_message", new=AsyncMock(return_value=queued)+ ) as deliver:+ await MessageSessionTool()._execute(+ OWNER, sender, session_id=TARGET_SESSION, message="hi"+ )+ assert deliver.await_args.kwargs["metadata"] == {+ "from_session_id": CALLER_SESSION,+ "from_expert_id": "expert-a",+ }++class TestWakeCarriesTheTargetsOwnExecutionContext:"""A woken turn is the TARGET's own turn, so it must run under thetarget's permissions, provider and credential.diff --git a/autogpt_platform/backend/backend/copilot/tools/sub_session_test.py b/autogpt_platform/backend/backend/copilot/tools/sub_session_test.pyindex 496857d8e9..a12e41f13c 100644--- a/autogpt_platform/backend/backend/copilot/tools/sub_session_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/sub_session_test.py@@ -466,6 +466,23 @@ class TestRunSubSession:mock_waiter.assert_awaited_once()assert mock_waiter.await_args.kwargs["permissions"] is perms+ @pytest.mark.asyncio+ async def test_sub_message_carries_parent_provenance(+ self, mock_queue, mock_waiter, mock_model+ ):+ """A plain Otto parent stamps its session with no expert, so the+ sub's thread can link back and label the sender as Otto."""+ await RunSubSessionTool()._execute(+ user_id="alice",+ session=_session("alice", session_id="s-parent"),+ prompt="hi",+ wait_for_result=0,+ )+ assert mock_waiter.await_args.kwargs["message_metadata"] == {+ "from_session_id": "s-parent",+ "from_expert_id": None,+ }+@pytest.mark.asyncioasync def test_wait_for_result_zero_returns_running(self, mock_queue, mock_waiter, mock_modeldiff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsxindex cdfcf6a8a7..b8dfe860f9 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/CopilotChatHost.tsx@@ -55,6 +55,7 @@ export function CopilotChatHost({dismissProviderLimit,sessionDryRun,sessionChatStatus,+ sessionSentFrom,expertIdentity,isResolvingExpertIdentity,isAdoptingExpertSession,@@ -79,6 +80,7 @@ export function CopilotChatHost({error={error}sessionId={sessionId}sessionChatStatus={sessionChatStatus}+ sessionSentFrom={sessionSentFrom}isLoadingSession={isLoadingSession}isSessionError={isSessionError}isCreatingSession={isCreatingSession}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sentFrom.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sentFrom.test.tsnew file mode 100644index 0000000000..10a17dea5e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/sentFrom.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it } from "vitest";+import {+ getSentFromDisplayName,+ getSentFromMetadata,+ getSessionSentFrom,+ isSessionOpeningMessage,+} from "../sentFrom";++const SESSION_ID = "3f2c1a9e-7b4d-4e8a-9c1b-2d3e4f5a6b7c";+const EXPERT_ID = "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d";++describe("getSentFromMetadata", () => {+ it("reads the sending session and expert off message metadata", () => {+ expect(+ getSentFromMetadata({+ from_session_id: SESSION_ID,+ from_expert_id: EXPERT_ID,+ from_expert_name: "Ari",+ }),+ ).toEqual({+ sessionId: SESSION_ID,+ expertId: EXPERT_ID,+ expertName: "Ari",+ });+ });++ it("keeps a plain Otto sender as a null expert", () => {+ expect(+ getSentFromMetadata({+ from_session_id: SESSION_ID,+ from_expert_id: null,+ }),+ ).toEqual({ sessionId: SESSION_ID, expertId: null, expertName: null });+ });++ it("ignores metadata without a valid sending session id", () => {+ expect(getSentFromMetadata(null)).toBeNull();+ expect(getSentFromMetadata({ kind: "expert_kickoff" })).toBeNull();+ expect(getSentFromMetadata({ from_session_id: "not-a-uuid" })).toBeNull();+ });+});++describe("getSessionSentFrom", () => {+ it("falls back to the session's delegation provenance", () => {+ expect(+ getSessionSentFrom({+ delegated_by_session_id: SESSION_ID,+ delegated_by_expert_id: EXPERT_ID,+ }),+ ).toEqual({ sessionId: SESSION_ID, expertId: EXPERT_ID, expertName: null });+ });++ it("returns null for a thread nobody delegated", () => {+ expect(getSessionSentFrom({})).toBeNull();+ expect(getSessionSentFrom(undefined)).toBeNull();+ });+});++describe("getSentFromDisplayName", () => {+ it("prefers the name stamped on the message, then the roster, then a default", () => {+ const stamped = {+ sessionId: SESSION_ID,+ expertId: EXPERT_ID,+ expertName: "Ari",+ };+ expect(getSentFromDisplayName(stamped, "Roster Ari")).toBe("Ari");+ const unnamed = { ...stamped, expertName: null };+ expect(getSentFromDisplayName(unnamed, "Roster Ari")).toBe("Roster Ari");+ expect(getSentFromDisplayName(unnamed, null)).toBe("an expert");+ expect(getSentFromDisplayName({ ...unnamed, expertId: null }, null)).toBe(+ "Otto",+ );+ });+});++describe("isSessionOpeningMessage", () => {+ function message(id: string, role: "user" | "assistant" = "user") {+ return { id, role, parts: [] };+ }++ it("is the user row hydrated at DB sequence 0", () => {+ expect(isSessionOpeningMessage(message("sess-seq-0"))).toBe(true);+ });++ it("is never a later row, whatever the client retained", () => {+ expect(isSessionOpeningMessage(message("sess-seq-1"))).toBe(false);+ expect(isSessionOpeningMessage(message("sess-seq-40"))).toBe(false);+ });++ it("is never a row without a DB sequence", () => {+ expect(isSessionOpeningMessage(message("user-streamed"))).toBe(false);+ expect(isSessionOpeningMessage(message("sess-idx-0"))).toBe(false);+ });++ it("is never an assistant row", () => {+ expect(isSessionOpeningMessage(message("sess-seq-0", "assistant"))).toBe(+ false,+ );+ });+});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 6c082e3ebc..c0c8e269bd 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@@ -40,6 +40,7 @@ import { isTokenDevtoolEnabled } from "../../tokenDevtool/gate";import { updateHistoryBreakdown } from "../../tokenDevtool/store";import { breakdownCacheKey } from "../../tokenDevtool/tokenMath";import { useAreWorkspaceFileCardsOpen } from "../../useAreWorkspaceFileCardsOpen";+import type { SentFrom } from "../../sentFrom";import {getKickoffAttemptToken,getKickoffExpertId,@@ -53,6 +54,7 @@ export interface ChatContainerProps {error: Error | undefined;sessionId: string | null;sessionChatStatus?: string;+ sessionSentFrom?: SentFrom | null;isLoadingSession: boolean;isSessionError?: boolean;isCreatingSession: boolean;@@ -120,6 +122,7 @@ export const ChatContainer = ({error,sessionId,sessionChatStatus,+ sessionSentFrom,isLoadingSession,isSessionError,isCreatingSession,@@ -314,6 +317,7 @@ export const ChatContainer = ({activeStreamStartedAt={activeStreamStartedAt}sessionID={sessionId}sessionChatStatus={sessionChatStatus}+ sessionSentFrom={sessionSentFrom}hasMoreMessages={hasMoreMessages}isLoadingMore={isLoadingMore}onLoadMore={onLoadMore}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 4d25c1c3e3..7b5e6f6874 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@@ -57,6 +57,13 @@ import {} from "./components/PendingUploadMessage";import { ThinkingIndicator } from "./components/ThinkingIndicator";import { UserMessageClamp } from "./components/UserMessageClamp";+import { SentFromBadge } from "./components/SentFromBadge";+import { getVisibleUserMessageParts } from "./userMessageParts";+import {+ getSentFromMetadata,+ isSessionOpeningMessage,+ type SentFrom,+} from "../../sentFrom";import type { PendingUploadSend } from "../../copilotStreamStore";import { Clock01Icon } from "@hugeicons/core-free-icons";import { Icon } from "@/components/atoms/Icon/Icon";@@ -114,6 +121,10 @@ interface Props {/** The roster is still loading for an expert-scoped session, so the* header must not yet claim the thread is Otto's. */isResolvingExpertIdentity?: boolean;+ /** Where this thread's opening task came from (session-level delegation+ * metadata). Shown on the row that opened the thread (DB sequence 0) when+ * that row carries no provenance of its own. */+ sessionSentFrom?: SentFrom | null;/** The layout floats its sidebar/files controls over the chat's top-left* corner on small viewports (see ThreadHeader). */hasFloatingControls?: boolean;@@ -331,6 +342,7 @@ export function ChatMessagesContainer({fileUrlBuilder,expertIdentity,isResolvingExpertIdentity = false,+ sessionSentFrom = null,hasFloatingControls = false,canOpenActivity = false,areFilesOpen = false,@@ -611,9 +623,11 @@ export function ChatMessagesContainer({// they never reach the user UI, and so one landing between two// tool calls can't split a chain. data-status surfaces via// ThinkingIndicator; data-compaction via CompactionCard.- const renderableParts = withToolDisplayNames(message.parts).filter(- (p) => !isBookkeepingPart(p),- );+ const renderableParts = withToolDisplayNames(+ message.role === "user"+ ? getVisibleUserMessageParts(message.parts)+ : message.parts,+ ).filter((p) => !isBookkeepingPart(p));// Only a message that is actively streaming can have a live// compaction phase — a stopped or failed turn must not leave an// eternal progress bar. Replayed/settled messages never carry@@ -655,6 +669,11 @@ export function ChatMessagesContainer({(p): p is FileUIPart => p.type === "file",);+ const sentFrom = readOnly+ ? null+ : (getSentFromMetadata(message.metadata) ??+ (isSessionOpeningMessage(message) ? sessionSentFrom : null));+return (<Messagefrom={message.role}@@ -688,7 +707,11 @@ export function ChatMessagesContainer({liveCompactionStats={liveCompactionStats}/>) : (- <UserMessageClamp>+ <UserMessageClamp+ trailing={+ sentFrom ? <SentFromBadge sentFrom={sentFrom} /> : null+ }+ >{renderableParts.map((part, i) => (<MessagePartRendererkey={`${message.id}-${i}`}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 fd6b32919b..8059f4df36 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@@ -1,9 +1,13 @@+import type { ComponentProps } from "react";import { act } from "@testing-library/react";import type { UIDataTypes, UIMessage, UITools } from "ai";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";+import type { TurnStatsMap } from "../../../helpers/convertChatSessionToUiMessages";++type Message = UIMessage<unknown, UIDataTypes, UITools>;vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {const actual =@@ -97,12 +101,17 @@ vi.mock("../components/QueueBadge", () => ({),}));-vi.mock("../components/CopyButton", () => ({ CopyButton: () => null }));+vi.mock("../components/CopyButton", () => ({+ CopyButton: ({ text }: { text: string }) => (+ <span data-testid="copy-message" data-text={text} />+ ),+}));vi.mock("../components/MessageAttachments", () => ({MessageAttachments: () => null,}));vi.mock("../components/MessagePartRenderer", () => ({- MessagePartRenderer: () => null,+ MessagePartRenderer: ({ part }: { part: { type: string; text?: string } }) =>+ part.type === "text" ? <span>{part.text}</span> : null,}));vi.mock("../components/ReasoningCollapse", () => ({ReasoningCollapse: () => null,@@ -169,8 +178,8 @@ class MockIntersectionObserver {}const baseProps = {- messages: [] as any[],- status: "ready" as const,+ messages: [] as Message[],+ status: "ready",error: undefined,isLoading: false,sessionID: "sess-123",@@ -179,7 +188,7 @@ const baseProps = {isLoadingMore: false,onLoadMore: vi.fn(),onRetry: vi.fn(),-};+} satisfies ComponentProps<typeof ChatMessagesContainer>;describe("ChatMessagesContainer — assistant rendering", () => {const messages = [@@ -541,10 +550,10 @@ describe("ChatMessagesContainer — turnStats", () => {it("renders the local timestamp on a user message (hover reveal)", () => {const userId = "user-1";- const turnStats = new Map([+ const turnStats: TurnStatsMap = new Map([[userId, { createdAt: "2026-04-23T08:32:09.000Z" }],]);- const messages = [+ const messages: Message[] = [{id: userId,role: "user" as const,@@ -552,11 +561,10 @@ describe("ChatMessagesContainer — turnStats", () => {},];render(- // eslint-disable-next-line @typescript-eslint/no-explicit-any<ChatMessagesContainer- {...(baseProps as any)}- messages={messages as any}- turnStats={turnStats as any}+ {...baseProps}+ messages={messages}+ turnStats={turnStats}/>,);// The timestamp is rendered in the MessageActions area alongside CopyButton;@@ -570,7 +578,7 @@ describe("ChatMessagesContainer — turnStats", () => {});it("skips the user timestamp when turnStats has no entry for that message id", () => {- const messages = [+ const messages: Message[] = [{id: "user-unknown",role: "user" as const,@@ -578,11 +586,10 @@ describe("ChatMessagesContainer — turnStats", () => {},];render(- // eslint-disable-next-line @typescript-eslint/no-explicit-any<ChatMessagesContainer- {...(baseProps as any)}- messages={messages as any}- turnStats={new Map() as any}+ {...baseProps}+ messages={messages}+ turnStats={new Map()}/>,);const labels = screen.queryAllByText((_, el) =>@@ -610,7 +617,7 @@ describe("ChatMessagesContainer — queue badges on user messages", () => {it("renders a QueueBadge when the row is the latest user in a queued session", () => {const userId = "user-q1";- const turnStats = new Map([+ const turnStats: TurnStatsMap = new Map([[userId,{@@ -619,7 +626,7 @@ describe("ChatMessagesContainer — queue badges on user messages", () => {},],]);- const messages = [+ const messages: Message[] = [{id: userId,role: "user" as const,@@ -629,11 +636,10 @@ describe("ChatMessagesContainer — queue badges on user messages", () => {},];render(- // eslint-disable-next-line @typescript-eslint/no-explicit-any<ChatMessagesContainer- {...(baseProps as any)}- messages={messages as any}- turnStats={turnStats as any}+ {...baseProps}+ messages={messages}+ turnStats={turnStats}sessionChatStatus="queued"/>,);@@ -641,12 +647,186 @@ describe("ChatMessagesContainer — queue badges on user messages", () => {expect(badge.getAttribute("data-session-id")).toBe("sess-123");});+ it.each([false, true])(+ "shows and copies only the delegated task (readOnly=%s)",+ (readOnly) => {+ const preamble =+ "[Delegated task from Ari, a teammate on this user's team — not " ++ "the user. They cannot see your thread, so report the outcome in your " ++ "final message. If the task needs something only the user can " ++ "provide, say what is missing instead of guessing.]";+ const message = {+ id: "sess-123-seq-0",+ role: "user" as const,+ parts: [+ { type: "text" as const, text: `${preamble}\n\nDraft the update.` },+ ],+ metadata: readOnly+ ? undefined+ : {+ from_session_id: "3f2c1a9e-7b4d-4e8a-9c1b-2d3e4f5a6b7c",+ from_expert_name: "Ari",+ },+ };+ render(+ <ChatMessagesContainer+ {...baseProps}+ messages={[message]}+ readOnly={readOnly}+ />,+ );++ expect(screen.getByText("Draft the update.")).toBeDefined();+ expect(screen.queryByText(/They cannot see your thread/)).toBeNull();+ expect(screen.getByTestId("copy-message").dataset.text).toBe(+ "Draft the update.",+ );+ expect(screen.queryAllByTestId("sent-from-badge")).toHaveLength(+ readOnly ? 0 : 1,+ );+ expect(message.parts[0].text).toBe(`${preamble}\n\nDraft the update.`);+ },+ );++ it("renders a Sent from badge linking to the session a delegated message came from", () => {+ const messages: Message[] = [+ {+ id: "user-d1",+ role: "user" as const,+ parts: [{ type: "text" as const, text: "draft the ops update" }],+ metadata: {+ from_session_id: "3f2c1a9e-7b4d-4e8a-9c1b-2d3e4f5a6b7c",+ from_expert_id: "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",+ from_expert_name: "Ari",+ },+ },+ ];+ render(<ChatMessagesContainer {...baseProps} messages={messages} />);+ const card = screen.getByTestId("sent-from-badge");+ expect(card.textContent).toContain("Sent from Ari");+ expect(card.getAttribute("href")).toBe(+ "/copilot?sessionId=3f2c1a9e-7b4d-4e8a-9c1b-2d3e4f5a6b7c",+ );+ });++ const sessionSentFrom = {+ sessionId: "3f2c1a9e-7b4d-4e8a-9c1b-2d3e4f5a6b7c",+ expertId: null,+ expertName: null,+ };++ function userRow(id: string, text: string) {+ return {+ id,+ role: "user" as const,+ parts: [{ type: "text" as const, text }],+ };+ }++ it("falls back to the session's delegation provenance on the opening message only", () => {+ const messages: Message[] = [+ userRow("sess-123-seq-0", "first task"),+ {+ id: "sess-123-seq-1",+ role: "assistant" as const,+ parts: [{ type: "text" as const, text: "done" }],+ },+ userRow("sess-123-seq-2", "typed by the user"),+ ];+ render(+ <ChatMessagesContainer+ {...baseProps}+ messages={messages}+ hasMoreMessages={false}+ sessionSentFrom={sessionSentFrom}+ />,+ );+ const cards = screen.getAllByTestId("sent-from-badge");+ expect(cards).toHaveLength(1);+ expect(cards[0].textContent).toContain("Sent from Otto");+ });++ it("does NOT fall back onto a later row when pagination stopped short of the opening row", () => {+ // hasMoreMessages goes false after repeated load errors or at the+ // history cap while older rows still exist; the first retained row is+ // then a later human message, not the one the delegation opened with.+ const messages: Message[] = [+ userRow("sess-123-seq-40", "typed by the user"),+ {+ id: "sess-123-seq-41",+ role: "assistant" as const,+ parts: [{ type: "text" as const, text: "sure" }],+ },+ ];+ render(+ <ChatMessagesContainer+ {...baseProps}+ messages={messages}+ hasMoreMessages={false}+ sessionSentFrom={sessionSentFrom}+ />,+ );+ expect(screen.queryByTestId("sent-from-badge")).toBeNull();+ });++ it("keeps the fallback on the opening row while more history is still loadable", () => {+ // The pagination flag flips true during a refetch; the opening row's+ // identity does not depend on it.+ render(+ <ChatMessagesContainer+ {...baseProps}+ messages={[userRow("sess-123-seq-0", "first task")]}+ hasMoreMessages={true}+ sessionSentFrom={sessionSentFrom}+ />,+ );+ expect(screen.getByTestId("sent-from-badge").textContent).toContain(+ "Sent from Otto",+ );+ });++ it("does NOT fall back onto a row whose id carries no DB sequence", () => {+ render(+ <ChatMessagesContainer+ {...baseProps}+ messages={[userRow("user-streamed", "first task")]}+ hasMoreMessages={false}+ sessionSentFrom={sessionSentFrom}+ />,+ );+ expect(screen.queryByTestId("sent-from-badge")).toBeNull();+ });++ it("does NOT fall back when the session carries no delegation provenance", () => {+ render(+ <ChatMessagesContainer+ {...baseProps}+ messages={[userRow("sess-123-seq-0", "hello")]}+ hasMoreMessages={false}+ sessionSentFrom={null}+ />,+ );+ expect(screen.queryByTestId("sent-from-badge")).toBeNull();+ });++ it("does NOT render a Sent from badge for an ordinary user message", () => {+ const messages: Message[] = [+ {+ id: "user-plain",+ role: "user" as const,+ parts: [{ type: "text" as const, text: "hello" }],+ },+ ];+ render(<ChatMessagesContainer {...baseProps} messages={messages} />);+ expect(screen.queryByTestId("sent-from-badge")).toBeNull();+ });+it("does NOT render a QueueBadge for normal (non-queued) user messages", () => {const userId = "user-n1";- const turnStats = new Map([+ const turnStats: TurnStatsMap = new Map([[userId, { createdAt: "2026-04-23T08:32:09.000Z" }],]);- const messages = [+ const messages: Message[] = [{id: userId,role: "user" as const,@@ -654,11 +834,10 @@ describe("ChatMessagesContainer — queue badges on user messages", () => {},];render(- // eslint-disable-next-line @typescript-eslint/no-explicit-any<ChatMessagesContainer- {...(baseProps as any)}- messages={messages as any}- turnStats={turnStats as any}+ {...baseProps}+ messages={messages}+ turnStats={turnStats}/>,);expect(screen.queryByTestId("queue-badge")).toBeNull();@@ -669,10 +848,10 @@ describe("ChatMessagesContainer — queue badges on user messages", () => {// latest user message, the badge should stay hidden unless the// OWNING session is in the queued state.const userId = "user-q2";- const turnStats = new Map([+ const turnStats: TurnStatsMap = new Map([[userId, { isLatestUserMessage: true, rawMessageId: "uuid-q2" }],]);- const messages = [+ const messages: Message[] = [{id: userId,role: "user" as const,@@ -680,11 +859,10 @@ describe("ChatMessagesContainer — queue badges on user messages", () => {},];render(- // eslint-disable-next-line @typescript-eslint/no-explicit-any<ChatMessagesContainer- {...(baseProps as any)}- messages={messages as any}- turnStats={turnStats as any}+ {...baseProps}+ messages={messages}+ turnStats={turnStats}sessionChatStatus="idle"/>,);@@ -759,6 +937,45 @@ describe("ChatMessagesContainer — readOnly mode", () => {},);+ it("renders no Sent from badge in a read-only transcript", () => {+ const messages: Message[] = [+ {+ id: "sess-123-seq-0",+ role: "user" as const,+ parts: [{ type: "text" as const, text: "first task" }],+ },+ {+ id: "sess-123-seq-1",+ role: "assistant" as const,+ parts: [{ type: "text" as const, text: "done" }],+ },+ {+ id: "sess-123-seq-2",+ role: "user" as const,+ parts: [{ type: "text" as const, text: "draft the ops update" }],+ metadata: {+ from_session_id: "3f2c1a9e-7b4d-4e8a-9c1b-2d3e4f5a6b7c",+ from_expert_id: null,+ from_expert_name: "Ari",+ },+ },+ ];+ render(+ <ChatMessagesContainer+ {...baseProps}+ messages={messages}+ readOnly+ hasMoreMessages={false}+ sessionSentFrom={{+ sessionId: "3f2c1a9e-7b4d-4e8a-9c1b-2d3e4f5a6b7c",+ expertId: null,+ expertName: null,+ }}+ />,+ );+ expect(screen.queryByTestId("sent-from-badge")).toBeNull();+ });+it("hides the load-older-messages sentinel even when more history exists", () => {render(<ChatMessagesContainer@@ -807,10 +1024,10 @@ describe("ChatMessagesContainer — readOnly mode", () => {it("hides the queue-badge gate even when the session is queued", () => {const userId = "user-q-readonly";- const turnStats = new Map([+ const turnStats: TurnStatsMap = new Map([[userId, { isLatestUserMessage: true, rawMessageId: "uuid-q-ro" }],]);- const messages = [+ const messages: Message[] = [{id: userId,role: "user" as const,diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/userMessageParts.contract.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/userMessageParts.contract.test.tsnew file mode 100644index 0000000000..c3865dbdad--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/userMessageParts.contract.test.ts@@ -0,0 +1,40 @@+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import { getVisibleUserMessageParts } from "../userMessageParts";++interface PreambleCase {+ kind: string;+ caller: string;+ context: string;+ prompt: string;+ message: string;+ visible: string;+}++// The backend's copy on purpose: the preamble wording lives in+// delegate_to_expert.py / handoff_to_expert.py, and this one file keeps the+// frontend matcher in step with it.+const preambleCases: { cases: PreambleCase[] } = JSON.parse(+ readFileSync(+ resolve(+ dirname(fileURLToPath(import.meta.url)),+ "../../../../../../../../backend/backend/copilot/tools/delegation_preamble_cases.json",+ ),+ "utf8",+ ),+);++describe("the shared backend/frontend delegation preamble", () => {+ it.each(preambleCases.cases)(+ "hides the $kind preamble the backend renders for $caller",+ (preambleCase) => {+ expect(+ getVisibleUserMessageParts([+ { type: "text", text: preambleCase.message },+ ]),+ ).toEqual([{ type: "text", text: preambleCase.visible }]);+ },+ );+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/userMessageParts.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/userMessageParts.test.tsnew file mode 100644index 0000000000..921a2be612--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/__tests__/userMessageParts.test.ts@@ -0,0 +1,75 @@+import type { UIMessage } from "ai";+import { describe, expect, it } from "vitest";+import { getVisibleUserMessageParts } from "../userMessageParts";++const delegation =+ "[Delegated task from Avery, a teammate on this user's team — not " ++ "the user. They cannot see your thread, so report the outcome in your " ++ "final message. If the task needs something only the user can " ++ "provide, say what is missing instead of guessing.]";++const handoff =+ "[Task handed to you by Avery, a teammate on this user's team. It " ++ "is yours now: they are not waiting on a report and cannot answer " ++ "follow-ups. Take it to completion and tell the user the outcome " ++ "yourself. If something only the user can provide is missing, ask " ++ "them.]";++describe("getVisibleUserMessageParts", () => {+ it.each([delegation, handoff])(+ "removes the generated preamble while preserving task content: %s",+ (preamble) => {+ const text = `${preamble}\n\n[Context: Launch on Friday.]\n\nReview **all** links.\n\n- [ ] Footer`;+ const parts: UIMessage["parts"] = [{ type: "text", text }];++ expect(getVisibleUserMessageParts(parts)).toEqual([+ {+ type: "text",+ text: "[Context: Launch on Friday.]\n\nReview **all** links.\n\n- [ ] Footer",+ },+ ]);+ expect(parts[0]).toEqual({ type: "text", text });+ },+ );++ it("preserves attachments and later text parts verbatim", () => {+ const attachment = {+ type: "file" as const,+ mediaType: "image/png",+ url: "https://example.com/brief.png",+ };+ const quotedPreamble = {+ type: "text" as const,+ text: `${delegation}\n\nA quoted example within the task.`,+ };+ const parts: UIMessage["parts"] = [+ attachment,+ { type: "text", text: `${delegation}\n\nReview the attached brief.` },+ quotedPreamble,+ ];++ expect(getVisibleUserMessageParts(parts)).toEqual([+ attachment,+ { type: "text", text: "Review the attached brief." },+ quotedPreamble,+ ]);+ });++ it.each([+ "An ordinary message.",+ "[Delegated task from Avery]\n\nKeep this user-written note.",+ "[Context: User-written background.]\n\nKeep this too.",+ `Please explain this wrapper:\n\n${delegation}\n\nTask`,+ `${delegation}\n\n`,+ ])("preserves ordinary, quoted and incomplete content: %s", (text) => {+ const parts: UIMessage["parts"] = [{ type: "text", text }];++ expect(getVisibleUserMessageParts(parts)).toBe(parts);+ });++ it("preserves a message without text", () => {+ const parts: UIMessage["parts"] = [];++ expect(getVisibleUserMessageParts(parts)).toBe(parts);+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/SentFromBadge.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/SentFromBadge.tsxnew file mode 100644index 0000000000..db0a6fd02f--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/SentFromBadge.tsx@@ -0,0 +1,29 @@+import { Icon } from "@/components/atoms/Icon/Icon";+import { ArrowTurnBackwardIcon } from "@hugeicons/core-free-icons";+import Link from "next/link";+import { getSentFromDisplayName, type SentFrom } from "../../../sentFrom";+import { useExpertMap } from "../../../useExpertMap";++interface Props {+ sentFrom: SentFrom;+}++export function SentFromBadge({ sentFrom }: Props) {+ const { expertsById } = useExpertMap();+ const resolvedName = sentFrom.expertId+ ? expertsById.get(sentFrom.expertId)?.name+ : null;+ const name = getSentFromDisplayName(sentFrom, resolvedName);++ return (+ <Link+ href={`/copilot?sessionId=${sentFrom.sessionId}`}+ data-testid="sent-from-badge"+ title="Open the thread this task was sent from"+ className="inline-flex items-center gap-1 rounded-full bg-purple-100 px-2 py-0.5 text-[11px] font-medium text-purple-800 transition-colors hover:bg-purple-200"+ >+ <Icon icon={ArrowTurnBackwardIcon} size={12} />+ Sent from {name}+ </Link>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/UserMessageClamp.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/UserMessageClamp.tsxindex fb97b01851..2a79f5b5db 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/UserMessageClamp.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/UserMessageClamp.tsx@@ -2,9 +2,10 @@ import { useLayoutEffect, useRef, useState } from "react";interface Props {children: React.ReactNode;+ trailing?: React.ReactNode;}-export function UserMessageClamp({ children }: Props) {+export function UserMessageClamp({ children, trailing }: Props) {const contentRef = useRef<HTMLDivElement>(null);const [isOverflowing, setIsOverflowing] = useState(false);const [expanded, setExpanded] = useState(false);@@ -15,19 +16,26 @@ export function UserMessageClamp({ children }: Props) {setIsOverflowing(el.scrollHeight > el.clientHeight + 1);}, [expanded, children]);+ const showToggle = isOverflowing || expanded;+return (<div><div ref={contentRef} className={expanded ? undefined : "line-clamp-6"}>{children}</div>- {(isOverflowing || expanded) && (- <button- type="button"- className="mt-1 text-xs font-medium text-purple-700 hover:underline"- onClick={() => setExpanded(!expanded)}- >- {expanded ? "Show less" : "Read more"}- </button>+ {(showToggle || trailing) && (+ <div className="mt-1 flex flex-wrap items-center gap-2">+ {showToggle && (+ <button+ type="button"+ className="text-xs font-medium text-purple-700 hover:underline"+ onClick={() => setExpanded(!expanded)}+ >+ {expanded ? "Show less" : "Read more"}+ </button>+ )}+ {trailing}+ </div>)}</div>);diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/UserMessageClamp.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/UserMessageClamp.test.tsxindex 2566a93406..97b595876e 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/UserMessageClamp.test.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/UserMessageClamp.test.tsx@@ -52,4 +52,31 @@ describe("UserMessageClamp", () => {expect(content.className).toContain("line-clamp-6");expect(screen.getByRole("button", { name: "Read more" })).toBeDefined();});++ it("renders the trailing badge even when nothing overflows", () => {+ setMeasuredHeights({ scrollHeight: 100, clientHeight: 100 });++ render(+ <UserMessageClamp trailing={<span>Sent from Ari</span>}>+ Short message+ </UserMessageClamp>,+ );++ expect(screen.getByText("Sent from Ari")).toBeDefined();+ expect(screen.queryByRole("button")).toBeNull();+ });++ it("keeps the trailing badge beside the Read more toggle", () => {+ setMeasuredHeights({ scrollHeight: 300, clientHeight: 120 });++ render(+ <UserMessageClamp trailing={<span>Sent from Ari</span>}>+ Very long message+ </UserMessageClamp>,+ );++ const toggle = screen.getByRole("button", { name: "Read more" });+ const badge = screen.getByText("Sent from Ari");+ expect(toggle.parentElement).toBe(badge.parentElement);+ });});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/userMessageParts.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/userMessageParts.tsnew file mode 100644index 0000000000..750487bfc8--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/userMessageParts.ts@@ -0,0 +1,34 @@+import type { UIMessage } from "ai";++const DELEGATION_PREAMBLE = new RegExp(+ "^\\[Delegated task from [^\\[\\]\\r\\n]+, a teammate on this user's team — not " ++ "the user\\. They cannot see your thread, so report the outcome in your " ++ "final message\\. If the task needs something only the user can " ++ "provide, say what is missing instead of guessing\\.\\]\\r?\\n\\r?\\n",+);++const HANDOFF_PREAMBLE = new RegExp(+ "^\\[Task handed to you by [^\\[\\]\\r\\n]+, a teammate on this user's team\\. It " ++ "is yours now: they are not waiting on a report and cannot answer " ++ "follow-ups\\. Take it to completion and tell the user the outcome " ++ "yourself\\. If something only the user can provide is missing, ask " ++ "them\\.\\]\\r?\\n\\r?\\n",+);++export function getVisibleUserMessageParts(parts: UIMessage["parts"]) {+ const firstTextIndex = parts.findIndex((part) => part.type === "text");+ const firstText = parts[firstTextIndex];+ if (firstText?.type !== "text") return parts;++ const preamble =+ firstText.text.match(DELEGATION_PREAMBLE) ??+ firstText.text.match(HANDOFF_PREAMBLE);+ if (!preamble) return parts;++ const text = firstText.text.slice(preamble[0].length);+ if (!text.trim()) return parts;++ return parts.map((part, index) =>+ index === firstTextIndex ? { ...firstText, text } : part,+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/sentFrom.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/sentFrom.tsnew file mode 100644index 0000000000..3f2f7e12dd--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/sentFrom.ts@@ -0,0 +1,65 @@+import type { ChatSessionMetadata } from "@/app/api/__generated__/models/chatSessionMetadata";+import { isValidUUID } from "@/lib/utils";+import type { UIMessage } from "ai";+import { extractDbSequence } from "./helpers/convertChatSessionToUiMessages";++export interface SentFrom {+ sessionId: string;+ expertId: string | null;+ expertName: string | null;+}++type SessionDelegation = Pick<+ ChatSessionMetadata,+ "delegated_by_session_id" | "delegated_by_expert_id"+>;++function readString(value: unknown): string | null {+ return typeof value === "string" && value.length > 0 ? value : null;+}++// A delegated, handed-off, sub-session or session-to-session message carries+// the sending session on its own metadata row (see the backend's+// sent_from_metadata helper).+export function getSentFromMetadata(metadata: unknown): SentFrom | null {+ if (!metadata || typeof metadata !== "object") return null;+ const value = metadata as Record<string, unknown>;+ const sessionId = readString(value.from_session_id);+ if (!sessionId || !isValidUUID(sessionId)) return null;+ return {+ sessionId,+ expertId: readString(value.from_expert_id),+ expertName: readString(value.from_expert_name),+ };+}++// Threads opened by a delegation before messages carried provenance only+// record it on the session, which covers the message that opened them.+export function getSessionSentFrom(+ metadata: SessionDelegation | null | undefined,+): SentFrom | null {+ const sessionId = metadata?.delegated_by_session_id;+ if (!sessionId || !isValidUUID(sessionId)) return null;+ return {+ sessionId,+ expertId: metadata?.delegated_by_expert_id ?? null,+ expertName: null,+ };+}++// The row that opened a thread is the one at DB sequence 0. Its hydrated id+// carries that sequence, so the check does not depend on how much history the+// client has retained: a paged, truncated or refetching thread can drop the+// opening row, but it can never present a later row at sequence 0.+export function isSessionOpeningMessage(message: UIMessage): boolean {+ return message.role === "user" && extractDbSequence(message) === 0;+}++export function getSentFromDisplayName(+ sentFrom: SentFrom,+ resolvedExpertName: string | null | undefined,+): string {+ if (sentFrom.expertName) return sentFrom.expertName;+ if (resolvedExpertName) return resolvedExpertName;+ return sentFrom.expertId ? "an expert" : "Otto";+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.tsindex d1fa67f50e..396d908ebc 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts@@ -19,6 +19,7 @@ import {type TurnStatsMap,} from "./helpers/convertChatSessionToUiMessages";import { resolveSessionDryRun } from "./helpers";+import { getSessionSentFrom } from "./sentFrom";import {getAvailableLLMTransports,resolveCopilotLLMAuthSelection,@@ -391,6 +392,11 @@ export function useChatSession({? (sessionQuery.data.data.expert_id ?? null): null;+ const sessionSentFrom =+ sessionQuery.data?.status === 200+ ? getSessionSentFrom(sessionQuery.data.data.metadata)+ : null;+return {sessionId,setSessionId,@@ -417,5 +423,6 @@ export function useChatSession({refetchSession: sessionQuery.refetch,sessionDryRun,sessionChatStatus,+ sessionSentFrom,};}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.tsindex ba274ace52..fe71f52356 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useCopilotPage.ts@@ -142,6 +142,7 @@ export function useCopilotPage() {refetchSession,sessionDryRun,sessionChatStatus,+ sessionSentFrom,} = useChatSession({dryRun: isDryRun,expertId,@@ -435,6 +436,7 @@ export function useCopilotPage() {// sessions) lives in the store and is consumed by the toggle button.sessionDryRun,sessionChatStatus,+ sessionSentFrom,expertIdentity,isResolvingExpertIdentity,isAdoptingExpertSession,