Skip to content

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

fix(platform/copilot): a team change or Soul edit asks the user once, and its card names the teammate (#15050)

Reinier van der Leerf4b8b5889fd3
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 4df99b3a30..9ce3a04fca 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -50,6 +50,7 @@ from backend.copilot.expert_kickoff import (
expert_kickoff_metadata,
scoped_client_message_id,
)
+from backend.copilot.gate.card_approval import record_card_decisions
from backend.copilot.llm_attribution import is_impersonated_request
from backend.copilot.model import (
CHAT_STATUS_IDLE,
@@ -1893,6 +1894,9 @@ async def stream_chat_post(
await enforce_codex_access_http(user_id)
message = request.message
+ if request.is_user_message:
+ # The only writer of card approvals: a model can add chat rows, not requests.
+ await record_card_decisions(user_id, session_id, message)
message_id = (
scoped_client_message_id(user_id, session_id, request.message_id)
if request.message_id
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
index c462aae003..6b0b4ac03e 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
@@ -581,6 +581,30 @@ def test_stream_chat_skips_the_expert_gate_for_a_non_expert_session(
mocks.enqueue.assert_awaited_once()
[email protected]("is_user_message", [True, False])
+def test_stream_chat_records_card_decisions_only_from_the_users_message(
+ mocker: pytest_mock.MockerFixture, test_user_id: str, is_user_message: bool
+) -> None:
+ """The only writer of the approvals the gate trusts for a proposal's confirm."""
+ _mock_stream_internals(mocker)
+ record = mocker.patch(
+ "backend.api.features.chat.routes.record_card_decisions",
+ new_callable=AsyncMock,
+ )
+ line = "Approved: create Otto (confirmation_id: c-1)."
+
+ response = client.post(
+ "/sessions/sess-1/stream",
+ json={"message": line, "is_user_message": is_user_message},
+ )
+
+ assert response.status_code == 200
+ if is_user_message:
+ record.assert_awaited_once_with(test_user_id, "sess-1", line)
+ else:
+ record.assert_not_awaited()
+
+
# ─── A sent message cancels the pending resume at the budget reset ────
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db.py b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
index 9367e15a60..0a94af78a9 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
@@ -364,6 +364,15 @@ async def list_templates(
return [_to_model(row) for row in rows]
+async def get_template(template_id: str) -> Expert | None:
+ """One live roster template, read by id rather than found in the roster."""
+ row = await prisma.models.Expert.prisma().find_first(
+ where={"id": template_id, "isTemplate": True, "isArchived": False},
+ include=_TEMPLATE_WORKFLOW_INCLUDE,
+ )
+ return _to_model(row) if row else None
+
+
def _template_where(
search_query: str | None, category: str | None
) -> prisma.types.ExpertWhereInput:
diff --git a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
index 4c22586224..f879fde661 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db_test.py
@@ -5991,6 +5991,23 @@ async def _template(name: str, **fields) -> prisma.models.Expert:
return template
[email protected](loop_scope="session")
+async def test_get_template_reads_one_live_template_and_nothing_else(
+ server: SpinTestServer, test_user
+):
+ """The gate names a held hire's template inside a 1 s budget, so it reads
+ that one row; a retired template or a hired expert is not a template."""
+ suffix = uuid.uuid4().hex[:8]
+ live = await _template(f"Ada {suffix}")
+ retired = await _template(f"Old {suffix}", isArchived=True)
+ hired = await experts_db.hire_expert(test_user.id, live.id, None)
+
+ found = await experts_db.get_template(live.id)
+ assert found is not None and found.name == live.name and found.is_template
+ assert await experts_db.get_template(retired.id) is None
+ assert await experts_db.get_template(hired.expert.id) is None
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_list_templates_filters_by_category(server: SpinTestServer):
"""A category chip narrows the roster, and never widens it: an expert
diff --git a/autogpt_platform/backend/backend/copilot/gate/__init__.py b/autogpt_platform/backend/backend/copilot/gate/__init__.py
index 4106079bcc..71c12b776f 100644
--- a/autogpt_platform/backend/backend/copilot/gate/__init__.py
+++ b/autogpt_platform/backend/backend/copilot/gate/__init__.py
@@ -3,7 +3,8 @@
Ordering is the design, cheapest and most certain first:
1. gate inactive -> ALLOW (today's behaviour)
-2. an approval for exactly these args -> ALLOW, consumed single-use
+2. an approval for exactly these args -> ALLOW, consumed single-use;
+ a proposal card's Approve of the id a confirm applies counts as one
3. what the call acts on: a block, workflow or MCP tool's own effect, or
the tool's; a call that runs nothing never asks
4. the user's rule on that subject in this chat -> allow, judge or ask
@@ -28,6 +29,7 @@ from backend.util.feature_flag import Flag, is_feature_enabled
from . import chat_rules, held
from . import review as review_store
+from .card_approval import approved_on_card
from .classifier import DecidedBy, Judgement, supervise
from .headline import Headline
from .policy import (
@@ -212,6 +214,8 @@ async def check_action(
# The first call's card and stored call stand; re-storing would
# re-point the late result at the retry's tool call id.
return Decision(allowed=False, reason=_ALREADY_HELD, review_id=review_id)
+ if await approved_on_card(tool_name, args, user_id, session_id):
+ return Decision(allowed=True, approved=True, decided=True)
subject = await subject_of() if subject_of is not None else None
effect = subject.effect if subject is not None else effect_for(tool_name)
diff --git a/autogpt_platform/backend/backend/copilot/gate/card_approval.py b/autogpt_platform/backend/backend/copilot/gate/card_approval.py
new file mode 100644
index 0000000000..f167914e4d
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/gate/card_approval.py
@@ -0,0 +1,76 @@
+"""A proposal card's Approve is the user's answer to the confirm it asks about.
+
+A hire, raise, update or Soul-edit card sends the decision as a chat line naming
+the proposal's one-time id (``decisionLine`` in ``ToolChain/ExpertCards.tsx``).
+The chat route records that line from the user's own request, and the gate reads
+the record: a model can put text into a chat, but never through that request.
+"""
+
+import logging
+import re
+from typing import Any
+
+from backend.data.redis_client import get_redis_async
+
+logger = logging.getLogger(__name__)
+
+_CONFIRMS = frozenset({"confirm_expert_change", "confirm_expert_soul_update"})
+_KEY = "copilot:gate:card_approval:"
+# A proposal lives 15 minutes, so an approval of it never needs longer.
+_TTL_SECONDS = 15 * 60
+_DECISION = re.compile(
+ r"^(?P<verdict>Approved|Not approved): .+ \(confirmation_id: (?P<id>[^\s()]+)\)\.$"
+)
+
+
+async def record_card_decisions(user_id: str, session_id: str, message: str) -> None:
+ """Called by the chat route for a message the user sent, and by nothing else."""
+ decisions = [
+ (match["verdict"] == "Approved", match["id"])
+ for line in message.splitlines()
+ if (match := _DECISION.match(line.strip()))
+ ]
+ if not decisions:
+ return
+ try:
+ redis = await get_redis_async()
+ async with redis.pipeline(transaction=True) as pipe:
+ for approved, confirmation_id in decisions:
+ if approved:
+ pipe.hset(_key(session_id), _field(user_id, confirmation_id), "1")
+ else:
+ pipe.hdel(_key(session_id), _field(user_id, confirmation_id))
+ pipe.expire(_key(session_id), _TTL_SECONDS)
+ await pipe.execute()
+ except Exception:
+ # Unrecorded, the confirm just goes to the mode's verdict.
+ logger.warning(
+ f"Could not record card decisions for session {session_id}", exc_info=True
+ )
+
+
+async def approved_on_card(
+ tool_name: str, args: dict[str, Any], user_id: str, session_id: str
+) -> bool:
+ """True once, when this user approved exactly this id on its card in this chat."""
+ confirmation_id = args.get("confirmation_id")
+ if tool_name not in _CONFIRMS or not isinstance(confirmation_id, str):
+ return False
+ try:
+ redis = await get_redis_async()
+ # HDEL's count is the answer, so two confirms of one approval cannot both pass.
+ field = _field(user_id, confirmation_id)
+ return await redis.hdel(_key(session_id), field) == 1
+ except Exception:
+ logger.warning(
+ f"Could not read card approvals for session {session_id}", exc_info=True
+ )
+ return False
+
+
+def _key(session_id: str) -> str:
+ return f"{_KEY}{session_id}"
+
+
+def _field(user_id: str, confirmation_id: str) -> str:
+ return f"{user_id}:{confirmation_id}"
diff --git a/autogpt_platform/backend/backend/copilot/gate/card_approval_test.py b/autogpt_platform/backend/backend/copilot/gate/card_approval_test.py
new file mode 100644
index 0000000000..92bcc31a06
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/gate/card_approval_test.py
@@ -0,0 +1,73 @@
+"""The card-approval record on a real Redis: what the chat route writes, the
+gate reads once, for that user, in that chat."""
+
+import asyncio
+import uuid
+
+import pytest
+
+from backend.copilot.gate import card_approval
+from backend.copilot.gate.card_approval import approved_on_card, record_card_decisions
+from backend.data import redis_client
+from backend.data.redis_client import get_redis_async
+from backend.util.testing import is_tcp_port_reachable
+
+pytestmark = pytest.mark.skipif(
+ not is_tcp_port_reachable(redis_client.HOST, redis_client.PORT),
+ reason="needs Redis",
+)
+_CONFIRM = "confirm_expert_change"
+
+
+async def test_an_approval_is_read_once_by_its_user_in_its_chat():
+ chat, other_chat = f"s-{uuid.uuid4()}", f"s-{uuid.uuid4()}"
+ await record_card_decisions(
+ "u-1",
+ chat,
+ "Approved: create Otto (confirmation_id: c-1).\n"
+ "Not approved: do not create Ada, discard that proposal "
+ "(confirmation_id: c-2).",
+ )
+ ttl = await (await get_redis_async()).ttl(card_approval._key(chat))
+
+ assert 0 < ttl <= card_approval._TTL_SECONDS
+ assert not await approved_on_card(
+ _CONFIRM, {"confirmation_id": "c-1"}, "u-1", other_chat
+ )
+ assert not await approved_on_card(_CONFIRM, {"confirmation_id": "c-1"}, "u-2", chat)
+ assert not await approved_on_card(_CONFIRM, {"confirmation_id": "c-2"}, "u-1", chat)
+ assert await approved_on_card(_CONFIRM, {"confirmation_id": "c-1"}, "u-1", chat)
+ assert not await approved_on_card(_CONFIRM, {"confirmation_id": "c-1"}, "u-1", chat)
+
+
+async def test_a_later_decline_withdraws_an_approval():
+ chat = f"s-{uuid.uuid4()}"
+ await record_card_decisions(
+ "u-1", chat, "Approved: create Otto (confirmation_id: c-1)."
+ )
+ await record_card_decisions(
+ "u-1",
+ chat,
+ "Not approved: do not create Otto, discard that proposal "
+ "(confirmation_id: c-1).",
+ )
+
+ assert not await approved_on_card(_CONFIRM, {"confirmation_id": "c-1"}, "u-1", chat)
+
+
+async def test_concurrent_confirms_of_one_approval_pass_exactly_once():
+ # Repeated: the first burst on a cold connection rarely interleaves.
+ for _ in range(5):
+ chat = f"s-{uuid.uuid4()}"
+ await record_card_decisions(
+ "u-1", chat, "Approved: create Otto (confirmation_id: c-1)."
+ )
+
+ results = await asyncio.gather(
+ *(
+ approved_on_card(_CONFIRM, {"confirmation_id": "c-1"}, "u-1", chat)
+ for _ in range(10)
+ )
+ )
+
+ assert sum(results) == 1
diff --git a/autogpt_platform/backend/backend/copilot/gate/headline.py b/autogpt_platform/backend/backend/copilot/gate/headline.py
index d70bbe8258..0c63d59065 100644
--- a/autogpt_platform/backend/backend/copilot/gate/headline.py
+++ b/autogpt_platform/backend/backend/copilot/gate/headline.py
@@ -33,10 +33,6 @@ _ASK: dict[str, tuple[str, tuple[str, ...]]] = {
"delete_schedule": ("Delete a schedule", ()),
"setup_agent_webhook_trigger": ("Set up the trigger", ("name",)),
"create_feature_request": ("File a feature request", ("title",)),
- "hire_expert": ("Hire", ("name",)),
- "raise_expert": ("Create teammate", ("name",)),
- "update_expert": ("Update teammate", ("name",)),
- "update_expert_soul": ("Change how this teammate works", ()),
"confirm_expert_change": ("Confirm the team change", ()),
"confirm_expert_soul_update": ("Confirm the teammate change", ()),
"install_expert_workflow": ("Give a teammate a workflow", ()),
@@ -67,7 +63,6 @@ _OBJECT_ID: dict[str, str] = {
"pause_schedule": "schedule_id",
"resume_schedule": "schedule_id",
"delete_schedule": "schedule_id",
- "update_expert": "expert_id",
"confirm_expert_change": "confirmation_id",
"confirm_expert_soul_update": "confirmation_id",
"install_expert_workflow": "library_agent_id",
diff --git a/autogpt_platform/backend/backend/copilot/gate/policy.py b/autogpt_platform/backend/backend/copilot/gate/policy.py
index 80db962bfb..dcbd0fe794 100644
--- a/autogpt_platform/backend/backend/copilot/gate/policy.py
+++ b/autogpt_platform/backend/backend/copilot/gate/policy.py
@@ -131,13 +131,9 @@ _PLATFORM = frozenset(
"confirm_expert_change",
"confirm_expert_soul_update",
"grant_expert_credential",
- "hire_expert",
"install_expert_workflow",
- "raise_expert",
"remove_expert_workflow",
"revoke_expert_credential",
- "update_expert",
- "update_expert_soul",
"message_session",
"run_sub_session",
# Deletes inside the workspace: the user may have put the thing there.
@@ -161,6 +157,12 @@ _UNGATED = frozenset(
"connect_integration",
"request_credential_grant",
"resume_capability",
+ # Previews: they only park a proposal and put it to the user on its own
+ # card. The confirm that applies it is what the gate holds.
+ "hire_expert",
+ "raise_expert",
+ "update_expert",
+ "update_expert_soul",
}
)
diff --git a/autogpt_platform/backend/backend/copilot/gate/reference_cards_test.py b/autogpt_platform/backend/backend/copilot/gate/reference_cards_test.py
index 525da92b91..cb4fd4cab2 100644
--- a/autogpt_platform/backend/backend/copilot/gate/reference_cards_test.py
+++ b/autogpt_platform/backend/backend/copilot/gate/reference_cards_test.py
@@ -64,7 +64,6 @@ _CALLS: list[tuple[str, str, dict[str, Any]]] = [
},
),
("Pause schedule", "pause_schedule", {"schedule_id": "sch-digest"}),
- ("Hire expert", "hire_expert", {"template_id": "tpl-ada", "name": "Ada"}),
("Message chat", "message_session", {"session_id": "s-q3", "message": "Done?"}),
(
"Grant credential",
@@ -224,11 +223,12 @@ def _preset(id: str, name: str, description: str, webhook_id: str | None) -> Mag
def _experts() -> MagicMock:
experts = MagicMock()
- ada = _template("tpl-ada", "Ada", "Keeps the books balanced.", None, "Finance")
grace = _template(
"tpl-grace", "Grace", "Ships on Thursdays.", "Release manager", "Engineering"
)
- experts.list_templates = AsyncMock(return_value=[ada, grace])
+ experts.get_template = AsyncMock(
+ side_effect=lambda template_id: grace if template_id == grace.id else None
+ )
experts.with_bundled_skills = AsyncMock(
side_effect=lambda templates, user_id: templates
)
@@ -265,8 +265,7 @@ def _template(
_SKILLS = {
- "tpl-ada": ["Month-end close", "Receipt matching", "Cash forecast", "Payroll"],
- "tpl-grace": ["Release notes", "Changelog"],
+ "tpl-grace": ["Release notes", "Changelog", "Incident review", "Hotfixes"],
}
diff --git a/autogpt_platform/backend/backend/copilot/gate/references.py b/autogpt_platform/backend/backend/copilot/gate/references.py
index 9b9c3ae64a..efd604c700 100644
--- a/autogpt_platform/backend/backend/copilot/gate/references.py
+++ b/autogpt_platform/backend/backend/copilot/gate/references.py
@@ -31,7 +31,6 @@ Entity = Literal[
"chat_session",
"expert",
"expert_or_name",
- "expert_template",
"expert_workflow",
"credential",
"routine",
@@ -294,22 +293,6 @@ async def _expert_or_name(reference: str, call: _Call) -> _Found | None:
return _teammate(expert) if expert else None
-async def _expert_template(template_id: str, call: _Call) -> _Found | None:
- template = await _template(template_id, call.user_id)
- if template is None:
- return None
- return _Found(
- kind="Expert template",
- name=template.name,
- href=f"/marketplace/experts/{quote(template.id, safe='')}",
- description=template.tagline or template.bio,
- meta=[template.job_title or template.role, _area(template)],
- avatar_url=template.avatar_url,
- avatar_color=template.color,
- skills=[skill.title for skill in template.bundled_skills],
- )
-
-
async def _expert_workflow(workflow_id: str, call: _Call) -> _Found | None:
label = await experts_db().get_workflow_label(call.user_id, workflow_id)
if label is None or label.name is None:
@@ -447,7 +430,6 @@ _RESOLVERS: dict[Entity, Callable[[str, _Call], Awaitable[_Found | None]]] = {
"chat_session": _chat_session,
"expert": _expert,
"expert_or_name": _expert_or_name,
- "expert_template": _expert_template,
"expert_workflow": _expert_workflow,
"credential": _credential,
"routine": _routine,
@@ -509,8 +491,7 @@ def _teammate(expert: Expert) -> _Found:
async def _template(template_id: str, user_id: str) -> ExpertTemplate | None:
- templates = await experts_db().list_templates()
- template = next((t for t in templates if t.id == template_id), None)
+ template = await experts_db().get_template(template_id)
if template is None:
return None
[card] = await experts_db().with_bundled_skills([template], user_id)
diff --git a/autogpt_platform/backend/backend/copilot/gate/references_test.py b/autogpt_platform/backend/backend/copilot/gate/references_test.py
index a6ea360c81..403282aa54 100644
--- a/autogpt_platform/backend/backend/copilot/gate/references_test.py
+++ b/autogpt_platform/backend/backend/copilot/gate/references_test.py
@@ -246,6 +246,42 @@ async def test_a_pending_team_change_is_named_only_in_its_own_chat(
redis.delete.assert_not_called()
+async def test_a_held_hire_is_named_however_slow_the_whole_roster_is():
+ """Prod timed out listing every template inside the budget and showed the
+ raw id instead of the name (2026-09-30); the template is read by id now."""
+ from backend.copilot.tools.expert_proposal import ExpertChangeProposal
+ from backend.copilot.tools.models import ExpertChangePreview
+
+ session = _session()
+ proposal = ExpertChangeProposal(
+ user_id="user-1",
+ session_id=session.session_id,
+ preview=ExpertChangePreview(kind="hire", name="Ada", template_id="tpl-ada"),
+ )
+ redis = MagicMock(get=AsyncMock(return_value=proposal.model_dump_json()))
+ template = MagicMock(id="tpl-ada", categories=["Finance"])
+ template.bundled_skills = [MagicMock(title="Payroll")]
+
+ async def list_the_roster():
+ await asyncio.sleep(references.LOOKUP_SECONDS * 10)
+ return [template]
+
+ experts = MagicMock()
+ experts.list_templates = AsyncMock(side_effect=list_the_roster)
+ experts.get_template = AsyncMock(return_value=template)
+ experts.with_bundled_skills = AsyncMock(side_effect=lambda ts, _: ts)
+ with (
+ patch.object(references, "get_redis_async", AsyncMock(return_value=redis)),
+ patch.object(references, "experts_db", return_value=experts),
+ ):
+ [ref] = await resolve_references(
+ "confirm_expert_change", {"confirmation_id": "c-1"}, "user-1", session
+ )
+
+ assert ref.name == "Ada"
+ assert ref.skills == ["Payroll"]
+
+
def _session() -> ChatSession:
return ChatSession.new(user_id="user-1", dry_run=False)
diff --git a/autogpt_platform/backend/backend/copilot/gate/review_test.py b/autogpt_platform/backend/backend/copilot/gate/review_test.py
index 4b62ad6118..d120bee841 100644
--- a/autogpt_platform/backend/backend/copilot/gate/review_test.py
+++ b/autogpt_platform/backend/backend/copilot/gate/review_test.py
@@ -102,9 +102,7 @@ def test_the_headline_names_the_action_and_its_object():
"object": "Q3 reports",
"object_key": "name",
}
- assert headline_for("raise_expert", {"name": "Ada"}).text == (
- "Create teammate “Ada”"
- )
+ assert headline_for("delete_skill", {"name": "Ada"}).text == ("Delete skill “Ada”")
assert headline_for("delete_folder", {"folder_id": "f1"}).text == (
"Delete library folder"
)
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_change_gate_test.py b/autogpt_platform/backend/backend/copilot/tools/expert_change_gate_test.py
new file mode 100644
index 0000000000..de7fac18b7
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_change_gate_test.py
@@ -0,0 +1,429 @@
+"""A hire, raise or Soul edit asks the user once: the preview never holds, and
+the card's own Approve, recorded by the chat route, answers the confirm.
+
+Driven through ``BaseTool.execute`` with the gate on, as both engines call it.
+"""
+
+import json
+import os
+import uuid
+from contextlib import contextmanager
+from datetime import UTC, datetime
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any, Callable
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from prisma.enums import ReviewStatus
+
+from backend.copilot.gate import card_approval, held
+from backend.copilot.gate.card_approval import record_card_decisions
+from backend.copilot.gate.classifier import Judgement
+from backend.copilot.gate.headline import Headline
+from backend.copilot.gate.review import review_payload
+from backend.copilot.model import (
+ AutopilotMode,
+ ChatMessage,
+ ChatSession,
+ ChatSessionMetadata,
+)
+from backend.copilot.trial_cost_context import TrialCostContext
+
+from . import hire_expert, raise_expert, update_soul
+from .base import BaseTool
+from .confirm_expert_change import ConfirmExpertChangeTool
+from .expert_change_test import _CHARTER, _USER, _env, _FakeRedis
+from .expert_delegation import sent_from_metadata
+from .hire_expert import HireExpertTool
+from .message_session import _render
+from .raise_expert import RaiseExpertTool
+from .update_expert import UpdateExpertTool
+from .update_soul import ConfirmExpertSoulUpdateTool, UpdateExpertSoulTool
+
+_GATE = "backend.copilot.gate"
+FIXTURES = (
+ Path(__file__).parents[4]
+ / "frontend/src/app/(platform)/copilot/components/ToolChain/__tests__"
+)
+_ID = "5f0c2a3e-7b1d-4c9e-8a6f-0d2b4e6c8a10"
+# What the card sends: ``decisionLine`` in ExpertCards.tsx, pinned by its test.
+_APPROVED = f"Approved: create Otto (confirmation_id: {_ID})."
+_IN_A_GROUP = (
+ "Not approved: do not create Ada, discard that proposal "
+ f"(confirmation_id: c-other).\n{_APPROVED}"
+)
+_DECLINED = (
+ "Not approved: do not create Otto, discard that proposal "
+ f"(confirmation_id: {_ID})."
+)
+_SOUL_APPROVED = f"Approved: update your Soul (confirmation_id: {_ID})."
+_FIXED_UUID = SimpleNamespace(uuid4=lambda: uuid.UUID(_ID))
+_PREVIEWS: list[tuple[BaseTool, dict[str, Any]]] = [
+ (HireExpertTool(), {"template_id": "tpl-scout"}),
+ (RaiseExpertTool(), _CHARTER),
+ (UpdateExpertTool(), {"expert_id": "exp-2", "name": "Nick"}),
+]
+
+
+def gate():
+ """The gate on, no approval on record; the supervisor holds whatever it sees."""
+ store = SimpleNamespace(
+ find_review=AsyncMock(return_value=None),
+ open_review=AsyncMock(return_value=Headline(ask="Confirm the team change")),
+ supervise=AsyncMock(
+ return_value=Judgement(allowed=False, reason="Check with the user.")
+ ),
+ remember=AsyncMock(return_value=True),
+ )
+ with (
+ patch(f"{_GATE}.is_feature_enabled", AsyncMock(return_value=True)),
+ patch(f"{_GATE}.review_store.find_review", store.find_review),
+ patch(f"{_GATE}.review_store.open_review", store.open_review),
+ patch(f"{_GATE}.held.remember", store.remember),
+ patch(f"{_GATE}.chat_rules.rule_for", AsyncMock(return_value=None)),
+ patch(f"{_GATE}.supervise", store.supervise),
+ patch(
+ f"{_GATE}.capture_cost_context",
+ AsyncMock(
+ side_effect=lambda user_id: TrialCostContext(
+ user_id=user_id, trial_id=None
+ )
+ ),
+ ),
+ patch(f"{_GATE}.reads.release_held_read", AsyncMock(return_value=None)),
+ patch(f"{_GATE}.reads.screen_read", AsyncMock(return_value=None)),
+ patch.object(hire_expert, "uuid", _FIXED_UUID),
+ patch.object(raise_expert, "uuid", _FIXED_UUID),
+ patch.object(update_soul, "uuid", _FIXED_UUID),
+ patch.object(
+ card_approval, "get_redis_async", AsyncMock(return_value=_Approvals())
+ ),
+ ):
+ yield store
+
+
[email protected]("mode", ["ask_first", "auto"])
+ "tool, args", _PREVIEWS, ids=[tool.name for tool, _ in _PREVIEWS]
+)
+async def test_a_preview_puts_its_card_up_without_a_gate_card(gate, mode, tool, args):
+ with _env():
+ output = _output(await tool.execute(_USER, _session(mode), "call-1", **args))
+
+ assert output["type"] == "expert_change_proposed"
+ assert output["confirmation_id"]
+ gate.open_review.assert_not_awaited()
+
+
[email protected]("mode", ["ask_first", "auto"])
+ "preview, args, reply, created",
+ [
+ (
+ HireExpertTool(),
+ {"template_id": "tpl-scout"},
+ f"Approved: hire Scout (confirmation_id: {_ID}).",
+ lambda db: db.hire_expert,
+ ),
+ (RaiseExpertTool(), _CHARTER, _APPROVED, lambda db: db.create_raised_expert),
+ # Send decisions puts one line per proposal in a single message.
+ (RaiseExpertTool(), _CHARTER, _IN_A_GROUP, lambda db: db.create_raised_expert),
+ ],
+ ids=["hire", "raise", "raise-in-a-group"],
+)
+async def test_one_approval_on_the_card_creates_the_teammate(
+ gate,
+ mode,
+ preview: BaseTool,
+ args: dict[str, Any],
+ reply: str,
+ created: Callable[[MagicMock], AsyncMock],
+):
+ session = _session(mode)
+ with _env() as db:
+ await preview.execute(_USER, session, "call-1", **args)
+ await _send(session, reply)
+ output = _output(
+ await ConfirmExpertChangeTool().execute(
+ _USER, session, "call-2", confirmation_id=_ID
+ )
+ )
+
+ assert output["type"] == "expert_change_applied"
+ created(db).assert_awaited_once()
+ gate.open_review.assert_not_awaited()
+ gate.supervise.assert_not_awaited()
+
+
[email protected]("mode", ["ask_first", "auto"])
+ "replies",
+ [
+ ["yes"],
+ [_DECLINED],
+ [_APPROVED.replace(_ID, "c-other")],
+ [_APPROVED, _DECLINED],
+ ],
+ ids=["typed-yes", "declined", "another-proposal", "approved-then-declined"],
+)
+async def test_a_confirm_the_card_did_not_approve_still_goes_to_the_gate(
+ gate, mode, replies
+):
+ session = _session(mode)
+ with _env() as db:
+ await RaiseExpertTool().execute(_USER, session, "call-1", **_CHARTER)
+ for reply in replies:
+ await _send(session, reply)
+ result = await ConfirmExpertChangeTool().execute(
+ _USER, session, "call-2", confirmation_id=_ID
+ )
+
+ assert _output(result)["type"] == "approval_required"
+ db.create_raised_expert.assert_not_awaited()
+ gate.open_review.assert_awaited_once()
+
+
[email protected]("mode", ["ask_first", "auto"])
+ "forwarded", ["message_session", "delegation"], ids=lambda kind: kind
+)
+async def test_an_approval_line_a_model_puts_in_the_chat_is_not_consent(
+ gate, mode, forwarded
+):
+ """Another session can write the card's exact line into this chat as a
+ user row; only the user's own request records an approval."""
+ session = _session(mode)
+ sender = _session(mode).model_copy(update={"session_id": "session-2"})
+ with _env() as db:
+ await RaiseExpertTool().execute(_USER, session, "call-1", **_CHARTER)
+ body = (
+ _render(sender, _APPROVED) if forwarded == "message_session" else _APPROVED
+ )
+ _reply(session, body, sent_from_metadata(sender))
+ result = await ConfirmExpertChangeTool().execute(
+ _USER, session, "call-2", confirmation_id=_ID
+ )
+
+ assert _output(result)["type"] == "approval_required"
+ db.create_raised_expert.assert_not_awaited()
+
+
[email protected]("mode", ["ask_first", "auto"])
+async def test_an_approval_line_a_model_puts_in_a_soul_chat_is_not_consent(gate, mode):
+ """The Soul confirm has no other check, so the recorded approval is its only way."""
+ session = _session(mode, expert_id="exp-1")
+ sender = _session(mode).model_copy(update={"session_id": "session-2"})
+ with _soul_env() as db:
+ await UpdateExpertSoulTool().execute(
+ _USER, session, "call-1", voice_preferences="Warmer."
+ )
+ _reply(session, _render(sender, _SOUL_APPROVED), sent_from_metadata(sender))
+ result = await ConfirmExpertSoulUpdateTool().execute(
+ _USER, session, "call-2", confirmation_id=_ID
+ )
+
+ assert _output(result)["type"] == "approval_required"
+ db.update_soul_fields_if_current.assert_not_awaited()
+
+
[email protected]("mode", ["ask_first", "auto"])
+ "reply, asks", [(_SOUL_APPROVED, False), ("yes", True)], ids=["card", "typed"]
+)
+async def test_a_soul_edit_is_asked_once_on_its_card(gate, mode, reply, asks):
+ session = _session(mode, expert_id="exp-1")
+ with _soul_env() as db:
+ preview = _output(
+ await UpdateExpertSoulTool().execute(
+ _USER, session, "call-1", voice_preferences="Warmer."
+ )
+ )
+ gate.open_review.assert_not_awaited()
+ await _send(session, reply)
+ output = _output(
+ await ConfirmExpertSoulUpdateTool().execute(
+ _USER, session, "call-2", confirmation_id=_ID
+ )
+ )
+
+ assert preview["type"] == "expert_soul_updated"
+ assert (output["type"] == "approval_required") is asks
+ assert db.update_soul_fields_if_current.await_count == (0 if asks else 1)
+ assert gate.open_review.await_count == (1 if asks else 0)
+
+
+# Each fixture is rendered by the frontend's tests; UPDATE_CARD_FIXTURE=1 rewrites them.
+async def test_the_gated_proposal_fixture_is_what_a_preview_returns(gate):
+ """ExpertCards.test.tsx: a preview that holds again returns a gate
+ refusal here instead, and no Approve button."""
+ with _env():
+ result = await RaiseExpertTool().execute(
+ _USER, _session("ask_first"), "call-1", **_CHARTER
+ )
+ _assert_fixture("gatedProposal.json", _output(result))
+
+
+async def test_the_soul_proposal_fixture_is_what_a_soul_preview_returns(gate):
+ with _soul_env():
+ result = await UpdateExpertSoulTool().execute(
+ _USER,
+ _session("ask_first", expert_id="exp-1"),
+ "call-1",
+ voice_preferences="Warmer.",
+ )
+ _assert_fixture("soulProposal.json", _output(result))
+
+
+async def test_the_held_confirm_fixture_is_what_an_approved_hold_delivers(gate):
+ """ChainMessagePartsCards.test.tsx: a confirm held after a typed "yes", and
+ the late result the next turn writes once the user approves its card."""
+ session = _session("ask_first")
+ with _env():
+ await RaiseExpertTool().execute(_USER, session, "call-1", **_CHARTER)
+ _reply(session, "yes")
+ stub = _output(
+ await ConfirmExpertChangeTool().execute(
+ _USER, session, "call-2", confirmation_id=_ID
+ )
+ )
+ review_id = stub["review_id"]
+ # The call as the gate stored it, so the late result is built from the real hold.
+ call: held.HeldCall = gate.remember.await_args.args[1]
+ assert call.review_id == review_id
+ gate.find_review.return_value = SimpleNamespace(
+ status=ReviewStatus.APPROVED, payload={}
+ )
+ approved = SimpleNamespace(
+ status=ReviewStatus.APPROVED,
+ session_id=session.session_id,
+ reviewed_at=datetime.now(UTC),
+ # The card the gate stored; the late result carries its arguments.
+ payload=review_payload(call.tool_name, call.args),
+ )
+ reviews = SimpleNamespace(
+ get_reviews_by_node_exec_ids=AsyncMock(return_value={review_id: approved})
+ )
+ with (
+ patch(f"{_GATE}.held._held", AsyncMock(return_value={review_id: call})),
+ patch(f"{_GATE}.held._claim", AsyncMock(return_value=True)),
+ patch(f"{_GATE}.held.review_db", return_value=reviews),
+ patch(f"{_GATE}.review_store.consume", AsyncMock(return_value=True)),
+ ):
+ [row] = await held.resolve_answered(_USER, session)
+
+ assert row.metadata["held_call"]["outcome"] == "approved"
+ part = {
+ "type": "tool-confirm_expert_change",
+ "toolCallId": "call-2",
+ "state": "output-available",
+ "input": call.args,
+ "output": stub,
+ }
+ result = {"content": row.content, "metadata": row.metadata}
+ _assert_fixture("heldConfirm.json", {"part": part, "result": result})
+
+
+def _assert_fixture(name: str, value: Any) -> None:
+ path = FIXTURES / name
+ if os.environ.get("UPDATE_CARD_FIXTURE"):
+ path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n")
+ assert (
+ json.loads(path.read_text()) == value
+ ), f"{name} is stale; rerun with UPDATE_CARD_FIXTURE=1"
+
+
+@contextmanager
+def _soul_env():
+ db = MagicMock()
+ db.get_expert = AsyncMock(
+ return_value=SimpleNamespace(
+ identity="You keep the books balanced.",
+ voice_preferences="Short and factual.",
+ boundaries="You never move money yourself.",
+ )
+ )
+ db.update_soul_fields_if_current = AsyncMock(return_value=True)
+ redis = AsyncMock(return_value=_FakeRedis())
+ with (
+ patch.object(update_soul, "experts_db", MagicMock(return_value=db)),
+ patch(
+ "backend.copilot.tools.soul_proposal.experts_db",
+ MagicMock(return_value=db),
+ ),
+ patch.object(update_soul, "get_redis_async", redis),
+ ):
+ yield db
+
+
+def _session(mode: AutopilotMode, expert_id: str | None = None) -> ChatSession:
+ return ChatSession(
+ session_id="session-1",
+ user_id=_USER,
+ usage=[],
+ started_at=datetime.now(UTC),
+ updated_at=datetime.now(UTC),
+ expert_id=expert_id,
+ metadata=ChatSessionMetadata(origin="interactive", autopilot_mode=mode),
+ messages=[ChatMessage(role="user", content="Add a teammate", sequence=0)],
+ )
+
+
+async def _send(session: ChatSession, content: str) -> None:
+ """What the chat route does with a message the user sends, then the row it saves."""
+ await record_card_decisions(_USER, session.session_id, content)
+ _reply(session, content)
+
+
+def _reply(session: ChatSession, content: str, metadata: dict | None = None) -> None:
+ session.messages.append(
+ ChatMessage(
+ role="user",
+ content=content,
+ sequence=len(session.messages),
+ metadata=metadata,
+ )
+ )
+
+
+def _output(result) -> dict[str, Any]:
+ return json.loads(result.output)
+
+
+class _Approvals:
+ """The Redis surface ``card_approval`` uses: a consuming delete, pipelined writes."""
+
+ def __init__(self):
+ self.hashes: dict[str, dict[str, str]] = {}
+
+ def pipeline(self, transaction: bool = True) -> "_Writes":
+ return _Writes(self.hashes)
+
+ async def hdel(self, key: str, field: str) -> int:
+ return 1 if self.hashes.get(key, {}).pop(field, None) is not None else 0
+
+
+class _Writes:
+ def __init__(self, hashes: dict[str, dict[str, str]]):
+ self.hashes = hashes
+ self.ops: list[Callable[[], object]] = []
+
+ async def __aenter__(self) -> "_Writes":
+ return self
+
+ async def __aexit__(self, *exc: object) -> None:
+ return None
+
+ def hset(self, key: str, field: str, value: str) -> None:
+ self.ops.append(lambda: self.hashes.setdefault(key, {}).update({field: value}))
+
+ def hdel(self, key: str, field: str) -> None:
+ self.ops.append(lambda: self.hashes.get(key, {}).pop(field, None))
+
+ def expire(self, key: str, seconds: int) -> None:
+ pass
+
+ async def execute(self) -> None:
+ for op in self.ops:
+ op()
diff --git a/autogpt_platform/backend/backend/copilot/tools/hire_expert.py b/autogpt_platform/backend/backend/copilot/tools/hire_expert.py
index 8a5fff9f74..9eb5bf706b 100644
--- a/autogpt_platform/backend/backend/copilot/tools/hire_expert.py
+++ b/autogpt_platform/backend/backend/copilot/tools/hire_expert.py
@@ -68,7 +68,6 @@ class HireExpertTool(BaseTool):
"template_id": {
"type": "string",
"description": ("Roster template to hire; never invent an id."),
- "entity": "expert_template",
},
"name": {
"type": "string",
diff --git a/autogpt_platform/backend/backend/copilot/tools/update_soul.py b/autogpt_platform/backend/backend/copilot/tools/update_soul.py
index 86c3c30ab0..a24d3eebad 100644
--- a/autogpt_platform/backend/backend/copilot/tools/update_soul.py
+++ b/autogpt_platform/backend/backend/copilot/tools/update_soul.py
@@ -81,8 +81,8 @@ class UpdateExpertSoulTool(BaseTool):
return (
"Propose an edit to this expert's Soul — identity/personality, "
"voice preferences, or boundaries. Never writes: it returns the "
- "before/after diff plus a one-time confirmation_id. Show the user "
- "the diff and, only after they explicitly approve, call "
+ "before/after diff plus a one-time confirmation_id. The user sees "
+ "the diff on a card; only after they approve, call "
"tool:confirm_expert_soul_update with that confirmation_id."
)
@@ -186,9 +186,11 @@ class UpdateExpertSoulTool(BaseTool):
)
return ExpertSoulUpdatedResponse(
message=(
- "Nothing saved yet. Show the user this before/after diff and ask "
- "them to approve. Only after they explicitly approve, call "
- "tool:confirm_expert_soul_update with this confirmation_id."
+ "Nothing saved yet. The user is looking at this diff on a card "
+ "with Approve and Decline buttons — do not repeat it in text. "
+ "Reply with one short line at most and wait. Only after they "
+ "explicitly approve, call tool:confirm_expert_soul_update with "
+ "this confirmation_id."
),
session_id=session_id,
applied=False,
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index 4b0b023159..b33ff6620c 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -725,6 +725,7 @@ class DatabaseManager(AppService):
# Hire / raise from the copilot chat tools, plus the counts their
# preview step uses to refuse a change that could never land.
list_templates = _(experts_db.list_templates)
+ get_template = _(experts_db.get_template)
with_bundled_skills = _(experts_db.with_bundled_skills)
hire_expert = _(experts_db.hire_expert)
expert_setup_status = _(experts_db.expert_setup_status)
@@ -1243,6 +1244,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
revoke_expert_credential = d.revoke_expert_credential
list_expert_credentials = d.list_expert_credentials
list_templates = d.list_templates
+ get_template = d.get_template
with_bundled_skills = d.with_bundled_skills
hire_expert = d.hire_expert
expert_setup_status = d.expert_setup_status
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/chatSurfaceFixtures.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/chatSurfaceFixtures.ts
index 7fa1cf4864..a2f8c7df25 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/chatSurfaceFixtures.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/chatSurfaceFixtures.ts
@@ -5,6 +5,7 @@ import {
EXPERT_CHANGE_TOOLS,
} from "../components/ToolChain/helpers";
import { EXPERT_ONBOARDING_PART_TYPE } from "../components/ExpertOnboardingCard/helpers";
+import soulProposal from "../components/ToolChain/__tests__/soulProposal.json";
type Message = UIMessage<unknown, UIDataTypes, UITools>;
type Part = Message["parts"][number];
@@ -445,6 +446,12 @@ export const CARD_FIXTURES: Record<string, CardFixture> = Object.fromEntries([
expertProposal("hire", "Theo", "Analyst"),
"Analyst",
),
+ card("update_expert_soul", soulProposal, "Update Soul"),
+ card(
+ "confirm_expert_soul_update",
+ { ...soulProposal, applied: true },
+ "Soul updated",
+ ),
]);
/** One turn: the user asks, and the assistant's reply is the card under test.
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx
index 46bd557330..08b423e86b 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/ApprovalQueue.stories.tsx
@@ -151,8 +151,8 @@ export const NamedSchedule: Story = {
args: queueOf([referenceCard("Pause schedule")]),
};
-export const NamedTemplate: Story = {
- args: queueOf([referenceCard("Hire expert")]),
+export const NamedHire: Story = {
+ args: queueOf([referenceCard("Confirm team change")]),
};
export const NamedChat: Story = {
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/referenceCards.json b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/referenceCards.json
index 8e0b00565d..77c8137b12 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/referenceCards.json
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/referenceCards.json
@@ -301,8 +301,8 @@
}
],
"reference_totals": {
- "agent_ids": 7,
- "folder_id": 1
+ "folder_id": 1,
+ "agent_ids": 7
},
"tool_call_id": "call-move_agents_to_folder",
"turn": 1,
@@ -421,94 +421,6 @@
"status": "WAITING"
}
},
- {
- "story": "Hire expert",
- "review": {
- "node_exec_id": "copilot-node-gate-hire_expert:3ffe656fbe28a59c",
- "node_id": "copilot-node-gate-hire_expert",
- "user_id": "user-1",
- "session_id": "s1",
- "graph_exec_id": null,
- "graph_id": null,
- "graph_version": null,
- "payload": {
- "tool": "hire_expert",
- "arguments": {
- "template_id": "tpl-ada",
- "name": "Ada"
- },
- "clipped": [],
- "fields": [
- {
- "key": "template_id",
- "label": "Template",
- "format": null
- },
- {
- "key": "name",
- "label": "Name",
- "format": null
- }
- ],
- "references": [
- {
- "key": "template_id",
- "entity": "expert_template",
- "id": "tpl-ada",
- "name": "Ada",
- "href": "/marketplace/experts/tpl-ada",
- "kind": "Expert template",
- "description": "Keeps the books balanced.",
- "meta": [
- {
- "text": "Finance",
- "cron": null,
- "label": null,
- "at": null
- }
- ],
- "avatar_url": null,
- "avatar_color": "#7c3aed",
- "skills": [
- "Month-end close",
- "Receipt matching",
- "Cash forecast",
- "Payroll"
- ],
- "summary": "Finance"
- }
- ],
- "reference_totals": {
- "template_id": 1
- },
- "tool_call_id": "call-hire_expert",
- "turn": 1,
- "mode": "ask_first",
- "subject": {
- "kind": "tool",
- "key": "hire_expert",
- "name": "Hire",
- "effect": "platform",
- "irreversible": false,
- "block_id": null
- },
- "reason": "Ask First is on for this chat, so this action needs your approval.",
- "reason_kind": "mode",
- "decided_by": null,
- "chat_rules_allowed": ["allow", "judge"],
- "headline": {
- "ask": "Hire",
- "object": "Ada",
- "object_key": "name"
- },
- "spend": null,
- "workflow": null
- },
- "instructions": "hire_expert",
- "editable": false,
- "status": "WAITING"
- }
- },
{
"story": "Message chat",
"review": {
@@ -1264,7 +1176,12 @@
],
"avatar_url": null,
"avatar_color": "#7c3aed",
- "skills": ["Release notes", "Changelog"],
+ "skills": [
+ "Release notes",
+ "Changelog",
+ "Incident review",
+ "Hotfixes"
+ ],
"summary": "Release manager · Engineering"
}
],
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/references.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/references.test.tsx
index 79b5ebd33b..e240be98de 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/references.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ApprovalQueue/__tests__/references.test.tsx
@@ -48,14 +48,6 @@ test("a list of ids reads as linked names, the unresolved one as its id", async
expect(view.getByText(/\+2 more/)).toBeDefined();
});
-test("a resolved id links to its page", async () => {
- renderCard(referenceCard("Hire expert"));
-
- const view = await card();
- const template = view.getByRole("link", { name: "Ada" });
- expect(template.getAttribute("href")).toBe("/marketplace/experts/tpl-ada");
-});
-
test("an id nothing resolved stays the raw id with no link", async () => {
renderCard(referenceCard("Unresolved id"));
@@ -66,13 +58,13 @@ test("an id nothing resolved stays the raw id with no link", async () => {
});
test("a stored link that leaves the app is dropped, the name kept", async () => {
- const review = referenceCard("Hire expert");
+ const review = referenceCard("Message chat");
const payload = review.payload as { references: { href: string }[] };
payload.references[0].href = "https://evil.example/phish";
renderCard(review);
const view = await card();
- expect(view.getByText("Ada", { selector: "span" })).toBeDefined();
+ expect(view.getByText("Q3 planning", { selector: "span" })).toBeDefined();
expect(view.queryAllByRole("link")).toHaveLength(0);
});
@@ -117,15 +109,15 @@ test("a chat's card says how long ago it was last active", async () => {
expect(tip.textContent).not.toContain("2026-09-24");
});
-test("a template's card lists its skills, as the marketplace card does", async () => {
- renderCard(referenceCard("Hire expert"));
+test("a hire's card lists its template's skills, as the marketplace card does", async () => {
+ renderCard(referenceCard("Confirm team change"));
const view = await card();
- await userEvent.hover(view.getByRole("link", { name: "Ada" }));
+ await userEvent.hover(view.getByText("Grace"));
const tip = within(await screen.findByRole("tooltip"));
expect(
- tip.getByText("Month-end close, Receipt matching, Cash forecast +1 more"),
+ tip.getByText("Release notes, Changelog, Incident review +1 more"),
).toBeDefined();
});
@@ -140,6 +132,16 @@ test("a card with nothing but its kind shows only the kind, title and ID", async
expect(lines).toEqual(["Expert workflow", "Receipt matcher", "wf-receipts"]);
});
+test("a held team change names who joins, never its one-time id", async () => {
+ renderCard(referenceCard("Confirm team change"));
+
+ const view = await card();
+ expect(
+ view.getByRole("heading", { name: /Confirm the team change.*Grace/ }),
+ ).toBeDefined();
+ expect(view.queryByText("cf-1")).toBeNull();
+});
+
test("a named thing with no page still shows its card, unlinked", async () => {
renderCard(referenceCard("Confirm team change"));
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChainMessageParts.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChainMessageParts.tsx
index 8ad3dcc72e..9a54b1465a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChainMessageParts.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/ChainMessageParts.tsx
@@ -1,6 +1,8 @@
import { isChainableToolPart, type MessagePart } from "../helpers";
import type { ToolUIPart } from "ai";
-import { useMemo } from "react";
+import { useContext, useMemo } from "react";
+import { HeldOutcomesContext } from "../HeldOutcomesContext";
+import { withHeldOutcome } from "../heldCallRows";
import { ExpertChangeGroup } from "../../ToolChain/ExpertCards";
import { buildChainSegments } from "../../ToolChain/helpers";
import { ToolChain } from "../../ToolChain/ToolChain";
@@ -33,6 +35,7 @@ export function ChainMessageParts({
liveCompactionCallId,
liveCompactionStats,
}: Props) {
+ const outcomes = useContext(HeldOutcomesContext);
// Kept per `parts` so each ToolChain gets the same `parts` array back and
// its own row derivation stays memoised.
const segments = useMemo(
@@ -56,11 +59,17 @@ export function ChainMessageParts({
/>
);
}
+ // Outside the chain a part renders from its held call's outcome; chain rows
+ // keep the stub, which applyHeldOutcome words.
if (segment.kind === "experts") {
return (
<ExpertChangeGroup
key={`${messageID}-experts-${segment.index}`}
- parts={segment.parts as ToolUIPart[]}
+ parts={
+ segment.parts.map((part) =>
+ withHeldOutcome(part, outcomes),
+ ) as ToolUIPart[]
+ }
isCurrentlyStreaming={isCurrentlyStreaming}
readOnly={readOnly}
/>
@@ -69,7 +78,7 @@ export function ChainMessageParts({
return (
<MessagePartRenderer
key={`${messageID}-${segment.index}`}
- part={segment.part}
+ part={withHeldOutcome(segment.part, outcomes)}
messageID={messageID}
partIndex={segment.index}
onRetry={onRetry}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ChainMessageParts.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ChainMessageParts.test.tsx
index 2e1070a614..6a794b01a2 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ChainMessageParts.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ChainMessageParts.test.tsx
@@ -1,5 +1,9 @@
import { cleanup, render, screen } from "@testing-library/react";
+import type { UIDataTypes, UIMessage, UITools } from "ai";
import { afterEach, describe, expect, it, vi } from "vitest";
+import heldConfirm from "../../../ToolChain/__tests__/heldConfirm.json";
+import { HeldOutcomesContext } from "../../HeldOutcomesContext";
+import { getHeldOutcomes } from "../../heldCallRows";
import type { MessagePart } from "../../helpers";
import { ChainMessageParts } from "../ChainMessageParts";
@@ -25,8 +29,16 @@ vi.mock("../MessagePartRenderer", () => ({
}));
vi.mock("../../../ToolChain/ExpertCards", () => ({
- ExpertChangeGroup: ({ parts }: { parts: unknown[] }) => (
- <div data-testid="expert-group" data-count={parts.length} />
+ ExpertChangeGroup: ({
+ parts,
+ }: {
+ parts: { output?: { type?: string } }[];
+ }) => (
+ <div
+ data-testid="expert-group"
+ data-count={parts.length}
+ data-outputs={parts.map((part) => part.output?.type).join(",")}
+ />
),
}));
@@ -185,4 +197,56 @@ describe("ChainMessageParts", () => {
expect(toolChainParts).toHaveLength(2);
expect(toolChainParts[1]).toBe(toolChainParts[0]);
});
+
+ it("redraws a held card outside the chain when its result lands, and keeps the chain's parts", () => {
+ const parts = [
+ {
+ type: "tool-web_search",
+ state: "output-available",
+ toolCallId: "search",
+ input: {},
+ output: {},
+ },
+ heldConfirm.part,
+ ] as MessagePart[];
+ const turn: Message = { id: "a1", role: "assistant", parts };
+ const lateResult: Message = {
+ id: "u1",
+ role: "user",
+ metadata: heldConfirm.result.metadata,
+ parts: [{ type: "text", text: heldConfirm.result.content }],
+ };
+ toolChainParts.length = 0;
+
+ const { rerender } = render(
+ <HeldOutcomesContext.Provider value={getHeldOutcomes([turn])}>
+ <ChainMessageParts
+ parts={parts}
+ messageID="a1"
+ isCurrentlyStreaming={false}
+ />
+ </HeldOutcomesContext.Provider>,
+ );
+ expect(screen.getByTestId("expert-group").dataset.outputs).toBe(
+ "approval_required",
+ );
+
+ rerender(
+ <HeldOutcomesContext.Provider value={getHeldOutcomes([turn, lateResult])}>
+ <ChainMessageParts
+ parts={parts}
+ messageID="a1"
+ isCurrentlyStreaming={false}
+ />
+ </HeldOutcomesContext.Provider>,
+ );
+
+ expect(screen.getByTestId("expert-group").dataset.outputs).toBe(
+ "expert_change_applied",
+ );
+ expect(toolChainParts).toHaveLength(2);
+ expect(toolChainParts[1]).toBe(toolChainParts[0]);
+ });
});
+
+type Message = UIMessage<unknown, UIDataTypes, UITools>;
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ChainMessagePartsCards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ChainMessagePartsCards.test.tsx
new file mode 100644
index 0000000000..161ff8df31
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/components/__tests__/ChainMessagePartsCards.test.tsx
@@ -0,0 +1,153 @@
+import { render, screen } from "@/tests/integrations/test-utils";
+import userEvent from "@testing-library/user-event";
+import type { ToolUIPart, UIDataTypes, UIMessage, UITools } from "ai";
+import { expect, test, vi } from "vitest";
+import { CopilotChatActionsProvider } from "../../../CopilotChatActionsProvider/CopilotChatActionsProvider";
+import heldConfirm from "../../../ToolChain/__tests__/heldConfirm.json";
+import soulProposal from "../../../ToolChain/__tests__/soulProposal.json";
+import { HeldOutcomesContext } from "../../HeldOutcomesContext";
+import { answeredLabel, getHeldOutcomes } from "../../heldCallRows";
+import { ChainMessageParts } from "../ChainMessageParts";
+
+// Both payloads are what the backend builds: expert_change_gate_test.py.
+type Message = UIMessage<unknown, UIDataTypes, UITools>;
+
+const heldTurn: Message = {
+ id: "a1",
+ role: "assistant",
+ parts: [heldConfirm.part as ToolUIPart],
+};
+const lateResult: Message = {
+ id: "u1",
+ role: "user",
+ metadata: heldConfirm.result.metadata,
+ parts: [{ type: "text", text: heldConfirm.result.content }],
+};
+
+function renderTurn(parts: Message["parts"], messages: Message[] = []) {
+ const onSend = vi.fn();
+ const view = render(
+ <CopilotChatActionsProvider onSend={onSend}>
+ <HeldOutcomesContext.Provider value={getHeldOutcomes(messages)}>
+ <ChainMessageParts
+ parts={parts}
+ messageID="a1"
+ isCurrentlyStreaming={false}
+ />
+ </HeldOutcomesContext.Provider>
+ </CopilotChatActionsProvider>,
+ );
+ return { ...view, onSend };
+}
+
+test("a held call drawn outside the chain renders its real card once answered", () => {
+ const { rerender } = renderTurn(heldTurn.parts, [heldTurn]);
+ expect(screen.queryByText("Expert created")).toBeNull();
+
+ rerender(
+ <HeldOutcomesContext.Provider
+ value={getHeldOutcomes([heldTurn, lateResult])}
+ >
+ <ChainMessageParts
+ parts={heldTurn.parts}
+ messageID="a1"
+ isCurrentlyStreaming={false}
+ />
+ </HeldOutcomesContext.Provider>,
+ );
+
+ expect(screen.getByText("Expert created")).toBeDefined();
+ expect(screen.getByText("Otto")).toBeDefined();
+});
+
+// The card and the wake's label read the same result row; each says what the
+// answer did. Bodies are what held._outcome writes for a held action.
+test.each([
+ ["approved", heldConfirm.result.content, true, "Result sent to Otto."],
+ [
+ "rejected",
+ "Nothing ran: the user declined this action. Do not retry it or reach the same effect another way.",
+ false,
+ "Declined; nothing was sent to Otto.",
+ ],
+ [
+ "expired",
+ "Nothing ran: the approval expired an hour after it was given. Propose the call again if it is still needed.",
+ false,
+ "Expired; nothing was sent to Otto.",
+ ],
+ [
+ "closed",
+ "Nothing ran: this card is no longer open.",
+ false,
+ "Closed; nothing ran.",
+ ],
+])(
+ "an out-of-chain hire answered %s shows its card only if it ran, and a true label",
+ (outcome, body, created, clause) => {
+ const messages = answeredHire(outcome, body);
+ renderTurn(heldTurn.parts, messages);
+
+ expect(screen.queryByText("Expert created") !== null).toBe(created);
+ expect(answeredLabel(messages, 1)).toBe(
+ `Approval answered: Confirm the team change. ${clause}`,
+ );
+ },
+);
+
+test("a Soul edit is put to the user on its own card, whose Approve the gate takes", async () => {
+ const user = userEvent.setup();
+ const { onSend } = renderTurn([
+ {
+ type: "tool-update_expert_soul",
+ state: "output-available",
+ toolCallId: "call-1",
+ input: { voice_preferences: "Warmer." },
+ output: soulProposal,
+ } as ToolUIPart,
+ ]);
+
+ expect(screen.getByText("Update Soul")).toBeDefined();
+ expect(screen.getByText("Voice")).toBeDefined();
+ expect(screen.getByText("Warmer.")).toBeDefined();
+ expect(screen.getByText("Was: Short and factual.")).toBeDefined();
+
+ await user.click(screen.getByRole("button", { name: "Approve" }));
+ await user.click(screen.getByRole("button", { name: "Send decisions" }));
+
+ // The line gate/card_approval.py takes for confirm_expert_soul_update.
+ expect(onSend).toHaveBeenCalledWith(
+ "Approved: update your Soul (confirmation_id: 5f0c2a3e-7b1d-4c9e-8a6f-0d2b4e6c8a10).",
+ );
+});
+
+function answeredHire(outcome: string, body: string): Message[] {
+ const wake: Message = {
+ id: "w1",
+ role: "user",
+ metadata: { held_calls_answered: true },
+ parts: [
+ {
+ type: "text",
+ text: "I answered an action that was waiting for my approval.",
+ },
+ ],
+ };
+ const header = heldConfirm.result.content.split("\n", 1)[0];
+ const result: Message = {
+ id: "u1",
+ role: "user",
+ metadata: {
+ held_call: { ...heldConfirm.result.metadata.held_call, outcome },
+ },
+ parts: [
+ {
+ type: "text",
+ text: body.startsWith("<held_call_result")
+ ? body
+ : `${header}\n${body}\n</held_call_result>`,
+ },
+ ],
+ };
+ return [heldTurn, wake, result];
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/heldCallRows.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/heldCallRows.ts
index ee5c4e5074..0e3da4ccbc 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/heldCallRows.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatMessagesContainer/heldCallRows.ts
@@ -2,6 +2,7 @@ import { AUTOPILOT_NAME } from "@/components/molecules/AutopilotAvatar/helpers";
import type { UIDataTypes, UIMessage, UITools } from "ai";
import { cardArguments, fallbackAsk } from "../ApprovalQueue/helpers";
import { heldAskText, heldToolName, isHeldReadId } from "../ToolChain/heldRow";
+import type { MessagePart } from "./helpers";
// Rows the server writes for a held call: the one that starts the turn when a
// card is answered, and the call's late result, which the reply narrates.
@@ -203,6 +204,18 @@ export function getHeldOutcomes(
return outcomes;
}
+// A part drawn outside the chain renders from what its held call returned, as
+// a chain row does through applyHeldOutcome.
+export function withHeldOutcome(
+ part: MessagePart,
+ outcomes: ReadonlyMap<string, HeldOutcome>,
+): MessagePart {
+ if (!("toolCallId" in part) || !("output" in part)) return part;
+ if (heldReviewId(part.output) === null) return part;
+ const outcome = outcomes.get(part.toolCallId);
+ return outcome ? ({ ...part, output: outcome.output } as MessagePart) : part;
+}
+
function heldCallMetadata(metadata: unknown) {
if (!metadata || typeof metadata !== "object") return null;
const held = (metadata as { held_call?: unknown }).held_call;
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx
index 9ef022e3e1..1a7a4abb0c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/ExpertCards.tsx
@@ -22,6 +22,7 @@ import { GenericTool } from "../../tools/GenericTool/GenericTool";
import { type ArtifactRef, useCopilotUIStore } from "../../store";
import { toastSendFailure } from "../../helpers/sendFailureToast";
import { CopilotChatActionsContext } from "../CopilotChatActionsProvider/useCopilotChatActions";
+import { SOUL_CHANGE_TOOLS } from "./helpers";
import { asObject, str } from "./resultHelpers";
interface Props {
@@ -95,16 +96,24 @@ function headerFor(
interface Proposal {
toolCallId: string;
- kind: ExpertKind | null;
+ kind: ExpertKind | "soul" | null;
name: string;
confirmationId: string;
}
-/** A hire/raise preview the user can still say yes or no to. */
+/** A hire/raise/Soul preview the user can still say yes or no to. */
function proposalOf(part: ToolUIPart): Proposal | null {
const output = asObject(part.output);
if (!output || output.applied === true) return null;
const confirmationId = str(output, "confirmation_id");
+ if (confirmationId && isSoulChange(output)) {
+ return {
+ toolCallId: part.toolCallId,
+ kind: "soul",
+ name: "your Soul",
+ confirmationId,
+ };
+ }
const preview = asObject(output.preview);
if (!confirmationId || !preview) return null;
return {
@@ -115,11 +124,12 @@ function proposalOf(part: ToolUIPart): Proposal | null {
};
}
+// gate/card_approval.py reads the Approved line as the answer to the confirm.
function decisionLine(proposal: Proposal, decision: Decision): string {
const verb =
proposal.kind === "hire"
? "hire"
- : proposal.kind === "update"
+ : proposal.kind === "update" || proposal.kind === "soul"
? "update"
: "create";
return decision === "approved"
@@ -272,48 +282,147 @@ export function ExpertChangeCard({
)}
</div>
{showFooter && (
- <div className={FOOTER}>
- <div className="min-w-0">{pager}</div>
- <div className="flex shrink-0 items-center gap-1.5">
- {decision && onUndo && (
- <Button
- variant="secondary"
- size="small"
- onClick={onUndo}
- leftIcon={<Icon icon={UndoIcon} size={14} />}
- className="h-8 !min-w-0 px-3"
- >
- {decision === "approved" ? "Unapprove" : "Undo decline"}
- </Button>
- )}
- {!decision && onDecide && (
- <>
- <Button
- variant="ghost"
- size="small"
- onClick={() => onDecide("declined")}
- className="h-8 !min-w-0 px-3"
- >
- Decline
- </Button>
- <Button
- variant="primary"
- size="small"
- onClick={() => onDecide("approved")}
- className="h-8 !min-w-0 px-3"
- >
- Approve
- </Button>
- </>
+ <DecisionFooter
+ pager={pager}
+ decision={decision}
+ onDecide={onDecide}
+ onUndo={onUndo}
+ action={action}
+ />
+ )}
+ </div>
+ );
+}
+
+const SOUL_LABELS: Record<string, string> = {
+ identity: "Identity and personality",
+ voice_preferences: "Voice",
+ boundaries: "Boundaries",
+};
+
+/** A Soul edit the expert proposes for itself, or the one it just saved:
+ * each changed field as it will read, with what it was. Labels match the
+ * team page's Soul editor (SoulDrawer). */
+function SoulChangeCard({
+ output,
+ pager,
+ decision = null,
+ onDecide,
+ onUndo,
+ action,
+}: Props) {
+ const showFooter = !!pager || !!onDecide || !!decision || !!action;
+ return (
+ <div className={SHELL}>
+ <div className={HEADER}>
+ <Icon icon={PencilEdit02Icon} size={18} className="text-zinc-400" />
+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-zinc-900">
+ {output.applied === true ? "Soul updated" : "Update Soul"}
+ </span>
+ </div>
+ <div className="flex flex-col gap-3 px-4 py-3">
+ {soulChanges(output).map((change) => (
+ <section key={change.field} className="flex flex-col gap-0.5">
+ <p className="text-xs font-medium text-zinc-700">
+ {SOUL_LABELS[change.field] ?? change.field}
+ </p>
+ <p className="whitespace-pre-line text-sm text-zinc-700">
+ {change.after || "Empty"}
+ </p>
+ {change.before && (
+ <p className="line-clamp-2 text-xs text-zinc-400">
+ Was: {change.before}
+ </p>
)}
- {action}
- </div>
- </div>
+ </section>
+ ))}
+ </div>
+ {showFooter && (
+ <DecisionFooter
+ pager={pager}
+ decision={decision}
+ onDecide={onDecide}
+ onUndo={onUndo}
+ action={action}
+ />
)}
</div>
);
}
+type FooterProps = Pick<
+ Props,
+ "pager" | "decision" | "onDecide" | "onUndo" | "action"
+>;
+
+function DecisionFooter({
+ pager,
+ decision = null,
+ onDecide,
+ onUndo,
+ action,
+}: FooterProps) {
+ return (
+ <div className={FOOTER}>
+ <div className="min-w-0">{pager}</div>
+ <div className="flex shrink-0 items-center gap-1.5">
+ {decision && onUndo && (
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={onUndo}
+ leftIcon={<Icon icon={UndoIcon} size={14} />}
+ className="h-8 !min-w-0 px-3"
+ >
+ {decision === "approved" ? "Unapprove" : "Undo decline"}
+ </Button>
+ )}
+ {!decision && onDecide && (
+ <>
+ <Button
+ variant="ghost"
+ size="small"
+ onClick={() => onDecide("declined")}
+ className="h-8 !min-w-0 px-3"
+ >
+ Decline
+ </Button>
+ <Button
+ variant="primary"
+ size="small"
+ onClick={() => onDecide("approved")}
+ className="h-8 !min-w-0 px-3"
+ >
+ Approve
+ </Button>
+ </>
+ )}
+ {action}
+ </div>
+ </div>
+ );
+}
+
+function isSoulChange(output: Record<string, unknown>): boolean {
+ return str(output, "type") === "expert_soul_updated";
+}
+
+function soulChanges(output: Record<string, unknown>) {
+ const changes = Array.isArray(output.changes) ? output.changes : [];
+ return changes.flatMap((item) => {
+ const change = asObject(item);
+ const field = change ? str(change, "field") : null;
+ if (!change || !field) return [];
+ return [
+ {
+ field,
+ before: str(change, "before") ?? "",
+ after: str(change, "after") ?? "",
+ },
+ ];
+ });
+}
+
export function ExpertChangeCardSkeleton() {
return (
<div className={SHELL}>
@@ -368,8 +477,9 @@ export function ExpertChangePart({
if (part.state === "output-error") return <GenericTool part={part} />;
const output = asObject(part.output);
if (output) {
+ const Card = isSoulChange(output) ? SoulChangeCard : ExpertChangeCard;
return (
- <ExpertChangeCard
+ <Card
output={output}
artifactId={part.toolCallId}
pager={pager}
@@ -381,7 +491,9 @@ export function ExpertChangePart({
/>
);
}
- return isCurrentlyStreaming ? <ExpertChangeCardSkeleton /> : null;
+ // The skeleton is an expert's shape; a Soul edit waits for its diff.
+ const soul = SOUL_CHANGE_TOOLS.has(part.type.slice("tool-".length));
+ return isCurrentlyStreaming && !soul ? <ExpertChangeCardSkeleton /> : null;
}
function isVisibleExpertPart(
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ExpertCards.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ExpertCards.test.tsx
index 2bb05e3e43..83fd8ebb75 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ExpertCards.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ExpertCards.test.tsx
@@ -17,6 +17,7 @@ import {
} from "../ExpertCards";
import type { ChainRow } from "../helpers";
import { ToolResult } from "../ToolResult";
+import gatedProposal from "./gatedProposal.json";
vi.mock("@/components/molecules/Toast/use-toast", () => ({
toast: vi.fn(),
@@ -411,6 +412,19 @@ describe("expert approval", () => {
);
}
+ it("offers Approve on a preview run under Ask First", async () => {
+ const user = userEvent.setup();
+ renderGroup([expertPart("output-available", gatedProposal)]);
+
+ await user.click(screen.getByRole("button", { name: "Approve" }));
+ await user.click(screen.getByRole("button", { name: "Send decisions" }));
+
+ // The line gate/card_approval.py takes as the answer to the confirm.
+ expect(onSend).toHaveBeenCalledWith(
+ "Approved: create Otto (confirmation_id: 5f0c2a3e-7b1d-4c9e-8a6f-0d2b4e6c8a10).",
+ );
+ });
+
it("moves to the next expert on each decision, then sends all of them", async () => {
const user = userEvent.setup();
renderGroup([proposal("Fiona", "a"), proposal("Bhaskar", "b")]);
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/gatedProposal.json b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/gatedProposal.json
new file mode 100644
index 0000000000..423ba8d235
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/gatedProposal.json
@@ -0,0 +1,19 @@
+{
+ "type": "expert_change_proposed",
+ "message": "Nothing created yet. The user is looking at this charter on a card with Approve and Decline buttons — do not repeat any of it in text. Reply with one short line at most and wait. Only after they explicitly approve, call tool:confirm_expert_change with this confirmation_id.",
+ "session_id": "session-1",
+ "applied": false,
+ "preview": {
+ "kind": "raise",
+ "name": "Otto",
+ "role": "Inbox triage",
+ "job_title": "Executive Assistant",
+ "tagline": "Sorts your morning inbox and drafts the routine replies.",
+ "about": "You group the morning inbox and draft routine replies.",
+ "boundaries": "You never send a reply yourself.",
+ "voice_preferences": "",
+ "avatar_url": "/autogpt-characters/v2.1/expert-general-01/neutral/128.webp",
+ "color": "violet-300"
+ },
+ "confirmation_id": "5f0c2a3e-7b1d-4c9e-8a6f-0d2b4e6c8a10"
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/heldConfirm.json b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/heldConfirm.json
new file mode 100644
index 0000000000..413679b8dd
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/heldConfirm.json
@@ -0,0 +1,42 @@
+{
+ "part": {
+ "type": "tool-confirm_expert_change",
+ "toolCallId": "call-2",
+ "state": "output-available",
+ "input": {
+ "confirmation_id": "5f0c2a3e-7b1d-4c9e-8a6f-0d2b4e6c8a10"
+ },
+ "output": {
+ "type": "approval_required",
+ "message": "Held for the user's approval (review copilot-node-gate-confirm_expert_change:3e0a034f1d6b732f); nothing has run yet. Ask First is on for this chat, so this action needs your approval. If they approve, the result arrives later as a <held_call_result> naming this call. Carry on with whatever does not depend on it. Do not retry it or reach the same effect another way.",
+ "session_id": "session-1",
+ "tool_name": "confirm_expert_change",
+ "reason": "Ask First is on for this chat, so this action needs your approval.",
+ "review_id": "copilot-node-gate-confirm_expert_change:3e0a034f1d6b732f",
+ "ask": "Confirm the team change",
+ "object": null
+ }
+ },
+ "result": {
+ "content": "<held_call_result tool=\"confirm_expert_change\" tool_call_id=\"call-2\" review_id=\"copilot-node-gate-confirm_expert_change:3e0a034f1d6b732f\">\n{\"type\":\"expert_change_applied\",\"message\":\"Otto is raised and on the team. Tell the user who joined and what they own.\",\"session_id\":\"session-1\",\"applied\":true,\"kind\":\"raise\",\"expert\":{\"id\":\"exp-2\",\"name\":\"Otto\",\"role\":\"Market research\",\"tagline\":\"Tracks your competitors and reports what changed.\",\"about\":\"You track competitors.\",\"boundaries\":\"You never contact anyone outside the team.\",\"voice_preferences\":\"Short and factual.\",\"color\":\"sky-300\"},\"failed_workflows\":[]}\n</held_call_result>",
+ "metadata": {
+ "held_call": {
+ "review_id": "copilot-node-gate-confirm_expert_change:3e0a034f1d6b732f",
+ "tool_name": "confirm_expert_change",
+ "tool_call_id": "call-2",
+ "outcome": "approved",
+ "arguments": {
+ "confirmation_id": "5f0c2a3e-7b1d-4c9e-8a6f-0d2b4e6c8a10"
+ },
+ "fields": [
+ {
+ "key": "confirmation_id",
+ "label": "Confirmation",
+ "format": null
+ }
+ ],
+ "clipped": []
+ }
+ }
+ }
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/soulProposal.json b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/soulProposal.json
new file mode 100644
index 0000000000..c1c0568cc8
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/soulProposal.json
@@ -0,0 +1,14 @@
+{
+ "type": "expert_soul_updated",
+ "message": "Nothing saved yet. The user is looking at this diff on a card with Approve and Decline buttons — do not repeat it in text. Reply with one short line at most and wait. Only after they explicitly approve, call tool:confirm_expert_soul_update with this confirmation_id.",
+ "session_id": "session-1",
+ "applied": false,
+ "changes": [
+ {
+ "field": "voice_preferences",
+ "before": "Short and factual.",
+ "after": "Warmer."
+ }
+ ],
+ "confirmation_id": "5f0c2a3e-7b1d-4c9e-8a6f-0d2b4e6c8a10"
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts
index bbac133066..f3ae16a298 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/helpers.ts
@@ -165,14 +165,21 @@ function getProviderIconSrc(tool: ToolUIPart): string | undefined {
// it into a chain would bury both behind a collapsed "summarized context".
export const COMPACTION_PART_TYPE = "tool-context_compaction";
-// Hiring, raising or updating an expert is the user's call, not a step the
-// model worked through — the card renders as its own message part so the
-// approval never sits inside a chain that collapses on top of it.
+export const SOUL_CHANGE_TOOLS = new Set([
+ "update_expert_soul",
+ "confirm_expert_soul_update",
+]);
+
+// Hiring, raising or updating an expert, or editing its Soul, is the user's
+// call, not a step the model worked through — the card renders as its own
+// message part so the approval never sits inside a chain that collapses on
+// top of it.
export const EXPERT_CHANGE_TOOLS = new Set([
"hire_expert",
"raise_expert",
"update_expert",
"confirm_expert_change",
+ ...SOUL_CHANGE_TOOLS,
]);
export function isExpertChangePart(part: MessagePart): boolean {