Skip to content

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

feat(platform): alert the owner when a scheduled chat pauses, list it on Home, resume it on reconnect (#15377)

Nicholas Tindleb8dda415406b
diff --git a/autogpt_platform/backend/backend/api/features/home/attention.py b/autogpt_platform/backend/backend/api/features/home/attention.py
index 3fa4763721..d44e8e4ece 100644
--- a/autogpt_platform/backend/backend/api/features/home/attention.py
+++ b/autogpt_platform/backend/backend/api/features/home/attention.py
@@ -11,6 +11,7 @@ from backend.copilot.briefing.outcome import as_utc, run_link
from backend.copilot.constants import AUTOPILOT_NAME
from backend.copilot.gate.review import GATE_NODE_PREFIX, GateReviewPayload
from backend.copilot.model import ChatSessionInfo, PendingQuestion
+from backend.copilot.scheduled_chats.service import PausedScheduledChat
from backend.executor.scheduler import CopilotTurnJobInfo, GraphExecutionJobInfo
from .helpers import setup_count, to_home_expert
@@ -28,12 +29,14 @@ def compose_attention_items(
schedules: list[GraphExecutionJobInfo | CopilotTurnJobInfo],
credits_balance: int | None,
questions: list[ChatSessionInfo] | None = None,
+ paused_chats: list[PausedScheduledChat] | None = None,
) -> list[HomeAttentionItem]:
expert_by_id = {expert.id: expert for expert in experts}
items = [_review_attention(review, now) for review in reviews]
items.extend(
_expert_attention(expert) for expert in experts if _needs_attention(expert)
)
+ items.extend(_paused_chat_attention(chat) for chat in paused_chats or [])
items.extend(
_question_attention(session, question, expert_by_id)
for session, question in _open_questions(questions or [])
@@ -206,6 +209,27 @@ def _expert_attention(expert: Expert) -> HomeAttentionItem:
)
+def _paused_chat_attention(chat: PausedScheduledChat) -> HomeAttentionItem:
+ """A scheduled chat paused after failing the same way three runs in a
+ row (SECRT-2879). The fix is on the card in its chat, so that is where
+ the item goes."""
+ href = (
+ f"/copilot?sessionId={quote(chat.session_id)}"
+ if chat.session_id
+ else "/library/followups"
+ )
+ return HomeAttentionItem(
+ id=f"paused-chat-{chat.schedule_key}",
+ kind="paused",
+ priority="high",
+ title=f"Scheduled chat “{chat.title}”",
+ description=chat.summary,
+ why_it_matters="It won't run again until it is fixed and resumed.",
+ created_at=as_utc(chat.paused_at),
+ primary_action=HomeAction(label="Fix it", href=href),
+ )
+
+
def _open_questions(
sessions: list[ChatSessionInfo],
) -> list[tuple[ChatSessionInfo, PendingQuestion]]:
diff --git a/autogpt_platform/backend/backend/api/features/home/attention_test.py b/autogpt_platform/backend/backend/api/features/home/attention_test.py
index d908d42172..9a3218ea97 100644
--- a/autogpt_platform/backend/backend/api/features/home/attention_test.py
+++ b/autogpt_platform/backend/backend/api/features/home/attention_test.py
@@ -9,6 +9,7 @@ from backend.copilot.constants import AUTOPILOT_NAME
from backend.copilot.gate.references import Reference
from backend.copilot.gate.review import node_id_for, review_payload
from backend.copilot.model import ChatSessionInfo, ChatSessionMetadata, PendingQuestion
+from backend.copilot.scheduled_chats.service import PausedScheduledChat
from backend.executor.scheduler import GraphExecutionJobInfo
from .attention import compose_attention_items
@@ -204,6 +205,61 @@ def test_paused_expert_explains_a_breached_budget() -> None:
assert items[0].description == "Weekly budget reached: 500 of 500 credits."
+def test_a_paused_scheduled_chat_points_at_the_card_in_its_chat() -> None:
+ """SECRT-2879: the fix (Reconnect, Resume) is on the card in the chat the
+ last run went to, so the item opens that chat."""
+ paused = PausedScheduledChat(
+ schedule_key="routine-1",
+ title="Morning briefing",
+ session_id="session 1",
+ reason="connection",
+ provider="twitter",
+ summary="Paused: can't use Twitter",
+ paused_at=NOW - timedelta(hours=1),
+ )
+
+ items = compose_attention_items(
+ now=NOW,
+ experts=[],
+ reviews=[],
+ schedules=[],
+ credits_balance=None,
+ paused_chats=[paused],
+ )
+
+ assert len(items) == 1
+ item = items[0]
+ assert item.kind == "paused" and item.priority == "high"
+ assert item.title == "Scheduled chat “Morning briefing”"
+ assert item.description == "Paused: can't use Twitter"
+ assert item.primary_action is not None
+ assert item.primary_action.href == "/copilot?sessionId=session%201"
+
+
+def test_a_paused_scheduled_chat_without_a_chat_opens_the_scheduled_page() -> None:
+ paused = PausedScheduledChat(
+ schedule_key="sched-1",
+ title="Check CI",
+ session_id=None,
+ reason="error",
+ provider=None,
+ summary="Paused: keeps failing",
+ paused_at=NOW,
+ )
+
+ items = compose_attention_items(
+ now=NOW,
+ experts=[],
+ reviews=[],
+ schedules=[],
+ credits_balance=None,
+ paused_chats=[paused],
+ )
+
+ assert items[0].primary_action is not None
+ assert items[0].primary_action.href == "/library/followups"
+
+
def test_paused_expert_without_a_breached_budget_stays_generic() -> None:
items = compose_attention_items(
now=NOW,
diff --git a/autogpt_platform/backend/backend/api/features/home/compose.py b/autogpt_platform/backend/backend/api/features/home/compose.py
index 47dac853e9..0a2b773b3c 100644
--- a/autogpt_platform/backend/backend/api/features/home/compose.py
+++ b/autogpt_platform/backend/backend/api/features/home/compose.py
@@ -5,6 +5,7 @@ from backend.api.features.graph_executions.review.model import PendingHumanRevie
from backend.api.features.library.model import LibraryAgentRef
from backend.copilot.briefing.models import BriefingContent
from backend.copilot.model import ChatSessionInfo
+from backend.copilot.scheduled_chats.service import PausedScheduledChat
from backend.data.activity_event import ActivityEvent
from backend.data.execution import ExecutionStatus, GraphExecutionMeta
from backend.data.execution_cost_summary import UserExecutionCostSummary
@@ -39,6 +40,7 @@ def compose_home_dashboard(
persisted_briefing: BriefingContent | None = None,
work_events: list[ActivityEvent] | None = None,
session_titles: dict[str, str | None] | None = None,
+ paused_chats: list[PausedScheduledChat] | None = None,
) -> HomeDashboardResponse:
hired = [
expert
@@ -78,6 +80,7 @@ def compose_home_dashboard(
schedules=schedules,
credits_balance=credits_balance,
questions=questions,
+ paused_chats=paused_chats,
),
briefing=compose_briefing(
now=now,
diff --git a/autogpt_platform/backend/backend/api/features/home/service.py b/autogpt_platform/backend/backend/api/features/home/service.py
index 8317cff47d..9e878ecae2 100644
--- a/autogpt_platform/backend/backend/api/features/home/service.py
+++ b/autogpt_platform/backend/backend/api/features/home/service.py
@@ -18,6 +18,8 @@ from backend.api.features.library import db as library_db
from backend.copilot import db as chat_db
from backend.copilot.briefing.models import BriefingContent
from backend.copilot.model import ChatSessionInfo
+from backend.copilot.scheduled_chats import service as scheduled_chats
+from backend.copilot.scheduled_chats.service import PausedScheduledChat
from backend.data import activity_event as activity_db
from backend.data import briefing as briefing_db
from backend.data import execution as execution_db
@@ -59,6 +61,7 @@ class HomeSourceData(BaseModel):
credits_balance: int | None
questions: list[ChatSessionInfo]
work_events: list[activity_db.ActivityEvent]
+ paused_chats: list[PausedScheduledChat]
timezone_name: str
@@ -107,6 +110,7 @@ async def build_home_dashboard(
persisted_briefing=persisted_briefing,
work_events=data.work_events,
session_titles=session_titles,
+ paused_chats=data.paused_chats,
)
@@ -189,6 +193,7 @@ async def _load_home_source_data(
work_events_task = asyncio.create_task(
_get_work_events(user_id=user_id, since=week_start)
)
+ paused_chats_task = asyncio.create_task(_get_paused_chats(user_id=user_id))
user_task = asyncio.create_task(user_db.get_user_by_id(user_id))
# Gather rather than awaiting one by one: a failure in the first task would
# otherwise leave the rest detached with their exceptions never retrieved.
@@ -201,6 +206,7 @@ async def _load_home_source_data(
credits_task,
questions_task,
work_events_task,
+ paused_chats_task,
user_task,
]
await asyncio.gather(*started)
@@ -216,6 +222,7 @@ async def _load_home_source_data(
credits_balance=credits_task.result(),
questions=questions_task.result(),
work_events=work_events_task.result(),
+ paused_chats=paused_chats_task.result(),
timezone_name=get_user_timezone_or_utc(user.timezone if user else None),
)
@@ -241,6 +248,18 @@ async def _get_schedules(
return []
+async def _get_paused_chats(*, user_id: str) -> list[PausedScheduledChat]:
+ # Fail-soft like schedules: a broken read costs these items, not the page.
+ try:
+ return await scheduled_chats.list_paused_scheduled_chats(user_id)
+ except Exception:
+ logger.warning(
+ "Home could not load paused scheduled chats for user %s",
+ user_id[:_LOG_ID_CHARS],
+ )
+ return []
+
+
async def _get_pending_questions(*, user_id: str) -> list[ChatSessionInfo]:
# Fail-soft like schedules and credits: a chat that was deleted or whose
# metadata no longer parses must cost the user one row, not the page.
diff --git a/autogpt_platform/backend/backend/api/features/home/service_test.py b/autogpt_platform/backend/backend/api/features/home/service_test.py
index 1d3fe8d95f..36382bb46d 100644
--- a/autogpt_platform/backend/backend/api/features/home/service_test.py
+++ b/autogpt_platform/backend/backend/api/features/home/service_test.py
@@ -6,6 +6,7 @@ from autogpt_libs.auth.models import RequestContext
from pytest_mock import MockerFixture
from backend.copilot.briefing.models import BriefingContent, BriefingRunItem
+from backend.copilot.scheduled_chats.service import PausedScheduledChat
from backend.data.execution import ExecutionStatus, GraphExecutionMeta
from backend.data.execution_cost_summary import UserExecutionCostSummary
from backend.util.feature_flag import Flag
@@ -104,6 +105,10 @@ def home_dependencies(mocker: MockerFixture):
"backend.api.features.home.service.activity_db.list_activity_events",
AsyncMock(return_value=[]),
)
+ mocker.patch(
+ "backend.api.features.home.service.scheduled_chats.list_paused_scheduled_chats",
+ AsyncMock(return_value=[]),
+ )
def _stored_briefing(**overrides) -> BriefingContent:
@@ -410,6 +415,46 @@ async def test_scheduler_and_credit_failures_degrade_instead_of_failing_the_page
assert dashboard.briefing.outcomes[0].title == "Booked the flight."
+async def test_a_paused_scheduled_chat_needs_attention(
+ mocker: MockerFixture, home_dependencies
+) -> None:
+ mocker.patch(
+ "backend.api.features.home.service.scheduled_chats.list_paused_scheduled_chats",
+ AsyncMock(
+ return_value=[
+ PausedScheduledChat(
+ schedule_key="sched-1",
+ title="Discord monitor",
+ session_id="session-1",
+ reason="connection",
+ provider="discord",
+ summary="Paused: can't use Discord",
+ paused_at=datetime.now(timezone.utc),
+ )
+ ]
+ ),
+ )
+
+ dashboard = await build_home_dashboard(user_id="user-1")
+
+ assert [item.id for item in dashboard.attention] == ["paused-chat-sched-1"]
+
+
+async def test_a_paused_chat_read_that_fails_costs_only_those_items(
+ mocker: MockerFixture, home_dependencies
+) -> None:
+ mocker.patch(
+ "backend.api.features.home.service.scheduled_chats.list_paused_scheduled_chats",
+ AsyncMock(side_effect=RuntimeError("db")),
+ )
+
+ dashboard = await build_home_dashboard(user_id="user-1")
+
+ assert dashboard.attention == []
+
+
class TestPendingQuestionsFlagGate:
"""Question items ship with the expert-team surface: without the
hire-experts flag, Home must not just return an empty list but must
diff --git a/autogpt_platform/backend/backend/api/features/integrations/codex_test.py b/autogpt_platform/backend/backend/api/features/integrations/codex_test.py
index 6daa0e8fd9..077950830e 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/codex_test.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/codex_test.py
@@ -222,6 +222,10 @@ def test_codex_callback_persists_one_safe_credential():
"backend.api.features.integrations.router.codex_login_coordinator"
) as coordinator,
patch("backend.api.features.integrations.router.creds_manager") as manager,
+ patch(
+ "backend.api.features.integrations.router."
+ "resume_after_reconnect_in_background"
+ ) as resume,
):
manager.store.verify_state_token = AsyncMock(return_value=_oauth_state())
coordinator.complete = AsyncMock(return_value=credentials)
@@ -232,6 +236,9 @@ def test_codex_callback_persists_one_safe_credential():
)
assert response.status_code == 200
+ # Signing in again is the fix for a scheduled chat paused on ChatGPT.
+ resume.assert_called_once()
+ assert resume.call_args.args[1] == "codex"
assert response.json() == {
"id": "codex-credential",
"provider": "codex",
diff --git a/autogpt_platform/backend/backend/api/features/integrations/conftest.py b/autogpt_platform/backend/backend/api/features/integrations/conftest.py
index be2a64c56f..6dc5a36b13 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/conftest.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/conftest.py
@@ -1,8 +1,19 @@
"""Override session-scoped fixtures so unit tests run without the server."""
+from unittest.mock import MagicMock
+
import pytest
@pytest.fixture(scope="session")
def server():
yield None
+
+
[email protected](autouse=True)
+def resume_after_reconnect(mocker) -> MagicMock:
+ """A connect resumes the owner's paused scheduled chats in the background.
+ Without the server there are none, so the call is only recorded."""
+ return mocker.patch(
+ "backend.api.features.integrations.router.resume_after_reconnect_in_background"
+ )
diff --git a/autogpt_platform/backend/backend/api/features/integrations/reconnect_routes_test.py b/autogpt_platform/backend/backend/api/features/integrations/reconnect_routes_test.py
new file mode 100644
index 0000000000..88629420a8
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/integrations/reconnect_routes_test.py
@@ -0,0 +1,101 @@
+"""A connect resumes the scheduled chats waiting on its provider (SECRT-2879)."""
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import fastapi
+import fastapi.testclient
+import pytest
+from autogpt_libs.auth.jwt_utils import get_jwt_payload
+from pydantic import SecretStr
+
+from backend.api.features.integrations.router import router
+from backend.data.model import OAuth2Credentials, OAuthState
+
+app = fastapi.FastAPI()
+app.include_router(router)
+client = fastapi.testclient.TestClient(app, raise_server_exceptions=False)
+
+ROUTER = "backend.api.features.integrations.router"
+SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"]
+
+
[email protected](autouse=True)
+def setup_auth(mock_jwt_user):
+ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]
+ yield
+ app.dependency_overrides.clear()
+
+
+def _oauth_callback(state: OAuthState | None):
+ handler = MagicMock()
+ handler.handle_default_scopes.side_effect = lambda scopes: scopes
+ handler.exchange_code_for_tokens = AsyncMock(
+ return_value=OAuth2Credentials(
+ provider="google",
+ title="My Google",
+ access_token=SecretStr("ya29.access-token"),
+ refresh_token=SecretStr("1//refresh-token"),
+ scopes=SCOPES,
+ username="[email protected]",
+ )
+ )
+ with (
+ patch(f"{ROUTER}._get_provider_oauth_handler", return_value=handler),
+ patch(f"{ROUTER}.creds_manager") as mock_mgr,
+ ):
+ mock_mgr.store.verify_state_token = AsyncMock(return_value=state)
+ mock_mgr.store.get_creds_by_provider = AsyncMock(return_value=[])
+ mock_mgr.create = AsyncMock()
+ return client.post(
+ "/google/callback", json={"code": "auth-code", "state_token": "state"}
+ )
+
+
+def _create_api_key(create: AsyncMock):
+ with patch(f"{ROUTER}.creds_manager") as mock_mgr:
+ mock_mgr.create = create
+ return client.post(
+ "/openai/credentials",
+ json={
+ "id": "new-cred",
+ "provider": "openai",
+ "type": "api_key",
+ "title": "New Key",
+ "api_key": "sk-new",
+ },
+ )
+
+
+def test_an_oauth_connect_resumes_what_waits_on_the_provider(
+ resume_after_reconnect: MagicMock, test_user_id: str
+):
+ state = OAuthState(
+ token="state", provider="google", expires_at=9999999999, scopes=SCOPES
+ )
+
+ assert _oauth_callback(state).status_code == 200
+
+ resume_after_reconnect.assert_called_once_with(test_user_id, "google")
+
+
+def test_a_failed_oauth_connect_resumes_nothing(resume_after_reconnect: MagicMock):
+ assert _oauth_callback(None).status_code == 400
+
+ resume_after_reconnect.assert_not_called()
+
+
+def test_an_api_key_resumes_what_waits_on_the_provider(
+ resume_after_reconnect: MagicMock, test_user_id: str
+):
+ assert _create_api_key(AsyncMock()).status_code == 201
+
+ resume_after_reconnect.assert_called_once_with(test_user_id, "openai")
+
+
+def test_an_api_key_that_was_not_stored_resumes_nothing(
+ resume_after_reconnect: MagicMock,
+):
+ response = _create_api_key(AsyncMock(side_effect=RuntimeError("db down")))
+
+ assert response.status_code == 500
+ resume_after_reconnect.assert_not_called()
diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.py
index f4ea249e1f..41500c44ce 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/router.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py
@@ -23,6 +23,9 @@ from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR, HTTP_502_BAD_GATEWA
from backend.api.features.library.db import set_preset_webhook, update_preset
from backend.api.features.library.model import LibraryAgentPreset
from backend.copilot.rate_limit import enforce_payment_paywall, is_user_paywalled
+from backend.copilot.scheduled_chats.reconnect import (
+ resume_after_reconnect_in_background,
+)
from backend.data.db_accessors import experts_db
from backend.data.execution import ExecutionTrigger
from backend.data.graph import NodeModel, get_graph, set_node_webhook
@@ -369,7 +372,10 @@ async def callback(
if provider == ProviderName.CODEX:
await enforce_codex_access_http(user_id)
valid_state = await _verify_callback_state(user_id, state_token, provider)
- return await _complete_codex_login(user_id, code, valid_state)
+ connected = await _complete_codex_login(user_id, code, valid_state)
+ # As every other connect: the fix for a chat paused on it.
+ resume_after_reconnect_in_background(user_id, provider.value)
+ return connected
failure_class: product_analytics.OAuthExchangeFailureClass = "invalid_state"
# Everything secret we send the provider, in case its error echoes it back.
@@ -411,6 +417,8 @@ async def callback(
credential_type=credentials.type,
method="oauth",
)
+ # Reconnecting is the fix for a scheduled chat paused on this provider.
+ resume_after_reconnect_in_background(user_id, provider.value)
return to_meta_response(credentials)
@@ -862,6 +870,7 @@ async def device_auth_poll(
credential_type=credentials.type,
method="device_code",
)
+ resume_after_reconnect_in_background(user_id, provider.value)
return DeviceAuthPollResponse(
status="approved",
credentials=to_meta_response(credentials),
@@ -1108,6 +1117,7 @@ async def create_credentials(
credential_type=credentials.type,
method="manual",
)
+ resume_after_reconnect_in_background(user_id, provider.value)
return to_meta_response(credentials)
diff --git a/autogpt_platform/backend/backend/api/features/integrations/router_test.py b/autogpt_platform/backend/backend/api/features/integrations/router_test.py
index 1fe91fd01f..d2d7cf2e1a 100644
--- a/autogpt_platform/backend/backend/api/features/integrations/router_test.py
+++ b/autogpt_platform/backend/backend/api/features/integrations/router_test.py
@@ -1125,7 +1125,9 @@ class TestDeviceAuthEndpoints:
mock_mgr.store.consume_state_token.assert_not_awaited()
- def test_poll_race_loser_does_not_create_a_second_credential(self):
+ def test_poll_race_loser_does_not_create_a_second_credential(
+ self, resume_after_reconnect: MagicMock
+ ):
"""Two polls can both see an approval; only the one that consumes wins.
`consume_state_token` returning None means another poll already handled
@@ -1184,6 +1186,7 @@ class TestDeviceAuthEndpoints:
assert response.json()["status"] == "approved"
assert response.json()["credentials"] is None
mock_merge.assert_not_awaited()
+ resume_after_reconnect.assert_not_called()
def test_poll_does_not_leak_upstream_error_text(self):
handler = MagicMock()
@@ -1204,7 +1207,9 @@ class TestDeviceAuthEndpoints:
assert response.status_code == 502
assert "internal-host-1" not in response.text
- def test_poll_stores_the_credential_on_the_winning_approval(self):
+ def test_poll_stores_the_credential_on_the_winning_approval(
+ self, resume_after_reconnect: MagicMock
+ ):
"""The primary success path: consume wins, credential is stored.
Every other approved-status test here makes `consume_state_token`
@@ -1264,6 +1269,8 @@ class TestDeviceAuthEndpoints:
assert stored.scopes == ["userinfo:read", "payment_methods.agentic"]
# And no secret rides along in the response.
assert "do-not-leak" not in response.text
+ # Only the winner resumes the scheduled chats this connect fixes.
+ resume_after_reconnect.assert_called_once_with(JWT_USER_ID, "stripe_link")
def test_poll_maps_a_missing_user_row_to_an_invalid_token(self):
"""A caller with no backend User row raises a Prisma RecordNotFound in
diff --git a/autogpt_platform/backend/backend/api/features/schedules/routes.py b/autogpt_platform/backend/backend/api/features/schedules/routes.py
index 3eddfe4361..09ed2da7f6 100644
--- a/autogpt_platform/backend/backend/api/features/schedules/routes.py
+++ b/autogpt_platform/backend/backend/api/features/schedules/routes.py
@@ -14,6 +14,7 @@ from backend.api.features.schedules.model import (
ScheduleUpdateRequest,
)
from backend.copilot.rate_limit import enforce_payment_paywall
+from backend.copilot.scheduled_chats import forget
from backend.copilot.scheduled_chats import service as scheduled_chats
from backend.data import graph as graph_db
from backend.data.onboarding import OnboardingStep, complete_onboarding_step
@@ -245,7 +246,7 @@ async def _forget_scheduled_chat(user_id: str, schedule_id: str) -> None:
answered: a 500 would say the delete failed. A streak left behind keeps
the chat listed as paused, and deleting it from there again clears it."""
try:
- await scheduled_chats.forget_scheduled_chat(user_id, schedule_id)
+ await forget.forget_scheduled_chat(user_id, schedule_id)
except Exception:
logger.warning(
"Could not clear the failure streak of deleted schedule %s",
diff --git a/autogpt_platform/backend/backend/api/features/schedules/routes_test.py b/autogpt_platform/backend/backend/api/features/schedules/routes_test.py
index e147e94ee6..9f4f6efd14 100644
--- a/autogpt_platform/backend/backend/api/features/schedules/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/schedules/routes_test.py
@@ -233,7 +233,7 @@ def test_list_all_schedules_does_not_scope_to_a_graph(
def test_delete_schedule_returns_the_id(mocker: pytest_mock.MockFixture) -> None:
sched = _patch_scheduler(mocker, delete_schedule=AsyncMock())
mocker.patch(
- "backend.api.features.schedules.routes.scheduled_chats.forget_scheduled_chat",
+ "backend.api.features.schedules.routes.forget.forget_scheduled_chat",
AsyncMock(),
)
@@ -251,7 +251,7 @@ def test_deleting_a_schedule_forgets_its_failure_streak(
its alert, or answer Resume."""
_patch_scheduler(mocker, delete_schedule=AsyncMock())
forget = mocker.patch(
- "backend.api.features.schedules.routes.scheduled_chats.forget_scheduled_chat",
+ "backend.api.features.schedules.routes.forget.forget_scheduled_chat",
AsyncMock(),
)
@@ -270,7 +270,7 @@ def test_a_retried_delete_still_forgets_the_streak(
mocker, delete_schedule=AsyncMock(side_effect=NotFoundError("gone"))
)
forget = mocker.patch(
- "backend.api.features.schedules.routes.scheduled_chats.forget_scheduled_chat",
+ "backend.api.features.schedules.routes.forget.forget_scheduled_chat",
AsyncMock(),
)
@@ -285,7 +285,7 @@ def test_a_delete_whose_streak_cleanup_fails_still_reports_the_delete(
failed; the paused row it leaves is cleared by deleting it again."""
_patch_scheduler(mocker, delete_schedule=AsyncMock())
mocker.patch(
- "backend.api.features.schedules.routes.scheduled_chats.forget_scheduled_chat",
+ "backend.api.features.schedules.routes.forget.forget_scheduled_chat",
AsyncMock(side_effect=RuntimeError("database down")),
)
@@ -370,7 +370,7 @@ def test_delete_schedule_maps_not_found_to_404(
mocker, delete_schedule=AsyncMock(side_effect=NotFoundError("gone"))
)
mocker.patch(
- "backend.api.features.schedules.routes.scheduled_chats.forget_scheduled_chat",
+ "backend.api.features.schedules.routes.forget.forget_scheduled_chat",
AsyncMock(),
)
diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/alerts.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/alerts.py
new file mode 100644
index 0000000000..259106d1ad
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/alerts.py
@@ -0,0 +1,73 @@
+"""The email side of a paused scheduled chat (SECRT-2879).
+
+A pause raises a ``PAUSED_FAILURES`` alert condition. The alert engine decides
+what that becomes: an email where user email is on, a line in a coalesced one,
+or a card in the next Briefing. It never sends the same condition twice in a
+day. Resuming the chat, reconnecting the provider or a run that works resolves
+it, which also cancels a send still in its ten-minute debounce.
+
+Runs in the DatabaseManager, so it writes the condition directly. Best effort
+throughout: an alert that cannot be written must not undo the pause.
+"""
+
+import logging
+from urllib.parse import quote
+
+from backend.copilot.scheduled_chats.failure_notices import provider_name
+from backend.copilot.scheduled_chats.forget import alert_key
+from backend.copilot.scheduled_chats.outcomes import RunFailure
+from backend.data.alerts import raise_alert_condition
+from backend.notifications.alert_causes import PausedFailuresCause
+
+logger = logging.getLogger(__name__)
+
+FOLLOWUPS_PATH = "/library/followups"
+
+
+def paused_cause(
+ failure: RunFailure, *, title: str, failures: int, session_id: str | None
+) -> PausedFailuresCause:
+ """Reads as: Morning briefing paused itself, the step “Twitter connection”
+ failed on 3 consecutive runs. Its button opens the chat, where the card
+ has the fix."""
+ return PausedFailuresCause(
+ agent=title,
+ step=step_label(failure),
+ consecutive_failures=failures,
+ cta_path=(
+ f"/copilot?sessionId={quote(session_id)}" if session_id else FOLLOWUPS_PATH
+ ),
+ )
+
+
+def step_label(failure: RunFailure) -> str:
+ """What failed, named as a step of the scheduled chat. The email reads
+ "The step “Twitter connection” failed", so an unnamed provider gets a
+ label of its own rather than "a connected service connection"."""
+ name = provider_name(failure.provider)
+ if failure.kind == "connection":
+ return f"{name} connection" if failure.provider else "Connected account"
+ if failure.kind == "chat_link":
+ return f"Posting to {name}" if failure.provider else "Posting to chat"
+ if failure.key == "turn:max_turns_exhausted":
+ return "Step limit"
+ if failure.kind == "budget":
+ return "Spending limit"
+ if failure.tool:
+ return failure.tool.replace("_", " ").capitalize()
+ return "One of its steps"
+
+
+async def raise_paused(
+ user_id: str, schedule_key: str, cause: PausedFailuresCause
+) -> None:
+ try:
+ await raise_alert_condition(
+ user_id, cause.cause, alert_key(schedule_key), cause.model_dump(mode="json")
+ )
+ except Exception:
+ logger.warning(
+ "Could not raise the paused alert for scheduled chat %s",
+ schedule_key,
+ exc_info=True,
+ )
diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/alerts_test.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/alerts_test.py
new file mode 100644
index 0000000000..e56f5225fe
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/alerts_test.py
@@ -0,0 +1,72 @@
+from prisma.enums import AlertCause
+
+from backend.copilot.scheduled_chats.alerts import (
+ FOLLOWUPS_PATH,
+ alert_key,
+ paused_cause,
+ step_label,
+)
+from backend.copilot.scheduled_chats.outcomes import RunFailure
+
+_TWITTER = RunFailure(key="connection:twitter", kind="connection", provider="twitter")
+
+
+def test_a_paused_chat_reads_as_paused_itself_with_the_failing_step():
+ cause = paused_cause(
+ _TWITTER, title="Morning briefing", failures=3, session_id="session 1"
+ )
+
+ assert cause.cause == AlertCause.PAUSED_FAILURES
+ assert cause.headline == "Morning briefing paused itself"
+ assert cause.preheader == (
+ "The step “Twitter connection” failed on 3 consecutive runs."
+ )
+ # The button opens the chat, where the card has Reconnect and Resume.
+ assert cause.cta_path == "/copilot?sessionId=session%201"
+
+
+def test_without_a_chat_the_button_opens_the_scheduled_page():
+ cause = paused_cause(_TWITTER, title="B", failures=3, session_id=None)
+
+ assert cause.cta_path == FOLLOWUPS_PATH
+
+
+def test_step_labels():
+ assert step_label(_TWITTER) == "Twitter connection"
+ assert (
+ step_label(
+ RunFailure(key="chat_link:discord", kind="chat_link", provider="discord")
+ )
+ == "Posting to Discord"
+ )
+ assert (
+ step_label(RunFailure(key="turn:max_budget_exhausted", kind="budget"))
+ == "Spending limit"
+ )
+ assert (
+ step_label(RunFailure(key="turn:max_turns_exhausted", kind="budget"))
+ == "Step limit"
+ )
+ assert (
+ step_label(RunFailure(key="tool:run_agent:x", kind="error", tool="run_agent"))
+ == "Run agent"
+ )
+
+
+def test_a_step_with_no_provider_named_still_reads_as_a_step():
+ """The email reads "The step “…” failed", so a connection or chat
+ platform it couldn't name gets a label of its own."""
+ assert (
+ step_label(
+ RunFailure(key="connection:run_block", kind="connection", tool="run_block")
+ )
+ == "Connected account"
+ )
+ assert (
+ step_label(RunFailure(key="chat_link:post", kind="chat_link", tool="post"))
+ == "Posting to chat"
+ )
+
+
+def test_one_alert_per_scheduled_chat():
+ assert alert_key("routine-1") == "scheduled_chat:routine-1"
diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/forget.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/forget.py
index 3c0c0b5e77..9bdbb983c1 100644
--- a/autogpt_platform/backend/backend/copilot/scheduled_chats/forget.py
+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/forget.py
@@ -1,16 +1,68 @@
-"""Dropping a routine's failure streak once its owner switches it off.
+"""Dropping a scheduled chat's failure streak once its owner deletes it or
+switches it off, and withdrawing its pause alert.
-Apart from ``service`` so the routines layer can call it: ``service`` reaches
-the copilot's tools, and the tools reach the routines layer.
+Apart from ``service`` and ``alerts`` so the routines layer and the copilot's
+own tools can call it: both reach the copilot's tools, and the tools reach the
+routines layer.
"""
-from prisma.models import ScheduledChatStreak
+import logging
+
+from prisma.models import ExpertRoutine, ScheduledChatStreak
+from prisma.types import ExpertRoutineWhereInput
+
+from backend.data.alerts import resolve_alert_condition
+
+logger = logging.getLogger(__name__)
+
+
+def alert_key(schedule_key: str) -> str:
+ return f"scheduled_chat:{schedule_key}"
+
+
+async def resolve_alert(user_id: str, schedule_key: str) -> None:
+ """Withdraw the chat's pause alert. Best effort: one left open only means
+ an email about a chat that runs again."""
+ try:
+ await resolve_alert_condition(user_id, alert_key(schedule_key))
+ except Exception:
+ logger.warning(
+ "Could not resolve the alert for scheduled chat %s",
+ schedule_key,
+ exc_info=True,
+ )
+
+
+def owned_routines(user_id: str) -> ExpertRoutineWhereInput:
+ """The account's own routines and its experts'. A streak's key is the
+ owner's routine only if it names one of these."""
+ return {"OR": [{"userId": user_id}, {"Expert": {"is": {"ownerUserId": user_id}}}]}
+
+
+async def forget_scheduled_chat(user_id: str, schedule_key: str) -> None:
+ """Drop the streak of a follow-up its owner deleted. Kept, a paused one
+ would stay listed as paused and under Needs you, with a Resume that says
+ it runs again, and its alert could still email about it.
+
+ A routine's streak is left alone: its paused jobs outlive any one
+ schedule id, and a streak dropped from under them would stop the routine
+ without a word."""
+ if await ExpertRoutine.prisma().find_first(
+ where={"id": schedule_key, **owned_routines(user_id)}
+ ):
+ return
+ await ScheduledChatStreak.prisma().delete_many(
+ where={"userId": user_id, "scheduleKey": schedule_key}
+ )
+ await resolve_alert(user_id, schedule_key)
async def forget_routine(user_id: str, routine_id: str) -> None:
"""Its jobs are deleted as it is switched off, and switching it on again
makes new ones that fire. Kept, a paused one would stay listed as paused,
- with a Resume that says it runs again."""
+ with a Resume that says it runs again, and its alert could still email
+ about it."""
await ScheduledChatStreak.prisma().delete_many(
where={"userId": user_id, "scheduleKey": routine_id}
)
+ await resolve_alert(user_id, routine_id)
diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/reconnect.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/reconnect.py
new file mode 100644
index 0000000000..2dfb654d82
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/reconnect.py
@@ -0,0 +1,75 @@
+"""Connecting a provider is the fix for a scheduled chat failing on it
+(SECRT-2879).
+
+The integrations routes call ``resume_after_reconnect_in_background`` after
+every successful connect, so the fix counts wherever the owner made it: the
+card's Reconnect button, the integrations page, or a chat's connect prompt.
+"""
+
+import asyncio
+import logging
+
+from prisma.models import ScheduledChatStreak
+
+from backend.copilot.scheduled_chats.service import resume_scheduled_chat
+
+logger = logging.getLogger(__name__)
+
+# Held so a resume that is still running is not garbage-collected mid-flight.
+_resumes: set[asyncio.Task[None]] = set()
+
+
+def resume_after_reconnect_in_background(
+ user_id: str, provider: str
+) -> asyncio.Task[None]:
+ """Start ``resume_after_reconnect`` without making the connect wait on it.
+
+ Resuming goes through the scheduler, whose calls can take minutes when it
+ is unwell, and the credential is saved either way.
+ """
+ task = asyncio.create_task(resume_after_reconnect(user_id, provider))
+ _resumes.add(task)
+ task.add_done_callback(_resumes.discard)
+ return task
+
+
+async def resume_after_reconnect(user_id: str, provider: str) -> None:
+ """Resume every scheduled chat paused on *provider*, and forget the ones
+ only told about it. Never raises."""
+ try:
+ # *provider* is the connect route's ProviderName value, and a streak's
+ # is what the failing tool put in ErrorResponse.details: the same
+ # vocabulary, which must stay the same. A failure that named no
+ # provider is not resumed here; Resume or a good run clears it.
+ rows = await ScheduledChatStreak.prisma().find_many(
+ where={"userId": user_id, "provider": provider, "failureKind": "connection"}
+ )
+ except Exception:
+ logger.warning(
+ "Could not load the scheduled chats waiting on %s", provider, exc_info=True
+ )
+ return
+ for row in rows:
+ try:
+ await _clear(user_id, row)
+ except Exception:
+ logger.warning(
+ "Could not resume scheduled chat %s after %s was reconnected",
+ row.scheduleKey,
+ provider,
+ exc_info=True,
+ )
+
+
+async def _clear(user_id: str, row: ScheduledChatStreak) -> None:
+ if row.pausedAt is None:
+ # Only told: its next run proves the fix. Until then nothing says the
+ # chat is failing, and a failure that persists counts afresh.
+ if await ScheduledChatStreak.prisma().delete_many(
+ where={"id": row.id, "pausedAt": None}
+ ):
+ return
+ # A run paused it after this read it: that run failed before the fix,
+ # and deleting the row would leave its jobs paused with nothing to
+ # list or resume them.
+ await resume_scheduled_chat(user_id, row.scheduleKey)
diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/reconnect_test.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/reconnect_test.py
new file mode 100644
index 0000000000..0aaf054255
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/reconnect_test.py
@@ -0,0 +1,92 @@
+import asyncio
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from backend.copilot.scheduled_chats import reconnect
+from backend.copilot.scheduled_chats.outcomes import classify_run, tool_failure_detail
+from backend.copilot.tools.expert_scope import provider_slug
+from backend.copilot.tools.helpers import _single_provider
+from backend.copilot.tools.models import ErrorResponse
+from backend.integrations.providers import ProviderName
+
+
+async def test_a_connect_does_not_wait_for_the_resume(mocker):
+ started = asyncio.Event()
+ release = asyncio.Event()
+
+ async def slow_resume(user_id: str, provider: str) -> None:
+ started.set()
+ await release.wait()
+
+ mocker.patch.object(reconnect, "resume_after_reconnect", side_effect=slow_resume)
+
+ task = reconnect.resume_after_reconnect_in_background("user-1", "discord")
+ await started.wait()
+
+ assert not task.done()
+ release.set()
+ await task
+
+
+def _told_row() -> SimpleNamespace:
+ """What the reconnect read: a chat only told about Discord."""
+ return SimpleNamespace(id="row-1", scheduleKey="sched-1", pausedAt=None)
+
+
+def _patch_rows(mocker, deleted: int) -> tuple[MagicMock, AsyncMock]:
+ rows = MagicMock(delete_many=AsyncMock(return_value=deleted))
+ mocker.patch.object(
+ reconnect.ScheduledChatStreak, "prisma", return_value=rows, create=True
+ )
+ resume = mocker.patch.object(reconnect, "resume_scheduled_chat", AsyncMock())
+ return rows, resume
+
+
+async def test_a_chat_only_told_is_forgotten_while_it_stays_unpaused(mocker):
+ rows, resume = _patch_rows(mocker, deleted=1)
+
+ await reconnect._clear("user-1", _told_row())
+
+ rows.delete_many.assert_awaited_once_with(where={"id": "row-1", "pausedAt": None})
+ resume.assert_not_awaited()
+
+
+async def test_a_chat_paused_since_it_was_read_is_resumed_not_dropped(mocker):
+ """A run still failing on the old connection paused it after the read.
+ Dropping the row would leave its jobs paused with nothing to resume them."""
+ _, resume = _patch_rows(mocker, deleted=0)
+
+ await reconnect._clear("user-1", _told_row())
+
+ resume.assert_awaited_once_with("user-1", "sched-1")
+
+
[email protected]("provider", list(ProviderName))
+def test_a_failing_tool_names_its_provider_as_the_connect_route_does(provider):
+ """A reconnect resumes the chats whose streak names the provider just
+ connected: the connect route's ProviderName value against what the
+ failing tool put in ErrorResponse.details. One vocabulary, kept so."""
+ output = ErrorResponse(
+ message="The saved credential was refused.",
+ error="credential_rejected",
+ details=_single_provider({provider_slug(provider)}),
+ ).model_dump_json()
+ detail = tool_failure_detail(output)
+ assert detail is not None
+
+ outcome = classify_run(
+ cancelled=False,
+ turn_error_code=None,
+ turn_errored=False,
+ tool_failures=[("run_block", detail)],
+ tool_successes=0,
+ )
+
+ assert outcome.failure is not None
+ assert outcome.failure.kind == "connection"
+ assert outcome.failure.provider == provider.value
diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/service.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/service.py
index f276339d95..9b55c27f72 100644
--- a/autogpt_platform/backend/backend/copilot/scheduled_chats/service.py
+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/service.py
@@ -13,18 +13,19 @@ from datetime import datetime, timezone
from prisma.errors import UniqueViolationError
from prisma.models import ExpertRoutine, ScheduledChatStreak
from prisma.types import (
- ExpertRoutineWhereInput,
ScheduledChatStreakWhereInput,
ScheduledChatStreakWhereUniqueInput,
)
from pydantic import BaseModel, ValidationError
+from backend.copilot.scheduled_chats import alerts
from backend.copilot.scheduled_chats.failure_notices import (
failing_notice,
pause_summary,
paused_notice,
resumed_notice,
)
+from backend.copilot.scheduled_chats.forget import owned_routines, resolve_alert
from backend.copilot.scheduled_chats.jobs import (
jobs_paused,
pause_jobs,
@@ -74,14 +75,21 @@ async def record_scheduled_run(run: ScheduledRun) -> None:
where = _key(run.user_id, run.schedule_key)
row = await ScheduledChatStreak.prisma().find_unique(where=where)
current = _streak_of(row)
- if current is not None and current.paused and await _still_paused(run):
+ saw_pause = current is not None and current.paused
+ if saw_pause and await _still_paused(run):
# It fired before the pause and finished after it, so it changes
# nothing. One that fired after was resumed some other way.
return
step = advance(current, run.outcome)
+ # A pause raised the alert whether or not its card got through, so the
+ # pause ending withdraws it, as the end of a streak the owner was told of.
+ withdraw = step.ended_notified or saw_pause
if step.streak is None:
- if row is not None:
- await _drop(row, saw_pause=current is not None and current.paused)
+ # Withdrawn only with the streak: a pause this run didn't see stands,
+ # and so does its alert.
+ dropped = row is not None and await _drop(row, saw_pause=saw_pause)
+ if dropped and withdraw:
+ await resolve_alert(run.user_id, run.schedule_key)
return
if step.streak == current:
return
@@ -104,7 +112,7 @@ async def record_scheduled_run(run: ScheduledRun) -> None:
title,
restarted=row is None or streak.failures == 1,
told=told,
- replaces_pause=current is not None and current.paused,
+ replaces_pause=saw_pause,
)
except Exception:
# A pause with no row behind it is never listed or resumed: the chat
@@ -116,6 +124,12 @@ async def record_scheduled_run(run: ScheduledRun) -> None:
# Another run of this chat paused it after this one read the streak,
# and told the owner. That pause stands.
return
+ if withdraw:
+ # A new failure replaced the streak the owner was told about, or the
+ # pause. Before any pause it raises: both are this chat's one alert.
+ await resolve_alert(run.user_id, run.schedule_key)
+ if paused:
+ await _raise_paused(run, row, streak, title)
notice = _notice(step, streak, paused=paused, told=told, title=title, row=row)
if notice is not None:
await _tell(run, row, notice, told=told)
@@ -135,6 +149,7 @@ async def resume_scheduled_chat(user_id: str, schedule_key: str) -> bool:
return False
await resume_jobs(user_id, row.scheduleIds)
await ScheduledChatStreak.prisma().delete(where={"id": row.id})
+ await resolve_alert(user_id, schedule_key)
if row.sessionId is not None:
try:
await post_notice(
@@ -154,29 +169,19 @@ async def resume_scheduled_chat(user_id: str, schedule_key: str) -> bool:
return True
-async def forget_scheduled_chat(user_id: str, schedule_key: str) -> None:
- """Drop the streak of a follow-up its owner deleted. Kept, a paused one
- would stay listed as paused, with a Resume that says it runs again.
-
- A routine's streak is left alone: its paused jobs outlive any one
- schedule id, and a streak dropped from under them would stop the routine
- without a word."""
- if await ExpertRoutine.prisma().find_first(
- where={"id": schedule_key, **_owned_by(user_id)}
- ):
- return
- await ScheduledChatStreak.prisma().delete_many(
- where={"userId": user_id, "scheduleKey": schedule_key}
- )
-
-
async def list_paused_scheduled_chats(user_id: str) -> list[PausedScheduledChat]:
rows = await ScheduledChatStreak.prisma().find_many(
where={"userId": user_id, "NOT": [{"pausedAt": None}]},
order={"pausedAt": "desc"},
)
+ if not rows:
+ # Home asks on every load; most have nothing paused.
+ return []
routines = await ExpertRoutine.prisma().find_many(
- where={"id": {"in": [row.scheduleKey for row in rows]}, **_owned_by(user_id)}
+ where={
+ "id": {"in": [row.scheduleKey for row in rows]},
+ **owned_routines(user_id),
+ }
)
routine_ids = {routine.id for routine in routines}
paused: list[PausedScheduledChat] = []
@@ -334,6 +339,39 @@ async def _save(
return None
+async def _raise_paused(
+ run: ScheduledRun, row: ScheduledChatStreak, streak: Streak, title: str
+) -> None:
+ """Raise the chat's pause alert. A resume can land between the pause's row
+ and this, its own withdrawal before the alert existed, so the alert stays
+ only if the row is still paused once it is raised."""
+ await alerts.raise_paused(
+ run.user_id,
+ run.schedule_key,
+ alerts.paused_cause(
+ streak.failure,
+ title=title,
+ failures=streak.failures,
+ session_id=run.session_id,
+ ),
+ )
+ try:
+ still_paused = await ScheduledChatStreak.prisma().count(
+ where={"id": row.id, "NOT": [{"pausedAt": None}]}
+ )
+ except Exception:
+ # Only a guard, and the pause most likely stands: keep the alert, and
+ # let the chat still be told.
+ logger.warning(
+ "Could not check scheduled chat %s is still paused",
+ run.schedule_key,
+ exc_info=True,
+ )
+ return
+ if not still_paused:
+ await resolve_alert(run.user_id, run.schedule_key)
+
+
async def _drop(row: ScheduledChatStreak, *, saw_pause: bool) -> bool:
"""End the streak a run read, and say whether it did. As in ``_save``, a
view from before a pause never ends that pause: its jobs are paused, and
@@ -372,9 +410,3 @@ def _streak_of(row: ScheduledChatStreak | None) -> Streak | None:
def _key(user_id: str, schedule_key: str) -> ScheduledChatStreakWhereUniqueInput:
return {"userId_scheduleKey": {"userId": user_id, "scheduleKey": schedule_key}}
-
-
-def _owned_by(user_id: str) -> ExpertRoutineWhereInput:
- """The account's own routines and its experts'. A streak's key is the
- owner's routine only if it names one of these."""
- return {"OR": [{"userId": user_id}, {"Expert": {"is": {"ownerUserId": user_id}}}]}
diff --git a/autogpt_platform/backend/backend/copilot/scheduled_chats/service_test.py b/autogpt_platform/backend/backend/copilot/scheduled_chats/service_test.py
index a07507ea60..a39fc5f1b3 100644
--- a/autogpt_platform/backend/backend/copilot/scheduled_chats/service_test.py
+++ b/autogpt_platform/backend/backend/copilot/scheduled_chats/service_test.py
@@ -10,13 +10,22 @@ from unittest.mock import AsyncMock, MagicMock, patch
from uuid import uuid4
import pytest
+from prisma.actions import ScheduledChatStreakActions
+from prisma.enums import AlertCause, AlertConditionStatus
from prisma.errors import UniqueViolationError
-from prisma.models import ChatMessage, ExpertRoutine, ScheduledChatStreak, User
+from prisma.models import (
+ AlertCondition,
+ ChatMessage,
+ ExpertRoutine,
+ ScheduledChatStreak,
+ User,
+)
from backend.api.features.experts import routines
from backend.copilot import db as copilot_db
-from backend.copilot.scheduled_chats import service
+from backend.copilot.scheduled_chats import forget, reconnect, service
from backend.copilot.scheduled_chats.outcomes import RunFailure, RunOutcome
+from backend.copilot.scheduled_chats.reconnect import resume_after_reconnect
from backend.copilot.scheduled_chats.service import (
ScheduledRun,
list_paused_scheduled_chats,
@@ -254,6 +263,11 @@ async def test_switching_a_paused_routine_off_forgets_its_streak(
assert await list_paused_scheduled_chats(user_id) == []
assert not await resume_scheduled_chat(user_id, routine.id)
+ # Nor is its owner emailed about a routine they switched off.
+ alert = await AlertCondition.prisma().find_first(
+ where={"userId": user_id, "causeKey": f"scheduled_chat:{routine.id}"}
+ )
+ assert alert is not None and alert.status == AlertConditionStatus.RESOLVED
finally:
await _cleanup(user_id)
@@ -455,6 +469,9 @@ async def test_a_good_run_that_read_the_streak_before_the_pause_keeps_it(
await record_scheduled_run(_run(user_id, session_id, RunOutcome()))
assert len(await list_paused_scheduled_chats(user_id)) == 1
+ # And its alert: withdrawn only with the streak.
+ alert = await _alert(user_id)
+ assert alert is not None and alert.status == AlertConditionStatus.PENDING
finally:
await _cleanup(user_id)
@@ -510,6 +527,34 @@ async def test_a_chat_resumed_some_other_way_starts_over(
await record_scheduled_run(_run(user_id, session_id, RunOutcome()))
assert await ScheduledChatStreak.prisma().count(where={"userId": user_id}) == 0
+ # The run that worked is the fix, so the pause alert is withdrawn too.
+ alert = await _alert(user_id)
+ assert alert is not None and alert.status == AlertConditionStatus.RESOLVED
+ finally:
+ await _cleanup(user_id)
+
+
[email protected](loop_scope="session")
+async def test_a_pause_whose_card_failed_has_its_alert_withdrawn_when_it_ends(
+ server: SpinTestServer, scheduler: MagicMock, mocker
+):
+ """The pause raised its alert, but its card didn't post, so the streak
+ reads as never told. Resumed some other way, the run that ends it must
+ still withdraw the alert."""
+ mocker.patch(f"{_SERVICE}.post_notice", side_effect=RuntimeError("db"))
+ user_id, session_id = await _owner()
+ try:
+ failed = RunOutcome(failure=_DISCORD, whole_run=True)
+ for _ in range(3):
+ await record_scheduled_run(_run(user_id, session_id, failed))
+ row = await ScheduledChatStreak.prisma().find_first(where={"userId": user_id})
+ assert row is not None and row.pausedAt is not None and row.notifiedAt is None
+ scheduler.get_execution_schedules.return_value = [MagicMock(id="sched-1")]
+
+ await record_scheduled_run(_run(user_id, session_id, RunOutcome()))
+
+ alert = await _alert(user_id)
+ assert alert is not None and alert.status == AlertConditionStatus.RESOLVED
finally:
await _cleanup(user_id)
@@ -558,6 +603,210 @@ async def test_resume_restarts_the_jobs_clears_the_streak_and_says_so(
await _cleanup(user_id)
+async def _alert(user_id: str) -> AlertCondition | None:
+ return await AlertCondition.prisma().find_first(
+ where={"userId": user_id, "causeKey": "scheduled_chat:sched-1"}
+ )
+
+
[email protected](loop_scope="session")
+async def test_a_chat_resumed_as_its_pause_raises_the_alert_is_left_without_one(
+ server: SpinTestServer, scheduler: MagicMock, mocker
+):
+ """The owner resumes from the paused list between the pause's row and its
+ alert: the resume's withdrawal finds nothing yet, and the alert must not
+ outlive the pause."""
+ raise_paused = service.alerts.raise_paused
+ user_id, session_id = await _owner()
+
+ async def resumed_first(*args, **kwargs):
+ assert await resume_scheduled_chat(user_id, "sched-1")
+ await raise_paused(*args, **kwargs)
+
+ mocker.patch.object(service.alerts, "raise_paused", new=resumed_first)
+ try:
+ failed = RunOutcome(failure=_DISCORD, whole_run=True)
+ for _ in range(3):
+ await record_scheduled_run(_run(user_id, session_id, failed))
+
+ alert = await _alert(user_id)
+ assert alert is not None and alert.status == AlertConditionStatus.RESOLVED
+ finally:
+ await _cleanup(user_id)
+
+
[email protected](loop_scope="session")
+async def test_a_pause_is_told_even_when_its_alert_cannot_be_checked(
+ server: SpinTestServer, scheduler: MagicMock
+):
+ """The check after the alert is only a guard: failing, it must not keep
+ the card from the chat, which has no next run to try again on."""
+ user_id, session_id = await _owner()
+ try:
+ failed = RunOutcome(failure=_DISCORD, whole_run=True)
+ for _ in range(2):
+ await record_scheduled_run(_run(user_id, session_id, failed))
+ failing = AsyncMock(side_effect=RuntimeError("db blip"))
+ with patch.object(ScheduledChatStreakActions, "count", failing):
+ await record_scheduled_run(_run(user_id, session_id, failed))
+ failing.assert_awaited_once()
+
+ headlines = [n.metadata["headline"] for n in await _notes(session_id)]
+ assert headlines[-1].startswith("Paused: ")
+ alert = await _alert(user_id)
+ assert alert is not None and alert.status == AlertConditionStatus.PENDING
+ finally:
+ await _cleanup(user_id)
+
+
[email protected](loop_scope="session")
+async def test_a_pause_raises_the_alert_and_resume_resolves_it(
+ server: SpinTestServer, scheduler: MagicMock
+):
+ """The alert engine turns it into the email (where user email is on) or
+ the Briefing card; resuming cancels a send still in its debounce."""
+ user_id, session_id = await _owner()
+ try:
+ failed = RunOutcome(failure=_DISCORD, whole_run=True)
+ for _ in range(3):
+ await record_scheduled_run(_run(user_id, session_id, failed))
+
+ alert = await _alert(user_id)
+ assert alert is not None
+ assert alert.cause == AlertCause.PAUSED_FAILURES
+ assert alert.status == AlertConditionStatus.PENDING
+ assert alert.data["agent"] == "Discord monitor"
+ assert alert.data["step"] == "Discord connection"
+
+ assert await resume_scheduled_chat(user_id, "sched-1")
+
+ alert = await _alert(user_id)
+ assert alert is not None and alert.status == AlertConditionStatus.RESOLVED
+ finally:
+ await _cleanup(user_id)
+
+
[email protected](loop_scope="session")
+async def test_reconnecting_the_provider_resumes_what_it_paused(
+ server: SpinTestServer, scheduler: MagicMock
+):
+ user_id, session_id = await _owner()
+ try:
+ failed = RunOutcome(failure=_DISCORD, whole_run=True)
+ for _ in range(3):
+ await record_scheduled_run(_run(user_id, session_id, failed))
+ # Another chat only told about Twitter, and one about Discord's twin.
+ twitter = RunOutcome(failure=_TWITTER, whole_run=False)
+ for _ in range(3):
+ await record_scheduled_run(
+ _run(user_id, session_id, twitter, schedule_key="briefing")
+ )
+
+ await resume_after_reconnect(user_id, "discord")
+
+ scheduler.resume_schedule.assert_awaited_once_with("sched-1", user_id=user_id)
+ alert = await _alert(user_id)
+ assert alert is not None and alert.status == AlertConditionStatus.RESOLVED
+ keys = {
+ row.scheduleKey
+ for row in await ScheduledChatStreak.prisma().find_many(
+ where={"userId": user_id}
+ )
+ }
+ assert keys == {"briefing"}
+
+ await resume_after_reconnect(user_id, "twitter")
+
+ assert await ScheduledChatStreak.prisma().count(where={"userId": user_id}) == 0
+ finally:
+ await _cleanup(user_id)
+
+
[email protected](loop_scope="session")
+async def test_a_chat_paused_while_a_reconnect_reads_it_is_resumed(
+ server: SpinTestServer, scheduler: MagicMock
+):
+ """The reconnect read the chat as only told, while a run still failing
+ on the old connection went on to pause it. Deleting from that stale read
+ would leave its jobs paused with nothing to list or resume them."""
+ user_id, session_id = await _owner()
+ try:
+ told = RunOutcome(failure=_DISCORD, whole_run=False)
+ for _ in range(3):
+ await record_scheduled_run(_run(user_id, session_id, told))
+ read = await ScheduledChatStreak.prisma().find_first(where={"userId": user_id})
+ assert read is not None and read.pausedAt is None
+ failed = RunOutcome(failure=_DISCORD, whole_run=True)
+ for _ in range(3):
+ await record_scheduled_run(_run(user_id, session_id, failed))
+ assert len(await list_paused_scheduled_chats(user_id)) == 1
+
+ await reconnect._clear(user_id, read)
+
+ scheduler.resume_schedule.assert_awaited_once_with("sched-1", user_id=user_id)
+ assert await list_paused_scheduled_chats(user_id) == []
+ finally:
+ await _cleanup(user_id)
+
+
[email protected](loop_scope="session")
+async def test_two_resumes_at_once_both_say_it_resumed(
+ server: SpinTestServer, scheduler: MagicMock, mocker
+):
+ """Reconnecting from the card resumes the chat twice at once: once from
+ the connect, once from the card. Both read the row before either clears
+ it; both say it resumed, and the chat gets one note."""
+ both_read_the_row = asyncio.Event()
+ waiting: list[str] = []
+
+ async def resume_jobs(user_id: str, schedule_ids: list[str]) -> None:
+ waiting.append(user_id)
+ if len(waiting) == 2:
+ both_read_the_row.set()
+ await both_read_the_row.wait()
+
+ mocker.patch(f"{_SERVICE}.resume_jobs", side_effect=resume_jobs)
+ user_id, session_id = await _owner()
+ try:
+ failed = RunOutcome(failure=_DISCORD, whole_run=True)
+ for _ in range(3):
+ await record_scheduled_run(_run(user_id, session_id, failed))
+
+ results = await asyncio.gather(
+ resume_scheduled_chat(user_id, "sched-1"),
+ resume_scheduled_chat(user_id, "sched-1"),
+ )
+
+ assert results == [True, True]
+ assert await list_paused_scheduled_chats(user_id) == []
+ headlines = [n.metadata["headline"] for n in await _notes(session_id)]
+ assert headlines.count("Resumed \u201cDiscord monitor\u201d") == 1
+ finally:
+ await _cleanup(user_id)
+
+
[email protected](loop_scope="session")
+async def test_one_chat_that_cannot_resume_does_not_hold_up_the_rest(
+ server: SpinTestServer, scheduler: MagicMock
+):
+ user_id, session_id = await _owner()
+ try:
+ failed = RunOutcome(failure=_DISCORD, whole_run=True)
+ for key in ("first", "second"):
+ for _ in range(3):
+ await record_scheduled_run(
+ _run(user_id, session_id, failed, schedule_key=key, schedule_id=key)
+ )
+ scheduler.resume_schedule.side_effect = [RuntimeError("scheduler down"), True]
+
+ await resume_after_reconnect(user_id, "discord")
+
+ assert scheduler.resume_schedule.await_count == 2
+ assert len(await list_paused_scheduled_chats(user_id)) == 1
+ finally:
+ await _cleanup(user_id)
+
+
@pytest.mark.asyncio(loop_scope="session")
async def test_a_resume_the_scheduler_refuses_keeps_the_chat_paused(
server: SpinTestServer, scheduler: MagicMock
@@ -683,11 +932,17 @@ async def test_a_deleted_chat_leaves_no_paused_ghost(
await record_scheduled_run(_run(user_id, session_id, failed))
await record_scheduled_run(_run(other_id, other_session, failed))
- await service.forget_scheduled_chat(user_id, "sched-1")
+ await forget.forget_scheduled_chat(user_id, "sched-1")
assert await ScheduledChatStreak.prisma().count(where={"userId": user_id}) == 0
assert await list_paused_scheduled_chats(user_id) == []
assert await resume_scheduled_chat(user_id, "sched-1") is False
+ # Nor does its alert email about a chat that is gone.
+ alert = await _alert(user_id)
+ assert alert is not None and alert.status == AlertConditionStatus.RESOLVED
+ other_alert = await _alert(other_id)
+ assert other_alert is not None
+ assert other_alert.status == AlertConditionStatus.PENDING
# Only the owner's own chat goes.
[left] = await list_paused_scheduled_chats(other_id)
# A follow-up, which the paused list can delete.
@@ -709,7 +964,7 @@ async def test_forgetting_a_routines_id_leaves_its_pause_alone(
for job in ("job-a", "job-b", "job-a"):
await record_scheduled_run(_routine_run(user_id, session_id, routine, job))
- await service.forget_scheduled_chat(user_id, routine.id)
+ await forget.forget_scheduled_chat(user_id, routine.id)
paused = await list_paused_scheduled_chats(user_id)
assert [p.schedule_key for p in paused] == [routine.id]
@@ -741,7 +996,7 @@ async def test_a_key_naming_someone_elses_routine_is_a_follow_up(
[paused] = await list_paused_scheduled_chats(user_id)
assert paused.routine is False
- await service.forget_scheduled_chat(user_id, foreign.id)
+ await forget.forget_scheduled_chat(user_id, foreign.id)
assert await list_paused_scheduled_chats(user_id) == []
finally:
diff --git a/autogpt_platform/backend/backend/copilot/tools/manage_schedules.py b/autogpt_platform/backend/backend/copilot/tools/manage_schedules.py
index 548e86d79d..4e3986d92f 100644
--- a/autogpt_platform/backend/backend/copilot/tools/manage_schedules.py
+++ b/autogpt_platform/backend/backend/copilot/tools/manage_schedules.py
@@ -11,7 +11,7 @@ from backend.api.features.schedule_visibility import (
)
from backend.copilot.model import ChatSession
from backend.data.activity_event import ActivityEventDraft
-from backend.data.db_accessors import library_db
+from backend.data.db_accessors import library_db, scheduled_chats_db
from backend.executor.scheduler import CopilotTurnJobInfo, GraphExecutionJobInfo
from backend.util.clients import get_scheduler_client
from backend.util.exceptions import NotAuthorizedError, NotFoundError
@@ -328,6 +328,7 @@ class DeleteScheduleTool(BaseTool):
session_id=session_id,
)
+ await _forget_streak(user_id, schedule_id)
return ScheduleDeletedResponse(
message=f"Schedule {schedule_id} deleted.",
schedule_id=schedule_id,
@@ -335,6 +336,22 @@ class DeleteScheduleTool(BaseTool):
)
+async def _forget_streak(user_id: str, schedule_id: str) -> None:
+ """A follow-up's failure streak is keyed by its schedule id: kept, a
+ paused one would stay listed with a Resume, and its alert up. The schedule
+ is gone either way, so a failure is logged, not answered, as the delete
+ route does. The executor has no Prisma of its own, so through the
+ DatabaseManager."""
+ try:
+ await scheduled_chats_db().forget_scheduled_chat(user_id, schedule_id)
+ except Exception:
+ logger.warning(
+ "Could not clear the failure streak of deleted schedule %s",
+ schedule_id,
+ exc_info=True,
+ )
+
+
class ScheduleToggledResponse(ToolResponseBase):
type: ResponseType = ResponseType.SCHEDULE_TOGGLED
schedule_id: str
diff --git a/autogpt_platform/backend/backend/copilot/tools/manage_schedules_test.py b/autogpt_platform/backend/backend/copilot/tools/manage_schedules_test.py
index e11606b085..be0a3a8c47 100644
--- a/autogpt_platform/backend/backend/copilot/tools/manage_schedules_test.py
+++ b/autogpt_platform/backend/backend/copilot/tools/manage_schedules_test.py
@@ -66,6 +66,17 @@ def list_tool():
return ListSchedulesTool()
[email protected](autouse=True)
+def forget_streak(mocker):
+ """The failure-streak cleanup a delete does, which reaches the database."""
+ forget = AsyncMock()
+ mocker.patch(
+ f"{_SCHEDULES_PATH}.scheduled_chats_db",
+ return_value=MagicMock(forget_scheduled_chat=forget),
+ )
+ return forget
+
+
@pytest.fixture
def delete_tool():
return DeleteScheduleTool()
@@ -268,7 +279,7 @@ async def test_delete_schedule_missing_id(delete_tool, session):
@pytest.mark.asyncio
-async def test_delete_schedule_success(delete_tool, session):
+async def test_delete_schedule_success(delete_tool, session, forget_streak):
mock_client = AsyncMock()
mock_client.get_execution_schedules = AsyncMock(return_value=[_make_graph_info()])
mock_client.delete_schedule = AsyncMock()
@@ -288,6 +299,25 @@ async def test_delete_schedule_success(delete_tool, session):
mock_client.delete_schedule.assert_called_once_with(
schedule_id="sched-1", user_id=_USER
)
+ # As the delete route does: a paused follow-up leaves no paused ghost.
+ forget_streak.assert_awaited_once_with(_USER, "sched-1")
+
+
+async def test_a_delete_whose_streak_cleanup_fails_still_says_deleted(
+ delete_tool, session, forget_streak
+):
+ forget_streak.side_effect = RuntimeError("db blip")
+ mock_client = AsyncMock()
+ mock_client.get_execution_schedules = AsyncMock(return_value=[_make_graph_info()])
+ mock_client.delete_schedule = AsyncMock()
+
+ with patch(f"{_SCHEDULES_PATH}.get_scheduler_client", return_value=mock_client):
+ result = await delete_tool._execute(
+ user_id=_USER, session=session, schedule_id="sched-1"
+ )
+
+ assert isinstance(result, ScheduleDeletedResponse)
@pytest.mark.asyncio
diff --git a/autogpt_platform/backend/backend/data/db_accessors.py b/autogpt_platform/backend/backend/data/db_accessors.py
index 46fd103519..1937426364 100644
--- a/autogpt_platform/backend/backend/data/db_accessors.py
+++ b/autogpt_platform/backend/backend/data/db_accessors.py
@@ -422,3 +422,16 @@ def posthog_lifecycle_db():
posthog_lifecycle_db = get_database_manager_async_client(should_retry=False)
return posthog_lifecycle_db
+
+
+def scheduled_chats_db():
+ if db.is_connected():
+ from backend.copilot.scheduled_chats import forget as _scheduled_chats_db
+
+ scheduled_chats_db = _scheduled_chats_db
+ else:
+ from backend.util.clients import get_database_manager_async_client
+
+ scheduled_chats_db = get_database_manager_async_client()
+
+ return scheduled_chats_db
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index d7dc320b08..4b0b023159 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -60,6 +60,7 @@ from backend.api.features.store.db import (
)
from backend.api.features.store.embeddings import backfill_missing_embeddings
from backend.copilot import db as chat_db
+from backend.copilot.scheduled_chats.forget import forget_scheduled_chat
from backend.copilot.scheduled_chats.service import record_scheduled_run
from backend.copilot.sharing.db import link_new_execution_to_chat_share
from backend.data import bot_analytics as bot_analytics_db
@@ -783,8 +784,10 @@ class DatabaseManager(AppService):
append_plain_session_message = _(chat_db.append_plain_session_message)
# And to tell a scheduled chat why its run was skipped, in that chat.
append_session_message = _(chat_db.append_session_message)
- # The copilot executor counts each scheduled run toward a failure streak.
+ # The copilot executor counts each scheduled run toward a failure streak,
+ # and drops a follow-up's streak when Otto deletes its schedule.
record_scheduled_run = _(record_scheduled_run)
+ forget_scheduled_chat = _(forget_scheduled_chat)
create_briefing = _(create_briefing)
get_briefing_for_date = _(get_briefing_for_date)
get_latest_briefings = _(get_latest_briefings)
@@ -999,6 +1002,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):
append_plain_session_message = d.append_plain_session_message
append_session_message = d.append_session_message
record_scheduled_run = d.record_scheduled_run
+ forget_scheduled_chat = d.forget_scheduled_chat
create_briefing = d.create_briefing
get_briefing_for_date = d.get_briefing_for_date
get_latest_briefings = d.get_latest_briefings
diff --git a/autogpt_platform/backend/backend/data/db_manager_test.py b/autogpt_platform/backend/backend/data/db_manager_test.py
index c1c3fee7ea..a4c065b697 100644
--- a/autogpt_platform/backend/backend/data/db_manager_test.py
+++ b/autogpt_platform/backend/backend/data/db_manager_test.py
@@ -63,6 +63,14 @@ def test_the_executor_can_record_a_scheduled_run() -> None:
manager._create_fastapi_endpoint(manager.record_scheduled_run)
+def test_the_executor_can_forget_a_deleted_scheduled_chat() -> None:
+ """Otto's delete_schedule tool runs in the copilot executor, which has no
+ Prisma: a direct call there fails, and its cleanup with it."""
+ assert hasattr(DatabaseManagerAsyncClient, "forget_scheduled_chat")
+ manager = DatabaseManager()
+ manager._create_fastapi_endpoint(manager.forget_scheduled_chat)
+
+
def test_the_scheduler_can_post_a_note_into_a_chat() -> None:
"""The scheduler has no Prisma of its own; a skipped run's note goes
through this RPC."""
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/ScheduledChatNoticeCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/ScheduledChatNoticeCard.test.tsx
index 553d8374e9..00e86a0d0f 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/ScheduledChatNoticeCard.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/__tests__/ScheduledChatNoticeCard.test.tsx
@@ -2,7 +2,9 @@ import {
getGetV1ListCredentialsMockHandler,
getGetV1ListProvidersMockHandler,
} from "@/app/api/__generated__/endpoints/integrations/integrations.msw";
+import { getGetHomeDashboardQueryKey } from "@/app/api/__generated__/endpoints/home/home";
import { getResumeScheduledChatMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";
+import { QueryClient } from "@tanstack/react-query";
import { server } from "@/mocks/mock-server";
import {
fireEvent,
@@ -11,7 +13,7 @@ import {
waitFor,
} from "@/tests/integrations/test-utils";
import { http, HttpResponse } from "msw";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import { ScheduledChatNoticeCard } from "../ScheduledChatNoticeCard";
import type { ScheduledChatNotice } from "../helpers";
@@ -69,6 +71,21 @@ describe("ScheduledChatNoticeCard", () => {
).toHaveProperty("disabled", true);
});
+ it("refreshes Home, which lists the paused chat, once it resumes", async () => {
+ const invalidate = vi.spyOn(QueryClient.prototype, "invalidateQueries");
+ server.use(getResumeScheduledChatMockHandler(() => ({ resumed: true })));
+ render(<ScheduledChatNoticeCard notice={PAUSED} sessionID="session-1" />);
+
+ fireEvent.click(screen.getByRole("button", { name: "Resume" }));
+
+ await waitFor(() =>
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: getGetHomeDashboardQueryKey(),
+ }),
+ );
+ invalidate.mockRestore();
+ });
+
it("treats a chat that is no longer paused as resumed", async () => {
server.use(
http.post("*/api/schedules/followups/:scheduleKey/resume", () =>
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/useScheduledChatNoticeCard.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/useScheduledChatNoticeCard.ts
index 03aafa0d92..54dab23b97 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/useScheduledChatNoticeCard.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ScheduledChatNoticeCard/useScheduledChatNoticeCard.ts
@@ -1,4 +1,5 @@
import { getGetV2GetSessionQueryKey } from "@/app/api/__generated__/endpoints/chat/chat";
+import { getGetHomeDashboardQueryKey } from "@/app/api/__generated__/endpoints/home/home";
import {
getListPausedScheduledChatsQueryKey,
useResumeScheduledChat,
@@ -27,6 +28,8 @@ export function useScheduledChatNoticeCard({ scheduleKey, sessionID }: Args) {
queryClient.invalidateQueries({
queryKey: getListPausedScheduledChatsQueryKey(),
});
+ // Home lists each paused chat under Needs you.
+ queryClient.invalidateQueries({ queryKey: getGetHomeDashboardQueryKey() });
void invalidateAllScheduleQueries(queryClient);
if (sessionID) {
queryClient.invalidateQueries({
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/followups/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/followups/__tests__/main.test.tsx
index 5a0bb78f5e..39d4e35d66 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/followups/__tests__/main.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/followups/__tests__/main.test.tsx
@@ -6,9 +6,11 @@ import {
getListPausedScheduledChatsMockHandler,
getResumeScheduledChatMockHandler,
} from "@/app/api/__generated__/endpoints/schedules/schedules.msw";
+import { getGetHomeDashboardQueryKey } from "@/app/api/__generated__/endpoints/home/home";
import type { CopilotTurnJobInfo } from "@/app/api/__generated__/models/copilotTurnJobInfo";
import type { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";
import { server } from "@/mocks/mock-server";
+import { QueryClient } from "@tanstack/react-query";
import { http, HttpResponse } from "msw";
import {
fireEvent,
@@ -575,10 +577,18 @@ describe("FollowupsPage", () => {
// A paused chat is still something scheduled: no empty state.
expect(screen.queryByTestId("followups-empty")).toBeNull();
+ const invalidate = vi.spyOn(QueryClient.prototype, "invalidateQueries");
fireEvent.click(
within(row).getByRole("button", { name: "Resume Discord monitor" }),
);
await waitFor(() => expect(resumedKey).toBe("routine-1"));
+ // Home lists the paused chat under Needs you, so it is refreshed too.
+ await waitFor(() =>
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: getGetHomeDashboardQueryKey(),
+ }),
+ );
+ invalidate.mockRestore();
});
test("a paused follow-up can be deleted from its row", async () => {
diff --git a/autogpt_platform/frontend/src/components/contextual/SchedulesPanel/components/PausedChatListItem/usePausedChatListItem.ts b/autogpt_platform/frontend/src/components/contextual/SchedulesPanel/components/PausedChatListItem/usePausedChatListItem.ts
index a5a4af4ca3..4fb1040d1a 100644
--- a/autogpt_platform/frontend/src/components/contextual/SchedulesPanel/components/PausedChatListItem/usePausedChatListItem.ts
+++ b/autogpt_platform/frontend/src/components/contextual/SchedulesPanel/components/PausedChatListItem/usePausedChatListItem.ts
@@ -1,3 +1,4 @@
+import { getGetHomeDashboardQueryKey } from "@/app/api/__generated__/endpoints/home/home";
import {
getListPausedScheduledChatsQueryKey,
useDeleteV1DeleteExecutionSchedule,
@@ -24,6 +25,8 @@ export function usePausedChatListItem({ paused }: Args) {
queryClient.invalidateQueries({
queryKey: getListPausedScheduledChatsQueryKey(),
});
+ // Home lists each paused chat under Needs you.
+ queryClient.invalidateQueries({ queryKey: getGetHomeDashboardQueryKey() });
return invalidateAllScheduleQueries(queryClient);
}