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.

[SECRT-2804] fix(backend/copilot): scheduled runs use the account picked when the schedule was made, never a chooser nobody answers (#15132)

Bentlye052d4e87eb7
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 1250a3b42d..da7be33b84 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
@@ -48,6 +48,7 @@ from backend.api.features.store.skill_catalog_checkout import catalog_checkout
from backend.api.features.store.skill_catalog_release import CatalogError, load_catalog
from backend.api.model import CreateGraph
from backend.blocks.io import AgentInputBlock
+from backend.copilot.credential_selection import CredentialPin
from backend.copilot.model import create_chat_session
from backend.copilot.tools.skills import _NAME_RE, read_user_skill_with_body
from backend.copilot.tools.skills_test import _FakeWorkspaceManager, _patch_skills_path
@@ -6809,6 +6810,46 @@ async def test_an_expert_can_record_a_routine_it_agreed_in_conversation(
] == [created.id]
[email protected](loop_scope="session")
+async def test_a_routine_keeps_the_account_it_was_set_up_on(
+ server: SpinTestServer, test_user
+):
+ """The account picked in the chat lives on the row, so switching the
+ routine off and on again, or rewording it, keeps running on it
+ (SECRT-2804). Re-enabling without naming pins leaves them alone."""
+ template = await _seed_template(name="Briefer", preload_listings=[])
+ hired = await experts_db.hire_expert(test_user.id, template.id, None)
+ work = CredentialPin(id="exa-new", title="Work")
+
+ created = await experts_db.create_routine(
+ test_user.id,
+ hired.expert.id,
+ title="Morning briefing",
+ prompt="Search Exa for AI news.",
+ crons=["H 8 * * *"],
+ credential_pins={"exa": work},
+ )
+ assert created.credential_pins == {"exa": work}
+
+ with patch.object(
+ routine_jobs, "get_scheduler_client", return_value=_fake_scheduler()
+ ):
+ reworded = await experts_db.enable_routine(
+ test_user.id, hired.expert.id, created.id, prompt="Search Exa daily."
+ )
+ assert reworded.credential_pins == {"exa": work}
+ moved = await experts_db.enable_routine(
+ test_user.id,
+ hired.expert.id,
+ created.id,
+ credential_pins={"exa": CredentialPin(id="exa-old", title="Personal")},
+ )
+ assert moved.credential_pins["exa"].id == "exa-old"
+ assert (await experts_db.get_routine(created.id)).credential_pins[
+ "exa"
+ ].id == "exa-old"
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_a_routine_belongs_to_its_owner_only(
server: SpinTestServer, test_user, other_user
diff --git a/autogpt_platform/backend/backend/api/features/experts/models.py b/autogpt_platform/backend/backend/api/features/experts/models.py
index 6390081653..74893781c0 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.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
@@ -257,6 +258,9 @@ class ExpertRoutine(BaseModel):
# Whether this routine's turns may reach the owner's connected services.
# Always False on anything a template shipped.
grants_credentials: bool = False
+ # ``{provider: pin}``: the account each of its turns runs on where the
+ # owner has several, chosen in the chat that set it up (SECRT-2804).
+ credential_pins: CredentialPins = {}
@property
def recurring(self) -> bool:
diff --git a/autogpt_platform/backend/backend/api/features/experts/routines.py b/autogpt_platform/backend/backend/api/features/experts/routines.py
index bf5d73463f..83103a7b9a 100644
--- a/autogpt_platform/backend/backend/api/features/experts/routines.py
+++ b/autogpt_platform/backend/backend/api/features/experts/routines.py
@@ -32,10 +32,12 @@ firing turn makes back to the row — lives in ``routine_jobs``.
import logging
from datetime import datetime, timezone
+import prisma
import prisma.enums
import prisma.models
import prisma.types
from apscheduler.triggers.cron import CronTrigger
+from pydantic import ValidationError
from backend.api.features.experts.models import ExpertRoutine
from backend.api.features.experts.routine_jobs import (
@@ -43,6 +45,7 @@ from backend.api.features.experts.routine_jobs import (
delete_routine_schedules,
spread_cron,
)
+from backend.copilot.credential_selection import CredentialPin, CredentialPins
from backend.data.user import get_user_by_id
from backend.util.clients import get_scheduler_client
from backend.util.timezone_utils import get_user_timezone_or_utc
@@ -72,9 +75,38 @@ def to_model(row: prisma.models.ExpertRoutine) -> ExpertRoutine:
enabled=row.enabledAt is not None and row.firedAt is None,
customized=row.customizedAt is not None,
grants_credentials=row.grantsCredentials,
+ credential_pins=_credential_pins(row.credentialPins),
)
+UNREADABLE_PIN = CredentialPin(
+ id="unreadable-pin", title="a saved account choice that could not be read"
+)
+"""Stands in for a stored pin that no longer parses. No account has its id, so
+the provider's steps fail naming the lost pin instead of running unpinned on
+whichever account comes first, the silent switch a pin exists to prevent."""
+
+
+def _credential_pins(raw: object) -> CredentialPins:
+ """Read the stored pins. An entry that no longer parses still pins its
+ provider, to ``UNREADABLE_PIN``: the routine loads and its other steps
+ run, while that provider's steps stop until the owner picks an account
+ again."""
+ if raw is None:
+ return {}
+ if not isinstance(raw, dict):
+ logger.error("Ignoring unreadable credential pins %r", type(raw).__name__)
+ return {}
+ pins: CredentialPins = {}
+ for provider, value in raw.items():
+ try:
+ pins[str(provider)] = CredentialPin.model_validate(value)
+ except ValidationError:
+ logger.warning("Unreadable credential pin for %s; its steps stop", provider)
+ pins[str(provider)] = UNREADABLE_PIN
+ return pins
+
+
async def get_routine(routine_id: str) -> ExpertRoutine | None:
"""Load one routine by id, for the fire path.
@@ -162,6 +194,7 @@ async def enable_routine(
session_mode: str | None = None,
pinned_session_id: str | None = None,
grants_credentials: bool | None = None,
+ credential_pins: CredentialPins | None = None,
) -> ExpertRoutine:
"""Switch a routine on, resolving the proposal into what actually runs.
@@ -268,6 +301,10 @@ async def enable_routine(
# direction, so a rewording never quietly widens what a routine can touch.
if grants_credentials is not None:
data["grantsCredentials"] = grants_credentials
+ # Same rule for the accounts it runs on: ``None`` keeps the ones chosen
+ # when it was set up.
+ if credential_pins is not None:
+ data["credentialPins"] = _pins_json(credential_pins)
if customized:
data["customizedAt"] = now
try:
@@ -291,6 +328,10 @@ async def enable_routine(
return to_model(updated)
+def _pins_json(pins: CredentialPins) -> prisma.Json:
+ return prisma.Json({provider: pin.model_dump() for provider, pin in pins.items()})
+
+
def _session_mode(value: str) -> prisma.enums.ExpertRoutineSession:
"""Parse a mode name, defaulting to THREAD rather than raising.
@@ -316,6 +357,7 @@ async def create_routine(
session_mode: str | None = None,
session_id: str | None = None,
grants_credentials: bool = True,
+ credential_pins: CredentialPins | None = None,
) -> ExpertRoutine:
"""Record standing work worked out with the owner in conversation.
@@ -356,6 +398,8 @@ async def create_routine(
"grantsCredentials": grants_credentials,
"customizedAt": datetime.now(timezone.utc),
}
+ if credential_pins:
+ data["credentialPins"] = _pins_json(credential_pins)
if expert_id is None:
data["userId"] = user_id
else:
diff --git a/autogpt_platform/backend/backend/api/features/experts/routines_test.py b/autogpt_platform/backend/backend/api/features/experts/routines_test.py
index ad518df201..28642f7b22 100644
--- a/autogpt_platform/backend/backend/api/features/experts/routines_test.py
+++ b/autogpt_platform/backend/backend/api/features/experts/routines_test.py
@@ -10,7 +10,12 @@ account.
from apscheduler.triggers.cron import CronTrigger
from backend.api.features.experts.routine_jobs import spread_cron
-from backend.api.features.experts.routines import _session_mode
+from backend.api.features.experts.routines import (
+ UNREADABLE_PIN,
+ _credential_pins,
+ _session_mode,
+)
+from backend.copilot.credential_selection import CredentialPin
from backend.copilot.permissions import (
CAPABILITY_GATE_NAMES,
ROUTINE_SELF_ESCALATION_TOOLS,
@@ -254,3 +259,55 @@ def test_an_unknown_session_mode_falls_back_to_thread():
thread — the mode that keeps its memory — not fail a call the owner already
agreed to."""
assert _session_mode("here").value == "THREAD"
+
+
+def test_a_routines_stored_pins_load_and_an_unreadable_one_still_pins():
+ pins = _credential_pins(
+ {"exa": {"id": "exa-new", "title": "Work"}, "github": "not a pin"}
+ )
+ assert pins == {
+ "exa": CredentialPin(id="exa-new", title="Work"),
+ "github": UNREADABLE_PIN,
+ }
+ assert _credential_pins(None) == {}
+
+
+async def test_an_unreadable_pin_stops_the_step_instead_of_switching_accounts():
+ # Dropping the pin would run the step on whichever GitHub account came
+ # first, the silent switch a pin exists to prevent.
+ import asyncio
+ from unittest.mock import AsyncMock, patch
+
+ from pydantic import SecretStr
+
+ from backend.copilot.credential_selection import set_turn_credential_pins
+ from backend.copilot.tools.helpers import unattended_missing_credentials_error
+ from backend.copilot.tools.utils import keep_to_pins
+ from backend.data.model import APIKeyCredentials
+
+ saved = [
+ APIKeyCredentials(
+ id=name, provider="github", title=name, api_key=SecretStr("k")
+ )
+ for name in ("personal", "work")
+ ]
+
+ async def turn():
+ set_turn_credential_pins(_credential_pins({"github": {"title": "no id"}}))
+ with patch(
+ "backend.copilot.tools.helpers.get_user_credentials",
+ AsyncMock(return_value=saved),
+ ):
+ error = await unattended_missing_credentials_error(
+ "Block 'Create PR'",
+ {"credentials": {"provider": "github", "types": ["api_key"]}},
+ "s1",
+ "test-user",
+ None,
+ )
+ return keep_to_pins(saved), error
+
+ usable, error = await asyncio.create_task(turn())
+ assert usable == []
+ assert error.error == "pinned_credential_missing"
+ assert UNREADABLE_PIN.title in error.message
diff --git a/autogpt_platform/backend/backend/copilot/context.py b/autogpt_platform/backend/backend/copilot/context.py
index a20ab19d75..caf8a4dfb4 100644
--- a/autogpt_platform/backend/backend/copilot/context.py
+++ b/autogpt_platform/backend/backend/copilot/context.py
@@ -135,6 +135,10 @@ _current_envelope: "ContextVar[TurnEnvelope | None]" = ContextVar(
_current_hidden_tools: ContextVar[frozenset[str]] = ContextVar(
"_current_hidden_tools", default=frozenset()
)
+# Whether anyone is watching the running turn; see ``set_turn_unattended``.
+_current_turn_unattended: ContextVar[bool] = ContextVar(
+ "_current_turn_unattended", default=False
+)
def encode_cwd_for_cli(cwd: str) -> str:
@@ -192,6 +196,23 @@ def get_current_hidden_tools() -> frozenset[str]:
return _current_hidden_tools.get()
+def set_turn_unattended(session: ChatSession, *, scheduled: bool) -> None:
+ """Record whether anyone is watching the running turn. The executor sets
+ it for every turn, so a value never carries over to the next one.
+
+ Nobody is when the scheduler fired the turn, even into the user's own
+ chat, or when an automation opened the chat: a scheduled run's own chat, a
+ sub-session, a graph's AutoPilot block. A legacy chat without an origin
+ counts as watched, the way ``pauses_irreversible_actions`` reads it.
+ """
+ _current_turn_unattended.set(scheduled or session.metadata.origin == "automation")
+
+
+def is_unattended_turn() -> bool:
+ """Whether nobody can answer a question this turn puts to the user."""
+ return _current_turn_unattended.get()
+
+
def get_current_sandbox() -> "AsyncSandbox | None":
"""Return the E2B sandbox for the current session, or None if not active."""
return _current_sandbox.get()
diff --git a/autogpt_platform/backend/backend/copilot/context_test.py b/autogpt_platform/backend/backend/copilot/context_test.py
index c04dcdcd6f..9011156640 100644
--- a/autogpt_platform/backend/backend/copilot/context_test.py
+++ b/autogpt_platform/backend/backend/copilot/context_test.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import contextvars
import os
import tempfile
from unittest.mock import MagicMock
@@ -16,9 +17,12 @@ from backend.copilot.context import (
get_execution_context,
get_sdk_cwd,
is_allowed_local_path,
+ is_unattended_turn,
resolve_sandbox_path,
set_execution_context,
+ set_turn_unattended,
)
+from backend.copilot.model import ChatSessionMetadata
from backend.copilot.permissions import CopilotPermissions
@@ -356,3 +360,32 @@ class TestEnvelopeDoesNotEscapeItsTurn:
# An assertion failure here must not cascade into the sibling
# test: this generator leaks the contextvar deliberately.
set_execution_context(None, None, envelope=None)
+
+
+# ---------------------------------------------------------------------------
+# Whether anyone is watching the turn (SECRT-2804)
+# ---------------------------------------------------------------------------
+
+
+ "origin, scheduled, unattended",
+ [
+ ("automation", False, True),
+ ("interactive", True, True),
+ ("interactive", False, False),
+ (None, False, False),
+ ],
+ ids=["automation chat", "scheduled into a user chat", "user chat", "legacy chat"],
+)
+def test_set_turn_unattended(origin, scheduled, unattended):
+ session = MagicMock(metadata=ChatSessionMetadata(origin=origin))
+
+ def turn() -> bool:
+ set_turn_unattended(session, scheduled=scheduled)
+ return is_unattended_turn()
+
+ assert contextvars.copy_context().run(turn) is unattended
+
+
+def test_a_turn_is_watched_until_the_executor_says_otherwise():
+ assert contextvars.copy_context().run(is_unattended_turn) is False
diff --git a/autogpt_platform/backend/backend/copilot/credential_selection.py b/autogpt_platform/backend/backend/copilot/credential_selection.py
index ed2fe2dd11..3b728aefe3 100644
--- a/autogpt_platform/backend/backend/copilot/credential_selection.py
+++ b/autogpt_platform/backend/backend/copilot/credential_selection.py
@@ -13,9 +13,18 @@ none was picked it asks instead of choosing (see
Kept in Redis rather than on the session row because it is advisory state with
a safe failure: losing it means the user is asked again, never that a run uses
an account they did not choose.
+
+A schedule made from a chat keeps the picks too, as *pins* stored on the
+schedule (SECRT-2804). Its turns run later with nobody to ask, often in a chat
+that never saw the pick, so the executor hands the schedule's pins to each
+turn it fires and they win over anything picked in the chat.
"""
import logging
+from collections.abc import Mapping
+from contextvars import ContextVar
+
+from pydantic import BaseModel
from backend.data.redis_client import get_redis_async
@@ -24,6 +33,37 @@ logger = logging.getLogger(__name__)
SELECTION_TTL = 30 * 86400 # 30 days, far longer than a chat stays active
+class CredentialPin(BaseModel):
+ """The account a schedule runs one provider on, chosen when it was made.
+
+ The title is kept so a run can still name the account after it was
+ deleted, which is when the name matters most.
+ """
+
+ id: str
+ title: str = ""
+
+
+CredentialPins = dict[str, CredentialPin]
+"""``{provider: pin}`` stored on a schedule."""
+
+_current_turn_pins: ContextVar[Mapping[str, CredentialPin]] = ContextVar(
+ "_current_turn_pins", default={}
+)
+
+
+def set_turn_credential_pins(pins: Mapping[str, CredentialPin] | None) -> None:
+ """Record the pins of the schedule that fired the running turn. The
+ executor sets it for every turn, so pins never carry over to the next."""
+ _current_turn_pins.set(dict(pins or {}))
+
+
+def turn_credential_pins() -> Mapping[str, CredentialPin]:
+ """``{provider: pin}`` for the running turn; empty unless a schedule with
+ pins fired it."""
+ return _current_turn_pins.get()
+
+
def _key(session_id: str) -> str:
return f"copilot:credential-selection:{session_id}"
@@ -47,20 +87,26 @@ async def remember_selection(session_id: str, selections: dict[str, str]) -> Non
async def selected_credentials(session_id: str | None) -> dict[str, str]:
"""``{provider: credential_id}`` picked in this session; empty when none.
+ The pins of the schedule that fired the running turn are laid over the
+ chat's picks: the schedule was set up to run on those accounts, whatever
+ the chat it lands in picked since.
+
Never raises. An unreadable selection degrades to "nothing picked", which
makes the tools ask rather than guess.
"""
+ pinned = {provider: pin.id for provider, pin in turn_credential_pins().items()}
if not session_id:
- return {}
+ return pinned
try:
redis = await get_redis_async()
raw = await redis.hgetall(_key(session_id))
except Exception:
logger.warning("Could not read credential selection for session %s", session_id)
- return {}
- return {
+ return pinned
+ picked = {
(k.decode() if isinstance(k, bytes) else k): (
v.decode() if isinstance(v, bytes) else v
)
for k, v in raw.items()
}
+ return {**picked, **pinned}
diff --git a/autogpt_platform/backend/backend/copilot/executor/processor.py b/autogpt_platform/backend/backend/copilot/executor/processor.py
index e5d4841def..20a61ba895 100644
--- a/autogpt_platform/backend/backend/copilot/executor/processor.py
+++ b/autogpt_platform/backend/backend/copilot/executor/processor.py
@@ -17,6 +17,8 @@ from typing import TYPE_CHECKING, Callable, cast
from backend.copilot import stream_registry
from backend.copilot.baseline import stream_chat_completion_baseline
from backend.copilot.config import ChatConfig
+from backend.copilot.context import set_turn_unattended
+from backend.copilot.credential_selection import set_turn_credential_pins
from backend.copilot.engine import resolve_use_sdk
from backend.copilot.expert_context import (
EXPERT_SESSION_MISSING_MESSAGE,
@@ -722,6 +724,8 @@ class CoPilotProcessor:
# (e.g. wait_for_session_result, SSE clients) receive the
# same events as they are produced.
envelope = taint_for_source_platform(entry.envelope, session)
+ set_turn_unattended(session, scheduled=entry.unattended)
+ set_turn_credential_pins(entry.credential_pins)
raw_stream = stream_fn(
session_id=entry.session_id,
message=entry.message or None,
diff --git a/autogpt_platform/backend/backend/copilot/executor/processor_test.py b/autogpt_platform/backend/backend/copilot/executor/processor_test.py
index b4f63f7270..84190dd45b 100644
--- a/autogpt_platform/backend/backend/copilot/executor/processor_test.py
+++ b/autogpt_platform/backend/backend/copilot/executor/processor_test.py
@@ -196,6 +196,72 @@ def _make_log() -> CoPilotLogMetadata:
return CoPilotLogMetadata(logger=logging.getLogger("test-copilot"))
+class TestExecuteAsyncScheduledTurnContext:
+ """The executor hands a scheduled turn's ``unattended`` flag and
+ credential pins to the tools through per-turn contextvars (SECRT-2804).
+ Every tool test sets those directly, so this seam is checked here."""
+
+ @staticmethod
+ async def _seen_by_the_turn(entry: CoPilotExecutionEntry) -> dict:
+ from backend.copilot.context import is_unattended_turn
+ from backend.copilot.credential_selection import turn_credential_pins
+
+ seen: dict = {}
+
+ def stream(**_kwargs):
+ seen["unattended"] = is_unattended_turn()
+ seen["pins"] = dict(turn_credential_pins())
+ return MagicMock()
+
+ with (
+ patch(
+ "backend.copilot.executor.processor.ChatConfig",
+ return_value=MagicMock(test_mode=True),
+ ),
+ patch(
+ "backend.copilot.executor.processor.stream_chat_completion_dummy",
+ side_effect=stream,
+ ),
+ patch(
+ "backend.copilot.executor.processor.stream_registry.stream_and_publish",
+ return_value=_TrackedStream(events=[]),
+ ),
+ patch(
+ "backend.copilot.executor.processor.stream_registry.mark_session_completed",
+ new=AsyncMock(),
+ ),
+ patch(
+ "backend.copilot.model.get_chat_session",
+ new=AsyncMock(return_value=ChatSession.new("user-1", dry_run=False)),
+ ),
+ ):
+ await asyncio.create_task(
+ CoPilotProcessor()._execute_async(
+ entry, threading.Event(), MagicMock(), _make_log()
+ )
+ )
+ return seen
+
+ @pytest.mark.asyncio
+ async def test_a_scheduled_turn_runs_unattended_on_its_pins(self) -> None:
+ from backend.copilot.credential_selection import CredentialPin
+
+ pin = CredentialPin(id="exa-new", title="Work key")
+ entry = _make_entry().model_copy(
+ update={"unattended": True, "credential_pins": {"exa": pin}}
+ )
+
+ seen = await self._seen_by_the_turn(entry)
+
+ assert seen == {"unattended": True, "pins": {"exa": pin}}
+
+ @pytest.mark.asyncio
+ async def test_a_typed_turn_is_watched_and_has_no_pins(self) -> None:
+ seen = await self._seen_by_the_turn(_make_entry())
+
+ assert seen == {"unattended": False, "pins": {}}
+
+
class TestExecuteAsyncAclose:
"""``_execute_async`` must call ``aclose`` on the published stream both
when the loop exits naturally and when ``cancel`` is set mid-stream —
diff --git a/autogpt_platform/backend/backend/copilot/executor/utils.py b/autogpt_platform/backend/backend/copilot/executor/utils.py
index 475f95b964..a194d878b5 100644
--- a/autogpt_platform/backend/backend/copilot/executor/utils.py
+++ b/autogpt_platform/backend/backend/copilot/executor/utils.py
@@ -10,7 +10,7 @@ import logging
from typing import TYPE_CHECKING, Any
from uuid import uuid4
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from backend.copilot.active_turns import (
ConcurrentTurnLimitError,
@@ -21,6 +21,7 @@ from backend.copilot.active_turns import (
)
from backend.copilot.config import CopilotLlmAuthProvider, CopilotLLMModel
from backend.copilot.context import get_current_envelope
+from backend.copilot.credential_selection import CredentialPins
from backend.copilot.permissions import CopilotPermissions
from backend.copilot.tree import (
SpawnRequest,
@@ -324,6 +325,17 @@ class CoPilotExecutionEntry(BaseModel):
at dispatch from the spawning turn's. ``None`` only for entries queued
before the field existed."""
+ unattended: bool = False
+ """The scheduler fired this turn, so nobody is watching it even if its chat
+ is the user's own. Tools then never hand a question back to the user
+ (SECRT-2804); see ``set_turn_unattended``."""
+
+ credential_pins: CredentialPins = Field(default_factory=dict)
+ """``{provider: pin}``: the accounts the schedule that fired this turn was
+ set up to run on. They win over the chat's own picks, and a pinned account
+ that is gone fails the step rather than falling back to another one; see
+ ``set_turn_credential_pins``. Empty for every other turn."""
+
request_arrival_at: float = 0.0
"""Unix-epoch seconds (server clock) when the originating HTTP
``/stream`` request arrived. The executor's turn-start drain uses
@@ -366,6 +378,8 @@ async def enqueue_copilot_turn(
message_metadata: dict[str, Any] | None = None,
*,
envelope: TurnEnvelope,
+ unattended: bool = False,
+ credential_pins: CredentialPins | None = None,
scheduled: ScheduledTurnOrigin | None = None,
) -> None:
"""Enqueue a CoPilot task for processing by the executor service.
@@ -410,6 +424,8 @@ async def enqueue_copilot_turn(
request_arrival_at=request_arrival_at,
message_metadata=message_metadata,
envelope=envelope,
+ unattended=unattended,
+ credential_pins=credential_pins or {},
scheduled=scheduled,
)
@@ -441,6 +457,8 @@ async def schedule_turn(
request_arrival_at: float = 0.0,
spawn: SpawnRequest | None = None,
message_metadata: dict[str, Any] | None = None,
+ unattended: bool = False,
+ credential_pins: CredentialPins | None = None,
scheduled: ScheduledTurnOrigin | None = None,
) -> None:
"""End-to-end "start a copilot turn": reserve a per-user concurrency
@@ -509,6 +527,8 @@ async def schedule_turn(
request_arrival_at=request_arrival_at,
spawn=spawn,
message_metadata=message_metadata,
+ unattended=unattended,
+ credential_pins=credential_pins,
scheduled=scheduled,
)
@@ -534,6 +554,8 @@ async def dispatch_turn(
request_arrival_at: float = 0.0,
spawn: SpawnRequest | None = None,
message_metadata: dict[str, Any] | None = None,
+ unattended: bool = False,
+ credential_pins: CredentialPins | None = None,
scheduled: ScheduledTurnOrigin | None = None,
) -> None:
"""Within an already-held turn slot, register the session in the
@@ -606,6 +628,8 @@ async def dispatch_turn(
request_arrival_at=request_arrival_at,
message_metadata=message_metadata,
envelope=envelope,
+ unattended=unattended,
+ credential_pins=credential_pins,
scheduled=scheduled,
)
slot.keep()
diff --git a/autogpt_platform/backend/backend/copilot/executor/utils_test.py b/autogpt_platform/backend/backend/copilot/executor/utils_test.py
index dab5ce82e2..c8a8be32f3 100644
--- a/autogpt_platform/backend/backend/copilot/executor/utils_test.py
+++ b/autogpt_platform/backend/backend/copilot/executor/utils_test.py
@@ -5,6 +5,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from backend.copilot.credential_selection import CredentialPin
from backend.copilot.executor import utils
from backend.copilot.executor.utils import (
COPILOT_CANCEL_EXCHANGE,
@@ -113,6 +114,30 @@ class TestCoPilotExecutionEntry:
restored = CoPilotExecutionEntry.model_validate_json(json_str)
assert restored == entry
+ def test_unattended_survives_the_queue_and_defaults_to_watched(self):
+ entry = CoPilotExecutionEntry(
+ session_id="s1", user_id="u1", message="hi", unattended=True
+ )
+ restored = CoPilotExecutionEntry.model_validate_json(entry.model_dump_json())
+ assert restored.unattended is True
+ # A message queued by a worker without the field is a watched turn.
+ legacy = CoPilotExecutionEntry.model_validate_json(
+ '{"session_id": "s1", "user_id": "u1", "message": "hi"}'
+ )
+ assert legacy.unattended is False
+
+ def test_credential_pins_survive_the_queue_and_default_to_none(self):
+ pin = CredentialPin(id="exa-new", title="Work key")
+ entry = CoPilotExecutionEntry(
+ session_id="s1", user_id="u1", message="hi", credential_pins={"exa": pin}
+ )
+ restored = CoPilotExecutionEntry.model_validate_json(entry.model_dump_json())
+ assert restored.credential_pins == {"exa": pin}
+ legacy = CoPilotExecutionEntry.model_validate_json(
+ '{"session_id": "s1", "user_id": "u1", "message": "hi"}'
+ )
+ assert legacy.credential_pins == {}
+
class TestCancelCoPilotEvent:
def test_basic(self):
diff --git a/autogpt_platform/backend/backend/copilot/tools/expert_scope.py b/autogpt_platform/backend/backend/copilot/tools/expert_scope.py
index d97f0e3444..b12a7e6374 100644
--- a/autogpt_platform/backend/backend/copilot/tools/expert_scope.py
+++ b/autogpt_platform/backend/backend/copilot/tools/expert_scope.py
@@ -8,6 +8,7 @@ expert's resources.
"""
import logging
+from collections.abc import Iterable
from enum import Enum
from typing import Any, cast
@@ -313,17 +314,29 @@ def _satisfies_requirement(credential: Credentials, entry: dict[str, Any]) -> bo
async def ungranted_credential_hint(
- user_id: str, expert_id: str | None, providers: set[str]
+ user_id: str,
+ expert_id: str | None,
+ providers: set[str],
+ requirements: Iterable[dict[str, Any]] | None = None,
) -> str:
"""Point at credentials the account already has but the expert lacks.
Appended to a missing-credentials message in expert chats so the user is
asked to grant an existing integration instead of connecting a duplicate
- the expert still could not use.
+ the expert still could not use. With *requirements* (the missing entries),
+ only a credential one of them would accept is named: granting one of the
+ wrong type or without the scopes would not let the next run through.
"""
if expert_id is None or not providers:
return ""
candidates = await _ungranted_credentials(user_id, expert_id, providers)
+ if requirements is not None:
+ entries = list(requirements)
+ candidates = [
+ c
+ for c in candidates
+ if any(_satisfies_requirement(c, entry) for entry in entries)
+ ]
if not candidates:
return ""
lines = "\n".join(
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.py
index 62e0b3aba7..b6b8688538 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py
@@ -19,6 +19,8 @@ from backend.copilot.constants import (
COPILOT_SESSION_PREFIX,
MAX_TOOL_WAIT_SECONDS,
)
+from backend.copilot.context import is_unattended_turn
+from backend.copilot.credential_selection import turn_credential_pins
from backend.copilot.model import ChatSession
from backend.copilot.sdk.env import config as chat_config
from backend.copilot.sdk.file_ref import FileRefExpansionError, expand_file_refs_in_args
@@ -71,6 +73,8 @@ from .models import (
from .utils import (
build_missing_credentials_from_field_info,
credential_rejection_status,
+ get_user_credentials,
+ is_per_target_credential,
match_credentials_to_requirements,
sanitize_provider_message,
)
@@ -363,11 +367,13 @@ async def execute_block(
except HTTPClientError as e:
# The provider refused the refresh (revoked grant, expired
# refresh token). The user can only fix that by
- # reconnecting, so hand them the card rather than an error.
+ # reconnecting, so hand them the card (or, with nobody
+ # watching, an error naming the account) rather than a
+ # bare failure.
# Anything else (store, config, handler setup) is not
# theirs to fix and takes the usual error path below.
await _release_credential_leases(credential_leases)
- return _build_credential_rejected_card(
+ return _credential_rejected_response(
block=block,
block_id=block_id,
input_data=input_data,
@@ -604,7 +610,7 @@ async def execute_block(
f"Provider rejected a stored credential for block {block.name} "
f"with HTTP {status_code}"
)
- return _build_credential_rejected_card(
+ return _credential_rejected_response(
block=block,
block_id=block_id,
input_data=input_data,
@@ -628,7 +634,7 @@ async def execute_block(
)
-def _build_credential_rejected_card(
+def _credential_rejected_response(
*,
block: AnyBlockSchema,
block_id: str,
@@ -637,15 +643,55 @@ def _build_credential_rejected_card(
session_id: str,
status_code: int | None,
exc: BaseException,
-) -> SetupRequirementsResponse:
- """Setup card for a credential the provider refused mid-execution.
+) -> SetupRequirementsResponse | ErrorResponse:
+ """The answer when the provider refused a stored credential.
- The rejected row is kept — a 401 is not proof the secret is wrong — so
- the ``rejection`` field is what stops the card re-offering it as ready.
+ A watched turn gets the reconnect card. A scheduled turn's card would go
+ unanswered (SECRT-2804), so it gets an error naming the account instead,
+ which the turn's reply passes on to the user.
"""
- missing_creds_dict = build_missing_credentials_from_field_info(
- _resolve_discriminated_credentials(block, input_data), matched_keys=set()
+ if not is_unattended_turn():
+ return _build_credential_rejected_card(
+ block=block,
+ block_id=block_id,
+ input_data=input_data,
+ matched_credentials=matched_credentials,
+ session_id=session_id,
+ status_code=status_code,
+ exc=exc,
+ )
+ rejected, provider = _rejected_credential(block, matched_credentials)
+ provider_name = provider.replace("_", " ").title() or "The provider"
+ named = f" '{rejected.title}'" if rejected and rejected.title else ""
+ refused = (
+ f"{provider_name} rejected the saved credential{named} (HTTP {status_code})"
+ if status_code is not None
+ else f"The saved {provider_name} credential{named} could not be refreshed"
+ )
+ logger.warning(
+ "Unattended copilot turn in session %s: block %s did not run, %s",
+ session_id,
+ block.name,
+ refused,
+ )
+ return ErrorResponse(
+ message=(
+ f"{refused}, so block '{block.name}' did not run. Nobody is "
+ "watching this turn (it was scheduled), so there is no one to "
+ "reconnect it now, and it did not switch to a different account. "
+ "Say plainly in your reply that this step was skipped, name that "
+ "credential, and tell the user to reconnect it or choose another "
+ "before the next run."
+ ),
+ error="credential_rejected",
+ session_id=session_id,
)
+
+
+def _rejected_credential(
+ block: AnyBlockSchema, matched_credentials: dict[str, CredentialsMetaInput]
+) -> tuple[CredentialsMetaInput | None, str]:
+ """The refused credential, when only one was in play, and its provider."""
rejected = (
next(iter(matched_credentials.values()))
if len(matched_credentials) == 1
@@ -657,6 +703,28 @@ def _build_credential_rejected_card(
if rejected
else get_block_provider(block) or ""
)
+ return rejected, provider
+
+
+def _build_credential_rejected_card(
+ *,
+ block: AnyBlockSchema,
+ block_id: str,
+ input_data: dict[str, Any],
+ matched_credentials: dict[str, CredentialsMetaInput],
+ session_id: str,
+ status_code: int | None,
+ exc: BaseException,
+) -> SetupRequirementsResponse:
+ """Setup card for a credential the provider refused mid-execution.
+
+ The rejected row is kept — a 401 is not proof the secret is wrong — so
+ the ``rejection`` field is what stops the card re-offering it as ready.
+ """
+ missing_creds_dict = build_missing_credentials_from_field_info(
+ _resolve_discriminated_credentials(block, input_data), matched_keys=set()
+ )
+ rejected, provider = _rejected_credential(block, matched_credentials)
provider_name = provider.replace("_", " ").title() or "The provider"
named = f" '{rejected.title}'" if rejected and rejected.title else ""
return SetupRequirementsResponse(
@@ -751,6 +819,127 @@ async def resolve_block_credentials(
)
+async def unattended_missing_credentials_error(
+ subject: str,
+ missing: dict[str, dict[str, Any]],
+ session_id: str,
+ user_id: str,
+ expert_id: str | None,
+) -> ErrorResponse:
+ """The answer when a turn nobody watches has no credential to run with.
+
+ *missing* holds the setup card's entries, one per credential field that
+ nothing fitted. A setup card there is never answered, and the step used to
+ end as a quiet "not configured" (SECRT-2804). Name the provider, so the
+ turn's reply tells the user what to connect, and log it so the failure can
+ be found.
+
+ When the schedule pinned an account that is gone or cannot do this step,
+ name that account: the run refused to switch to another one, and the user
+ has to know which. When the account already has a credential the expert was never
+ granted and a field would accept, say to grant that one, since connecting
+ another would not help.
+ """
+ providers = {provider_slug(m.get("provider", "")) for m in missing.values()}
+ providers -= {""}
+ names = ", ".join(sorted(providers)) or "an integration"
+ pinned = await _pinned_account_error(
+ subject, providers, session_id, user_id, expert_id
+ )
+ if pinned is not None:
+ return pinned
+ grant_hint = await ungranted_credential_hint(
+ user_id, expert_id, providers, missing.values()
+ )
+ logger.warning(
+ "Unattended copilot turn in session %s: %s has no %s credential to use",
+ session_id,
+ subject,
+ names,
+ )
+ if grant_hint:
+ state = "granted to this expert"
+ fix = (
+ "grant this expert one of the existing credentials listed below, "
+ f"or connect {names} in their integrations,"
+ )
+ else:
+ state = "connected"
+ fix = f"connect {names} in their integrations"
+ return ErrorResponse(
+ message=(
+ f"{subject} has no {names} credential {state}, so this step "
+ "did not run. Nobody is watching this turn (it was "
+ "scheduled), so there is no one to fix it now. Say plainly "
+ "in your reply that this step was skipped and that the user needs "
+ f"to {fix} before the next run."
+ )
+ + grant_hint,
+ error="missing_credentials",
+ session_id=session_id,
+ )
+
+
+async def _pinned_account_error(
+ subject: str,
+ providers: set[str],
+ session_id: str,
+ user_id: str,
+ expert_id: str | None,
+) -> ErrorResponse | None:
+ """The error when a missing provider is pinned to an account this run
+ could not use, or ``None`` when no pin explains it."""
+ pins = turn_credential_pins()
+ pinned = set(pins) & providers
+ if not pinned:
+ return None
+ by_id = {c.id: c for c in await get_user_credentials(user_id, expert_id)}
+ lost = sorted(p for p in pinned if pins[p].id not in by_id)
+ unfit = sorted(
+ p
+ for p in pinned
+ if pins[p].id in by_id and not is_per_target_credential(by_id[pins[p].id])
+ )
+ if not lost and not unfit:
+ return None
+
+ def account(p: str) -> str:
+ return (
+ f"the {p} account '{pins[p].title or pins[p].id}' "
+ f"(credential_id={pins[p].id})"
+ )
+
+ detail = "; ".join(
+ [
+ f"{account(p)}, which has been deleted or is no longer available "
+ "to this run"
+ for p in lost
+ ]
+ + [
+ f"{account(p)}, which cannot do this step (it lacks the type or "
+ "permissions the step needs)"
+ for p in unfit
+ ]
+ )
+ logger.warning(
+ "Unattended copilot turn in session %s: %s is pinned to %s",
+ session_id,
+ subject,
+ detail,
+ )
+ return ErrorResponse(
+ message=(
+ f"{subject} did not run. This schedule is set to use {detail}. It "
+ "did not switch to a different account. Say plainly in your reply "
+ "that this step was skipped, name that account, and tell the user "
+ "to reconnect it with the access this step needs, or choose "
+ "another account for this schedule, before the next run."
+ ),
+ error="pinned_credential_missing" if lost else "pinned_credential_unusable",
+ session_id=session_id,
+ )
+
+
@dataclass
class BlockPreparation:
"""Result of successful block validation, ready for execution or task creation.
@@ -909,12 +1098,19 @@ async def prepare_block_for_execution(
dry_run or validate_only
):
credentials_fields_info = _resolve_discriminated_credentials(block, input_data)
+ missing_entries = build_missing_credentials_from_field_info(
+ credentials_fields_info, set(matched_credentials.keys())
+ )
+ if missing_credentials and is_unattended_turn():
+ return await unattended_missing_credentials_error(
+ f"Block '{block.name}'",
+ missing_entries,
+ session_id,
+ user_id,
+ session.expert_id,
+ )
missing_creds_dict = await annotate_expert_grants(
- user_id,
- session.expert_id,
- build_missing_credentials_from_field_info(
- credentials_fields_info, set(matched_credentials.keys())
- ),
+ user_id, session.expert_id, missing_entries
)
missing_creds_list = list(missing_creds_dict.values())
if missing_credentials:
@@ -926,6 +1122,7 @@ async def prepare_block_for_execution(
user_id,
session.expert_id,
{provider_slug(m.provider) for m in missing_credentials},
+ missing_entries.values(),
)
else:
message = (
diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
index 91f9a79a7f..3878b0f812 100644
--- a/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/helpers_test.py
@@ -1,13 +1,19 @@
"""Tests for execute_block, prepare_block_for_execution, and check_hitl_review."""
+import asyncio
from collections.abc import AsyncIterator
from typing import Any, ClassVar, Literal
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from pydantic import SecretStr
from backend.blocks._base import BlockType
+from backend.blocks.exa.search import ExaSearchBlock
from backend.copilot.constants import COPILOT_NODE_PREFIX, COPILOT_SESSION_PREFIX
+from backend.copilot.context import set_turn_unattended
+from backend.copilot.credential_selection import CredentialPin, set_turn_credential_pins
+from backend.copilot.model import ChatSession
from backend.copilot.rate_limit import UserPaywalledError
from backend.copilot.tools.helpers import (
BlockPreparation,
@@ -28,10 +34,13 @@ from backend.copilot.tools.models import (
SetupRequirementsResponse,
)
from backend.data.model import (
+ APIKeyCredentials,
CredentialsFieldInfo,
CredentialsMetaInput,
CredentialsType,
+ OAuth2Credentials,
)
+from backend.integrations.credentials_store import exa_credentials
from backend.integrations.providers import ProviderName
from ._test_data import make_session
@@ -2003,3 +2012,240 @@ async def _store_workspace_file(path: str):
dry_run=False,
expert_id="expert-a",
)
+
+
+# ---------------------------------------------------------------------------
+# Credential choice on unattended turns (SECRT-2804)
+# ---------------------------------------------------------------------------
+
+
+def _exa_key(cred_id: str) -> APIKeyCredentials:
+ return APIKeyCredentials(
+ id=cred_id, provider="exa", title=cred_id, api_key=SecretStr("k")
+ )
+
+
+async def _prepare_exa_search(
+ session: ChatSession,
+ saved_creds: list,
+ *,
+ scheduled: bool = False,
+ pins: dict[str, CredentialPin] | None = None,
+ chat_picks: dict[str, str] | None = None,
+) -> Any:
+ """Prepare an Exa search the way run_block does, in a turn the executor
+ marked the way it marks every turn, with the pins of the schedule that
+ fired it. Run as its own task so the marking stays inside it."""
+ redis = MagicMock()
+ redis.hgetall = AsyncMock(return_value=chat_picks or {})
+
+ async def turn():
+ set_turn_unattended(session, scheduled=scheduled)
+ set_turn_credential_pins(pins)
+ with (
+ patch(
+ "backend.copilot.tools.utils.IntegrationCredentialsManager"
+ ) as creds_mgr,
+ patch(
+ "backend.copilot.credential_selection.get_redis_async",
+ AsyncMock(return_value=redis),
+ ),
+ patch(
+ "backend.copilot.tools.helpers.expand_file_refs_in_args",
+ AsyncMock(side_effect=lambda d, *a, **kw: d),
+ ),
+ ):
+ creds_mgr.return_value.store = AsyncMock()
+ # The store lists the user's own credentials first, oldest first,
+ # then the platform's.
+ creds_mgr.return_value.store.get_all_creds.return_value = [
+ *saved_creds,
+ exa_credentials,
+ ]
+ return await prepare_block_for_execution(
+ block_id=ExaSearchBlock().id,
+ input_data={"query": "daily briefing"},
+ user_id=_USER,
+ session=session,
+ session_id=session.session_id,
+ dry_run=False,
+ )
+
+ return await asyncio.create_task(turn())
+
+
+def _scheduled_session() -> ChatSession:
+ session = make_session(_USER)
+ session.metadata.origin = "automation"
+ return session
+
+
+async def test_scheduled_turn_with_two_exa_keys_runs_on_the_first_saved() -> None:
+ # Nobody is watching a scheduled turn, so a "which account?" card would
+ # never be answered and the step would end as "not configured".
+ result = await _prepare_exa_search(
+ _scheduled_session(), [_exa_key("exa-old"), _exa_key("exa-new")]
+ )
+
+ assert isinstance(result, BlockPreparation), getattr(result, "message", result)
+ assert result.matched_credentials["credentials"].id == "exa-old"
+
+
+async def test_scheduled_turn_into_a_users_chat_does_not_ask_either() -> None:
+ # A pinned follow-up fires into the user's own (interactive) chat; the
+ # turn is still unattended.
+ result = await _prepare_exa_search(
+ make_session(_USER),
+ [_exa_key("exa-old"), _exa_key("exa-new")],
+ scheduled=True,
+ )
+
+ assert isinstance(result, BlockPreparation), getattr(result, "message", result)
+ assert result.matched_credentials["credentials"].id == "exa-old"
+
+
+async def test_interactive_turn_with_two_exa_keys_still_asks() -> None:
+ result = await _prepare_exa_search(
+ make_session(_USER), [_exa_key("exa-old"), _exa_key("exa-new")]
+ )
+
+ assert isinstance(result, SetupRequirementsResponse)
+
+
+async def test_scheduled_turn_without_any_exa_key_fails_naming_the_provider() -> None:
+ # No platform key configured and none saved: nothing fits.
+ missing = CredentialsMetaInput(
+ id="credentials", provider=ProviderName("exa"), type="api_key"
+ )
+ with patch(
+ "backend.copilot.tools.helpers.match_credentials_to_requirements",
+ AsyncMock(return_value=({}, [missing])),
+ ):
+ result = await _prepare_exa_search(_scheduled_session(), [])
+
+ assert isinstance(result, ErrorResponse)
+ assert "exa" in result.message.lower()
+ assert ExaSearchBlock().name in result.message
+
+
+async def test_scheduled_expert_turn_names_the_credential_to_grant() -> None:
+ # The account has an Exa key, but the expert was never granted it, so
+ # connecting another one would not help: the reply must say to grant it.
+ missing = CredentialsMetaInput(
+ id="credentials", provider=ProviderName("exa"), type="api_key"
+ )
+ session = make_session(_USER, expert_id="expert-a")
+ session.metadata.origin = "automation"
+ with (
+ patch(
+ "backend.copilot.tools.helpers.match_credentials_to_requirements",
+ AsyncMock(return_value=({}, [missing])),
+ ),
+ patch(
+ "backend.copilot.tools.expert_scope._ungranted_credentials",
+ AsyncMock(return_value=[_exa_key("exa-old")]),
+ ),
+ ):
+ result = await _prepare_exa_search(session, [])
+
+ assert isinstance(result, ErrorResponse)
+ assert "exa-old" in result.message
+ assert "grant" in result.message.lower()
+
+
+async def test_scheduled_turn_uses_the_pinned_exa_key_not_the_oldest() -> None:
+ # The user picked the newer key when the schedule was made.
+ result = await _prepare_exa_search(
+ _scheduled_session(),
+ [_exa_key("exa-old"), _exa_key("exa-new")],
+ pins={"exa": CredentialPin(id="exa-new", title="Work key")},
+ )
+
+ assert isinstance(result, BlockPreparation), getattr(result, "message", result)
+ assert result.matched_credentials["credentials"].id == "exa-new"
+
+
+async def test_the_schedules_pin_wins_over_a_pick_in_the_chat_it_lands_in() -> None:
+ # A follow-up firing into the user's own chat, where they later picked the
+ # other key for something else: the schedule still runs on its own.
+ result = await _prepare_exa_search(
+ make_session(_USER),
+ [_exa_key("exa-old"), _exa_key("exa-new")],
+ scheduled=True,
+ pins={"exa": CredentialPin(id="exa-new", title="Work key")},
+ chat_picks={"exa": "exa-old"},
+ )
+
+ assert isinstance(result, BlockPreparation), getattr(result, "message", result)
+ assert result.matched_credentials["credentials"].id == "exa-new"
+
+
+async def test_a_deleted_pinned_key_fails_naming_it_instead_of_switching() -> None:
+ # The pinned key is gone. The other key and the platform's would both fit,
+ # and running on either is the silent switch the pin exists to prevent.
+ result = await _prepare_exa_search(
+ _scheduled_session(),
+ [_exa_key("exa-old")],
+ pins={"exa": CredentialPin(id="exa-new", title="Work key")},
+ )
+
+ assert isinstance(result, ErrorResponse), result
+ assert result.error == "pinned_credential_missing"
+ assert "Work key" in result.message
+ assert "exa-new" in result.message
+ assert "exa-old" not in result.message
+
+
+async def test_a_pin_for_another_provider_leaves_exa_alone() -> None:
+ result = await _prepare_exa_search(
+ _scheduled_session(),
+ [_exa_key("exa-old"), _exa_key("exa-new")],
+ pins={"github": CredentialPin(id="gh-gone", title="Old GitHub")},
+ )
+
+ assert isinstance(result, BlockPreparation), getattr(result, "message", result)
+ assert result.matched_credentials["credentials"].id == "exa-old"
+
+
+async def test_scheduled_expert_turn_does_not_offer_a_credential_of_the_wrong_type() -> (
+ None
+):
+ # The Exa block takes an API key. An ungranted Exa OAuth credential would
+ # be refused by the next run too, so it must not be the one to grant.
+ missing = CredentialsMetaInput(
+ id="credentials", provider=ProviderName("exa"), type="api_key"
+ )
+ session = make_session(_USER, expert_id="expert-a")
+ session.metadata.origin = "automation"
+ wrong_type = OAuth2Credentials(
+ id="exa-oauth",
+ provider="exa",
+ title="exa-oauth",
+ access_token=SecretStr("t"),
+ scopes=[],
+ )
+ with (
+ patch(
+ "backend.copilot.tools.helpers.match_credentials_to_requirements",
+ AsyncMock(return_value=({}, [missing])),
+ ),
+ patch(
+ "backend.copilot.tools.expert_scope._ungranted_credentials",
+ AsyncMock(return_value=[wrong_type]),
+ ),
+ ):
+ result = await _prepare_exa_search(session, [])
+
+ assert isinstance(result, ErrorResponse)
+ assert "exa-oauth" not in result.message
+ assert "connect exa" in result.message
diff --git a/autogpt_platform/backend/backend/copilot/tools/routines.py b/autogpt_platform/backend/backend/copilot/tools/routines.py
index aec57286fb..dd10e32f23 100644
--- a/autogpt_platform/backend/backend/copilot/tools/routines.py
+++ b/autogpt_platform/backend/backend/copilot/tools/routines.py
@@ -21,13 +21,24 @@ from backend.api.features.experts.routines import (
RoutineNotFoundError,
RoutineUnansweredAsksError,
)
+from backend.copilot.credential_selection import CredentialPins
from backend.copilot.model import ChatSession, get_chat_session
from backend.data.activity_event import ActivityEventDraft
from backend.data.db_accessors import experts_db
from .base import BaseTool
from .expert_scope import RoutineOwner, resolve_routine_owner
-from .models import ErrorResponse, ResponseType, ToolResponseBase
+from .models import (
+ ErrorResponse,
+ ResponseType,
+ SetupRequirementsResponse,
+ ToolResponseBase,
+)
+from .schedule_credentials import (
+ INTEGRATIONS_PARAM,
+ has_account_choices,
+ pin_schedule_credentials,
+)
logger = logging.getLogger(__name__)
@@ -208,6 +219,7 @@ class ScheduleRoutineTool(BaseTool):
"the user agreed to THIS routine using their accounts."
),
},
+ "integrations": INTEGRATIONS_PARAM,
"expert_id": _EXPERT_ID_PARAM,
},
"required": ["enabled"],
@@ -264,9 +276,14 @@ class ScheduleRoutineTool(BaseTool):
pinned = await self._pinned_session(user_id, session, owner, kwargs)
if isinstance(pinned, ErrorResponse):
return pinned
+ credential_pins = await self._credential_pins(
+ user_id, session, owner, routine_id, enabled, kwargs
+ )
+ if isinstance(credential_pins, SetupRequirementsResponse):
+ return credential_pins
try:
routine = await self._apply(
- user_id, owner, routine_id, enabled, pinned, kwargs
+ user_id, owner, routine_id, enabled, pinned, credential_pins, kwargs
)
except RoutineUnansweredAsksError as e:
return ErrorResponse(
@@ -356,6 +373,44 @@ class ScheduleRoutineTool(BaseTool):
session_id=current,
)
+ async def _credential_pins(
+ self,
+ user_id: str,
+ session: ChatSession,
+ owner: RoutineOwner,
+ routine_id: str,
+ enabled: bool,
+ kwargs: dict[str, Any],
+ ) -> CredentialPins | SetupRequirementsResponse | None:
+ """The accounts the routine's turns run on, chosen now, while the
+ owner is here to say which (SECRT-2804).
+
+ ``None`` leaves the row's pins as they are: switching a routine off,
+ or one that reaches no connected service, has no account to choose.
+ Changing one starts from the pins it has, so only a provider named
+ again, or picked again in this chat, moves to another account.
+ """
+ integrations = kwargs.get("integrations")
+ if not enabled or not await has_account_choices(session, integrations):
+ return None
+ existing = None
+ grant = kwargs.get("grants_credentials")
+ if routine_id:
+ current = await experts_db().get_routine(routine_id)
+ if current is not None and current.expert_id == owner.expert_id:
+ existing = current.credential_pins
+ if grant is None:
+ grant = current.grants_credentials
+ if grant is False:
+ return None
+ return await pin_schedule_credentials(
+ user_id,
+ session,
+ owner.expert_id,
+ integrations,
+ existing,
+ )
+
async def _apply(
self,
user_id: str,
@@ -363,6 +418,7 @@ class ScheduleRoutineTool(BaseTool):
routine_id: str,
enabled: bool,
pinned_session_id: str | None,
+ credential_pins: CredentialPins | None,
kwargs: dict[str, Any],
) -> ExpertRoutine:
run_at = _run_at(kwargs.get("delay_seconds"))
@@ -383,6 +439,7 @@ class ScheduleRoutineTool(BaseTool):
# ``None`` is "they did not say", which on a new row is the
# default rather than a change to leave alone.
grants_credentials=True if grant is None else bool(grant),
+ credential_pins=credential_pins,
)
if not enabled:
return created
@@ -409,6 +466,7 @@ class ScheduleRoutineTool(BaseTool):
# Absent means "leave the grant alone", so rewording a routine
# never quietly widens what it can touch.
grants_credentials=grant,
+ credential_pins=credential_pins,
)
@@ -440,4 +498,14 @@ def _confirmation(routine: ExpertRoutine) -> str:
when = f"once at {routine.run_at:%Y-%m-%d %H:%M} UTC"
else:
when = "at no time it can name"
- return f"'{routine.title}' is on: {when}, {where}. {reach}"
+ accounts = ""
+ if routine.grants_credentials and routine.credential_pins:
+ accounts = (
+ " Every run uses these accounts: "
+ + ", ".join(
+ f"{provider}: '{pin.title or pin.id}'"
+ for provider, pin in sorted(routine.credential_pins.items())
+ )
+ + "."
+ )
+ return f"'{routine.title}' is on: {when}, {where}. {reach}{accounts}"
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent.py b/autogpt_platform/backend/backend/copilot/tools/run_agent.py
index f9e40b573d..f7f3ac27c4 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_agent.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent.py
@@ -13,6 +13,7 @@ from backend.api.features.library.model import (
)
from backend.copilot.config import ChatConfig
from backend.copilot.constants import MAX_TOOL_WAIT_SECONDS
+from backend.copilot.context import is_unattended_turn
from backend.copilot.gate.subject import (
NO_OP,
Subject,
@@ -67,7 +68,11 @@ from .expert_scope import (
require_installed_workflow,
ungranted_credential_hint,
)
-from .helpers import get_inputs_from_schema, get_picker_inputs_from_schema
+from .helpers import (
+ get_inputs_from_schema,
+ get_picker_inputs_from_schema,
+ unattended_missing_credentials_error,
+)
from .models import (
AgentDetails,
AgentDetailsResponse,
@@ -594,11 +599,12 @@ class RunAgentTool(BaseTool):
user_id: str,
expert_id: str | None,
inputs: dict[str, Any] | None = None,
- ) -> SetupRequirementsResponse | None:
+ ) -> SetupRequirementsResponse | ErrorResponse | None:
"""Turn a credential-only ``GraphValidationError`` into the inline
setup-requirements card; return ``None`` if *any* non-credential
error is present so the caller falls back to the plain text path
- (otherwise structural errors would be hidden)."""
+ (otherwise structural errors would be hidden). A turn nobody watches
+ gets the unattended missing-credential error instead of a card."""
messages = [
msg
for node_errors in error.node_errors.values()
@@ -613,9 +619,16 @@ class RunAgentTool(BaseTool):
# creds are now invalid, so narrowing to `error.node_errors` would
# leak the stale mapping. Passing ``None`` means no field is
# treated as "already connected".
- credentials_dict = await annotate_expert_grants(
- user_id, expert_id, build_missing_credentials_from_graph(graph, None)
- )
+ missing = build_missing_credentials_from_graph(graph, None)
+ if is_unattended_turn():
+ return await unattended_missing_credentials_error(
+ f"Agent '{graph.name}'",
+ missing,
+ session_id,
+ user_id,
+ expert_id,
+ )
+ credentials_dict = await annotate_expert_grants(user_id, expert_id, missing)
return SetupRequirementsResponse(
message=(
f"Agent '{graph.name}' has credentials that are missing or "
@@ -736,6 +749,14 @@ class RunAgentTool(BaseTool):
expert_id,
build_missing_credentials_from_graph(graph, graph_credentials),
)
+ if is_unattended_turn():
+ return graph_credentials, await unattended_missing_credentials_error(
+ f"Agent '{graph.name}'",
+ missing_credentials_dict,
+ session_id,
+ user_id,
+ expert_id,
+ )
return graph_credentials, SetupRequirementsResponse(
message=self._build_inputs_message(graph, MSG_WHAT_VALUES_TO_USE)
+ await ungranted_credential_hint(
@@ -746,6 +767,7 @@ class RunAgentTool(BaseTool):
for m in missing_credentials_dict.values()
}
- {""},
+ missing_credentials_dict.values(),
),
session_id=session_id,
setup_info=SetupInfo(
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py b/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
index b296172a9a..33b646e05b 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent_test.py
@@ -1,9 +1,11 @@
+import asyncio
import uuid
from unittest.mock import AsyncMock, MagicMock, patch
import orjson
import pytest
+from backend.copilot.context import set_turn_unattended
from backend.data.execution import ExecutionStatus
from backend.data.model import USER_TIMEZONE_NOT_SET
from backend.executor.scheduler import GraphExecutionJobInfo
@@ -1917,3 +1919,38 @@ async def test_validation_error_card_carries_expert_grants(
assert all(
entry["expert_grant"]["expert_id"] == "expert-a" for entry in missing.values()
)
+
+
[email protected](loop_scope="session")
+async def test_validation_race_on_a_scheduled_turn_fails_instead_of_asking():
+ """A preset's stale credential reaches the race handler without the
+ prerequisite check; on a turn nobody watches, a setup card would never
+ be answered, so the step must fail naming the provider (SECRT-2804)."""
+ graph = MagicMock(id="graph-1", version=1)
+ graph.name = "Daily Scraper"
+ error = GraphValidationError(
+ message="Graph is invalid",
+ node_errors={"some-node-id": {"credentials": "These credentials are required"}},
+ )
+ session = make_session("test-user")
+ session.metadata.origin = "automation"
+
+ async def turn():
+ set_turn_unattended(session, scheduled=False)
+ return await RunAgentTool()._handle_graph_validation_race(
+ error=error,
+ graph=graph,
+ user_id="test-user",
+ session_id=session.session_id,
+ action_verb="running",
+ )
+
+ with patch(
+ "backend.copilot.tools.run_agent.build_missing_credentials_from_graph",
+ return_value={"credentials": {"provider": "firecrawl"}},
+ ):
+ response = await asyncio.create_task(turn())
+
+ assert isinstance(response, ErrorResponse)
+ assert response.error == "missing_credentials"
+ assert "firecrawl" in response.message
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
index 7a49b82ea6..e972edf81e 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py
@@ -1503,6 +1503,54 @@ class TestExecuteBlockCredentialRejection:
# The picker must be offered again, or there is no way back.
assert "credentials" in response.setup_info.user_readiness.missing_credentials
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_a_scheduled_turn_gets_an_error_naming_the_rejected_credential(
+ self, caplog
+ ):
+ # Nobody answers a card on a scheduled turn (SECRT-2804): the reply has
+ # to say the step was skipped and which credential to reconnect.
+ from backend.util.exceptions import BlockUnknownError
+ from backend.util.request import HTTPClientError
+
+ try:
+ raise HTTPClientError("HTTP 401 Error: token=sk-live-abc", 401)
+ except HTTPClientError as inner:
+ wrapped = BlockUnknownError("failed", "AyrsharePostBlock", "block-id")
+ wrapped.__cause__ = inner
+
+ with patch(
+ "backend.copilot.tools.helpers.is_unattended_turn", return_value=True
+ ):
+ response = await self._run(wrapped)
+
+ assert isinstance(response, ErrorResponse)
+ assert response.error == "credential_rejected"
+ assert "'Work Ayrshare key' (HTTP 401)" in response.message
+ assert "did not run" in response.message
+ assert "did not switch" in response.message
+ assert "sk-live-abc" not in response.message
+ assert "sk-live-abc" not in caplog.text
+
+ @pytest.mark.asyncio(loop_scope="session")
+ async def test_a_scheduled_turn_gets_an_error_when_a_refresh_is_refused(
+ self, caplog
+ ):
+ from backend.util.request import HTTPClientError
+
+ with patch(
+ "backend.copilot.tools.helpers.is_unattended_turn", return_value=True
+ ):
+ response = await self._run(
+ RuntimeError("the block must not run"),
+ load_error=HTTPClientError("HTTP 400: refresh_token=rt-secret", 400),
+ )
+
+ assert isinstance(response, ErrorResponse)
+ assert response.error == "credential_rejected"
+ assert "'Work Ayrshare key' could not be refreshed" in response.message
+ assert "rt-secret" not in response.message
+ assert "rt-secret" not in caplog.text
+
@pytest.mark.asyncio(loop_scope="session")
async def test_non_auth_block_failure_still_returns_an_error(self):
from backend.util.exceptions import BlockExecutionError
diff --git a/autogpt_platform/backend/backend/copilot/tools/schedule_credentials.py b/autogpt_platform/backend/backend/copilot/tools/schedule_credentials.py
new file mode 100644
index 0000000000..bace052ee0
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/schedule_credentials.py
@@ -0,0 +1,163 @@
+"""Choose, while a schedule is being made, the accounts its turns will use.
+
+A scheduled turn runs with nobody watching, so it cannot ask which of two
+accounts to use, and taking the first saved one silently runs a user's work on
+whichever key they happened to add first (SECRT-2804). The chat that makes the
+schedule is the one moment someone can answer. So the schedule tools ask there,
+with the same card a block run uses, and store each choice on the schedule as a
+pin that every one of its turns runs on.
+
+What a schedule will need cannot be read off its prompt, which is free text.
+Two things are known: the integrations the model says the work uses, and the
+accounts the user already picked in this chat. Both are pinned; a provider
+with a single account of the user's own needs no pin, since there is nothing
+to choose between.
+"""
+
+import logging
+from typing import Any
+
+from backend.copilot.context import is_unattended_turn
+from backend.copilot.credential_selection import (
+ CredentialPin,
+ CredentialPins,
+ selected_credentials,
+)
+from backend.copilot.model import ChatSession
+from backend.data.model import Credentials, CredentialsFieldInfo, CredentialsType
+from backend.integrations.credentials_store import is_system_credential
+from backend.integrations.providers import ProviderName
+
+from .expert_scope import provider_slug
+from .models import SetupInfo, SetupRequirementsResponse, UserReadiness
+from .utils import build_missing_credentials_from_field_info, get_user_credentials
+
+logger = logging.getLogger(__name__)
+
+INTEGRATIONS_PARAM: dict[str, Any] = {
+ "type": "array",
+ "items": {"type": "string"},
+ "description": (
+ "Providers the work uses, e.g. ['exa']. If the user has several "
+ "accounts for one, a card asks which; call again once they pick."
+ ),
+}
+
+
+async def has_account_choices(
+ session: ChatSession, integrations: list[str] | None
+) -> bool:
+ """Whether this call names an integration or this chat picked an account,
+ i.e. whether there is anything for ``pin_schedule_credentials`` to do."""
+ return bool(_providers(integrations)) or bool(
+ await selected_credentials(session.session_id)
+ )
+
+
+async def pin_schedule_credentials(
+ user_id: str,
+ session: ChatSession,
+ expert_id: str | None,
+ integrations: list[str] | None,
+ existing: CredentialPins | None = None,
+) -> CredentialPins | SetupRequirementsResponse:
+ """The pins to store on a schedule, or the card asking for a choice.
+
+ *expert_id* is the scope the schedule runs in, so only accounts its turns
+ could use are offered. *existing* is what a routine being changed already
+ holds; a pick made in this chat replaces it, which is how the user moves a
+ routine to another account.
+ """
+ pins: CredentialPins = dict(existing or {})
+ picked = await selected_credentials(session.session_id)
+ providers = _providers(integrations)
+ if not picked and not providers:
+ return pins
+ own = [
+ c
+ for c in await get_user_credentials(user_id, expert_id)
+ if not is_system_credential(c.id)
+ ]
+ by_id = {c.id: c for c in own}
+
+ for provider, credential_id in picked.items():
+ cred = by_id.get(credential_id)
+ if cred is not None and provider_slug(cred.provider) == provider:
+ pins[provider] = CredentialPin(id=cred.id, title=cred.title or "")
+
+ choices: dict[str, list[Credentials]] = {}
+ for provider in providers:
+ pin = pins.get(provider)
+ if pin is not None and pin.id in by_id:
+ continue
+ fits = [c for c in own if provider_slug(c.provider) == provider]
+ if len(fits) > 1:
+ choices[provider] = fits
+ else:
+ # A pin whose account is gone, now with one account or none left:
+ # nothing to choose, so the turn takes what there is.
+ pins.pop(provider, None)
+
+ if not choices:
+ return pins
+ if is_unattended_turn():
+ # A scheduled turn scheduling more work has nobody to ask either.
+ logger.info(
+ "Unattended turn in session %s scheduled work using %s without "
+ "pinning an account; its turns will use the first saved one",
+ session.session_id,
+ ", ".join(sorted(choices)),
+ )
+ return pins
+ return _choice_card(session.session_id, choices)
+
+
+def _providers(integrations: list[str] | None) -> list[str]:
+ seen: list[str] = []
+ for raw in integrations or []:
+ provider = str(raw).strip().lower()
+ if provider and provider not in seen:
+ seen.append(provider)
+ return seen
+
+
+def _choice_card(
+ session_id: str, choices: dict[str, list[Credentials]]
+) -> SetupRequirementsResponse:
+ fields = {
+ f"{provider}_credentials": CredentialsFieldInfo[ProviderName, CredentialsType](
+ credentials_provider=frozenset([ProviderName(provider)]),
+ credentials_types=frozenset(c.type for c in fits),
+ credentials_scopes=None,
+ )
+ for provider, fits in choices.items()
+ }
+ missing = build_missing_credentials_from_field_info(fields, set())
+ accounts = "; ".join(
+ f"{provider}: " + ", ".join(repr(c.title or c.id) for c in fits)
+ for provider, fits in choices.items()
+ )
+ return SetupRequirementsResponse(
+ message=(
+ "Nothing is scheduled yet. The user has more than one account for "
+ f"{', '.join(sorted(choices))} ({accounts}), and nobody will be "
+ "there to ask when it runs. Ask them which account this schedule "
+ "should use with the card below, then call this tool again with "
+ "the same arguments; every run will use the account they pick."
+ ),
+ session_id=session_id,
+ setup_info=SetupInfo(
+ agent_id="schedule_accounts",
+ agent_name="Scheduled run",
+ user_readiness=UserReadiness(
+ has_all_credentials=False,
+ missing_credentials=missing,
+ ready_to_run=False,
+ ),
+ requirements={
+ "credentials": list(missing.values()),
+ "inputs": [],
+ "execution_modes": [],
+ },
+ ),
+ )
diff --git a/autogpt_platform/backend/backend/copilot/tools/schedule_credentials_test.py b/autogpt_platform/backend/backend/copilot/tools/schedule_credentials_test.py
new file mode 100644
index 0000000000..a6298d9745
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/schedule_credentials_test.py
@@ -0,0 +1,316 @@
+"""Choosing, when a schedule is made, the accounts its turns run on (SECRT-2804)."""
+
+from contextlib import contextmanager
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from pydantic import SecretStr
+
+from backend.api.features.experts.models import ExpertRoutine
+from backend.copilot.credential_selection import CredentialPin
+from backend.copilot.model import ChatSession
+from backend.copilot.tools.models import SetupRequirementsResponse
+from backend.copilot.tools.routines import RoutineResponse, ScheduleRoutineTool
+from backend.copilot.tools.schedule_followup import (
+ ScheduleCreatedResponse,
+ ScheduleFollowupTool,
+)
+from backend.data.model import APIKeyCredentials
+from backend.executor.scheduler import CopilotTurnJobInfo
+from backend.integrations.credentials_store import exa_credentials
+
+from ._test_data import make_session
+
+_USER = "user-1"
+_PINS = "backend.copilot.tools.schedule_credentials"
+_FOLLOWUP = "backend.copilot.tools.schedule_followup"
+_ROUTINES = "backend.copilot.tools.routines"
+
+
+def _exa_key(cred_id: str, title: str) -> APIKeyCredentials:
+ return APIKeyCredentials(
+ id=cred_id, provider="exa", title=title, api_key=SecretStr("k")
+ )
+
+
+_PERSONAL = _exa_key("exa-old", "Personal")
+_WORK = _exa_key("exa-new", "Work")
+
+
+@contextmanager
+def _account(saved: list, picks: dict[str, str] | None = None):
+ """The user's saved credentials (oldest first, then the platform's) and
+ what they picked in this chat."""
+ with (
+ patch(
+ f"{_PINS}.get_user_credentials",
+ AsyncMock(return_value=[*saved, exa_credentials]),
+ ),
+ patch(f"{_PINS}.selected_credentials", AsyncMock(return_value=picks or {})),
+ ):
+ yield
+
+
+@contextmanager
+def _scheduler():
+ client = AsyncMock()
+ client.add_copilot_turn_schedule = AsyncMock(
+ return_value=CopilotTurnJobInfo(
+ schedule_id="cop-1",
+ user_id=_USER,
+ session_id=None,
+ message="Daily briefing",
+ run_at=None,
+ cron="0 9 * * *",
+ id="cop-1",
+ name="briefing",
+ next_run_time="2026-10-03T09:00:00+00:00",
+ timezone="UTC",
+ )
+ )
+ user_db = MagicMock()
+ user_db.get_user_by_id = AsyncMock(return_value=MagicMock(timezone="UTC"))
+ with (
+ patch(f"{_FOLLOWUP}.get_scheduler_client", return_value=client),
+ patch(f"{_FOLLOWUP}.user_db", return_value=user_db),
+ patch(
+ f"{_FOLLOWUP}.is_followups_feature_enabled",
+ AsyncMock(return_value=True),
+ ),
+ ):
+ yield client
+
+
+async def _schedule_briefing(session: ChatSession, **kwargs):
+ return await ScheduleFollowupTool()._execute(
+ user_id=_USER,
+ session=session,
+ message="Daily briefing: search Exa for AI news",
+ cron="0 9 * * *",
+ **kwargs,
+ )
+
+
+# ---------------------------------------------------------------------------
+# schedule_followup
+# ---------------------------------------------------------------------------
+
+
+async def test_a_briefing_using_one_of_two_exa_keys_asks_which_first():
+ with _account([_PERSONAL, _WORK]), _scheduler() as scheduler:
+ result = await _schedule_briefing(make_session(_USER), integrations=["exa"])
+
+ assert isinstance(result, SetupRequirementsResponse)
+ missing = result.setup_info.user_readiness.missing_credentials
+ assert [entry["provider"] for entry in missing.values()] == ["exa"]
+ assert "Personal" in result.message and "Work" in result.message
+ scheduler.add_copilot_turn_schedule.assert_not_awaited()
+
+
+async def test_once_they_pick_the_schedule_stores_that_key():
+ with (
+ _account([_PERSONAL, _WORK], picks={"exa": "exa-new"}),
+ _scheduler() as scheduler,
+ ):
+ result = await _schedule_briefing(make_session(_USER), integrations=["exa"])
+
+ assert isinstance(result, ScheduleCreatedResponse), result
+ kwargs = scheduler.add_copilot_turn_schedule.call_args.kwargs
+ assert kwargs["credential_pins"] == {
+ "exa": CredentialPin(id="exa-new", title="Work")
+ }
+ assert "Work" in result.message
+
+
+async def test_a_pick_already_made_in_the_chat_is_kept_without_naming_it():
+ with (
+ _account([_PERSONAL, _WORK], picks={"exa": "exa-new"}),
+ _scheduler() as scheduler,
+ ):
+ await _schedule_briefing(make_session(_USER))
+
+ kwargs = scheduler.add_copilot_turn_schedule.call_args.kwargs
+ assert kwargs["credential_pins"]["exa"].id == "exa-new"
+
+
+async def test_a_single_exa_key_needs_no_choice_and_no_pin():
+ with _account([_PERSONAL]), _scheduler() as scheduler:
+ result = await _schedule_briefing(make_session(_USER), integrations=["exa"])
+
+ assert isinstance(result, ScheduleCreatedResponse)
+ assert scheduler.add_copilot_turn_schedule.call_args.kwargs["credential_pins"] == {}
+
+
+async def test_a_pick_of_someone_elses_credential_is_not_pinned():
+ with (
+ _account([_PERSONAL, _WORK], picks={"exa": "not-mine"}),
+ _scheduler() as scheduler,
+ ):
+ result = await _schedule_briefing(make_session(_USER))
+
+ assert isinstance(result, ScheduleCreatedResponse)
+ assert scheduler.add_copilot_turn_schedule.call_args.kwargs["credential_pins"] == {}
+
+
+async def test_nothing_named_and_nothing_picked_never_reads_credentials():
+ lookup = AsyncMock()
+ with (
+ patch(f"{_PINS}.get_user_credentials", lookup),
+ patch(f"{_PINS}.selected_credentials", AsyncMock(return_value={})),
+ _scheduler() as scheduler,
+ ):
+ result = await _schedule_briefing(make_session(_USER))
+
+ assert isinstance(result, ScheduleCreatedResponse)
+ lookup.assert_not_awaited()
+ assert scheduler.add_copilot_turn_schedule.call_args.kwargs["credential_pins"] == {}
+
+
+# ---------------------------------------------------------------------------
+# schedule_routine
+# ---------------------------------------------------------------------------
+
+
+def _routine(**overrides) -> ExpertRoutine:
+ return ExpertRoutine(
+ **{
+ "id": "routine-1",
+ "title": "Morning briefing",
+ "prompt": "Search Exa for AI news",
+ "crons": ["0 9 * * *"],
+ "session_mode": "THREAD",
+ "source": "OWNER",
+ "enabled": True,
+ "grants_credentials": True,
+ **overrides,
+ }
+ )
+
+
+def experts():
+ db = MagicMock()
+ db.get_routine = AsyncMock(return_value=None)
+ db.create_routine = AsyncMock(return_value=_routine(enabled=False))
+ db.enable_routine = AsyncMock(return_value=_routine())
+ db.disable_routine = AsyncMock(return_value=_routine(enabled=False))
+ with patch(f"{_ROUTINES}.experts_db", return_value=db):
+ yield db
+
+
+async def _routine_call(**kwargs):
+ return await ScheduleRoutineTool()._execute(
+ _USER, ChatSession.new(_USER, dry_run=False), **kwargs
+ )
+
+
+async def test_a_new_routine_using_one_of_two_exa_keys_asks_which_first(experts):
+ with _account([_PERSONAL, _WORK]):
+ result = await _routine_call(
+ title="Morning briefing",
+ prompt="Search Exa for AI news",
+ crons=["0 9 * * *"],
+ enabled=True,
+ integrations=["exa"],
+ )
+
+ assert isinstance(result, SetupRequirementsResponse)
+ experts.create_routine.assert_not_awaited()
+
+
+async def test_a_new_routine_stores_the_picked_key_on_its_row(experts):
+ with _account([_PERSONAL, _WORK], picks={"exa": "exa-new"}):
+ result = await _routine_call(
+ title="Morning briefing",
+ prompt="Search Exa for AI news",
+ crons=["0 9 * * *"],
+ enabled=True,
+ integrations=["exa"],
+ )
+
+ assert isinstance(result, RoutineResponse), result
+ pins = experts.create_routine.await_args.kwargs["credential_pins"]
+ assert pins == {"exa": CredentialPin(id="exa-new", title="Work")}
+
+
+async def test_changing_a_routine_keeps_its_key_unless_another_is_picked(experts):
+ experts.get_routine = AsyncMock(
+ return_value=_routine(
+ credential_pins={"exa": CredentialPin(id="exa-new", title="Work")}
+ )
+ )
+ with _account([_PERSONAL, _WORK]):
+ result = await _routine_call(
+ routine_id="routine-1",
+ enabled=True,
+ prompt="Search Exa for robotics news",
+ integrations=["exa"],
+ )
+
+ assert isinstance(result, RoutineResponse), result
+ pins = experts.enable_routine.await_args.kwargs["credential_pins"]
+ assert pins["exa"].id == "exa-new"
+
+
+async def test_a_pick_in_the_chat_moves_a_routine_to_that_key(experts):
+ experts.get_routine = AsyncMock(
+ return_value=_routine(
+ credential_pins={"exa": CredentialPin(id="exa-new", title="Work")}
+ )
+ )
+ with _account([_PERSONAL, _WORK], picks={"exa": "exa-old"}):
+ await _routine_call(routine_id="routine-1", enabled=True)
+
+ pins = experts.enable_routine.await_args.kwargs["credential_pins"]
+ assert pins["exa"].id == "exa-old"
+
+
+async def test_a_routine_whose_key_was_deleted_asks_again(experts):
+ experts.get_routine = AsyncMock(
+ return_value=_routine(
+ credential_pins={"exa": CredentialPin(id="exa-gone", title="Old")}
+ )
+ )
+ with _account([_PERSONAL, _WORK]):
+ result = await _routine_call(
+ routine_id="routine-1", enabled=True, integrations=["exa"]
+ )
+
+ assert isinstance(result, SetupRequirementsResponse)
+ experts.enable_routine.assert_not_awaited()
+
+
+async def test_switching_a_routine_off_leaves_its_keys_alone(experts):
+ with _account([_PERSONAL, _WORK], picks={"exa": "exa-old"}):
+ await _routine_call(routine_id="routine-1", enabled=False)
+
+ experts.get_routine.assert_not_awaited()
+ experts.disable_routine.assert_awaited_once()
+
+
+async def test_a_routine_that_reaches_no_service_pins_nothing(experts):
+ with _account([_PERSONAL, _WORK]):
+ result = await _routine_call(
+ title="Draft only",
+ prompt="Draft a note",
+ crons=["0 9 * * *"],
+ enabled=True,
+ integrations=["exa"],
+ grants_credentials=False,
+ )
+
+ assert isinstance(result, RoutineResponse), result
+ assert experts.create_routine.await_args.kwargs["credential_pins"] is None
diff --git a/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py b/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py
index eda1f8bbe3..a641d097f6 100644
--- a/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py
+++ b/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py
@@ -36,6 +36,7 @@ from typing import Any
from apscheduler.triggers.cron import CronTrigger
+from backend.copilot.credential_selection import CredentialPins
from backend.copilot.model import ChatSession, get_chat_session
from backend.copilot.tools.session_context import is_followups_feature_enabled
from backend.copilot.tracking import track_chat_outcome
@@ -44,7 +45,13 @@ from backend.util.clients import get_scheduler_client
from backend.util.timezone_utils import get_user_timezone_or_utc
from .base import BaseTool
-from .models import ErrorResponse, ResponseType, ToolResponseBase
+from .models import (
+ ErrorResponse,
+ ResponseType,
+ SetupRequirementsResponse,
+ ToolResponseBase,
+)
+from .schedule_credentials import INTEGRATIONS_PARAM, pin_schedule_credentials
logger = logging.getLogger(__name__)
@@ -147,6 +154,7 @@ class ScheduleFollowupTool(BaseTool):
"type": "string",
"description": "Optional short label shown in the schedules UI.",
},
+ "integrations": INTEGRATIONS_PARAM,
},
"required": ["message"],
}
@@ -255,6 +263,14 @@ class ScheduleFollowupTool(BaseTool):
session_id=current_session_id,
)
+ # Last, once nothing else can refuse the call: asking the user to pick
+ # an account for a schedule that then fails validation wastes the pick.
+ pins = await pin_schedule_credentials(
+ user_id, session, session.expert_id, kwargs.get("integrations")
+ )
+ if isinstance(pins, SetupRequirementsResponse):
+ return pins
+
try:
info = await get_scheduler_client().add_copilot_turn_schedule(
user_id=user_id,
@@ -270,6 +286,7 @@ class ScheduleFollowupTool(BaseTool):
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,
+ credential_pins=pins,
)
except ValueError as e:
return ErrorResponse(
@@ -300,9 +317,18 @@ class ScheduleFollowupTool(BaseTool):
else f"once at {info.next_run_time}"
)
return ScheduleCreatedResponse(
- message=f"Follow-up scheduled {when_str}{target_note}.",
+ message=f"Follow-up scheduled {when_str}{target_note}." + _pins_note(pins),
schedule_id=info.id,
next_run_time=info.next_run_time,
is_recurring=is_recurring,
session_id=current_session_id,
)
+
+
+def _pins_note(pins: CredentialPins) -> str:
+ if not pins:
+ return ""
+ accounts = ", ".join(
+ f"{provider}: '{pin.title or pin.id}'" for provider, pin in sorted(pins.items())
+ )
+ return f" Every run uses these accounts: {accounts}."
diff --git a/autogpt_platform/backend/backend/copilot/tools/utils.py b/autogpt_platform/backend/backend/copilot/tools/utils.py
index 7f588b570c..41f0b829da 100644
--- a/autogpt_platform/backend/backend/copilot/tools/utils.py
+++ b/autogpt_platform/backend/backend/copilot/tools/utils.py
@@ -6,7 +6,11 @@ from collections.abc import Mapping
from typing import Any
from backend.api.features.library import model as library_model
-from backend.copilot.credential_selection import selected_credentials
+from backend.copilot.context import is_unattended_turn
+from backend.copilot.credential_selection import (
+ selected_credentials,
+ turn_credential_pins,
+)
from backend.data.db_accessors import library_db, store_db
from backend.data.graph import GraphModel
from backend.data.model import (
@@ -282,12 +286,13 @@ async def match_credentials_to_requirements(
if not requirements:
return matched, missing
- available_creds = await get_user_credentials(user_id, expert_id)
+ available_creds = keep_to_pins(await get_user_credentials(user_id, expert_id))
selected = await selected_credentials(session_id)
+ can_ask = _can_ask_user(session_id)
for field_name, field_info in requirements.items():
matching_cred = find_matching_credential(
- available_creds, field_info, selected, ask_when_ambiguous=bool(session_id)
+ available_creds, field_info, selected, ask_when_ambiguous=can_ask
)
if matching_cred:
@@ -356,6 +361,45 @@ async def scope_credentials_to_expert(
return filter_credentials_for_expert(credentials, allowed)
+def keep_to_pins(available: list[Credentials]) -> list[Credentials]:
+ """For each provider the running turn's schedule pinned, leave only the
+ pinned account.
+
+ The user chose that account for the schedule. Running on another of
+ theirs, or on the platform's, is the silent switch the pin exists to
+ prevent, whether the pinned one was deleted or cannot do this step (a
+ missing scope). Then nothing fits, and the unattended error names the
+ pinned account (SECRT-2804). Host-scoped and MCP credentials are one per
+ target, not one per account, so a pin for one target leaves the others.
+ """
+ pins = turn_credential_pins()
+ if not pins:
+ return available
+ return [
+ c
+ for c in available
+ if _provider_slug(c) not in pins
+ or c.id == pins[_provider_slug(c)].id
+ or is_per_target_credential(c)
+ ]
+
+
+def is_per_target_credential(cred: Credentials) -> bool:
+ """One credential per host or MCP server, rather than one per account."""
+ return cred.type == "host_scoped" or cred.provider == ProviderName.MCP
+
+
+def _can_ask_user(session_id: str | None) -> bool:
+ """Whether a choice between the user's accounts can be handed back to them.
+
+ Only a chat tool can, and only on a turn someone is watching. A scheduled
+ turn's setup card goes unanswered and the step ends as "not configured"
+ (SECRT-2804), so there the first fit is used, as it is for every other
+ caller with nobody to ask. A pick made earlier in the chat still wins.
+ """
+ return bool(session_id) and not is_unattended_turn()
+
+
def find_matching_credential(
available_creds: list[Credentials],
field_info: CredentialsFieldInfo,
@@ -377,9 +421,18 @@ def find_matching_credential(
for cred in fits:
if selected.get(_provider_slug(cred)) == cred.id:
return cred
+ own = [c for c in fits if not is_system_credential(c.id)]
if not ask_when_ambiguous:
+ if len(own) > 1 and is_unattended_turn():
+ # A schedule made before accounts were chosen at creation.
+ logger.info(
+ "Unattended turn with no account pinned for %s: using the "
+ "first saved of %d (%s)",
+ _provider_slug(own[0]),
+ len(own),
+ fits[0].id,
+ )
return fits[0] if fits else None
- own = [c for c in fits if not is_system_credential(c.id)]
if len(own) > 1:
return None
return own[0] if own else (fits[0] if fits else None)
@@ -451,8 +504,10 @@ async def match_user_credentials_to_graph(
# Get the credentials available for the user, narrowed to the expert's grants
creds_manager = IntegrationCredentialsManager()
- available_creds = await scope_credentials_to_expert(
- user_id, expert_id, await creds_manager.store.get_all_creds(user_id)
+ available_creds = keep_to_pins(
+ await scope_credentials_to_expert(
+ user_id, expert_id, await creds_manager.store.get_all_creds(user_id)
+ )
)
selected = await selected_credentials(session_id)
@@ -469,7 +524,7 @@ async def match_user_credentials_to_graph(
available_creds,
credential_requirements,
selected,
- ask_when_ambiguous=bool(session_id),
+ ask_when_ambiguous=_can_ask_user(session_id),
)
if matching_cred:
diff --git a/autogpt_platform/backend/backend/copilot/tools/utils_test.py b/autogpt_platform/backend/backend/copilot/tools/utils_test.py
index 3f9eddf22d..b87b29664e 100644
--- a/autogpt_platform/backend/backend/copilot/tools/utils_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/utils_test.py
@@ -286,3 +286,167 @@ def test_a_system_credential_is_used_when_the_user_has_none_of_their_own():
assert _find([openai_credentials], ask=True, field=field) is openai_credentials
own = _key_cred("own-openai", provider="openai")
assert _find([own, openai_credentials], ask=True, field=field) is own
+
+
+# ---------------------------------------------------------------------------
+# A scheduled turn keeps to the account its schedule pinned (SECRT-2804)
+# ---------------------------------------------------------------------------
+
+
+def _github_oauth(cred_id: str, scopes: list[str]):
+ from backend.data.model import OAuth2Credentials
+
+ return OAuth2Credentials(
+ id=cred_id,
+ provider="github",
+ title=cred_id,
+ access_token=SecretStr("t"),
+ scopes=scopes,
+ )
+
+
+async def _match_with_pins(saved: list, requirements: dict, pins: dict):
+ """Match in a turn fired by a schedule with *pins*, as its own task so the
+ pins stay inside it."""
+ import asyncio
+
+ from backend.copilot.credential_selection import set_turn_credential_pins
+ from backend.copilot.tools.utils import match_credentials_to_requirements
+
+ async def turn():
+ set_turn_credential_pins(pins)
+ with (
+ patch(
+ "backend.copilot.tools.utils.IntegrationCredentialsManager"
+ ) as creds_mgr,
+ patch(
+ "backend.copilot.credential_selection.get_redis_async",
+ AsyncMock(return_value=MagicMock(hgetall=AsyncMock(return_value={}))),
+ ),
+ ):
+ creds_mgr.return_value.store = AsyncMock()
+ creds_mgr.return_value.store.get_all_creds.return_value = saved
+ return await match_credentials_to_requirements(
+ "test-user", requirements, session_id="s1"
+ )
+
+ return await asyncio.create_task(turn())
+
+
+async def test_a_pinned_account_without_the_scope_does_not_switch_accounts():
+ # The schedule runs on "work". A step needing `repo` must not quietly run
+ # on "personal", which has it: that is the switch the pin exists to stop.
+ from backend.copilot.credential_selection import CredentialPin
+
+ field = CredentialsFieldInfo.model_validate(
+ {
+ "credentials_provider": ["github"],
+ "credentials_types": ["oauth2"],
+ "credentials_scopes": ["repo"],
+ },
+ by_alias=True,
+ )
+ matched, missing = await _match_with_pins(
+ [_github_oauth("personal", ["repo"]), _github_oauth("work", ["read:user"])],
+ {"credentials": field},
+ {"github": CredentialPin(id="work", title="Work")},
+ )
+ assert matched == {}
+ assert len(missing) == 1
+
+
+async def test_a_pin_for_one_host_leaves_the_credentials_for_other_hosts():
+ from backend.copilot.credential_selection import CredentialPin
+
+ other_host = HostScopedCredentials(
+ id="other-host",
+ provider="http",
+ host="api.other.com",
+ headers={"Authorization": SecretStr("Bearer token")},
+ title="other-host",
+ )
+ field = CredentialsFieldInfo.model_validate(
+ {
+ "credentials_provider": ["http"],
+ "credentials_types": ["host_scoped"],
+ "discriminator": "url",
+ "discriminator_values": ["https://api.other.com/v1"],
+ },
+ by_alias=True,
+ )
+ matched, _ = await _match_with_pins(
+ [_host_cred("example-host"), other_host],
+ {"credentials": field},
+ {"http": CredentialPin(id="example-host", title="example-host")},
+ )
+ assert matched["credentials"].id == "other-host"
+
+
+async def test_the_error_names_a_pinned_account_that_cannot_do_the_step():
+ import asyncio
+
+ from backend.copilot.credential_selection import (
+ CredentialPin,
+ set_turn_credential_pins,
+ )
+ from backend.copilot.tools.helpers import unattended_missing_credentials_error
+
+ async def turn():
+ set_turn_credential_pins({"github": CredentialPin(id="work", title="Work")})
+ with patch(
+ "backend.copilot.tools.helpers.get_user_credentials",
+ AsyncMock(return_value=[_github_oauth("work", ["read:user"])]),
+ ):
+ return await unattended_missing_credentials_error(
+ "Block 'Create PR'",
+ {"credentials": {"provider": "github", "types": ["oauth2"]}},
+ "s1",
+ "test-user",
+ None,
+ )
+
+ result = await asyncio.create_task(turn())
+ assert result.error == "pinned_credential_unusable"
+ assert "'Work'" in result.message
+ assert "did not switch" in result.message
+
+
+async def test_a_pin_for_one_host_is_not_blamed_for_a_step_on_another():
+ # A host pin never filters another host's credentials (see keep_to_pins),
+ # so a step on a host with none failed for want of one, as it would
+ # unpinned. Naming the pinned account would send the user to fix the wrong
+ # credential.
+ import asyncio
+
+ from backend.copilot.credential_selection import (
+ CredentialPin,
+ set_turn_credential_pins,
+ )
+ from backend.copilot.tools.helpers import unattended_missing_credentials_error
+
+ async def turn():
+ set_turn_credential_pins(
+ {"http": CredentialPin(id="example-host", title="example-host")}
+ )
+ with (
+ patch(
+ "backend.copilot.tools.helpers.get_user_credentials",
+ AsyncMock(return_value=[_host_cred("example-host")]),
+ ),
+ patch(
+ "backend.copilot.tools.helpers.ungranted_credential_hint",
+ AsyncMock(return_value=""),
+ ),
+ ):
+ return await unattended_missing_credentials_error(
+ "Block 'Send Web Request'",
+ {"credentials": {"provider": "http", "types": ["host_scoped"]}},
+ "s1",
+ "test-user",
+ None,
+ )
+
+ result = await asyncio.create_task(turn())
+ assert result.error == "missing_credentials"
+ assert "has no http credential" in result.message
+ assert "example-host" not in result.message
diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.py
index a318618741..69b6d25767 100644
--- a/autogpt_platform/backend/backend/executor/scheduler.py
+++ b/autogpt_platform/backend/backend/executor/scheduler.py
@@ -29,6 +29,7 @@ from sqlalchemy import MetaData, create_engine
from backend.api.features.experts.models import ExpertRoutine
from backend.copilot.active_turns import ConcurrentTurnLimitError
+from backend.copilot.credential_selection import CredentialPins
from backend.copilot.dream.scheduling import (
COMMUNITY_REBUILD_REGISTRATION_PREFIX,
NIGHTLY_BATCH_REGISTRATION_PREFIX,
@@ -552,6 +553,11 @@ async def _execute_copilot_turn(**kwargs):
is_user_message=persist_as_user_turn,
tool_call_id="scheduled_followup",
tool_name="schedule_followup",
+ # Even when the target is the user's own chat, nobody is there to
+ # answer this turn's questions, e.g. which of two accounts to use.
+ unattended=True,
+ # So the accounts are the ones chosen when the schedule was made.
+ credential_pins=_credential_pins_for_turn(args, routine),
organization_id=args.organization_id,
team_id=args.team_id,
llm_auth_provider=target_session.metadata.llm_auth_provider,
@@ -631,6 +637,26 @@ async def _execute_copilot_turn(**kwargs):
)
+def _credential_pins_for_turn(
+ args: "CopilotTurnJobArgs", routine: ExpertRoutine | None
+) -> CredentialPins:
+ """The accounts this fire runs on, chosen in the chat that made it.
+
+ A routine keeps them on its row, so switching it off and on again, or
+ rewording it, keeps them; a follow-up keeps them in its job. A schedule
+ made before pins existed has none, and its turns take the first saved
+ credential when several fit (SECRT-2804).
+ """
+ pins = routine.credential_pins if routine is not None else args.credential_pins
+ if not pins:
+ logger.info(
+ "Copilot turn schedule %s has no pinned credentials; where several "
+ "fit, its turn uses the first saved one",
+ args.schedule_id,
+ )
+ return pins
+
+
def _session_id_label(args: "CopilotTurnJobArgs") -> str:
"""Log-safe short label for a (possibly None) session_id."""
return args.session_id[:12] if args.session_id else "<new>"
@@ -726,6 +752,9 @@ async def _reschedule_one_shot(
# an ungranted routine that merely lost a race to the concurrency
# cap would come back with everything the mute exists to withhold.
routine_id=args.routine_id,
+ # And the accounts it was set up to run on, or the retry would
+ # take the first saved one instead.
+ credential_pins=args.credential_pins,
)
logger.info(
f"Rescheduled one-shot copilot turn for session "
@@ -1690,6 +1719,10 @@ class CopilotTurnJobArgs(BaseModel):
# decides whether the turn may touch a connected service at all. None keeps
# ordinary ``schedule_followup`` jobs on their existing path.
routine_id: str | None = None
+ # ``{provider: pin}``: the account the user chose for each provider when
+ # the follow-up was made, which every fire runs on (SECRT-2804). A routine
+ # keeps its pins on its row instead. Empty on rows persisted before pins.
+ credential_pins: CredentialPins = Field(default_factory=dict)
def _timezone_from_job(job_obj: JobObj) -> str:
@@ -2322,6 +2355,7 @@ class Scheduler(AppService):
team_id: str | None = None,
expert_id: str | None = None,
routine_id: str | None = None,
+ credential_pins: CredentialPins | None = None,
) -> CopilotTurnJobInfo:
"""Schedule a copilot turn at a future time.
@@ -2359,6 +2393,7 @@ class Scheduler(AppService):
team_id=team_id,
expert_id=expert_id,
routine_id=routine_id,
+ credential_pins=credential_pins or {},
)
default_name = (
f"copilot turn (session {session_id[:8]})"
diff --git a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
index 8a609e4b4d..6276e56ccb 100644
--- a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
+++ b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py
@@ -16,6 +16,7 @@ from apscheduler.triggers.cron import CronTrigger
from apscheduler.triggers.date import DateTrigger
from backend.api.features.experts.models import ExpertRoutine
+from backend.copilot.credential_selection import CredentialPin
from backend.copilot.executor.utils import ScheduledTurnOrigin
from backend.copilot.permissions import (
CAPABILITY_GATE_NAMES,
@@ -338,6 +339,93 @@ async def test_execute_copilot_turn_creates_fresh_session_when_session_id_is_non
assert call_kwargs["scheduled"] == ScheduledTurnOrigin(schedule_id="sched-1")
+async def test_execute_copilot_turn_into_the_users_chat_is_marked_unattended():
+ """A follow-up pinned to the user's own chat still has nobody watching it,
+ so its tools must not hand questions back to the user (SECRT-2804)."""
+ args = _args()
+ mock_schedule_turn = AsyncMock()
+ users_chat = MagicMock(session_id="session-1", expert_id=None)
+
+ with (
+ patch("backend.executor.scheduler.schedule_turn", new=mock_schedule_turn),
+ patch(
+ "backend.executor.scheduler.get_chat_session",
+ new=AsyncMock(return_value=users_chat),
+ ),
+ ):
+ await _execute_copilot_turn(**args.model_dump(mode="json"))
+
+ mock_schedule_turn.assert_awaited_once()
+ assert mock_schedule_turn.call_args.kwargs["unattended"] is True
+
+
+_WORK_KEY = CredentialPin(id="exa-new", title="Work key")
+
+
+async def _fire_into_users_chat(args: CopilotTurnJobArgs, routine=None) -> dict:
+ mock_schedule_turn = AsyncMock()
+ users_chat = MagicMock(session_id="session-1", expert_id=None)
+ store = MagicMock(get_routine=AsyncMock(return_value=routine))
+ with (
+ patch("backend.executor.scheduler.schedule_turn", new=mock_schedule_turn),
+ patch(
+ "backend.executor.scheduler.get_chat_session",
+ new=AsyncMock(return_value=users_chat),
+ ),
+ patch(f"{_SCHEDULER_PATH}.experts_db", return_value=store),
+ ):
+ await _execute_copilot_turn(**args.model_dump(mode="json"))
+ mock_schedule_turn.assert_awaited_once()
+ return mock_schedule_turn.call_args.kwargs
+
+
+async def test_a_followups_turn_runs_on_the_accounts_picked_when_it_was_made():
+ kwargs = await _fire_into_users_chat(_args(credential_pins={"exa": _WORK_KEY}))
+ assert kwargs["credential_pins"] == {"exa": _WORK_KEY}
+
+
+async def test_a_routines_turn_runs_on_the_accounts_on_its_row():
+ """A routine keeps its pins on the row, so they survive it being switched
+ off and on, which re-creates its jobs."""
+ routine = ExpertRoutine(
+ id="routine-1",
+ title="Briefing",
+ prompt="Brief me",
+ crons=["0 9 * * *"],
+ enabled=True,
+ grants_credentials=True,
+ credential_pins={"exa": _WORK_KEY},
+ )
+ kwargs = await _fire_into_users_chat(
+ _args(routine_id="routine-1", run_at=None, cron="0 9 * * *"), routine
+ )
+ assert kwargs["credential_pins"] == {"exa": _WORK_KEY}
+
+
+async def test_a_schedule_made_before_pins_fires_with_none(caplog):
+ legacy = CopilotTurnJobArgs.model_validate(
+ {"user_id": "user-1", "session_id": "session-1", "message": "check CI"}
+ )
+ with caplog.at_level(logging.INFO, logger=_SCHEDULER_PATH):
+ kwargs = await _fire_into_users_chat(legacy)
+ assert kwargs["credential_pins"] == {}
+ assert "no pinned credentials" in caplog.text
+
+
+async def test_reschedule_after_cap_keeps_the_pinned_accounts():
+ args = _args(cap_retry_count=0, credential_pins={"exa": _WORK_KEY})
+ 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["credential_pins"] == {"exa": _WORK_KEY}
+
+
@pytest.mark.asyncio
async def test_execute_copilot_turn_creates_fresh_expert_session_in_same_scope():
args = _args(
diff --git a/autogpt_platform/backend/migrations/20261002120000_routine_credential_pins/migration.sql b/autogpt_platform/backend/migrations/20261002120000_routine_credential_pins/migration.sql
new file mode 100644
index 0000000000..a7ab134236
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20261002120000_routine_credential_pins/migration.sql
@@ -0,0 +1,3 @@
+-- The account each turn of a routine uses where the owner has several for one
+-- provider, chosen in the chat that set it up (SECRT-2804).
+ALTER TABLE "ExpertRoutine" ADD COLUMN "credentialPins" JSONB;
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 40cfe6805f..9fd355e203 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -1363,6 +1363,10 @@ model ExpertRoutine {
// Seeded and shared rows always arrive false; only an owner binding this
// routine to their connections sets it.
grantsCredentials Boolean @default(false)
+ // {provider: {id, title}}: the account each turn uses where the owner has
+ // several for one provider, chosen in the chat that set the routine up. A
+ // pinned account that is gone fails the step instead of switching accounts.
+ credentialPins Json?
// Mirrors AgentPreset.deactivatedByExpertArchive: re-hire resumes exactly
// what archiving paused, never one the owner had switched off themselves.
pausedByExpertArchive Boolean @default(false)
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 110371bf5e..30cb238083 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -19739,6 +19739,13 @@
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Routine Id"
},
+ "credential_pins": {
+ "additionalProperties": {
+ "$ref": "#/components/schemas/CredentialPin"
+ },
+ "type": "object",
+ "title": "Credential Pins"
+ },
"id": { "type": "string", "title": "Id" },
"name": { "type": "string", "title": "Name" },
"next_run_time": { "type": "string", "title": "Next Run Time" },
@@ -20264,6 +20271,16 @@
"required": ["creators", "pagination"],
"title": "CreatorsResponse"
},
+ "CredentialPin": {
+ "properties": {
+ "id": { "type": "string", "title": "Id" },
+ "title": { "type": "string", "title": "Title", "default": "" }
+ },
+ "type": "object",
+ "required": ["id"],
+ "title": "CredentialPin",
+ "description": "The account a schedule runs one provider on, chosen when it was made.\n\nThe title is kept so a run can still name the account after it was\ndeleted, which is when the name matters most."
+ },
"CredentialRejection": {
"properties": {
"provider": { "type": "string", "title": "Provider" },