Skip to content

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

fix(backend): expert attribution for chat-created schedules and triggers (#14026)

Abhimanyu Yadavdcd6dab6d323
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 1764ae6cbe..6a303270ab 100644
--- a/autogpt_platform/backend/backend/api/features/experts/experts_db.py
+++ b/autogpt_platform/backend/backend/api/features/experts/experts_db.py
@@ -14,6 +14,10 @@ from backend.api.features.experts.models import (
HireResult,
)
from backend.api.features.library import db as library_db
+from backend.data.db import prisma as db_client
+from backend.data.expert_attribution import (
+ resolve_attributable_expert as resolve_attributable_expert_row,
+)
from backend.data.expert_spend import get_weekly_spend
from backend.data.user import get_user_by_id
from backend.util.timezone_utils import get_user_timezone_or_utc
@@ -496,6 +500,21 @@ async def resolve_expert_for_graph(user_id: str, graph_id: str) -> str | None:
return expert_ids.pop()
+async def resolve_attributable_expert(
+ user_id: str, expert_id: str | None
+) -> str | None:
+ """Read-only expert-attribution lookup.
+
+ Durable writes use the same shared guard with a row lock inside their own
+ transaction; this lookup is for discovery and compatibility only.
+ """
+ return await resolve_attributable_expert_row(
+ db_client,
+ user_id,
+ expert_id,
+ )
+
+
async def archive_expert(user_id: str, expert_id: str) -> None:
updated = await prisma.models.Expert.prisma().update_many(
where={"id": expert_id, "ownerUserId": user_id, "isTemplate": False},
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 bdb13b8075..bed8843ec7 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
@@ -11,8 +11,11 @@ import pytest
import backend.api.features.store.model as store_model
from backend.api.features.experts import experts_db, scheduling, seed
from backend.api.features.experts.models import ExpertSoulFieldsPatch, ExpertSoulUpdate
+from backend.api.features.library import db as library_db
+from backend.api.features.library import model as library_model
from backend.api.model import CreateGraph
from backend.blocks.io import AgentInputBlock
+from backend.copilot.model import create_chat_session
from backend.data.graph import Graph, Node
from backend.data.user import get_or_create_user
from backend.usecases.sample import create_test_user
@@ -409,6 +412,57 @@ async def test_hire_schedule_failure_marks_needs_setup(
assert result.failed_preloads == []
[email protected](loop_scope="session")
+async def test_attributed_writes_fall_back_when_archived_after_validation(
+ server: SpinTestServer,
+):
+ """An archive between an earlier lookup and either durable write wins.
+
+ ChatSession and AgentPreset must both persist without the stale expert id;
+ otherwise their work would be permanently rejected by the archived-expert
+ run-budget gate.
+ """
+ slv_id = await _seed_store_listing(server)
+ owner = await _create_seed_user()
+ template = await _seed_template(name="Maria", preload_listings=[slv_id])
+ hired = await experts_db.hire_expert(owner.id, template.id, None)
+ expert_id = hired.expert.id
+ workflow = hired.expert.workflows[0]
+ assert workflow.library_agent_id is not None
+ library_agent = await prisma.models.LibraryAgent.prisma().find_unique(
+ where={"id": workflow.library_agent_id}
+ )
+ assert library_agent is not None
+
+ assert (
+ await experts_db.resolve_attributable_expert(owner.id, expert_id) == expert_id
+ )
+ await prisma.models.Expert.prisma().update(
+ where={"id": expert_id}, data={"isArchived": True}
+ )
+
+ session = await create_chat_session(
+ owner.id,
+ dry_run=False,
+ expert_id=expert_id,
+ )
+ assert session.expert_id is None
+
+ preset = await library_db.create_preset(
+ owner.id,
+ library_model.LibraryAgentPresetCreatable(
+ graph_id=library_agent.agentGraphId,
+ graph_version=library_agent.agentGraphVersion,
+ inputs={},
+ credentials={},
+ name="Atomic attribution fallback",
+ description="",
+ ),
+ expert_id=expert_id,
+ )
+ assert preset.expert_id is None
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_archive_pauses_detaches_and_revive_reattaches(
server: SpinTestServer, test_user
diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.py
index 9f59ca008e..70bd6ae221 100644
--- a/autogpt_platform/backend/backend/api/features/library/db.py
+++ b/autogpt_platform/backend/backend/api/features/library/db.py
@@ -19,6 +19,7 @@ from backend.api.features.library.exceptions import (
)
from backend.data.db import transaction
from backend.data.execution import get_graph_execution
+from backend.data.expert_attribution import resolve_attributable_expert
from backend.data.graph import GraphSettings
from backend.data.includes import (
AGENT_PRESET_INCLUDE,
@@ -1983,9 +1984,9 @@ async def create_preset(
webhook_id: Internal-only; not part of the public request model. Only
trusted callers (the setup-trigger flow, legacy migration) pass a
webhook they provisioned for the caller.
- expert_id: Expert attribution, resolved by the route layer (this
- module cannot import experts_db without a cycle). Runs fired by
- the preset inherit it.
+ expert_id: Requested expert attribution. Active ownership is validated
+ atomically with preset persistence. Runs fired by the preset
+ inherit the validated value.
Returns:
The newly created LibraryAgentPreset.
@@ -2039,12 +2040,34 @@ async def create_preset(
create_input["organizationId"] = graph.organization_id
if graph.team_id:
create_input["teamId"] = graph.team_id
- if expert_id:
- create_input["expertId"] = expert_id
- new_preset = await prisma.models.AgentPreset.prisma().create(
- data=create_input,
- include=AGENT_PRESET_INCLUDE,
- )
+ requested_expert_id = expert_id
+ if requested_expert_id:
+ async with transaction() as tx:
+ expert_id = await resolve_attributable_expert(
+ tx,
+ user_id,
+ requested_expert_id,
+ lock_for_update=True,
+ )
+ if expert_id:
+ create_input["expertId"] = expert_id
+ new_preset = await prisma.models.AgentPreset.prisma(tx).create(
+ data=create_input,
+ include=AGENT_PRESET_INCLUDE,
+ )
+ if expert_id is None:
+ logger.warning(
+ "Ignoring inactive/unowned expert %s while creating preset "
+ "%s for user %s",
+ requested_expert_id,
+ preset.name,
+ user_id,
+ )
+ else:
+ new_preset = await prisma.models.AgentPreset.prisma().create(
+ data=create_input,
+ include=AGENT_PRESET_INCLUDE,
+ )
return library_model.LibraryAgentPreset.from_db(new_preset)
diff --git a/autogpt_platform/backend/backend/api/features/library/triggers.py b/autogpt_platform/backend/backend/api/features/library/triggers.py
index 5c20aeae88..d173e87aad 100644
--- a/autogpt_platform/backend/backend/api/features/library/triggers.py
+++ b/autogpt_platform/backend/backend/api/features/library/triggers.py
@@ -36,6 +36,7 @@ async def setup_triggered_preset(
description: str,
trigger_config: dict[str, Any],
agent_credentials: dict[str, CredentialsMetaInput],
+ expert_id: str | None = None,
) -> models.LibraryAgentPreset:
"""Create a webhook-triggered ``LibraryAgentPreset`` for the given graph.
@@ -61,6 +62,14 @@ async def setup_triggered_preset(
f"Graph #{graph_id} does not have a webhook trigger node"
)
+ # A supplied session expert wins and deliberately suppresses graph-match
+ # re-attribution. create_preset validates it under the same transaction as
+ # the durable write, falling back to an unattributed preset if archival
+ # wins the race. With no supplied expert, preserve the existing unique
+ # graph-match behaviour; create_preset atomically re-validates that result.
+ if expert_id is None:
+ expert_id = await experts_db.resolve_expert_for_graph(user_id, graph.id)
+
trigger_config_with_credentials = {
**trigger_config,
**(
@@ -95,9 +104,7 @@ async def setup_triggered_preset(
is_active=True,
),
webhook_id=new_webhook.id,
- # A trigger on an expert-installed workflow fires as the expert's
- # work: unique (user, graph) → expert matches keep the attribution.
- expert_id=await experts_db.resolve_expert_for_graph(user_id, graph.id),
+ expert_id=expert_id,
)
diff --git a/autogpt_platform/backend/backend/api/features/library/triggers_test.py b/autogpt_platform/backend/backend/api/features/library/triggers_test.py
index c3f21a9964..bad00c1793 100644
--- a/autogpt_platform/backend/backend/api/features/library/triggers_test.py
+++ b/autogpt_platform/backend/backend/api/features/library/triggers_test.py
@@ -27,9 +27,10 @@ def _graph():
return graph
-def _patches(*, graph, webhook=..., feedback=None, preset=None):
+def _patches(*, graph, webhook=..., feedback=None, preset=None, graph_expert=None):
"""Patch triggers.py's collaborators. ``webhook=...`` defaults to a stub
- webhook; pass ``webhook=None`` + ``feedback`` to exercise the rejection."""
+ webhook; pass ``webhook=None`` + ``feedback`` to exercise the rejection.
+ ``graph_expert`` is the expert the graph-match fallback resolves to."""
new_webhook = MagicMock(id="wh-1") if webhook is ... else webhook
return (
patch(f"{_PATH}.get_graph", new=AsyncMock(return_value=graph)),
@@ -41,12 +42,12 @@ def _patches(*, graph, webhook=..., feedback=None, preset=None):
patch(f"{_PATH}.db.create_preset", new=AsyncMock(return_value=preset)),
patch(
f"{_PATH}.experts_db.resolve_expert_for_graph",
- new=AsyncMock(return_value=None),
+ new=AsyncMock(return_value=graph_expert),
),
)
-async def _setup():
+async def _setup(*, expert_id=None):
return await setup_triggered_preset(
user_id=_USER,
graph_id="graph-1",
@@ -55,6 +56,7 @@ async def _setup():
description="",
trigger_config={"repo": "owner/repo"},
agent_credentials={},
+ expert_id=expert_id,
)
@@ -70,6 +72,60 @@ async def test_creates_preset_on_success():
create_mock.assert_awaited_once()
+async def test_setup_prefers_session_expert_over_graph_match():
+ """A trigger created inside an expert chat requests that expert directly;
+ create_preset performs the atomic active-owner validation."""
+ preset = MagicMock(id="preset-1")
+ p_graph, p_creds, p_webhook, p_create, p_expert = _patches(
+ graph=_graph(), preset=preset, graph_expert="expert-graph"
+ )
+ with (
+ p_graph,
+ p_creds,
+ p_webhook,
+ p_expert as expert_mock,
+ p_create as create_mock,
+ ):
+ await _setup(expert_id="expert-session")
+ assert create_mock.call_args.kwargs["expert_id"] == "expert-session"
+ expert_mock.assert_not_awaited() # short-circuited by the session expert
+
+
+async def test_setup_supplied_session_expert_never_graph_reattributes():
+ """A supplied session expert goes straight to the atomic create guard.
+ Even if it has become invalid, this layer must not replace Expert A with a
+ graph match for Expert B; create_preset will persist None instead."""
+ preset = MagicMock(id="preset-1")
+ p_graph, p_creds, p_webhook, p_create, p_expert = _patches(
+ graph=_graph(), preset=preset, graph_expert="expert-graph"
+ )
+ with (
+ p_graph,
+ p_creds,
+ p_webhook,
+ p_expert as expert_mock,
+ p_create as create_mock,
+ ):
+ await _setup(expert_id="expert-archived")
+ assert create_mock.call_args.kwargs["expert_id"] == "expert-archived"
+ expert_mock.assert_not_awaited() # no graph-match re-attribution
+
+
+async def test_setup_falls_back_to_graph_expert_without_session_expert():
+ """A plain chat / route caller passes no expert: attribution falls back to
+ the graph's unique expert match — unchanged behaviour."""
+ preset = MagicMock(id="preset-1")
+ p_graph, p_creds, p_webhook, p_create, p_expert = _patches(
+ graph=_graph(), preset=preset, graph_expert="expert-graph"
+ )
+ with p_graph, p_creds, p_webhook, p_expert, p_create as create_mock:
+ await _setup()
+ assert create_mock.call_args.kwargs["expert_id"] == "expert-graph"
+
+
@pytest.mark.asyncio
async def test_graph_not_found_raises():
p_graph, p_creds, p_webhook, p_create, p_expert = _patches(graph=None)
diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.py
index c936fbc445..6c2d60982f 100644
--- a/autogpt_platform/backend/backend/copilot/db.py
+++ b/autogpt_platform/backend/backend/copilot/db.py
@@ -21,6 +21,7 @@ from prisma.types import (
from pydantic import BaseModel
from backend.data import db
+from backend.data.expert_attribution import resolve_attributable_expert
from backend.util.json import SafeJson, sanitize_string
from .model import (
@@ -276,7 +277,58 @@ async def create_chat_session(
metadata: ChatSessionMetadata | None = None,
expert_id: str | None = None,
) -> ChatSessionInfo:
- """Create a new chat session in the database."""
+ """Create a chat session, atomically validating expert attribution."""
+ requested_expert_id = expert_id
+ if requested_expert_id:
+ async with db.transaction() as tx:
+ expert_id = await resolve_attributable_expert(
+ tx,
+ user_id,
+ requested_expert_id,
+ lock_for_update=True,
+ )
+ prisma_session = await PrismaChatSession.prisma(tx).create(
+ data=_chat_session_create_input(
+ session_id=session_id,
+ user_id=user_id,
+ organization_id=organization_id,
+ team_id=team_id,
+ metadata=metadata,
+ expert_id=expert_id,
+ )
+ )
+ if expert_id is None:
+ logger.warning(
+ "Ignoring inactive/unowned expert %s while creating chat "
+ "session %s for user %s",
+ requested_expert_id,
+ session_id,
+ user_id,
+ )
+ return ChatSessionInfo.from_db(prisma_session)
+
+ prisma_session = await PrismaChatSession.prisma().create(
+ data=_chat_session_create_input(
+ session_id=session_id,
+ user_id=user_id,
+ organization_id=organization_id,
+ team_id=team_id,
+ metadata=metadata,
+ expert_id=None,
+ )
+ )
+ return ChatSessionInfo.from_db(prisma_session)
+
+
+def _chat_session_create_input(
+ *,
+ session_id: str,
+ user_id: str,
+ organization_id: str | None,
+ team_id: str | None,
+ metadata: ChatSessionMetadata | None,
+ expert_id: str | None,
+) -> ChatSessionCreateInput:
data = ChatSessionCreateInput(
id=session_id,
userId=user_id,
@@ -289,8 +341,7 @@ async def create_chat_session(
**({"expertId": expert_id} if expert_id else {}),
metadata=SafeJson((metadata or ChatSessionMetadata()).model_dump()),
)
- prisma_session = await PrismaChatSession.prisma().create(data=data)
- return ChatSessionInfo.from_db(prisma_session)
+ return data
async def update_chat_session(
diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.py
index 90e2dcf078..45be6ef569 100644
--- a/autogpt_platform/backend/backend/copilot/model.py
+++ b/autogpt_platform/backend/backend/copilot/model.py
@@ -1181,8 +1181,9 @@ async def create_chat_session(
The builder panel uses this to bind a chat to the currently-
opened agent and to resume the same session on refresh.
source_platform: External chat platform that originated the session.
- expert_id: Hired expert this session is scoped to. Ownership and
- archived state must be validated by the caller.
+ expert_id: Requested hired-expert scope. The database validates active
+ ownership atomically with session persistence and falls back to a
+ plain session if the expert is no longer attributable.
Raises:
DatabaseError: If the database write fails. We fail fast to ensure
@@ -1203,7 +1204,7 @@ async def create_chat_session(
# Create in database first - fail fast if this fails
try:
- await chat_db().create_chat_session(
+ persisted = await chat_db().create_chat_session(
session_id=session.session_id,
user_id=user_id,
organization_id=organization_id,
@@ -1211,6 +1212,7 @@ async def create_chat_session(
metadata=session.metadata,
expert_id=expert_id,
)
+ session.expert_id = persisted.expert_id
except Exception as e:
logger.error(f"Failed to create session {session.session_id} in database: {e}")
raise DatabaseError(
diff --git a/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py b/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py
index 2a9e7773ed..f093998d34 100644
--- a/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py
+++ b/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py
@@ -248,9 +248,11 @@ class ScheduleFollowupTool(BaseTool):
name=name,
user_timezone=user_timezone,
# Capture the scheduling chat's tenant so a fresh session
- # minted at fire time lands in the same org/team.
+ # minted at fire time lands in the same org/team, and its
+ # expert so those follow-up runs stay attributed to her.
organization_id=session.organization_id if session else None,
team_id=session.team_id if session else None,
+ expert_id=session.expert_id if session else None,
)
except ValueError as e:
return ErrorResponse(
diff --git a/autogpt_platform/backend/backend/copilot/tools/schedule_followup_test.py b/autogpt_platform/backend/backend/copilot/tools/schedule_followup_test.py
index bebc682b01..3aca35975c 100644
--- a/autogpt_platform/backend/backend/copilot/tools/schedule_followup_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/schedule_followup_test.py
@@ -129,6 +129,88 @@ async def test_one_shot_delay_omitted_session_id_passes_new_chat_sentinel(
assert "fresh chat" in result.message # user-facing copy reflects sentinel
+async def test_expert_session_attributes_followup_to_expert(tool):
+ """A follow-up scheduled from an expert chat carries the expert id so the
+ fresh session minted at fire time (and its runs) stays attributed to her."""
+ session = make_session(_USER, expert_id="expert-1")
+ mock_user_db = MagicMock()
+ mock_user_db().get_user_by_id = AsyncMock(return_value=MagicMock(timezone="UTC"))
+ mock_client = AsyncMock()
+ mock_client.add_copilot_turn_schedule = AsyncMock(return_value=_info())
+
+ with (
+ patch(f"{_TOOL_PATH}.user_db", return_value=mock_user_db()),
+ patch(f"{_TOOL_PATH}.get_scheduler_client", return_value=mock_client),
+ patch(
+ f"{_TOOL_PATH}.is_followups_feature_enabled",
+ new=AsyncMock(return_value=True),
+ ),
+ ):
+ result = await tool._execute(
+ user_id=_USER, session=session, message="check CI", delay_seconds=1200
+ )
+
+ assert isinstance(result, ScheduleCreatedResponse)
+ call_kwargs = mock_client.add_copilot_turn_schedule.call_args.kwargs
+ assert call_kwargs["expert_id"] == "expert-1"
+
+
+async def test_expert_session_attributes_recurring_cron_followup(tool):
+ """Recurring cron follow-ups from an expert chat carry the expert id too —
+ every weekly fire mints a session attributed to her, not just one-shots."""
+ session = make_session(_USER, expert_id="expert-1")
+ mock_user_db = MagicMock()
+ mock_user_db().get_user_by_id = AsyncMock(return_value=MagicMock(timezone="UTC"))
+ mock_client = AsyncMock()
+ mock_client.add_copilot_turn_schedule = AsyncMock(
+ return_value=_info(cron="0 9 * * 1")
+ )
+
+ with (
+ patch(f"{_TOOL_PATH}.user_db", return_value=mock_user_db()),
+ patch(f"{_TOOL_PATH}.get_scheduler_client", return_value=mock_client),
+ patch(
+ f"{_TOOL_PATH}.is_followups_feature_enabled",
+ new=AsyncMock(return_value=True),
+ ),
+ ):
+ result = await tool._execute(
+ user_id=_USER, session=session, message="weekly check", cron="0 9 * * 1"
+ )
+
+ assert isinstance(result, ScheduleCreatedResponse)
+ assert result.is_recurring is True
+ call_kwargs = mock_client.add_copilot_turn_schedule.call_args.kwargs
+ assert call_kwargs["cron"] == "0 9 * * 1"
+ assert call_kwargs["expert_id"] == "expert-1"
+
+
+async def test_plain_session_does_not_attribute_followup(tool, session):
+ """A plain (non-expert) chat forwards no expert to the scheduler."""
+ mock_user_db = MagicMock()
+ mock_user_db().get_user_by_id = AsyncMock(return_value=MagicMock(timezone="UTC"))
+ mock_client = AsyncMock()
+ mock_client.add_copilot_turn_schedule = AsyncMock(return_value=_info())
+
+ with (
+ patch(f"{_TOOL_PATH}.user_db", return_value=mock_user_db()),
+ patch(f"{_TOOL_PATH}.get_scheduler_client", return_value=mock_client),
+ patch(
+ f"{_TOOL_PATH}.is_followups_feature_enabled",
+ new=AsyncMock(return_value=True),
+ ),
+ ):
+ await tool._execute(
+ user_id=_USER, session=session, message="check CI", delay_seconds=1200
+ )
+
+ call_kwargs = mock_client.add_copilot_turn_schedule.call_args.kwargs
+ assert call_kwargs["expert_id"] is None
+
+
@pytest.mark.asyncio
async def test_explicit_null_session_id_passes_new_chat_sentinel(tool, session):
"""Explicit ``session_id=None`` is equivalent to omitting it — both are
diff --git a/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py
index bb631987d5..9b6cd33c26 100644
--- a/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py
+++ b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger.py
@@ -219,6 +219,7 @@ class SetupAgentWebhookTriggerTool(BaseTool):
description=(kwargs.get("description") or "").strip(),
trigger_config=kwargs.get("trigger_config") or {},
agent_credentials=agent_credentials,
+ expert_id=session.expert_id,
)
except (
InvalidInputError,
diff --git a/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger_test.py b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger_test.py
index c12adf6725..bf63e5f3f2 100644
--- a/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/setup_agent_webhook_trigger_test.py
@@ -173,6 +173,36 @@ async def test_manual_webhook_no_creds_proceeds(tool, session):
setup_mock.assert_awaited_once()
+async def test_expert_session_attributes_trigger_to_expert(tool):
+ """A trigger set up inside an expert chat threads that expert's id through
+ to preset creation, so its webhook fires count as the expert's work."""
+ session = make_session(_USER, expert_id="expert-1")
+ graph = _make_graph(manual=True, regular_credentials={})
+ preset = _make_preset(provider="generic_webhook", url="https://x/ingress")
+ ctxs, setup_mock = _patches(graph, preset=preset)
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
+ result = await tool._execute(
+ user_id=_USER, session=session, name="My Trigger", graph_id="graph-1"
+ )
+ assert isinstance(result, TriggerSetupResponse)
+ assert setup_mock.call_args.kwargs["expert_id"] == "expert-1"
+
+
+async def test_plain_session_does_not_attribute_trigger(tool, session):
+ """A plain (non-expert) chat forwards no expert; setup_triggered_preset's
+ graph-level fallback still applies but the tool passes None."""
+ graph = _make_graph(manual=True, regular_credentials={})
+ preset = _make_preset(provider="generic_webhook", url="https://x/ingress")
+ ctxs, setup_mock = _patches(graph, preset=preset)
+ with ctxs[0], ctxs[1], ctxs[2], ctxs[3], ctxs[4]:
+ await tool._execute(
+ user_id=_USER, session=session, name="My Trigger", graph_id="graph-1"
+ )
+ assert setup_mock.call_args.kwargs["expert_id"] is None
+
+
@pytest.mark.asyncio
async def test_manual_webhook_missing_body_cred_returns_card(tool, session):
"""Manual webhook whose body needs a (missing) credential -> connect card."""
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index c9245d8cc8..daf47e96e8 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -497,6 +497,7 @@ class DatabaseManager(AppService):
# Exposed so the Prisma-less copilot executor can resolve expert
# identity/team context via db_accessors.experts_db().
get_expert = _(experts_db.get_expert)
+ resolve_attributable_expert = _(experts_db.resolve_attributable_expert)
list_experts = _(experts_db.list_experts)
enforce_expert_run_budget = _(experts_scheduling.enforce_expert_run_budget)
update_soul_fields = _(experts_db.update_soul_fields)
@@ -819,6 +820,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
# ============ Experts ============ #
get_expert = d.get_expert
+ resolve_attributable_expert = d.resolve_attributable_expert
list_experts = d.list_experts
enforce_expert_run_budget = d.enforce_expert_run_budget
update_soul_fields = d.update_soul_fields
diff --git a/autogpt_platform/backend/backend/data/expert_attribution.py b/autogpt_platform/backend/backend/data/expert_attribution.py
new file mode 100644
index 0000000000..b084a6934c
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/expert_attribution.py
@@ -0,0 +1,44 @@
+from typing import LiteralString, cast
+
+from prisma import Prisma
+
+from backend.data.db import get_database_schema
+
+
+async def resolve_attributable_expert(
+ client: Prisma,
+ user_id: str,
+ expert_id: str | None,
+ *,
+ lock_for_update: bool = False,
+) -> str | None:
+ """Resolve an active, hired expert owned by ``user_id``.
+
+ Durable expert-attributed writes call this inside their transaction with
+ ``lock_for_update=True``. The row lock serializes the write against expert
+ archival, closing the validation-to-persistence race.
+ """
+ if not expert_id:
+ return None
+
+ schema = get_database_schema()
+ schema_prefix = f'"{schema}".' if schema != "public" else ""
+ lock_clause = " FOR UPDATE" if lock_for_update else ""
+ query = cast(
+ LiteralString,
+ f"""
+ SELECT "id"
+ FROM {schema_prefix}"Expert"
+ WHERE "id" = $1
+ AND "ownerUserId" = $2
+ AND "isTemplate" = FALSE
+ AND "isArchived" = FALSE
+ {lock_clause}
+ """,
+ )
+ rows = await client.query_raw(
+ query,
+ expert_id,
+ user_id,
+ )
+ return str(rows[0]["id"]) if rows else None
diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.py
index 6a68e42607..5c7340487b 100644
--- a/autogpt_platform/backend/backend/executor/scheduler.py
+++ b/autogpt_platform/backend/backend/executor/scheduler.py
@@ -264,7 +264,14 @@ async def _execute_copilot_turn(**kwargs):
dry_run=False,
organization_id=args.organization_id,
team_id=args.team_id,
+ expert_id=args.expert_id,
)
+ if args.expert_id and new_session.expert_id is None:
+ logger.warning(
+ f"Copilot turn schedule {args.schedule_id}: expert "
+ f"{args.expert_id} is no longer active/owned — "
+ f"created a plain (non-expert) session instead"
+ )
target_session_id = new_session.session_id
target_session = new_session
logger.info(
@@ -371,6 +378,9 @@ async def _reschedule_one_shot_after_cap(args: "CopilotTurnJobArgs") -> None:
# turn to the user's default org after a cap retry.
organization_id=args.organization_id,
team_id=args.team_id,
+ # And for expert attribution — dropping it would fire the retried
+ # turn into a plain session, escaping the expert's thread/budget.
+ expert_id=args.expert_id,
)
logger.info(
f"Rescheduled one-shot copilot turn for session "
@@ -1257,6 +1267,11 @@ class CopilotTurnJobArgs(BaseModel):
# Optional for backward compat with rows persisted before org tagging.
organization_id: str | None = None
team_id: str | None = None
+ # Expert captured at schedule time so a fresh session minted at fire time
+ # is scoped to the same expert as the chat that scheduled the follow-up —
+ # its runs then count toward the expert's budget and surface on her thread.
+ # None for plain (non-expert) chats. Optional for backward compat.
+ expert_id: str | None = None
def _timezone_from_job(job_obj: JobObj) -> str:
@@ -1802,6 +1817,7 @@ class Scheduler(AppService):
cap_retry_count: int = 0,
organization_id: str | None = None,
team_id: str | None = None,
+ expert_id: str | None = None,
) -> CopilotTurnJobInfo:
"""Schedule a copilot turn at a future time.
@@ -1826,6 +1842,7 @@ class Scheduler(AppService):
user_timezone=user_timezone,
organization_id=organization_id,
team_id=team_id,
+ expert_id=expert_id,
)
default_name = (
f"copilot turn (session {session_id[:8]})"
diff --git a/autogpt_platform/backend/backend/executor/scheduler_test.py b/autogpt_platform/backend/backend/executor/scheduler_test.py
index 893a7da896..681b5fdebd 100644
--- a/autogpt_platform/backend/backend/executor/scheduler_test.py
+++ b/autogpt_platform/backend/backend/executor/scheduler_test.py
@@ -71,6 +71,45 @@ def _stub_scheduler() -> Scheduler:
return s
+class TestAddCopilotTurnScheduleExpertAttribution:
+ """A follow-up scheduled from an expert chat must persist that expert id in
+ the job args, so the fresh session minted at fire time is scoped to her and
+ its runs count as the expert's work. Plain chats persist no expert.
+
+ In-process (no SpinTestServer): the RPC return-value round-trip is unrelated
+ to attribution — what matters is the persisted CopilotTurnJobArgs that fire
+ time reads back, which is exactly what ``_persist_schedule`` receives here.
+ """
+
+ @staticmethod
+ def _fake_job() -> MagicMock:
+ job = MagicMock(id="cop-1", next_run_time=None)
+ job.name = "copilot turn"
+ job.trigger = MagicMock(timezone="UTC")
+ return job
+
+ def _persisted_args(self, *, expert_id=None):
+ s = _stub_scheduler()
+ with patch.object(
+ s, "_persist_schedule", return_value=self._fake_job()
+ ) as persist:
+ s.add_copilot_turn_schedule(
+ user_id="user-1",
+ session_id=None,
+ message="check CI",
+ run_at=datetime(2026, 5, 24, 4, 0, tzinfo=timezone.utc),
+ user_timezone="UTC",
+ expert_id=expert_id,
+ )
+ return persist.call_args.kwargs["job_args"]
+
+ def test_expert_session_persists_expert_id(self) -> None:
+ assert self._persisted_args(expert_id="expert-1").expert_id == "expert-1"
+
+ def test_plain_session_persists_no_expert(self) -> None:
+ assert self._persisted_args().expert_id is None
+
+
class TestAddCommunityRebuildSchedule:
def test_registers_with_expected_cron_and_jobstore(self) -> None:
s = _stub_scheduler()
diff --git a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
index b9073ad52f..b1ef6ece06 100644
--- a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
+++ b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
@@ -226,6 +226,7 @@ async def test_execute_copilot_turn_creates_fresh_session_when_session_id_is_non
dry_run=False,
organization_id="org-sched",
team_id="team-sched",
+ expert_id=None,
)
mock_get_session.assert_not_awaited() # we created a new one, no lookup
mock_schedule_turn.assert_awaited_once()
@@ -236,6 +237,74 @@ async def test_execute_copilot_turn_creates_fresh_session_when_session_id_is_non
assert call_kwargs["team_id"] == "team-sched"
+async def test_execute_copilot_turn_forwards_expert_id_to_fresh_session():
+ """A follow-up scheduled from an expert chat mints its fresh session scoped
+ to that expert, so runs inside the scheduled turn stay attributed to her.
+ Session persistence performs the active-owner check atomically."""
+ args = _args(session_id=None, expert_id="expert-1")
+ new_session = MagicMock(session_id="new-session-uuid", expert_id="expert-1")
+ mock_create_session = AsyncMock(return_value=new_session)
+
+ with (
+ patch("backend.executor.scheduler.schedule_turn", new=AsyncMock()),
+ patch("backend.executor.scheduler.get_chat_session", new=AsyncMock()),
+ patch(
+ "backend.executor.scheduler.create_chat_session", new=mock_create_session
+ ),
+ ):
+ await _execute_copilot_turn(**args.model_dump(mode="json"))
+
+ assert mock_create_session.call_args.kwargs["expert_id"] == "expert-1"
+
+
+async def test_execute_copilot_turn_degrades_to_plain_session_when_expert_archived():
+ """If the expert was archived (or un-owned) between scheduling and fire
+ time, the atomic session write returns a plain session and the scheduled
+ turn still dispatches there."""
+ args = _args(session_id=None, expert_id="expert-1")
+ new_session = MagicMock(session_id="new-session-uuid", expert_id=None)
+ mock_create_session = AsyncMock(return_value=new_session)
+ mock_schedule_turn = AsyncMock()
+
+ with (
+ patch("backend.executor.scheduler.schedule_turn", new=mock_schedule_turn),
+ patch("backend.executor.scheduler.get_chat_session", new=AsyncMock()),
+ patch(
+ "backend.executor.scheduler.create_chat_session", new=mock_create_session
+ ),
+ ):
+ await _execute_copilot_turn(**args.model_dump(mode="json"))
+
+ assert mock_create_session.call_args.kwargs["expert_id"] == "expert-1"
+ mock_schedule_turn.assert_awaited_once() # turn still fires, just plain
+
+
+async def test_execute_copilot_turn_existing_session_skips_expert_revalidation():
+ """A follow-up into an EXISTING session doesn't mint a session, so no
+ expert re-validation happens — the session keeps whatever expert scope it
+ already has, and the fire path must not add a per-fire expert lookup."""
+ args = _args(expert_id="expert-1") # session_id="session-1" from _args base
+ mock_create_session = AsyncMock()
+
+ with (
+ patch("backend.executor.scheduler.schedule_turn", new=AsyncMock()),
+ patch(
+ "backend.executor.scheduler.get_chat_session",
+ new=AsyncMock(return_value=MagicMock()),
+ ),
+ patch(
+ "backend.executor.scheduler.create_chat_session",
+ new=mock_create_session,
+ ),
+ ):
+ await _execute_copilot_turn(**args.model_dump(mode="json"))
+
+ mock_create_session.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_execute_copilot_turn_dispatches_when_session_exists():
args = _args()
@@ -435,6 +504,19 @@ async def test_reschedule_after_cap_preserves_user_timezone():
assert kwargs["user_timezone"] == "America/New_York"
+async def test_reschedule_after_cap_preserves_expert_id():
+ """The reschedule path must forward the original expert_id, otherwise a
+ capped expert follow-up retries into a plain session and its work escapes
+ the expert's thread and budget."""
+ args = _args(cap_retry_count=0, expert_id="expert-1")
+ mock_client = AsyncMock()
+ with patch(f"{_SCHEDULER_PATH}.get_scheduler_client", return_value=mock_client):
+ await _reschedule_one_shot_after_cap(args)
+ kwargs = mock_client.add_copilot_turn_schedule.call_args.kwargs
+ assert kwargs["expert_id"] == "expert-1"
+
+
@pytest.mark.asyncio
async def test_reschedule_after_cap_drops_when_max_retries_reached():
args = _args(cap_retry_count=_MAX_CAP_RETRIES)
@@ -517,6 +599,18 @@ async def test_execute_graph_forwards_expert_id():
assert mock_add.call_args.kwargs["expert_id"] == "expert-1"
+def test_copilot_turn_args_expert_id_defaults_to_none():
+ """Legacy persisted copilot-turn kwargs predate expert attribution; they
+ must deserialize with ``expert_id=None``."""
+ args = CopilotTurnJobArgs(
+ user_id="u",
+ session_id="s",
+ message="m",
+ run_at=datetime.now(tz=timezone.utc),
+ )
+ assert args.expert_id is None
+
+
def test_copilot_turn_args_cap_retry_count_defaults_to_zero():
args = CopilotTurnJobArgs(
user_id="u",
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 2abdaa1b21..9ab505f55d 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -16149,6 +16149,10 @@
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Team Id"
},
+ "expert_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Expert Id"
+ },
"id": { "type": "string", "title": "Id" },
"name": { "type": "string", "title": "Name" },
"next_run_time": { "type": "string", "title": "Next Run Time" },