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.

feat(platform): per-expert default approval mode for new web chats (#15115)

Abhimanyu Yadav2048fa53ff7d
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.py
index 1a9afc8f3d..f6a4074a44 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py
@@ -484,6 +484,9 @@ class CreateSessionRequest(BaseModel):
llm_credential_id: str | None = Field(default=None, max_length=128)
expert_id: str | None = Field(default=None, max_length=128)
expert_kickoff: bool = False
+ # The approval mode the chat starts on. Leave unset to start on the
+ # expert's default (or the platform default); send only a deliberate pick.
+ autopilot_mode: AutopilotMode | None = None
class CreateSessionResponse(BaseModel):
@@ -882,6 +885,7 @@ async def create_session(
builder_graph_id = request.builder_graph_id if request else None
expert_id = request.expert_id if request else None
expert_kickoff = request.expert_kickoff if request else False
+ autopilot_mode = request.autopilot_mode if request else None
if expert_kickoff and expert_id is None:
raise HTTPException(
@@ -929,6 +933,7 @@ async def create_session(
builder_graph_id,
organization_id=ctx.org_id,
team_id=ctx.team_id,
+ autopilot_mode=autopilot_mode,
)
elif expert_kickoff and expert_id is not None:
session = await get_or_create_expert_kickoff_session(
@@ -939,6 +944,7 @@ async def create_session(
team_id=ctx.team_id,
llm_auth_provider=llm_auth_provider,
llm_credential_id=llm_credential_id,
+ autopilot_mode=autopilot_mode,
)
else:
try:
@@ -950,6 +956,7 @@ async def create_session(
llm_auth_provider=llm_auth_provider,
llm_credential_id=llm_credential_id,
expert_id=expert_id,
+ autopilot_mode=autopilot_mode,
)
except experts_db.ExpertNotFoundError as e:
raise HTTPException(status_code=404, detail="Expert not found") from e
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 5493629301..c82ee6c502 100644
--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py
@@ -22,7 +22,7 @@ from backend.copilot import transports as chat_transports
from backend.copilot.at_reset import cancel_resume_at_reset_in_background
from backend.copilot.config import CopilotLlmAuthProvider
from backend.copilot.continuation import KEEP_GOING_NOTE
-from backend.copilot.model import ChatSession
+from backend.copilot.model import AutopilotMode, ChatSession
from backend.copilot.offers import EntitlementUnavailable
from backend.copilot.rate_limit import SubscriptionTier
from backend.copilot.response_model import StreamFinish, StreamStatus, StreamTextDelta
@@ -1767,6 +1767,7 @@ def _mock_create_chat_session(mocker: pytest_mock.MockerFixture):
llm_auth_provider: CopilotLlmAuthProvider = "platform",
llm_credential_id: str | None = None,
expert_id: str | None = None,
+ autopilot_mode: AutopilotMode | None = None,
):
return ChatSession.new(
user_id,
@@ -1774,6 +1775,7 @@ def _mock_create_chat_session(mocker: pytest_mock.MockerFixture):
llm_auth_provider=llm_auth_provider,
llm_credential_id=llm_credential_id,
expert_id=expert_id,
+ autopilot_mode=autopilot_mode,
)
return mocker.patch(
@@ -4605,11 +4607,13 @@ def test_create_session_with_builder_graph_id_uses_get_or_create(
*,
organization_id: str | None = None,
team_id: str | None = None,
+ autopilot_mode: AutopilotMode | None = None,
) -> ChatSession:
return ChatSession.new(
user_id,
dry_run=False,
builder_graph_id=graph_id,
+ autopilot_mode=autopilot_mode,
)
mocker.patch(
@@ -5196,3 +5200,89 @@ def test_credential_selection_rejects_a_provider_named_twice(
assert response.status_code == 422
assert response.json()["detail"] == "duplicate_provider"
remember.assert_not_awaited()
+
+
+def test_create_session_passes_a_picked_mode_through(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ mock_create = _mock_create_chat_session(mocker)
+ _mock_get_expert(mocker, _make_expert("expert-1"))
+
+ response = client.post(
+ "/sessions", json={"expert_id": "expert-1", "autopilot_mode": "ask_first"}
+ )
+
+ assert response.status_code == 200
+ assert mock_create.call_args.kwargs["autopilot_mode"] == "ask_first"
+
+
+def test_create_session_without_a_pick_leaves_the_mode_to_the_server(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ mock_create = _mock_create_chat_session(mocker)
+ _mock_get_expert(mocker, _make_expert("expert-1"))
+
+ response = client.post("/sessions", json={"expert_id": "expert-1"})
+
+ assert response.status_code == 200
+ assert mock_create.call_args.kwargs["autopilot_mode"] is None
+
+
+def test_create_session_rejects_an_unknown_mode(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ mock_create = _mock_create_chat_session(mocker)
+
+ response = client.post("/sessions", json={"autopilot_mode": "yolo"})
+
+ assert response.status_code == 422
+ mock_create.assert_not_awaited()
+
+
+def test_expert_kickoff_receives_the_picked_mode(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ expert_id = "3f8b0f7e-9f30-4a3b-a6a1-000000000002"
+ _mock_get_expert(mocker, _make_expert(expert_id))
+ existing = ChatSession.new(test_user_id, dry_run=False, expert_id=expert_id)
+ mock_get_or_create = mocker.patch.object(
+ chat_routes,
+ "get_or_create_expert_kickoff_session",
+ new=AsyncMock(return_value=existing),
+ )
+
+ response = client.post(
+ "/sessions",
+ json={
+ "expert_id": expert_id,
+ "expert_kickoff": True,
+ "autopilot_mode": "unsupervised",
+ },
+ )
+
+ assert response.status_code == 200
+ assert mock_get_or_create.await_args.kwargs["autopilot_mode"] == "unsupervised"
+
+
+def test_a_builder_session_keeps_the_picked_mode(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+) -> None:
+ mock_get_or_create = mocker.patch(
+ "backend.api.features.chat.routes.get_or_create_builder_session",
+ new=AsyncMock(
+ return_value=ChatSession.new(
+ test_user_id, dry_run=False, builder_graph_id="graph-1"
+ )
+ ),
+ )
+
+ response = client.post(
+ "/sessions", json={"builder_graph_id": "graph-1", "autopilot_mode": "ask_first"}
+ )
+
+ assert response.status_code == 200
+ assert mock_get_or_create.await_args.kwargs["autopilot_mode"] == "ask_first"
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 5f0f50d8f5..de0d5916ed 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
@@ -94,6 +94,7 @@ from backend.api.features.orgs.db import get_user_default_team
from backend.api.features.store import skill_db
from backend.api.features.store.categories import category_match_values
from backend.blocks import get_output_block_ids
+from backend.copilot.autopilot_mode import AUTOPILOT_MODES, AutopilotMode
from backend.copilot.briefing.outcome import DEFAULT_AGENT_NAME, run_link
from backend.copilot.tools.skills import (
BuiltInSkillError,
@@ -297,6 +298,7 @@ def _to_model(
weekly_spend=weekly_spend,
schedules_paused_at=row.schedulesPausedAt,
learning_paused_at=row.learningPausedAt,
+ autopilot_mode=autopilot_mode_of(row),
pod_id=row.podId,
setup_status=_setup_status(row),
setup_failures=row.setupFailures or [],
@@ -518,7 +520,12 @@ async def list_expert_identities(user_id: str) -> list[ExpertIdentity]:
return await query_raw_with_schema(
"""
SELECT "id", "name", "avatarUrl" AS "avatar_url", "color", "role",
- "jobTitle" AS "job_title", "isArchived" AS "is_archived"
+ "jobTitle" AS "job_title", "isArchived" AS "is_archived",
+ CASE
+ WHEN "autopilotMode" IN ('ask_first', 'auto', 'unsupervised')
+ THEN "autopilotMode"
+ ELSE NULL
+ END AS "autopilot_mode"
FROM {schema_prefix}"Expert"
WHERE "ownerUserId" = $1 AND "isTemplate" = false
""",
@@ -1779,6 +1786,66 @@ async def update_budget(
return expert
+def autopilot_mode_of(row: prisma.models.Expert) -> AutopilotMode | None:
+ """The stored default, or None for anything that is not a known mode."""
+ mode = row.autopilotMode
+ return cast(AutopilotMode, mode) if mode in AUTOPILOT_MODES else None
+
+
+async def get_autopilot_mode(user_id: str, expert_id: str) -> AutopilotMode | None:
+ """The approval mode *expert_id*'s new web chats start on.
+
+ Same ownership predicate as the setters: a shared, template or archived
+ expert reads as None, so a session opened on it falls to the platform
+ default rather than a default somebody else chose.
+ """
+ row = await prisma.models.Expert.prisma().find_first(
+ where={
+ "id": expert_id,
+ "ownerUserId": user_id,
+ "isTemplate": False,
+ "isArchived": False,
+ "visibility": ResourceVisibility.PRIVATE,
+ }
+ )
+ return autopilot_mode_of(row) if row is not None else None
+
+
+async def update_autopilot_mode(
+ user_id: str, expert_id: str, mode: AutopilotMode | None
+) -> Expert:
+ """Set the approval mode new web chats with the expert start on.
+
+ Only the owner of an active, private hire may change it: an unsupervised
+ default lets every new thread act without approval, so a shared expert
+ must not be flipped by a non-owner. Open threads keep their own mode.
+ """
+ updated = await prisma.models.Expert.prisma().update_many(
+ where={
+ "id": expert_id,
+ "ownerUserId": user_id,
+ "isTemplate": False,
+ "isArchived": False,
+ "visibility": ResourceVisibility.PRIVATE,
+ },
+ data={"autopilotMode": mode},
+ )
+ if updated == 0:
+ raise ExpertNotFoundError(expert_id)
+
+ if mode == "unsupervised":
+ emit_funnel_event(
+ user_id,
+ PostHogEvent.EXPERT_MODE_SET_UNSUPERVISED,
+ {"expert_id": expert_id},
+ )
+
+ expert = await get_expert(user_id, expert_id)
+ if expert is None:
+ raise ExpertNotFoundError(expert_id)
+ return expert
+
+
async def update_soul_if_current(
user_id: str,
expert_id: str,
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 4682236ea5..4c22586224 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
@@ -58,6 +58,7 @@ from backend.data.user import get_or_create_user
from backend.executor import utils as execution_utils
from backend.util.exceptions import ConflictError, ExpertRunPausedError, NotFoundError
from backend.util.json import SafeJson
+from backend.util.posthog_events import PostHogEvent
from backend.util.test import SpinTestServer
EXPECTED_ROSTER_PRELOAD_SLUGS = {
@@ -2039,6 +2040,7 @@ def test_expert_identity_projection_columns_exist_in_schema():
"role",
"jobTitle",
"isArchived",
+ "autopilotMode",
} <= fields
assert {"ownerUserId", "isTemplate"} <= fields
@@ -7241,3 +7243,98 @@ async def test_a_routine_proposal_nobody_answered_still_refuses(
with pytest.raises(routines.RoutineUnansweredAsksError):
await experts_db.enable_routine(test_user.id, hired.expert.id, installed[0].id)
+
+
+# ─── Approval mode ─────────────────────────────────────────────────────
+
+
[email protected](loop_scope="session")
+async def test_update_autopilot_mode_persists_per_expert(
+ server: SpinTestServer, test_user
+):
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ assert hired.expert.autopilot_mode is None
+
+ with patch.object(experts_db, "emit_funnel_event") as emit:
+ updated = await experts_db.update_autopilot_mode(
+ test_user.id, hired.expert.id, "ask_first"
+ )
+
+ assert updated.autopilot_mode == "ask_first"
+ emit.assert_not_called()
+ reloaded = await experts_db.get_expert(test_user.id, hired.expert.id)
+ assert reloaded is not None
+ assert reloaded.autopilot_mode == "ask_first"
+ assert (
+ await experts_db.get_autopilot_mode(test_user.id, hired.expert.id)
+ == "ask_first"
+ )
+ identities = await experts_db.list_expert_identities(test_user.id)
+ identity = next(item for item in identities if item.id == hired.expert.id)
+ assert identity.autopilot_mode == "ask_first"
+
+ cleared = await experts_db.update_autopilot_mode(
+ test_user.id, hired.expert.id, None
+ )
+ assert cleared.autopilot_mode is None
+
+
[email protected](loop_scope="session")
+async def test_setting_unsupervised_at_expert_level_is_audited(
+ server: SpinTestServer, test_user
+):
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ with patch.object(experts_db, "emit_funnel_event") as emit:
+ await experts_db.update_autopilot_mode(
+ test_user.id, hired.expert.id, "unsupervised"
+ )
+
+ emit.assert_called_once_with(
+ test_user.id,
+ PostHogEvent.EXPERT_MODE_SET_UNSUPERVISED,
+ {"expert_id": hired.expert.id},
+ )
+
+
[email protected](loop_scope="session")
+async def test_update_autopilot_mode_is_owner_only_and_hire_only(
+ server: SpinTestServer, test_user, other_user
+):
+ template = await _seed_template(name="Maria", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ with pytest.raises(experts_db.ExpertNotFoundError):
+ await experts_db.update_autopilot_mode(other_user.id, hired.expert.id, "auto")
+ with pytest.raises(experts_db.ExpertNotFoundError):
+ await experts_db.update_autopilot_mode(test_user.id, template.id, "auto")
+ assert await experts_db.get_autopilot_mode(other_user.id, hired.expert.id) is None
+
+ await experts_db.archive_expert(test_user.id, hired.expert.id)
+ with pytest.raises(experts_db.ExpertNotFoundError):
+ await experts_db.update_autopilot_mode(
+ test_user.id, hired.expert.id, "ask_first"
+ )
+
+
[email protected](loop_scope="session")
+async def test_hiring_copies_no_autopilot_mode_and_junk_reads_as_default(
+ server: SpinTestServer, test_user
+):
+ template = await _seed_template(name="Maria", preload_listings=[])
+ await prisma.models.Expert.prisma().update(
+ where={"id": template.id}, data={"autopilotMode": "unsupervised"}
+ )
+
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+
+ assert hired.expert.autopilot_mode is None
+ await prisma.models.Expert.prisma().update(
+ where={"id": hired.expert.id}, data={"autopilotMode": "not-a-mode"}
+ )
+ assert await experts_db.get_autopilot_mode(test_user.id, hired.expert.id) is None
+ identities = await experts_db.list_expert_identities(test_user.id)
+ identity = next(item for item in identities if item.id == hired.expert.id)
+ assert identity.autopilot_mode is None
diff --git a/autogpt_platform/backend/backend/api/features/experts/models.py b/autogpt_platform/backend/backend/api/features/experts/models.py
index c4871b6347..357496a997 100644
--- a/autogpt_platform/backend/backend/api/features/experts/models.py
+++ b/autogpt_platform/backend/backend/api/features/experts/models.py
@@ -13,6 +13,7 @@ from pydantic import (
)
from backend.api.features.experts.avatar_catalog import resolve_avatar_url
+from backend.copilot.autopilot_mode import AutopilotMode
from backend.copilot.credential_selection import CredentialPins
from backend.data.expert_run_output import OutputType
from backend.data.skill_capacity import MAX_SKILLS_PER_EXPERT, skill_name_key
@@ -147,6 +148,8 @@ class ExpertIdentity(BaseModel):
role: str
job_title: str | None = None
is_archived: bool
+ # The approval mode a new web chat with this expert starts on.
+ autopilot_mode: AutopilotMode | None = None
@field_validator("avatar_url")
@classmethod
@@ -318,6 +321,9 @@ class Expert(BaseModel):
# Set while the owner has paused nightly skill learning for this expert.
# Existing skills stay usable; only future automated learning stops.
learning_paused_at: datetime | None = None
+ # Approval mode every new web chat with this expert starts on; None =
+ # platform default. Hire-only, never set on templates.
+ autopilot_mode: AutopilotMode | None = None
# Owner-scoped grouping. None = ungrouped ("unpodded").
pod_id: str | None = None
# A hire's workflows, skills and routines land after it is returned.
@@ -548,6 +554,16 @@ class ExpertBudgetUpdate(BaseModel):
weekly_budget: int | None = Field(default=None, ge=0, le=WEEKLY_BUDGET_MAX_CREDITS)
+class ExpertModeUpdate(BaseModel):
+ """Set the approval mode new web chats with an expert start on.
+
+ ``None`` clears it back to the platform default. The field is required,
+ so an empty body cannot clear it by accident.
+ """
+
+ autopilot_mode: AutopilotMode | None
+
+
class ExpertAvatarUpdate(BaseModel):
"""Swap an expert's picture. ``None`` clears it back to the generated marble."""
diff --git a/autogpt_platform/backend/backend/api/features/experts/routes.py b/autogpt_platform/backend/backend/api/features/experts/routes.py
index ec8b69a90a..0217905009 100644
--- a/autogpt_platform/backend/backend/api/features/experts/routes.py
+++ b/autogpt_platform/backend/backend/api/features/experts/routes.py
@@ -23,6 +23,7 @@ from backend.api.features.experts.models import (
ExpertCredentialRef,
ExpertDetachPreview,
ExpertIdentity,
+ ExpertModeUpdate,
ExpertPod,
ExpertRun,
ExpertSetupItem,
@@ -47,6 +48,7 @@ from backend.copilot.config import ChatConfig
from backend.copilot.tools.e2b_sandbox import SandboxOwner, kill_expert_sandbox
from backend.copilot.tools.skills import SkillVersionConflictError, SkillWriteLockError
from backend.util.exceptions import NotFoundError
+from backend.util.feature_flag import Flag, is_feature_enabled
logger = logging.getLogger(__name__)
@@ -591,6 +593,35 @@ async def update_expert_budget(
raise fastapi.HTTPException(status_code=404, detail=str(e))
+ "/{expert_id}/mode",
+ operation_id="update_expert_mode",
+ responses={
+ 403: {"description": "Approval modes are not enabled for this account"},
+ 404: {"description": "Expert not found"},
+ },
+)
+async def update_expert_mode(
+ expert_id: str,
+ request: ExpertModeUpdate,
+ user_id: str = Security(autogpt_auth_lib.get_user_id),
+) -> Expert:
+ """Set the approval mode new web chats with this expert start on.
+
+ Threads already open keep the mode stored on them, and the composer's
+ selector still overrides it per thread. Routines, scheduled follow-ups
+ and chats driven from a linked chat platform are not gated by it.
+ """
+ if not await is_feature_enabled(Flag.COPILOT_AUTO_MODE, user_id, default=False):
+ raise fastapi.HTTPException(status_code=403, detail="feature_disabled")
+ try:
+ return await experts_db.update_autopilot_mode(
+ user_id, expert_id, request.autopilot_mode
+ )
+ except experts_db.ExpertNotFoundError as e:
+ raise fastapi.HTTPException(status_code=404, detail=str(e))
+
+
@router.post(
"/{expert_id}/workflows",
operation_id="install_expert_workflow",
diff --git a/autogpt_platform/backend/backend/api/features/experts/routes_test.py b/autogpt_platform/backend/backend/api/features/experts/routes_test.py
index 75a0b92f7d..f88f766ab8 100644
--- a/autogpt_platform/backend/backend/api/features/experts/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/routes_test.py
@@ -933,6 +933,7 @@ def test_list_expert_identities_returns_lifetime_roster_projection(
"role": "Marketing Specialist",
"job_title": None,
"is_archived": True,
+ "autopilot_mode": None,
}
]
mock_list.assert_awaited_once_with(test_user_id)
@@ -2177,3 +2178,125 @@ def test_existing_custom_avatar_can_be_kept_without_review(mocker):
"/experts/expert-1/avatar", json={"avatar_url": expert.avatar_url}
)
assert response.status_code == 200
+
+
+# ─── Approval mode ─────────────────────────────────────────────────────
+
+
+def auto_mode_on(mocker: pytest_mock.MockerFixture) -> AsyncMock:
+ return mocker.patch(
+ "backend.api.features.experts.routes.is_feature_enabled",
+ new_callable=AsyncMock,
+ return_value=True,
+ )
+
+
+def test_update_expert_mode_returns_updated_expert(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+ auto_mode_on: AsyncMock,
+) -> None:
+ mock_update = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.update_autopilot_mode",
+ new_callable=AsyncMock,
+ return_value=_make_expert(autopilot_mode="ask_first"),
+ )
+
+ response = client.patch(
+ "/experts/expert-1/mode", json={"autopilot_mode": "ask_first"}
+ )
+
+ assert response.status_code == 200
+ assert response.json()["autopilot_mode"] == "ask_first"
+ mock_update.assert_awaited_once_with(test_user_id, "expert-1", "ask_first")
+
+
+def test_update_expert_mode_null_restores_platform_default(
+ mocker: pytest_mock.MockerFixture,
+ test_user_id: str,
+ auto_mode_on: AsyncMock,
+) -> None:
+ mock_update = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.update_autopilot_mode",
+ new_callable=AsyncMock,
+ return_value=_make_expert(autopilot_mode=None),
+ )
+
+ response = client.patch("/experts/expert-1/mode", json={"autopilot_mode": None})
+
+ assert response.status_code == 200
+ assert response.json()["autopilot_mode"] is None
+ mock_update.assert_awaited_once_with(test_user_id, "expert-1", None)
+
+
+def test_update_expert_mode_rejects_an_unknown_mode(
+ mocker: pytest_mock.MockerFixture,
+ auto_mode_on: AsyncMock,
+) -> None:
+ mock_update = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.update_autopilot_mode",
+ new_callable=AsyncMock,
+ )
+
+ response = client.patch("/experts/expert-1/mode", json={"autopilot_mode": "yolo"})
+
+ assert response.status_code == 422
+ mock_update.assert_not_awaited()
+
+
+def test_update_expert_mode_rejects_a_body_without_a_mode(
+ mocker: pytest_mock.MockerFixture,
+ auto_mode_on: AsyncMock,
+) -> None:
+ """Only an explicit null clears the default; an empty body is not a clear."""
+ mock_update = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.update_autopilot_mode",
+ new_callable=AsyncMock,
+ )
+
+ response = client.patch("/experts/expert-1/mode", json={})
+
+ assert response.status_code == 422
+ mock_update.assert_not_awaited()
+
+
+def test_update_expert_mode_not_found_returns_404(
+ mocker: pytest_mock.MockerFixture,
+ auto_mode_on: AsyncMock,
+) -> None:
+ """Templates, archived and other users' experts all read as missing."""
+ mocker.patch(
+ "backend.api.features.experts.routes.experts_db.update_autopilot_mode",
+ new_callable=AsyncMock,
+ side_effect=experts_db.ExpertNotFoundError("expert-1"),
+ )
+
+ response = client.patch(
+ "/experts/expert-1/mode", json={"autopilot_mode": "unsupervised"}
+ )
+
+ assert response.status_code == 404
+
+
+def test_update_expert_mode_is_refused_while_the_flag_is_off(
+ mocker: pytest_mock.MockerFixture,
+) -> None:
+ """Not a 404: the UI needs to tell the expert apart from the feature."""
+ mocker.patch(
+ "backend.api.features.experts.routes.is_feature_enabled",
+ new_callable=AsyncMock,
+ return_value=False,
+ )
+ mock_update = mocker.patch(
+ "backend.api.features.experts.routes.experts_db.update_autopilot_mode",
+ new_callable=AsyncMock,
+ )
+
+ response = client.patch(
+ "/experts/expert-1/mode", json={"autopilot_mode": "ask_first"}
+ )
+
+ assert response.status_code == 403
+ assert response.json()["detail"] == "feature_disabled"
+ mock_update.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/copilot/autopilot_mode.py b/autogpt_platform/backend/backend/copilot/autopilot_mode.py
new file mode 100644
index 0000000000..988a7dbc4e
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/autopilot_mode.py
@@ -0,0 +1,10 @@
+"""Approval modes a chat runs in.
+
+A leaf module so callers that only need the type (the expert models and
+``experts_db``) do not import the whole copilot session model with it.
+"""
+
+from typing import Literal, get_args
+
+AutopilotMode = Literal["ask_first", "auto", "unsupervised"]
+AUTOPILOT_MODES: frozenset[str] = frozenset(get_args(AutopilotMode))
diff --git a/autogpt_platform/backend/backend/copilot/gate/policy.py b/autogpt_platform/backend/backend/copilot/gate/policy.py
index 6491614974..7b6a8120c5 100644
--- a/autogpt_platform/backend/backend/copilot/gate/policy.py
+++ b/autogpt_platform/backend/backend/copilot/gate/policy.py
@@ -7,10 +7,31 @@ decision here must hold even if it always answered "allow".
from enum import Enum
from typing import Any
-from backend.copilot.model import AutopilotMode
+from backend.copilot.autopilot_mode import AutopilotMode
DEFAULT_MODE: AutopilotMode = "auto"
+# Strictest first: a chat in ``ask_first`` asks the most.
+_MODES_BY_STRICTNESS: tuple[AutopilotMode, ...] = ("ask_first", "auto", "unsupervised")
+
+
+def strictest_mode(*modes: AutopilotMode) -> AutopilotMode:
+ return min(modes, key=_MODES_BY_STRICTNESS.index)
+
+
+def child_autopilot_mode(
+ parent: AutopilotMode | None, expert_default: AutopilotMode | None
+) -> AutopilotMode | None:
+ """The mode a delegated thread starts on.
+
+ An expert with no default follows the chat that delegated to it. One with
+ a default never gets a looser thread than that chat: a parent in
+ ``ask_first`` cannot farm work out to an unsupervised teammate.
+ """
+ if expert_default is None:
+ return parent
+ return strictest_mode(parent or DEFAULT_MODE, expert_default)
+
class Effect(str, Enum):
READ = "read"
diff --git a/autogpt_platform/backend/backend/copilot/gate/policy_test.py b/autogpt_platform/backend/backend/copilot/gate/policy_test.py
index d4f86915c6..0418d461ae 100644
--- a/autogpt_platform/backend/backend/copilot/gate/policy_test.py
+++ b/autogpt_platform/backend/backend/copilot/gate/policy_test.py
@@ -7,8 +7,10 @@ from backend.copilot.gate.policy import (
MCP_FILE_WRITE_TOOLS,
Effect,
Verdict,
+ child_autopilot_mode,
classified_tools,
effect_for,
+ strictest_mode,
verdict_for,
)
from backend.copilot.tools import TOOL_REGISTRY
@@ -72,3 +74,23 @@ def test_reading_a_truncated_tool_result_is_a_read():
from backend.copilot.sdk.tool_adapter import _READ_TOOL_NAME
assert effect_for(_READ_TOOL_NAME) is Effect.READ
+
+
+def test_the_strictest_mode_is_the_one_that_asks_most():
+ assert strictest_mode("auto", "ask_first") == "ask_first"
+ assert strictest_mode("unsupervised", "auto") == "auto"
+ assert strictest_mode("unsupervised") == "unsupervised"
+
+
+def test_a_delegated_thread_follows_its_parent_when_the_expert_has_no_default():
+ assert child_autopilot_mode("ask_first", None) == "ask_first"
+ assert child_autopilot_mode("unsupervised", None) == "unsupervised"
+ assert child_autopilot_mode(None, None) is None
+
+
+def test_a_delegated_thread_is_never_looser_than_its_parent():
+ assert child_autopilot_mode("ask_first", "unsupervised") == "ask_first"
+ # A parent on the platform default cannot hand out an unsupervised thread.
+ assert child_autopilot_mode(None, "unsupervised") == "auto"
+ assert child_autopilot_mode("unsupervised", "ask_first") == "ask_first"
+ assert child_autopilot_mode("auto", "auto") == "auto"
diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.py
index 8774d25b00..16c0d802c5 100644
--- a/autogpt_platform/backend/backend/copilot/model.py
+++ b/autogpt_platform/backend/backend/copilot/model.py
@@ -35,7 +35,9 @@ from backend.util.exceptions import (
NotFoundError,
RedisError,
)
+from backend.util.feature_flag import Flag, is_feature_enabled
+from .autopilot_mode import AutopilotMode
from .config import ChatConfig, CopilotLlmAuthProvider
logger = logging.getLogger(__name__)
@@ -64,7 +66,6 @@ RoutingSource = Literal[
# an interactive origin — "has no expert_id" only means "not an expert chat",
# which an AutoPilotBlock session also satisfies.
ChatSessionOrigin = Literal["interactive", "automation"]
-AutopilotMode = Literal["ask_first", "auto", "unsupervised"]
# Redis cache key prefix for chat sessions
@@ -521,6 +522,7 @@ class ChatSession(ChatSessionInfo):
delegated_by_expert_id: str | None = None,
delegated_by_session_id: str | None = None,
handed_off_from_expert_id: str | None = None,
+ autopilot_mode: AutopilotMode | None = None,
) -> Self:
return cls(
session_id=session_id or str(uuid.uuid4()),
@@ -541,6 +543,7 @@ class ChatSession(ChatSessionInfo):
delegated_by_expert_id=delegated_by_expert_id,
delegated_by_session_id=delegated_by_session_id,
handed_off_from_expert_id=handed_off_from_expert_id,
+ autopilot_mode=autopilot_mode,
),
organization_id=organization_id,
team_id=team_id,
@@ -1380,6 +1383,8 @@ async def create_chat_session(
delegated_by_expert_id: str | None = None,
delegated_by_session_id: str | None = None,
handed_off_from_expert_id: str | None = None,
+ autopilot_mode: AutopilotMode | None = None,
+ inherited_autopilot_mode: AutopilotMode | None = None,
) -> ChatSession:
"""Create a new chat session and persist it.
@@ -1404,6 +1409,17 @@ async def create_chat_session(
Doubles as the poll capability for cross-expert delegation.
handed_off_from_expert_id: Expert that handed this work off for good,
set only by ``handoff_to_expert``. Provenance only.
+ autopilot_mode: The approval mode the chat starts on. An explicit
+ value wins; otherwise an expert session starts on the expert's
+ own default, and anything else on the platform default. Stored
+ on the session, so a later change to the expert's default never
+ rewrites an open thread. Ignored while the approval-mode flag
+ is off, like the per-thread override.
+ inherited_autopilot_mode: The mode a delegated thread must start on,
+ already decided by the caller from the parent chat and the
+ target expert (``gate.policy.child_autopilot_mode``). Stored
+ as-is: it is a constraint rather than a pick, so the flag does
+ not drop it and the expert is not read a second time.
Raises:
DatabaseError: If the database write fails. We fail fast to ensure
@@ -1414,6 +1430,9 @@ async def create_chat_session(
organization_id, team_id = await experts_db().resolve_private_expert_tenancy(
user_id, expert_id
)
+ autopilot_mode = await _resolve_new_session_autopilot_mode(
+ user_id, expert_id, autopilot_mode, origin, inherited_autopilot_mode
+ )
session = ChatSession.new(
user_id,
@@ -1430,6 +1449,7 @@ async def create_chat_session(
delegated_by_expert_id=delegated_by_expert_id,
delegated_by_session_id=delegated_by_session_id,
handed_off_from_expert_id=handed_off_from_expert_id,
+ autopilot_mode=autopilot_mode,
)
# Create in database first - fail fast if this fails
@@ -1463,6 +1483,30 @@ async def create_chat_session(
return session
+async def _resolve_new_session_autopilot_mode(
+ user_id: str,
+ expert_id: str | None,
+ requested: AutopilotMode | None,
+ origin: ChatSessionOrigin,
+ inherited: AutopilotMode | None = None,
+) -> AutopilotMode | None:
+ """Inherited > explicit request > the expert's default > None (platform default).
+
+ The expert default is for threads a person drives: a routine, a
+ scheduled follow-up or a block-opened session is not gated, so it is
+ not looked up for one.
+ """
+ if inherited is not None:
+ return inherited
+ if requested is None and (expert_id is None or origin != "interactive"):
+ return None
+ if not await is_feature_enabled(Flag.COPILOT_AUTO_MODE, user_id, default=False):
+ return None
+ if requested is not None or expert_id is None:
+ return requested
+ return await experts_db().get_autopilot_mode(user_id, expert_id)
+
+
def expert_kickoff_session_id(
user_id: str,
expert_id: str,
@@ -1486,8 +1530,13 @@ async def get_or_create_expert_kickoff_session(
team_id: str | None = None,
llm_auth_provider: CopilotLlmAuthProvider = "platform",
llm_credential_id: str | None = None,
+ autopilot_mode: AutopilotMode | None = None,
) -> ChatSession:
- """Atomically create or adopt the canonical expert kickoff session."""
+ """Atomically create or adopt the canonical expert kickoff session.
+
+ ``autopilot_mode`` only shapes a session created here; an adopted
+ kickoff keeps the mode it already has.
+ """
sessions, _ = await get_user_sessions(
user_id,
limit=1,
@@ -1515,6 +1564,7 @@ async def get_or_create_expert_kickoff_session(
llm_auth_provider=llm_auth_provider,
llm_credential_id=llm_credential_id,
expert_id=expert_id,
+ autopilot_mode=autopilot_mode,
)
except DatabaseError:
existing = await get_chat_session(session_id, user_id)
@@ -1528,6 +1578,7 @@ async def get_or_create_builder_session(
graph_id: str,
organization_id: str | None = None,
team_id: str | None = None,
+ autopilot_mode: AutopilotMode | None = None,
) -> ChatSession:
"""Return the user's builder session for *graph_id*, creating it if absent.
@@ -1570,6 +1621,7 @@ async def get_or_create_builder_session(
builder_graph_id=graph_id,
organization_id=organization_id,
team_id=team_id,
+ autopilot_mode=autopilot_mode,
)
await library_db().update_library_agent(
library_agent_id=library_agent.id,
diff --git a/autogpt_platform/backend/backend/copilot/model_test.py b/autogpt_platform/backend/backend/copilot/model_test.py
index 7d1807139b..4f16150bb7 100644
--- a/autogpt_platform/backend/backend/copilot/model_test.py
+++ b/autogpt_platform/backend/backend/copilot/model_test.py
@@ -1,6 +1,7 @@
import asyncio
from contextlib import asynccontextmanager
from typing import cast
+from unittest.mock import MagicMock
import pytest
from openai.types.chat import (
@@ -1382,6 +1383,7 @@ async def test_create_expert_session_forces_personal_tenancy(
mock_experts_db.resolve_private_expert_tenancy = mocker.AsyncMock(
return_value=("personal-org", "personal-team")
)
+ mock_experts_db.get_autopilot_mode = mocker.AsyncMock(return_value=None)
mock_chat_db = mocker.MagicMock()
mock_chat_db.create_chat_session = mocker.AsyncMock(
return_value=mocker.MagicMock(expert_id="expert-1")
@@ -1905,6 +1907,38 @@ async def test_get_or_create_builder_session_writes_pointer_on_create(
assert call_kwargs["settings"].builder_chat_session_id == "sess-new"
+async def test_get_or_create_builder_session_creates_on_the_picked_mode(
+ mocker: MockerFixture,
+) -> None:
+ """A builder session opened with an explicit mode is created on it."""
+ library_agent = mocker.MagicMock(
+ id="lib-1",
+ settings=mocker.MagicMock(builder_chat_session_id=None),
+ )
+ library_db_mock = mocker.MagicMock(
+ get_library_agent_by_graph_id=mocker.AsyncMock(return_value=library_agent),
+ update_library_agent=mocker.AsyncMock(),
+ )
+ mocker.patch("backend.copilot.model.library_db", return_value=library_db_mock)
+ mocker.patch(
+ "backend.copilot.model.get_chat_session",
+ new_callable=mocker.AsyncMock,
+ return_value=None,
+ )
+ create_mock = mocker.patch(
+ "backend.copilot.model.create_chat_session",
+ new_callable=mocker.AsyncMock,
+ return_value=ChatSession.new(
+ "u1", dry_run=False, builder_graph_id="graph-mine"
+ ),
+ )
+
+ await get_or_create_builder_session("u1", "graph-mine", autopilot_mode="ask_first")
+
+ assert create_mock.call_args.kwargs["autopilot_mode"] == "ask_first"
+
+
@pytest.mark.asyncio
async def test_get_or_create_builder_session_recreates_when_pointer_stale(
mocker: MockerFixture,
@@ -2341,3 +2375,147 @@ async def test_delete_chat_session_not_found_runs_no_cleanup(
redis.delete.assert_not_called()
close_browser.assert_not_called()
delete_embedding.assert_not_called()
+
+
+def _mock_session_creation(
+ mocker: MockerFixture, *, flag_on: bool, expert_default: str | None = None
+) -> tuple[MagicMock, MagicMock]:
+ mock_experts_db = mocker.MagicMock()
+ mock_experts_db.resolve_private_expert_tenancy = mocker.AsyncMock(
+ return_value=("personal-org", "personal-team")
+ )
+ mock_experts_db.get_autopilot_mode = mocker.AsyncMock(return_value=expert_default)
+ mock_chat_db = mocker.MagicMock()
+ mock_chat_db.create_chat_session = mocker.AsyncMock(
+ side_effect=lambda **kwargs: mocker.MagicMock(expert_id=kwargs.get("expert_id"))
+ )
+ mocker.patch("backend.copilot.model.experts_db", return_value=mock_experts_db)
+ mocker.patch("backend.copilot.model.chat_db", return_value=mock_chat_db)
+ mocker.patch(
+ "backend.copilot.model.cache_chat_session", new_callable=mocker.AsyncMock
+ )
+ mocker.patch(
+ "backend.copilot.model.is_feature_enabled",
+ new_callable=mocker.AsyncMock,
+ return_value=flag_on,
+ )
+ return mock_experts_db, mock_chat_db
+
+
[email protected](loop_scope="session")
+async def test_a_new_expert_thread_starts_on_the_experts_default_mode(
+ mocker: MockerFixture,
+) -> None:
+ mock_experts_db, mock_chat_db = _mock_session_creation(
+ mocker, flag_on=True, expert_default="ask_first"
+ )
+
+ session = await create_chat_session("owner-1", dry_run=False, expert_id="e-1")
+
+ assert session.metadata.autopilot_mode == "ask_first"
+ mock_experts_db.get_autopilot_mode.assert_awaited_once_with("owner-1", "e-1")
+ stored = mock_chat_db.create_chat_session.await_args.kwargs["metadata"]
+ assert stored.autopilot_mode == "ask_first"
+
+
[email protected](loop_scope="session")
+async def test_an_explicit_mode_beats_the_experts_default(
+ mocker: MockerFixture,
+) -> None:
+ mock_experts_db, _ = _mock_session_creation(
+ mocker, flag_on=True, expert_default="ask_first"
+ )
+
+ session = await create_chat_session(
+ "owner-1", dry_run=False, expert_id="e-1", autopilot_mode="unsupervised"
+ )
+
+ assert session.metadata.autopilot_mode == "unsupervised"
+ mock_experts_db.get_autopilot_mode.assert_not_awaited()
+
+
[email protected](loop_scope="session")
+async def test_an_expert_without_a_default_leaves_the_platform_default(
+ mocker: MockerFixture,
+) -> None:
+ _mock_session_creation(mocker, flag_on=True, expert_default=None)
+
+ session = await create_chat_session("owner-1", dry_run=False, expert_id="e-1")
+
+ assert session.metadata.autopilot_mode is None
+
+
[email protected](loop_scope="session")
+async def test_a_plain_chat_never_consults_the_flag_or_an_expert(
+ mocker: MockerFixture,
+) -> None:
+ mock_experts_db, _ = _mock_session_creation(mocker, flag_on=True)
+ flag = mocker.patch(
+ "backend.copilot.model.is_feature_enabled", new_callable=mocker.AsyncMock
+ )
+
+ session = await create_chat_session("owner-1", dry_run=False)
+
+ assert session.metadata.autopilot_mode is None
+ flag.assert_not_awaited()
+ mock_experts_db.get_autopilot_mode.assert_not_awaited()
+
+
[email protected](loop_scope="session")
+async def test_the_stored_default_is_ignored_while_the_flag_is_off(
+ mocker: MockerFixture,
+) -> None:
+ mock_experts_db, _ = _mock_session_creation(
+ mocker, flag_on=False, expert_default="unsupervised"
+ )
+
+ session = await create_chat_session(
+ "owner-1", dry_run=False, expert_id="e-1", autopilot_mode="ask_first"
+ )
+
+ assert session.metadata.autopilot_mode is None
+ mock_experts_db.get_autopilot_mode.assert_not_awaited()
+
+
[email protected](loop_scope="session")
+async def test_an_automation_session_never_reads_the_experts_default(
+ mocker: MockerFixture,
+) -> None:
+ """Routines and block-opened sessions are not gated, so the default
+ chosen for web chats must not be looked up for them."""
+ mock_experts_db, _ = _mock_session_creation(
+ mocker, flag_on=True, expert_default="ask_first"
+ )
+
+ session = await create_chat_session(
+ "owner-1", dry_run=False, expert_id="e-1", origin="automation"
+ )
+
+ assert session.metadata.autopilot_mode is None
+ mock_experts_db.get_autopilot_mode.assert_not_awaited()
+
+
[email protected](loop_scope="session")
+async def test_an_inherited_mode_is_stored_as_is_without_the_flag_or_a_lookup(
+ mocker: MockerFixture,
+) -> None:
+ """Delegation hands over a constraint, not a pick: it survives the flag
+ being off and never re-reads the expert, so a default written to the
+ expert in between cannot loosen the thread."""
+ mock_experts_db, _ = _mock_session_creation(
+ mocker, flag_on=False, expert_default="unsupervised"
+ )
+ flag = mocker.patch(
+ "backend.copilot.model.is_feature_enabled", new_callable=mocker.AsyncMock
+ )
+
+ session = await create_chat_session(
+ "owner-1",
+ dry_run=False,
+ expert_id="e-1",
+ inherited_autopilot_mode="ask_first",
+ )
+
+ assert session.metadata.autopilot_mode == "ask_first"
+ flag.assert_not_awaited()
+ mock_experts_db.get_autopilot_mode.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert.py b/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert.py
index 8f306acf4a..c31f5e58f8 100644
--- a/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert.py
+++ b/autogpt_platform/backend/backend/copilot/tools/delegate_to_expert.py
@@ -36,6 +36,7 @@ from backend.api.features.experts.models import Expert
from backend.copilot.active_turns import spawn_limit_message
from backend.copilot.budget_signal import build_spawn_state_note
from backend.copilot.context import get_current_permissions
+from backend.copilot.gate.policy import DEFAULT_MODE, child_autopilot_mode
from backend.copilot.model import (
ChatSession,
child_session_origin,
@@ -305,6 +306,12 @@ class DelegateToExpertTool(BaseTool):
delegated_by_expert_id=session.expert_id,
delegated_by_session_id=session.session_id,
origin=child_session_origin(session.metadata),
+ # Decided here, from the expert row already in hand, so the
+ # thread cannot pick up a looser default written in between.
+ inherited_autopilot_mode=child_autopilot_mode(
+ session.metadata.autopilot_mode, target.autopilot_mode
+ )
+ or DEFAULT_MODE,
)
return new_session.session_id
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.py
index 85bd61e350..e849e75db1 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
@@ -37,6 +37,7 @@ def _session(
sess.metadata.llm_auth_provider = "platform"
sess.metadata.llm_credential_id = None
sess.metadata.delegated_by_session_id = None
+ sess.metadata.autopilot_mode = None
# Set explicitly: a bare MagicMock attribute is truthy, so an origin
# assertion would pass even if the kwarg were dropped.
sess.metadata.origin = origin
@@ -59,6 +60,7 @@ def _expert(
expert.color = "violet"
expert.is_archived = is_archived
expert.schedules_paused_at = schedules_paused_at
+ expert.autopilot_mode = None
return expert
@@ -113,6 +115,7 @@ def mock_sessions(monkeypatch):
# Without this the MagicMock answers any origin assertion truthily, so
# a test for origin propagation would pass with the kwarg dropped.
sess.metadata.origin = kwargs.get("origin")
+ sess.metadata.autopilot_mode = kwargs.get("inherited_autopilot_mode")
sess.metadata.handed_off_from_expert_id = kwargs.get(
"handed_off_from_expert_id"
)
@@ -187,6 +190,55 @@ class TestDelegatedSessionOrigin:
assert mock_sessions[0].metadata.origin == "automation"
+class TestDelegatedSessionMode:
+ """A delegated thread is never looser than the chat that opened it, and
+ follows that chat when the teammate has no default of its own."""
+
+ @pytest.mark.asyncio
+ async def test_an_expert_without_a_default_follows_the_parent(
+ self, roster, mock_turn, mock_sessions
+ ):
+ parent = _session()
+ parent.metadata.autopilot_mode = "ask_first"
+ await DelegateToExpertTool()._execute(
+ user_id="alice", session=parent, expert_id="expert-b", prompt="hi"
+ )
+ assert mock_sessions[0].metadata.autopilot_mode == "ask_first"
+
+ @pytest.mark.asyncio
+ async def test_an_unsupervised_expert_cannot_loosen_an_ask_first_parent(
+ self, roster, mock_turn, mock_sessions
+ ):
+ roster["expert-b"].autopilot_mode = "unsupervised"
+ parent = _session()
+ parent.metadata.autopilot_mode = "ask_first"
+ await DelegateToExpertTool()._execute(
+ user_id="alice", session=parent, expert_id="expert-b", prompt="hi"
+ )
+ assert mock_sessions[0].metadata.autopilot_mode == "ask_first"
+
+ @pytest.mark.asyncio
+ async def test_a_stricter_expert_default_applies_to_its_thread(
+ self, roster, mock_turn, mock_sessions
+ ):
+ roster["expert-b"].autopilot_mode = "ask_first"
+ await DelegateToExpertTool()._execute(
+ user_id="alice", session=_session(), expert_id="expert-b", prompt="hi"
+ )
+ assert mock_sessions[0].metadata.autopilot_mode == "ask_first"
+
+ @pytest.mark.asyncio
+ async def test_a_thread_with_nothing_to_inherit_is_pinned_to_the_platform_default(
+ self, roster, mock_turn, mock_sessions
+ ):
+ """Pinned rather than left for the session layer to look up again:
+ a default written to the expert in between must not reach it."""
+ await DelegateToExpertTool()._execute(
+ user_id="alice", session=_session(), expert_id="expert-b", prompt="hi"
+ )
+ assert mock_sessions[0].metadata.autopilot_mode == "auto"
+
+
class TestValidation:
@pytest.mark.asyncio
async def test_missing_expert_id_returns_error(self):
diff --git a/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert.py b/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert.py
index c6d6b35fda..c34f0e7a3a 100644
--- a/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert.py
+++ b/autogpt_platform/backend/backend/copilot/tools/handoff_to_expert.py
@@ -28,6 +28,7 @@ from backend.api.features.experts.models import Expert
from backend.copilot.active_turns import spawn_limit_message
from backend.copilot.budget_signal import build_spawn_state_note
from backend.copilot.context import get_current_permissions
+from backend.copilot.gate.policy import DEFAULT_MODE, child_autopilot_mode
from backend.copilot.model import (
ChatSession,
child_session_origin,
@@ -182,6 +183,12 @@ class HandoffToExpertTool(BaseTool):
delegated_by_session_id=session.session_id,
handed_off_from_expert_id=session.expert_id,
origin=child_session_origin(session.metadata),
+ # Same cap delegation applies: an Ask-first chat cannot hand its
+ # work to a thread that runs it unsupervised.
+ inherited_autopilot_mode=child_autopilot_mode(
+ session.metadata.autopilot_mode, target.autopilot_mode
+ )
+ or DEFAULT_MODE,
)
outcome, result = await self._queue_task(
user_id, session, inner.session_id, prompt, context
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.py
index a83317bd79..750524908e 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
@@ -47,6 +47,7 @@ def _session(
# delegator id would send the chain walk off reading ancestors.
sess.metadata.origin = origin
sess.metadata.delegated_by_session_id = None
+ sess.metadata.autopilot_mode = None
sess.expert_id = expert_id
return sess
@@ -66,6 +67,7 @@ def _expert(
expert.color = "violet"
expert.is_archived = is_archived
expert.schedules_paused_at = schedules_paused_at
+ expert.autopilot_mode = None
return expert
@@ -130,6 +132,7 @@ def mock_sessions(monkeypatch, deleted_sessions):
sess.metadata.handed_off_from_expert_id = kwargs.get(
"handed_off_from_expert_id"
)
+ sess.metadata.autopilot_mode = kwargs.get("inherited_autopilot_mode")
created.append(sess)
return sess
@@ -524,6 +527,59 @@ class TestTransfer:
assert "[" not in name_span and "]" not in name_span
+class TestHandedOffSessionMode:
+ """A receiving thread is never looser than the chat that handed it the
+ work, and follows that chat when the target has no default of its own."""
+
+ @pytest.mark.asyncio
+ async def test_an_expert_without_a_default_follows_the_parent(
+ self, roster, mock_turn, mock_sessions
+ ):
+ parent = _session(expert_id="expert-a")
+ parent.metadata.autopilot_mode = "ask_first"
+ await HandoffToExpertTool()._execute(
+ user_id="alice", session=parent, expert_id="expert-b", prompt="own it"
+ )
+ assert mock_sessions[0].metadata.autopilot_mode == "ask_first"
+
+ @pytest.mark.asyncio
+ async def test_an_unsupervised_expert_cannot_loosen_an_ask_first_parent(
+ self, roster, mock_turn, mock_sessions
+ ):
+ roster["expert-b"].autopilot_mode = "unsupervised"
+ parent = _session(expert_id="expert-a")
+ parent.metadata.autopilot_mode = "ask_first"
+ await HandoffToExpertTool()._execute(
+ user_id="alice", session=parent, expert_id="expert-b", prompt="own it"
+ )
+ assert mock_sessions[0].metadata.autopilot_mode == "ask_first"
+
+ @pytest.mark.asyncio
+ async def test_a_stricter_expert_default_applies_to_its_thread(
+ self, roster, mock_turn, mock_sessions
+ ):
+ roster["expert-b"].autopilot_mode = "ask_first"
+ await HandoffToExpertTool()._execute(
+ user_id="alice",
+ session=_session(expert_id="expert-a"),
+ expert_id="expert-b",
+ prompt="own it",
+ )
+ assert mock_sessions[0].metadata.autopilot_mode == "ask_first"
+
+ @pytest.mark.asyncio
+ async def test_a_thread_with_nothing_to_inherit_is_pinned_to_the_platform_default(
+ self, roster, mock_turn, mock_sessions
+ ):
+ await HandoffToExpertTool()._execute(
+ user_id="alice",
+ session=_session(expert_id="expert-a"),
+ expert_id="expert-b",
+ prompt="own it",
+ )
+ assert mock_sessions[0].metadata.autopilot_mode == "auto"
+
+
class TestTerminalResponse:
"""A handoff is terminal for the caller: it names the new owner, links the
receiving thread, and points at no poll (``_in_caller_scope`` denies the
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index ebbf9a8675..43f758ad45 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -607,6 +607,7 @@ class DatabaseManager(AppService):
resolve_attributable_expert = _(experts_db.resolve_attributable_expert)
list_experts = _(experts_db.list_experts)
resolve_private_expert_tenancy = _(experts_db.resolve_private_expert_tenancy)
+ get_autopilot_mode = _(experts_db.get_autopilot_mode)
# The scheduler's fire path reads the routine behind a copilot-turn job to
# find its durable thread and whether the owner granted it anything.
create_routine = _(experts_db.create_routine)
@@ -1111,6 +1112,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
resolve_attributable_expert = d.resolve_attributable_expert
list_experts = d.list_experts
resolve_private_expert_tenancy = d.resolve_private_expert_tenancy
+ get_autopilot_mode = d.get_autopilot_mode
get_routine = d.get_routine
record_routine_thread = d.record_routine_thread
record_routine_fired = d.record_routine_fired
diff --git a/autogpt_platform/backend/backend/util/posthog_events.py b/autogpt_platform/backend/backend/util/posthog_events.py
index f550ebe770..663747ab2a 100644
--- a/autogpt_platform/backend/backend/util/posthog_events.py
+++ b/autogpt_platform/backend/backend/util/posthog_events.py
@@ -38,6 +38,7 @@ class PostHogEvent(StrEnum):
WRITING_STYLE_ADDED = "writing_style_added"
WORKFLOW_INSTALLED_ON_EXPERT = "workflow_installed_on_expert"
EXPERT_FIRED = "expert_fired"
+ EXPERT_MODE_SET_UNSUPERVISED = "expert_mode_set_unsupervised"
BRIEFING_GENERATED = "briefing_generated"
BRIEFING_DELIVERED = "briefing_delivered"
diff --git a/autogpt_platform/backend/backend/util/posthog_events_test.py b/autogpt_platform/backend/backend/util/posthog_events_test.py
index 5e6e533713..918fb0baab 100644
--- a/autogpt_platform/backend/backend/util/posthog_events_test.py
+++ b/autogpt_platform/backend/backend/util/posthog_events_test.py
@@ -23,6 +23,7 @@ LIVE_EVENT_NAMES = {
"writing_style_added",
"workflow_installed_on_expert",
"expert_fired",
+ "expert_mode_set_unsupervised",
"briefing_generated",
"briefing_delivered",
"chat_tool_called",
diff --git a/autogpt_platform/backend/migrations/20261017120000_add_expert_autopilot_mode/migration.sql b/autogpt_platform/backend/migrations/20261017120000_add_expert_autopilot_mode/migration.sql
new file mode 100644
index 0000000000..041d4380cf
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20261017120000_add_expert_autopilot_mode/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "Expert" ADD COLUMN "autopilotMode" TEXT;
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 1c2a6b8f7d..3c081678ad 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -1254,6 +1254,11 @@ model Expert {
// unaffected. Cleared by the resume-learning endpoint.
learningPausedAt DateTime?
+ // Approval mode every new web chat with this expert starts on
+ // ("ask_first" | "auto" | "unsupervised"). null = platform default.
+ // Hire-only: templates never carry one and a hire copies nothing.
+ autopilotMode String?
+
// Null until the credential allow-list has been seeded from the expert's
// installed workflows. Distinguishes "never curated" from "deliberately
// empty": without it, revoking an expert's last credential would look
diff --git a/autogpt_platform/backend/snapshots/expert_pod_assign b/autogpt_platform/backend/snapshots/expert_pod_assign
index 19109c5cec..57310124e9 100644
--- a/autogpt_platform/backend/snapshots/expert_pod_assign
+++ b/autogpt_platform/backend/snapshots/expert_pod_assign
@@ -1,4 +1,5 @@
{
+ "autopilot_mode": null,
"avatar_url": null,
"bio": null,
"boundaries": "Ask before external actions.",
diff --git a/autogpt_platform/backend/snapshots/expert_raise_attachment_installation_failure b/autogpt_platform/backend/snapshots/expert_raise_attachment_installation_failure
index 4bcdf926f8..83e2569c9c 100644
--- a/autogpt_platform/backend/snapshots/expert_raise_attachment_installation_failure
+++ b/autogpt_platform/backend/snapshots/expert_raise_attachment_installation_failure
@@ -1,5 +1,6 @@
{
"expert": {
+ "autopilot_mode": null,
"avatar_url": null,
"bio": null,
"boundaries": "",
diff --git a/autogpt_platform/backend/snapshots/expert_raise_attachments b/autogpt_platform/backend/snapshots/expert_raise_attachments
index f59d57623b..9502a79a0f 100644
--- a/autogpt_platform/backend/snapshots/expert_raise_attachments
+++ b/autogpt_platform/backend/snapshots/expert_raise_attachments
@@ -1,5 +1,6 @@
{
"expert": {
+ "autopilot_mode": null,
"avatar_url": null,
"bio": null,
"boundaries": "",
diff --git a/autogpt_platform/backend/snapshots/expert_raise_default b/autogpt_platform/backend/snapshots/expert_raise_default
index 7137b3b6c9..271ca9458e 100644
--- a/autogpt_platform/backend/snapshots/expert_raise_default
+++ b/autogpt_platform/backend/snapshots/expert_raise_default
@@ -1,5 +1,6 @@
{
"expert": {
+ "autopilot_mode": null,
"avatar_url": null,
"bio": null,
"boundaries": "",
diff --git a/autogpt_platform/backend/snapshots/expert_soul_update b/autogpt_platform/backend/snapshots/expert_soul_update
index a2424b22ee..c69eec2d2c 100644
--- a/autogpt_platform/backend/snapshots/expert_soul_update
+++ b/autogpt_platform/backend/snapshots/expert_soul_update
@@ -1,4 +1,5 @@
{
+ "autopilot_mode": null,
"avatar_url": null,
"bio": null,
"boundaries": "Never invent customer evidence.",
diff --git a/autogpt_platform/backend/snapshots/expert_templates_list b/autogpt_platform/backend/snapshots/expert_templates_list
index 3a42cbc018..02a583bb5d 100644
--- a/autogpt_platform/backend/snapshots/expert_templates_list
+++ b/autogpt_platform/backend/snapshots/expert_templates_list
@@ -1,5 +1,6 @@
[
{
+ "autopilot_mode": null,
"avatar_url": null,
"bio": null,
"boundaries": "Ask before external actions.",
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-mode-selector.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-mode-selector.test.tsx
index 832e240a1e..572495a3db 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-mode-selector.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/__tests__/autopilot-mode-selector.test.tsx
@@ -1,7 +1,9 @@
import {
getGetV2ListChatTransportsMockHandler,
+ getGetV2ListSessionsMockHandler200,
getPostV2CreateSessionMockHandler,
} from "@/app/api/__generated__/endpoints/chat/chat.msw";
+import { getListExpertIdentitiesMockHandler } from "@/app/api/__generated__/endpoints/experts/experts.msw";
import { server } from "@/mocks/mock-server";
import {
assistantTextChunks,
@@ -20,7 +22,7 @@ import {
typeAndSend,
} from "./sse-helpers";
-const flags = vi.hoisted(() => ({ autoMode: false }));
+const flags = vi.hoisted(() => ({ autoMode: false, experts: false }));
vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {
const actual =
@@ -30,7 +32,11 @@ vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {
return {
...actual,
useGetFlag: (flag: string) =>
- flag === actual.Flag.COPILOT_AUTO_MODE ? flags.autoMode : false,
+ flag === actual.Flag.COPILOT_AUTO_MODE
+ ? flags.autoMode
+ : flag === actual.Flag.HIRE_EXPERTS
+ ? flags.experts
+ : false,
};
});
@@ -59,6 +65,7 @@ vi.mock("@/lib/auth/hooks/useAuth", () => ({
beforeEach(() => {
flags.autoMode = true;
+ flags.experts = false;
});
afterEach(() => {
@@ -176,6 +183,103 @@ describe("AutoPilot mode selector", () => {
await waitFor(() => expect(bodies).toHaveLength(1), { timeout: 5000 });
expect(bodies[0]).toMatchObject({ autopilot_mode: "ask_first" });
});
+ it("starts a new expert thread on the expert's default without sending it", async () => {
+ flags.experts = true;
+ const bodies = captureStreamBodies();
+ const createBodies: Record<string, unknown>[] = [];
+ server.use(
+ getListExpertIdentitiesMockHandler([mariaIdentity("ask_first")]),
+ getGetV2ListSessionsMockHandler200({ sessions: [], total: 0 }),
+ getGetV2ListChatTransportsMockHandler({
+ transports: [
+ {
+ auth_provider: "platform",
+ credential_id: null,
+ label: "AutoGPT Platform",
+ available: true,
+ default: true,
+ },
+ ],
+ }),
+ getPostV2CreateSessionMockHandler(async ({ request }) => {
+ createBodies.push((await request.json()) as Record<string, unknown>);
+ return {
+ id: TEST_SESSION_ID,
+ created_at: "2026-05-13T00:00:00Z",
+ user_id: "test-user",
+ expert_id: "expert-maria",
+ };
+ }),
+ );
+
+ renderHost({ searchParams: "?expertId=expert-maria" });
+
+ expect(await findModeButton(/approval mode: ask first/i)).toBeDefined();
+ await typeAndSend("hi");
+
+ await waitFor(() => expect(bodies).toHaveLength(1), { timeout: 5000 });
+ expect(createBodies).toHaveLength(1);
+ expect(createBodies[0]).not.toHaveProperty("autopilot_mode");
+ expect(bodies[0]).not.toHaveProperty("autopilot_mode");
+ });
+
+ it("drops a pick left over from an earlier new chat that was never sent", async () => {
+ flags.experts = true;
+ const createBodies: Record<string, unknown>[] = [];
+ server.use(
+ getListExpertIdentitiesMockHandler([mariaIdentity("ask_first")]),
+ getGetV2ListSessionsMockHandler200({ sessions: [], total: 0 }),
+ getGetV2ListChatTransportsMockHandler({
+ transports: [
+ {
+ auth_provider: "platform",
+ credential_id: null,
+ label: "AutoGPT Platform",
+ available: true,
+ default: true,
+ },
+ ],
+ }),
+ getPostV2CreateSessionMockHandler(async ({ request }) => {
+ createBodies.push((await request.json()) as Record<string, unknown>);
+ return {
+ id: TEST_SESSION_ID,
+ created_at: "2026-05-13T00:00:00Z",
+ user_id: "test-user",
+ expert_id: "expert-maria",
+ };
+ }),
+ );
+ captureStreamBodies();
+ // Picked while composing an earlier new chat, then abandoned.
+ useAutopilotModeStore.getState().choose(null, "unsupervised");
+
+ renderHost({ searchParams: "?expertId=expert-maria" });
+
+ expect(await findModeButton(/approval mode: ask first/i)).toBeDefined();
+ await typeAndSend("hi");
+
+ await waitFor(() => expect(createBodies).toHaveLength(1), {
+ timeout: 5000,
+ });
+ expect(createBodies[0]).not.toHaveProperty("autopilot_mode");
+ });
+
+ it("keeps a thread's stored mode over the expert's default", async () => {
+ flags.experts = true;
+ server.use(
+ getListExpertIdentitiesMockHandler([mariaIdentity("ask_first")]),
+ );
+
+ renderHost({
+ sessionOverride: {
+ expert_id: "expert-maria",
+ metadata: { dry_run: false, autopilot_mode: "unsupervised" },
+ },
+ });
+
+ expect(await findModeButton(/approval mode: unsupervised/i)).toBeDefined();
+ });
});
describe("autopilotModeStore", () => {
@@ -189,6 +293,17 @@ describe("autopilotModeStore", () => {
});
});
+ it("clearing the new chat pick leaves session picks alone", () => {
+ const store = useAutopilotModeStore.getState();
+ store.choose(null, "ask_first");
+ store.choose("session-1", "unsupervised");
+ store.clearNewChatChoice();
+
+ expect(useAutopilotModeStore.getState().choices).toEqual({
+ "session-1": "unsupervised",
+ });
+ });
+
it("binds nothing when the new chat had no pick", () => {
useAutopilotModeStore.getState().bindNewChatToSession("created-1");
@@ -229,3 +344,15 @@ async function pickMode(trigger: RegExp, option: RegExp) {
await user.click(await findModeButton(trigger));
await user.click(await screen.findByRole("menuitemradio", { name: option }));
}
+
+function mariaIdentity(autopilotMode: "ask_first" | "auto" | "unsupervised") {
+ return {
+ id: "expert-maria",
+ name: "Maria",
+ avatar_url: null,
+ color: "orange-500",
+ role: "Marketing",
+ is_archived: false,
+ autopilot_mode: autopilotMode,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/autopilotModeStore.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/autopilotModeStore.ts
index 635fd924ca..d2d4fd4c43 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/autopilotModeStore.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/autopilotModeStore.ts
@@ -14,6 +14,10 @@ interface AutopilotModeStore {
choices: Record<string, AutopilotMode>;
choose: (sessionId: string | null, mode: AutopilotMode) => void;
bindNewChatToSession: (sessionId: string) => void;
+ /** Drop a pick left over from a new chat that was never sent, so it cannot
+ * follow the user into the next new chat (and override that expert's
+ * default). */
+ clearNewChatChoice: () => void;
}
export const useAutopilotModeStore = create<AutopilotModeStore>((set) => ({
@@ -32,6 +36,14 @@ export const useAutopilotModeStore = create<AutopilotModeStore>((set) => ({
return { choices };
});
},
+ clearNewChatChoice() {
+ set((state) => {
+ if (!(NEW_CHAT in state.choices)) return state;
+ const choices = { ...state.choices };
+ delete choices[NEW_CHAT];
+ return { choices };
+ });
+ },
}));
export function useAutopilotModeChoice(sessionId: string | null) {
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.tsx
index 2034013b22..2b9af69531 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
@@ -259,11 +259,13 @@ export const ChatContainer = ({
const isVoiceModeEnabled = useGetFlag(Flag.COPILOT_VOICE_MODE);
const isAutoModeEnabled = useGetFlag(Flag.COPILOT_AUTO_MODE);
+ // A thread keeps the mode stored on it; a new expert chat starts on the
+ // expert's own default until its first send creates the session.
+ const initialMode = sessionId
+ ? sessionAutopilotMode
+ : (expertIdentity?.autopilotMode ?? null);
const modeSelector = isAutoModeEnabled ? (
- <AutopilotModeSelector
- sessionId={sessionId}
- persistedMode={sessionAutopilotMode}
- />
+ <AutopilotModeSelector sessionId={sessionId} persistedMode={initialMode} />
) : undefined;
const silenceTimeoutMs = useVoiceSilenceTimeout();
const voice = useVoiceMode({
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AutopilotModeSelector/UnsupervisedConfirmDialog.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AutopilotModeSelector/UnsupervisedConfirmDialog.tsx
index 4c14da3950..effab1ffa9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AutopilotModeSelector/UnsupervisedConfirmDialog.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ChatInput/components/AutopilotModeSelector/UnsupervisedConfirmDialog.tsx
@@ -4,20 +4,27 @@ import { Button } from "@/components/atoms/Button/Button";
import { Text } from "@/components/atoms/Text/Text";
import { Dialog } from "@/components/molecules/Dialog/Dialog";
+const DEFAULT_DESCRIPTION =
+ "AutoPilot will not ask before anything in this chat. Edits, commands and actions outside the platform, like sending a message or an email, run without your approval.";
+
interface Props {
isOpen: boolean;
onConfirm: () => void;
onCancel: () => void;
+ title?: string;
+ description?: string;
}
export function UnsupervisedConfirmDialog({
isOpen,
onConfirm,
onCancel,
+ title = "Run this chat unsupervised?",
+ description = DEFAULT_DESCRIPTION,
}: Props) {
return (
<Dialog
- title="Run this chat unsupervised?"
+ title={title}
styling={{ maxWidth: "30rem", minWidth: "auto" }}
controlled={{
isOpen,
@@ -27,11 +34,7 @@ export function UnsupervisedConfirmDialog({
}}
>
<Dialog.Content>
- <Text variant="body">
- AutoPilot will not ask before anything in this chat. Edits, commands
- and actions outside the platform, like sending a message or an email,
- run without your approval.
- </Text>
+ <Text variant="body">{description}</Text>
<Dialog.Footer>
<Button variant="secondary" onClick={onCancel}>
Cancel
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
index 2ed1608e73..a537ea213f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useChatSession.ts
@@ -27,7 +27,10 @@ import {
getAvailableLLMTransports,
resolveCopilotLLMAuthSelection,
} from "./helpers/copilotLlmAuth";
-import { useAutopilotModeStore } from "./autopilotModeStore";
+import {
+ getAutopilotModeChoice,
+ useAutopilotModeStore,
+} from "./autopilotModeStore";
import { useCopilotStreamStore } from "./copilotStreamStore";
import { latestExpertSessionParams } from "./expertSessionQuery";
import {
@@ -52,6 +55,17 @@ export function useChatSession({
const [sessionId, setSessionId] = useQueryState("sessionId", parseAsString);
const queryClient = useQueryClient();
const copilotLlmAuth = useCopilotUIStore((state) => state.copilotLlmAuth);
+ const clearNewChatChoice = useAutopilotModeStore(
+ (state) => state.clearNewChatChoice,
+ );
+
+ // A mode picked in a new chat belongs to that composer and recipient. Once
+ // the user moves on without sending (another new chat, a different expert)
+ // the pick must not travel with them, or it would override the next
+ // expert's own default.
+ useEffect(() => {
+ if (!sessionId) clearNewChatChoice();
+ }, [sessionId, expertId, clearNewChatChoice]);
const transportQuery = useGetV2ListChatTransports({
query: {
@@ -319,6 +333,10 @@ export function useChatSession({
if (dryRun) sessionData.dry_run = true;
if (expertId) sessionData.expert_id = expertId;
if (options?.expertKickoff) sessionData.expert_kickoff = true;
+ // Same rule as the route: only a mode the user picked travels, so a new
+ // expert thread starts on the expert's own default rather than "auto".
+ const pickedMode = getAutopilotModeChoice(null);
+ if (pickedMode) sessionData.autopilot_mode = pickedMode;
const body =
Object.keys(sessionData).length > 0
? { data: sessionData }
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertMap.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertMap.ts
index 5f5a6095f4..cb3bee71fa 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertMap.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/useExpertMap.ts
@@ -1,6 +1,7 @@
import { useListExpertIdentities } from "@/app/api/__generated__/endpoints/experts/experts";
import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import { useMemo } from "react";
+import type { AutopilotMode } from "./autopilotModeStore";
/**
* Why a thread is read-only. `fired` is the only reason we can state as fact;
@@ -18,6 +19,8 @@ export interface ExpertIdentity {
jobTitle?: string | null;
isArchived: boolean;
readOnlyReason: ExpertReadOnlyReason | null;
+ /** The approval mode a new chat with this expert starts on. */
+ autopilotMode?: AutopilotMode | null;
}
export type ExpertIdentityMap = Map<string, ExpertIdentity>;
@@ -101,6 +104,7 @@ export function useExpertMap() {
jobTitle: expert.job_title ?? null,
isArchived: expert.is_archived,
readOnlyReason: expert.is_archived ? ("fired" as const) : null,
+ autopilotMode: expert.autopilot_mode ?? null,
}));
const activeExperts = identities.filter((expert) => !expert.isArchived);
return {
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/approval-mode.test.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/approval-mode.test.tsx
new file mode 100644
index 0000000000..71daa764fe
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/__tests__/approval-mode.test.tsx
@@ -0,0 +1,280 @@
+import {
+ getGetExpertActivityMockHandler,
+ getGetExpertMockHandler,
+ getListExpertRunsMockHandler,
+ getUpdateExpertModeMockHandler,
+} from "@/app/api/__generated__/endpoints/experts/experts.msw";
+import { getGetV1ListExecutionSchedulesForAUserMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";
+import {
+ getGetHomeDashboardMockHandler,
+ getGetHomeDashboardResponseMock200,
+} from "@/app/api/__generated__/endpoints/home/home.msw";
+import { Expert } from "@/app/api/__generated__/models/expert";
+import { server } from "@/mocks/mock-server";
+import { render, screen, waitFor } from "@/tests/integrations/test-utils";
+import userEvent from "@testing-library/user-event";
+import { http, HttpResponse } from "msw";
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import ExpertDetailPage from "../page";
+
+vi.mock("@/services/environment", async (importActual) => {
+ const actual = await importActual<typeof import("@/services/environment")>();
+ return {
+ ...actual,
+ environment: {
+ ...actual.environment,
+ getAGPTServerBaseUrl: () => "http://localhost:18006",
+ },
+ };
+});
+
+vi.mock("framer-motion", async (importActual) => {
+ const actual = await importActual<typeof import("framer-motion")>();
+ return { ...actual, useReducedMotion: () => true };
+});
+
+const flags = vi.hoisted(() => ({ autoMode: true }));
+const toastMock = vi.hoisted(() => vi.fn());
+
+vi.mock("@/components/molecules/Toast/use-toast", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/components/molecules/Toast/use-toast")
+ >();
+ return { ...actual, toast: toastMock };
+});
+
+vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {
+ const actual =
+ await importOriginal<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >();
+ return {
+ ...actual,
+ useFlagStatus: () => ({ enabled: true, ready: true }),
+ useGetFlag: (flag: string) =>
+ flag === actual.Flag.COPILOT_AUTO_MODE ? flags.autoMode : false,
+ };
+});
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({
+ push: vi.fn(),
+ replace: vi.fn(),
+ prefetch: vi.fn(),
+ back: vi.fn(),
+ forward: vi.fn(),
+ refresh: vi.fn(),
+ }),
+ usePathname: () => "/team/expert-maria",
+ useSearchParams: () => new URLSearchParams(),
+ useParams: () => ({ expertId: "expert-maria" }),
+ notFound: () => {
+ throw new Error("NEXT_NOT_FOUND");
+ },
+}));
+
+const maria: Expert = {
+ id: "expert-maria",
+ name: "Maria",
+ avatar_url: null,
+ role: "Marketing Strategist",
+ bio: null,
+ skills: [],
+ tagline: null,
+ identity: "You are Maria.",
+ voice_preferences: "",
+ boundaries: "",
+ protected_soul_rules: [],
+ is_template: false,
+ source_template_id: "template-maria",
+ is_archived: false,
+ workflows: [],
+};
+
+let expertResponse: Expert;
+let patchBodies: Record<string, unknown>[];
+
+beforeEach(() => {
+ flags.autoMode = true;
+ toastMock.mockReset();
+ expertResponse = maria;
+ patchBodies = [];
+ server.use(
+ getGetHomeDashboardMockHandler(
+ getGetHomeDashboardResponseMock200({ attention: [] }),
+ ),
+ getGetExpertMockHandler(() => expertResponse),
+ getGetV1ListExecutionSchedulesForAUserMockHandler([]),
+ getListExpertRunsMockHandler([]),
+ getGetExpertActivityMockHandler({ timezone: "UTC", days: [] }),
+ getUpdateExpertModeMockHandler(async ({ request }) => {
+ const body = (await request.clone().json()) as Record<string, unknown>;
+ patchBodies.push(body);
+ expertResponse = {
+ ...maria,
+ autopilot_mode: body.autopilot_mode as Expert["autopilot_mode"],
+ };
+ return expertResponse;
+ }),
+ );
+});
+
+afterEach(() => {
+ window.localStorage.removeItem("team-workflows-view");
+});
+
+async function openSettings() {
+ const user = userEvent.setup();
+ await user.click(await screen.findByRole("tab", { name: "Settings" }));
+ return user;
+}
+
+describe("Expert approval mode", () => {
+ test("starts on Auto and saves a picked mode for the expert", async () => {
+ render(<ExpertDetailPage />);
+ const user = await openSettings();
+
+ const section = await screen.findByRole("region", {
+ name: "Maria approval mode",
+ });
+ expect(section.textContent).toContain("Routines, scheduled runs");
+ expect(
+ screen.getByRole("radio", { name: /auto \(default\)/i }),
+ ).toHaveProperty("checked", true);
+
+ await user.click(screen.getByRole("radio", { name: /ask first/i }));
+
+ await waitFor(() =>
+ expect(patchBodies).toEqual([{ autopilot_mode: "ask_first" }]),
+ );
+ await waitFor(() =>
+ expect(screen.getByRole("radio", { name: /ask first/i })).toHaveProperty(
+ "checked",
+ true,
+ ),
+ );
+ await waitFor(() =>
+ expect(toastMock).toHaveBeenCalledWith({
+ title: "Approval mode updated",
+ }),
+ );
+ });
+
+ test("keeps the choices locked until the expert refetch lands", async () => {
+ let releaseRefetch = () => {};
+ const refetchHeld = new Promise<void>((resolve) => {
+ releaseRefetch = resolve;
+ });
+ server.use(
+ getGetExpertMockHandler(async () => {
+ if (patchBodies.length > 0) await refetchHeld;
+ return expertResponse;
+ }),
+ );
+ render(<ExpertDetailPage />);
+ const user = await openSettings();
+
+ await user.click(await screen.findByRole("radio", { name: /ask first/i }));
+
+ await waitFor(() =>
+ expect(patchBodies).toEqual([{ autopilot_mode: "ask_first" }]),
+ );
+ expect(toastMock).not.toHaveBeenCalled();
+ expect(
+ screen.getByRole("radio", { name: /ask first/i }).closest("fieldset")
+ ?.disabled,
+ ).toBe(true);
+
+ releaseRefetch();
+
+ await waitFor(() =>
+ expect(toastMock).toHaveBeenCalledWith({
+ title: "Approval mode updated",
+ }),
+ );
+ expect(
+ screen.getByRole("radio", { name: /ask first/i }).closest("fieldset")
+ ?.disabled,
+ ).toBe(false);
+ });
+
+ test("shows the stored default on load", async () => {
+ expertResponse = { ...maria, autopilot_mode: "unsupervised" };
+ render(<ExpertDetailPage />);
+ await openSettings();
+
+ expect(
+ await screen.findByRole("radio", { name: /unsupervised/i }),
+ ).toHaveProperty("checked", true);
+ });
+
+ test("saves Unsupervised only after the confirm", async () => {
+ render(<ExpertDetailPage />);
+ const user = await openSettings();
+
+ await user.click(
+ await screen.findByRole("radio", { name: /unsupervised/i }),
+ );
+ expect(
+ await screen.findByRole("heading", {
+ name: "Run Maria unsupervised by default?",
+ }),
+ ).toBeDefined();
+ await user.click(screen.getByRole("button", { name: "Cancel" }));
+ await waitFor(() =>
+ expect(
+ screen.queryByRole("heading", {
+ name: "Run Maria unsupervised by default?",
+ }),
+ ).toBeNull(),
+ );
+ expect(patchBodies).toEqual([]);
+ expect(
+ screen.getByRole("radio", { name: /auto \(default\)/i }),
+ ).toHaveProperty("checked", true);
+
+ await user.click(screen.getByRole("radio", { name: /unsupervised/i }));
+ await user.click(
+ await screen.findByRole("button", { name: "Run unsupervised" }),
+ );
+
+ await waitFor(() =>
+ expect(patchBodies).toEqual([{ autopilot_mode: "unsupervised" }]),
+ );
+ });
+
+ test("explains when approval modes are off for the account", async () => {
+ server.use(
+ http.patch("*/api/experts/expert-maria/mode", () =>
+ HttpResponse.json({ detail: "feature_disabled" }, { status: 403 }),
+ ),
+ );
+ render(<ExpertDetailPage />);
+ const user = await openSettings();
+
+ await user.click(await screen.findByRole("radio", { name: /ask first/i }));
+
+ await waitFor(() =>
+ expect(toastMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ title: "Approval modes are not enabled for your account",
+ variant: "destructive",
+ }),
+ ),
+ );
+ });
+
+ test("is hidden while the flag is off", async () => {
+ flags.autoMode = false;
+ render(<ExpertDetailPage />);
+ await openSettings();
+
+ expect(
+ await screen.findByRole("region", { name: "Fire Maria" }),
+ ).toBeDefined();
+ expect(
+ screen.queryByRole("region", { name: "Maria approval mode" }),
+ ).toBeNull();
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertModeSection/ExpertModeSection.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertModeSection/ExpertModeSection.tsx
new file mode 100644
index 0000000000..ce1283243d
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertModeSection/ExpertModeSection.tsx
@@ -0,0 +1,100 @@
+"use client";
+
+import { Expert } from "@/app/api/__generated__/models/expert";
+import { DEFAULT_AUTOPILOT_MODE } from "@/app/(platform)/copilot/autopilotModeStore";
+import { AUTOPILOT_MODE_OPTIONS } from "@/app/(platform)/copilot/components/ChatInput/components/AutopilotModeSelector/helpers";
+import { UnsupervisedConfirmDialog } from "@/app/(platform)/copilot/components/ChatInput/components/AutopilotModeSelector/UnsupervisedConfirmDialog";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Text } from "@/components/atoms/Text/Text";
+import { cn } from "@/lib/utils";
+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
+import { useExpertModeSection } from "./useExpertModeSection";
+
+interface Props {
+ expert: Expert;
+}
+
+export function ExpertModeSection({ expert }: Props) {
+ const isAutoModeEnabled = useGetFlag(Flag.COPILOT_AUTO_MODE);
+ if (!isAutoModeEnabled) return null;
+ return <ExpertModeOptions expert={expert} />;
+}
+
+function ExpertModeOptions({ expert }: Props) {
+ const {
+ mode,
+ isPending,
+ selectMode,
+ isConfirmOpen,
+ confirmUnsupervised,
+ cancelUnsupervised,
+ } = useExpertModeSection({ expert });
+
+ return (
+ <section
+ aria-label={`${expert.name} approval mode`}
+ className="rounded-xl border border-zinc-200 bg-white p-4"
+ >
+ <Text variant="large-medium">Approvals</Text>
+ <Text variant="small" tone="secondary" className="mt-1">
+ How every new web chat with {expert.name} starts. You can still change
+ it per chat from the composer, and chats already open keep their own
+ setting. Routines, scheduled runs and chats from Slack, Discord, Teams
+ or Telegram are not affected.
+ </Text>
+ <fieldset className="mt-4 flex flex-col gap-2" disabled={isPending}>
+ <legend className="sr-only">
+ Approval mode for new chats with {expert.name}
+ </legend>
+ {AUTOPILOT_MODE_OPTIONS.map((option) => {
+ const isSelected = option.value === mode;
+ return (
+ <label
+ key={option.value}
+ className={cn(
+ "flex cursor-pointer items-start gap-3 rounded-xl p-3 text-left transition-colors has-[:focus-visible]:outline has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-zinc-800",
+ isSelected
+ ? "bg-white ring-2 ring-inset ring-zinc-800"
+ : "bg-zinc-50 ring-1 ring-inset ring-zinc-200 hover:bg-zinc-100",
+ option.value === "unsupervised" &&
+ isSelected &&
+ "bg-amber-50 ring-amber-600",
+ )}
+ >
+ <input
+ type="radio"
+ name="expert-autopilot-mode"
+ value={option.value}
+ checked={isSelected}
+ onChange={() => selectMode(option.value)}
+ className="sr-only"
+ />
+ <Icon
+ icon={option.icon}
+ size={18}
+ className="mt-0.5 shrink-0 text-zinc-700"
+ aria-hidden="true"
+ />
+ <span className="flex flex-col gap-0.5">
+ <span className="text-sm font-medium text-zinc-900">
+ {option.label}
+ {option.value === DEFAULT_AUTOPILOT_MODE ? " (default)" : ""}
+ </span>
+ <span className="text-xs text-zinc-500">
+ {option.description}
+ </span>
+ </span>
+ </label>
+ );
+ })}
+ </fieldset>
+ <UnsupervisedConfirmDialog
+ isOpen={isConfirmOpen}
+ onConfirm={confirmUnsupervised}
+ onCancel={cancelUnsupervised}
+ title={`Run ${expert.name} unsupervised by default?`}
+ description={`AutoPilot will not ask before anything in new chats with ${expert.name}. Edits, commands and actions outside the platform, like sending a message or an email, run without your approval unless you switch a chat back from the composer.`}
+ />
+ </section>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertModeSection/useExpertModeSection.ts b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertModeSection/useExpertModeSection.ts
new file mode 100644
index 0000000000..3158303472
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/components/ExpertModeSection/useExpertModeSection.ts
@@ -0,0 +1,83 @@
+import {
+ getGetExpertQueryKey,
+ getListExpertIdentitiesQueryKey,
+ getListExpertsQueryKey,
+ useUpdateExpertMode,
+} from "@/app/api/__generated__/endpoints/experts/experts";
+import { Expert } from "@/app/api/__generated__/models/expert";
+import {
+ type AutopilotMode,
+ DEFAULT_AUTOPILOT_MODE,
+} from "@/app/(platform)/copilot/autopilotModeStore";
+import { toast } from "@/components/molecules/Toast/use-toast";
+import { ApiError } from "@/lib/autogpt-server-api/helpers";
+import { useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+
+interface Args {
+ expert: Expert;
+}
+
+export function useExpertModeSection({ expert }: Args) {
+ const queryClient = useQueryClient();
+ const [isConfirmOpen, setIsConfirmOpen] = useState(false);
+ const mode: AutopilotMode = expert.autopilot_mode ?? DEFAULT_AUTOPILOT_MODE;
+
+ const { mutate, isPending } = useUpdateExpertMode({
+ mutation: {
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: getGetExpertQueryKey(expert.id),
+ }),
+ queryClient.invalidateQueries({ queryKey: getListExpertsQueryKey() }),
+ queryClient.invalidateQueries({
+ queryKey: getListExpertIdentitiesQueryKey(),
+ }),
+ ]);
+ toast({ title: "Approval mode updated" });
+ },
+ onError: (error) => {
+ const isDisabled = error instanceof ApiError && error.status === 403;
+ toast({
+ title: isDisabled
+ ? "Approval modes are not enabled for your account"
+ : "Could not update the approval mode",
+ description: isDisabled ? undefined : "Please try again.",
+ variant: "destructive",
+ });
+ },
+ },
+ });
+
+ function save(value: AutopilotMode) {
+ mutate({ expertId: expert.id, data: { autopilot_mode: value } });
+ }
+
+ function selectMode(value: AutopilotMode) {
+ if (value === mode || isPending) return;
+ if (value === "unsupervised") {
+ setIsConfirmOpen(true);
+ return;
+ }
+ save(value);
+ }
+
+ function confirmUnsupervised() {
+ setIsConfirmOpen(false);
+ save("unsupervised");
+ }
+
+ function cancelUnsupervised() {
+ setIsConfirmOpen(false);
+ }
+
+ return {
+ mode,
+ isPending,
+ selectMode,
+ isConfirmOpen,
+ confirmUnsupervised,
+ cancelUnsupervised,
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/page.tsx b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/page.tsx
index c0f58ba76b..2350109f5a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/[expertId]/page.tsx
@@ -49,6 +49,7 @@ import { ExpertSoulSection } from "./components/ExpertSoulSection";
import { ExpertComputerSection } from "./components/ExpertComputerSection/ExpertComputerSection";
import { ExpertDetailHeader } from "./components/ExpertDetailHeader";
import { ExpertIntegrationsSection } from "./components/ExpertIntegrationsSection/ExpertIntegrationsSection";
+import { ExpertModeSection } from "./components/ExpertModeSection/ExpertModeSection";
import { ExpertNeedsYouSection } from "./components/ExpertNeedsYouSection/ExpertNeedsYouSection";
import { ExpertSchedulesSection } from "./components/ExpertSchedulesSection";
import { ExpertSettingsSection } from "./components/ExpertSettingsSection";
@@ -266,7 +267,10 @@ export default function ExpertDetailPage() {
</TabsLineContent>
<TabsLineContent value="settings">
- <ExpertSettingsSection expert={expert} onFire={openFire} />
+ <div className="flex flex-col gap-4">
+ <ExpertModeSection expert={expert} />
+ <ExpertSettingsSection expert={expert} onFire={openFire} />
+ </div>
</TabsLineContent>
</TabsLine>
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/team/__tests__/main.test.tsx
index cb2481a2a7..7d9da059a3 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/__tests__/main.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/__tests__/main.test.tsx
@@ -58,6 +58,7 @@ const toastMock = vi.hoisted(() => vi.fn());
const { setFlagStatusMock } = vi.hoisted(() => ({
setFlagStatusMock: vi.fn(() => ({ enabled: true, ready: true })),
}));
+const autoModeFlag = vi.hoisted(() => ({ enabled: false }));
function libraryResponse(
agents: LibraryAgent[],
@@ -114,6 +115,7 @@ beforeEach(() => {
afterEach(() => {
setFlagStatusMock.mockReturnValue({ enabled: true, ready: true });
+ autoModeFlag.enabled = false;
toastMock.mockReset();
});
@@ -136,6 +138,10 @@ vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {
flag === "hire-experts"
? setFlagStatusMock()
: actual.useFlagStatus(flag as never),
+ useGetFlag: (flag: string) =>
+ flag === actual.Flag.COPILOT_AUTO_MODE
+ ? autoModeFlag.enabled
+ : actual.useGetFlag(flag as never),
};
});
@@ -257,6 +263,33 @@ describe("TeamPage", () => {
expect(within(card).queryByText("SEO Audit")).toBeNull();
});
+ test("badges an expert whose new chats start unsupervised", async () => {
+ autoModeFlag.enabled = true;
+ server.use(
+ getListExpertsMockHandler([
+ { ...hiredMaria, autopilot_mode: "unsupervised" },
+ ]),
+ );
+
+ render(<TeamPage />);
+
+ const card = await screen.findByRole("link", { name: "View Maria" });
+ expect(within(card).getByText("Unsupervised")).toBeDefined();
+ });
+
+ test("hides the unsupervised badge while approval modes are off", async () => {
+ server.use(
+ getListExpertsMockHandler([
+ { ...hiredMaria, autopilot_mode: "unsupervised" },
+ ]),
+ );
+
+ render(<TeamPage />);
+
+ const card = await screen.findByRole("link", { name: "View Maria" });
+ expect(within(card).queryByText("Unsupervised")).toBeNull();
+ });
+
test("links the card content to the expert page", async () => {
server.use(getListExpertsMockHandler([hiredMaria]));
diff --git a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx
index cb8bca8e66..8eb918e310 100644
--- a/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/team/components/ExpertTeamCard/ExpertTeamCard.tsx
@@ -5,6 +5,7 @@ import { getCategoryHex } from "@/components/molecules/ExpertAvatar/colors";
import { ExpertIdentityDetails } from "@/components/molecules/ExpertIdentityDetails/ExpertIdentityDetails";
import { CategoryTag } from "@/app/(platform)/marketplace/components/CategoryChip/CategoryTag";
import { ExpertTagline } from "@/components/molecules/ExpertIdentityDetails/components/ExpertTagline";
+import { Badge } from "@/components/atoms/Badge/Badge";
import { Button } from "@/components/atoms/Button/Button";
import { Text } from "@/components/atoms/Text/Text";
import {
@@ -16,6 +17,7 @@ import {
SparklesIcon,
} from "@hugeicons/core-free-icons";
import { creditsToUsdLabel } from "@/lib/credits";
+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";
import Link from "next/link";
import { MouseEvent } from "react";
@@ -64,6 +66,7 @@ export function ExpertTeamCard({
closeFire,
} = useExpertTeamCard(expert);
const isPaused = Boolean(expert.schedules_paused_at);
+ const isAutoModeEnabled = useGetFlag(Flag.COPILOT_AUTO_MODE);
function handleInstallClick() {
onInstallWorkflow(expert.id);
@@ -149,6 +152,11 @@ export function ExpertTeamCard({
/>
<div className="flex items-center gap-2 empty:hidden">
{topic ? <CategoryTag category={topic} /> : null}
+ {isAutoModeEnabled && expert.autopilot_mode === "unsupervised" ? (
+ <Badge variant="warning" size="small">
+ Unsupervised
+ </Badge>
+ ) : null}
<IntegrationIcons
expertName={expert.name}
providers={expert.credential_providers ?? []}
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index d8a116d932..7de0e52239 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -7918,6 +7918,56 @@
}
}
},
+ "/api/experts/{expert_id}/mode": {
+ "patch": {
+ "tags": ["v2", "experts", "experts", "private"],
+ "summary": "Update Expert Mode",
+ "description": "Set the approval mode new web chats with this expert start on.\n\nThreads already open keep the mode stored on them, and the composer's\nselector still overrides it per thread. Routines, scheduled follow-ups\nand chats driven from a linked chat platform are not gated by it.",
+ "operationId": "update_expert_mode",
+ "security": [{ "HTTPBearerJWT": [] }],
+ "parameters": [
+ {
+ "name": "expert_id",
+ "in": "path",
+ "required": true,
+ "schema": { "type": "string", "title": "Expert Id" }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/ExpertModeUpdate" }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/Expert" }
+ }
+ }
+ },
+ "401": {
+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"
+ },
+ "403": {
+ "description": "Approval modes are not enabled for this account"
+ },
+ "404": { "description": "Expert not found" },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/experts/{expert_id}/onboarding": {
"get": {
"tags": ["v2", "experts", "experts", "private"],
@@ -21944,6 +21994,16 @@
"type": "boolean",
"title": "Expert Kickoff",
"default": false
+ },
+ "autopilot_mode": {
+ "anyOf": [
+ {
+ "type": "string",
+ "enum": ["ask_first", "auto", "unsupervised"]
+ },
+ { "type": "null" }
+ ],
+ "title": "Autopilot Mode"
}
},
"additionalProperties": false,
@@ -23696,6 +23756,16 @@
],
"title": "Learning Paused At"
},
+ "autopilot_mode": {
+ "anyOf": [
+ {
+ "type": "string",
+ "enum": ["ask_first", "auto", "unsupervised"]
+ },
+ { "type": "null" }
+ ],
+ "title": "Autopilot Mode"
+ },
"pod_id": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Pod Id"
@@ -23976,7 +24046,17 @@
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Job Title"
},
- "is_archived": { "type": "boolean", "title": "Is Archived" }
+ "is_archived": { "type": "boolean", "title": "Is Archived" },
+ "autopilot_mode": {
+ "anyOf": [
+ {
+ "type": "string",
+ "enum": ["ask_first", "auto", "unsupervised"]
+ },
+ { "type": "null" }
+ ],
+ "title": "Autopilot Mode"
+ }
},
"type": "object",
"required": ["id", "name", "avatar_url", "role", "is_archived"],
@@ -24005,6 +24085,24 @@
"required": ["learning_paused"],
"title": "ExpertLearningPolicyRequest"
},
+ "ExpertModeUpdate": {
+ "properties": {
+ "autopilot_mode": {
+ "anyOf": [
+ {
+ "type": "string",
+ "enum": ["ask_first", "auto", "unsupervised"]
+ },
+ { "type": "null" }
+ ],
+ "title": "Autopilot Mode"
+ }
+ },
+ "type": "object",
+ "required": ["autopilot_mode"],
+ "title": "ExpertModeUpdate",
+ "description": "Set the approval mode new web chats with an expert start on.\n\n``None`` clears it back to the platform default. The field is required,\nso an empty body cannot clear it by accident."
+ },
"ExpertOnboardingResponse": {
"properties": {
"type": {
@@ -24412,6 +24510,16 @@
],
"title": "Learning Paused At"
},
+ "autopilot_mode": {
+ "anyOf": [
+ {
+ "type": "string",
+ "enum": ["ask_first", "auto", "unsupervised"]
+ },
+ { "type": "null" }
+ ],
+ "title": "Autopilot Mode"
+ },
"pod_id": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Pod Id"