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): replace the email system with the Briefing/Alert/Verdict/Ops design (#14003)

Toran Bruce Richardsdb7408d43dcb
diff --git a/.github/workflows/cla-label-sync.yml b/.github/workflows/cla-label-sync.yml
index 0d05f088be..3a1fa11003 100644
--- a/.github/workflows/cla-label-sync.yml
+++ b/.github/workflows/cla-label-sync.yml
@@ -300,7 +300,7 @@ jobs:
if (hasSigned && !claStatus.passed) {
console.log(`PR #${prNumber}: was signed but now shows ${claStatus.state} — debouncing ${DEMOTE_DEBOUNCE_SECONDS}s before demoting`);
await new Promise(resolve => setTimeout(resolve, DEMOTE_DEBOUNCE_MS));
-
+
// Re-fetch the PR — a new commit could have been pushed, or the
// PR closed, while we were waiting. Evaluate the refreshed state
// rather than the one captured before the delay.
@@ -309,12 +309,12 @@ jobs:
repo: context.repo.repo,
pull_number: prNumber
});
-
+
if (refreshedPr.state !== 'open') {
console.log(`PR #${prNumber}: no longer open after debounce — skipping`);
continue;
}
-
+
pr = refreshedPr;
currentLabels = refreshedPr.labels.map(l => l.name);
hasPending = currentLabels.includes(LABEL_PENDING);
@@ -322,7 +322,7 @@ jobs:
claStatus = await getClaStatus(refreshedPr.head.sha);
console.log(`PR #${prNumber}: post-debounce CLA ${claStatus.passed ? 'passed' : 'still ' + claStatus.state}`);
}
-
+
if (claStatus.passed) {
// ✅ CLA signed - add signed label, remove pending
if (!hasSigned) {
diff --git a/autogpt_platform/backend/.env.default b/autogpt_platform/backend/.env.default
index a4f9cac099..c0f1192250 100644
--- a/autogpt_platform/backend/.env.default
+++ b/autogpt_platform/backend/.env.default
@@ -228,6 +228,29 @@ POSTMARK_SERVER_API_TOKEN=
POSTMARK_WEBHOOK_TOKEN=
+# Senders are separated so subscription mail, product notifications and
+# internal ops mail each carry their own reputation. Alerts and Briefings must
+# go out on a transactional stream, separate from marketing mail.
+BILLING_SENDER_EMAIL=AutoGPT <[email protected]>
+PRODUCT_SENDER_EMAIL=AutoGPT <[email protected]>
+OPS_SENDER_EMAIL=AutoGPT Platform <[email protected]>
+POSTMARK_TRANSACTIONAL_STREAM=outbound
+
+# Hero art and the logo are hosted images: Outlook does not render inline SVG
+# and Gmail does not display data-URI images. Serve backend/notifications/assets
+# from this base URL.
+EMAIL_ASSET_BASE_URL=https://cdn.agpt.co/email
+DOCS_BASE_URL=https://docs.agpt.co
+DISCORD_INVITE_URL=https://discord.gg/autogpt
+ADMIN_PANEL_BASE_URL=https://admin.agpt.co
+
+# MailerLite owns the six-email onboarding tour and the monthly changelog; the
+# backend only manages who is in each audience. See
+# backend/notifications/DEPLOYMENT.md for the one-time setup.
+MAILERLITE_API_TOKEN=
+MAILERLITE_ONBOARDING_GROUP_ID=
+MAILERLITE_CHANGELOG_GROUP_ID=
+
# Error Tracking
SENTRY_DSN=
diff --git a/autogpt_platform/backend/backend/api/features/orgs/regression_test.py b/autogpt_platform/backend/backend/api/features/orgs/regression_test.py
index fa2482db00..fd3f7d0c06 100644
--- a/autogpt_platform/backend/backend/api/features/orgs/regression_test.py
+++ b/autogpt_platform/backend/backend/api/features/orgs/regression_test.py
@@ -1526,16 +1526,9 @@ class TestRegressionUserSettings:
mock_user = MagicMock()
mock_user.id = USER_ID
mock_user.email = "[email protected]"
- mock_user.notifyOnAgentRun = True
- mock_user.notifyOnZeroBalance = False
- mock_user.notifyOnLowBalance = False
- mock_user.notifyOnBlockExecutionFailed = False
- mock_user.notifyOnContinuousAgentError = False
- mock_user.notifyOnDailySummary = False
- mock_user.notifyOnWeeklySummary = False
- mock_user.notifyOnMonthlySummary = False
- mock_user.notifyOnAgentApproved = False
- mock_user.notifyOnAgentRejected = False
+ mock_user.briefingFrequency = "WEEKLY"
+ mock_user.alertsEnabled = True
+ mock_user.notifyOnStoreVerdict = True
mock_user.maxEmailsPerDay = 3
self.mock_user_actions.find_unique_or_raise = AsyncMock(return_value=mock_user)
@@ -1571,16 +1564,9 @@ class TestRegressionUserSettings:
mock_user.stripeCustomerId = None
mock_user.topUpConfig = None
mock_user.onboardingCompletedAt = None
- mock_user.notifyOnAgentRun = True
- mock_user.notifyOnZeroBalance = False
- mock_user.notifyOnLowBalance = False
- mock_user.notifyOnBlockExecutionFailed = False
- mock_user.notifyOnContinuousAgentError = False
- mock_user.notifyOnDailySummary = False
- mock_user.notifyOnWeeklySummary = False
- mock_user.notifyOnMonthlySummary = False
- mock_user.notifyOnAgentApproved = False
- mock_user.notifyOnAgentRejected = False
+ mock_user.briefingFrequency = "WEEKLY"
+ mock_user.alertsEnabled = True
+ mock_user.notifyOnStoreVerdict = True
mock_user.maxEmailsPerDay = 3
mock_user.subscriptionTier = "NO_TIER"
self.mock_user_actions.update = AsyncMock(return_value=mock_user)
diff --git a/autogpt_platform/backend/backend/api/features/store/db.py b/autogpt_platform/backend/backend/api/features/store/db.py
index 8d8bb5a57e..c9451835c6 100644
--- a/autogpt_platform/backend/backend/api/features/store/db.py
+++ b/autogpt_platform/backend/backend/api/features/store/db.py
@@ -18,12 +18,8 @@ from backend.data.graph import (
get_sub_graphs,
)
from backend.data.includes import AGENT_GRAPH_INCLUDE
-from backend.data.notifications import (
- AgentApprovalData,
- AgentRejectionData,
- NotificationEventModel,
-)
-from backend.notifications.notifications import queue_notification_async
+from backend.data.notifications import NotificationEventModel, VerdictData
+from backend.notifications.queue import queue_notification_async
from backend.util.exceptions import DatabaseError, NotFoundError, PreconditionFailed
from backend.util.settings import Settings
@@ -1711,62 +1707,52 @@ async def _send_submission_review_notification(
base_url = settings.config.frontend_base_url or settings.config.platform_base_url
+ reviewer_name = reviewer.name if reviewer and reviewer.name else DEFAULT_ADMIN_NAME
+ reviewed_at = reviewed_listing_version.reviewedAt or datetime.now(tz=timezone.utc)
+ reviewed_at_label = f"{reviewed_at.day} {reviewed_at.strftime('%B')}"
+
if is_approved:
store_agent = await prisma.models.StoreAgent.prisma().find_first_or_raise(
where={"listing_version_id": reviewed_listing_version.id}
)
-
- # Send approval notification
- creator_username = store_agent.creator_username
- notification_data = AgentApprovalData(
- agent_name=reviewed_listing_version.name,
- graph_id=reviewed_listing_version.agentGraphId,
- graph_version=reviewed_listing_version.agentGraphVersion,
- reviewer_name=(
- reviewer.name if reviewer and reviewer.name else DEFAULT_ADMIN_NAME
- ),
- reviewer_email=(reviewer.email if reviewer else DEFAULT_ADMIN_EMAIL),
- comments=external_comments,
- reviewed_at=(
- reviewed_listing_version.reviewedAt or datetime.now(tz=timezone.utc)
- ),
- store_url=(
- f"{base_url}/marketplace/agent/{creator_username}/{store_agent.slug}"
- ),
+ store_url = (
+ f"{base_url}/marketplace/agent/{store_agent.creator_username}/"
+ f"{store_agent.slug}"
)
-
- notification_event = NotificationEventModel[AgentApprovalData](
- user_id=creator_user_id,
- type=prisma.enums.NotificationType.AGENT_APPROVED,
- data=notification_data,
+ notification_data = VerdictData(
+ outcome="approved",
+ agent_name=reviewed_listing_version.name,
+ version=reviewed_listing_version.version,
+ reviewer_name=reviewer_name,
+ reviewed_at_label=reviewed_at_label,
+ comments=external_comments or "",
+ store_url=store_url,
+ share_url=store_url,
)
else:
- # Send rejection notification
+ # "Changes requested", not "rejected": the old framing told creators to
+ # leave, this one tells them how to get in.
graph_id = reviewed_listing_version.agentGraphId
- notification_data = AgentRejectionData(
+ notification_data = VerdictData(
+ outcome="changes",
agent_name=reviewed_listing_version.name,
- graph_id=reviewed_listing_version.agentGraphId,
- graph_version=reviewed_listing_version.agentGraphVersion,
- reviewer_name=(
- reviewer.name if reviewer and reviewer.name else DEFAULT_ADMIN_NAME
- ),
- reviewer_email=(reviewer.email if reviewer else DEFAULT_ADMIN_EMAIL),
- comments=external_comments,
- reviewed_at=reviewed_listing_version.reviewedAt
- or datetime.now(tz=timezone.utc),
+ version=reviewed_listing_version.version,
+ reviewer_name=reviewer_name,
+ reviewed_at_label=reviewed_at_label,
+ comments=external_comments or "",
resubmit_url=f"{base_url}/build?flowID={graph_id}",
)
- notification_event = NotificationEventModel[AgentRejectionData](
- user_id=creator_user_id,
- type=prisma.enums.NotificationType.AGENT_REJECTED,
- data=notification_data,
- )
+ notification_event = NotificationEventModel[VerdictData](
+ user_id=creator_user_id,
+ type=prisma.enums.NotificationType.VERDICT,
+ data=notification_data,
+ )
# Queue the notification for immediate sending
await queue_notification_async(notification_event)
logger.info(
- f"Queued {'approval' if is_approved else 'rejection'} notification "
+ f"Queued {'approved' if is_approved else 'changes-requested'} verdict "
f"for agent '{reviewed_listing_version.name}' of user #{creator_user_id}"
)
diff --git a/autogpt_platform/backend/backend/api/features/store/db_test.py b/autogpt_platform/backend/backend/api/features/store/db_test.py
index 749fdd5eaf..a36327f3a9 100644
--- a/autogpt_platform/backend/backend/api/features/store/db_test.py
+++ b/autogpt_platform/backend/backend/api/features/store/db_test.py
@@ -179,16 +179,9 @@ async def test_create_store_submission(mocker):
metadata="{}", # type: ignore[reportArgumentType]
integrations="",
maxEmailsPerDay=1,
- notifyOnAgentRun=True,
- notifyOnZeroBalance=True,
- notifyOnLowBalance=True,
- notifyOnBlockExecutionFailed=True,
- notifyOnContinuousAgentError=True,
- notifyOnDailySummary=True,
- notifyOnWeeklySummary=True,
- notifyOnMonthlySummary=True,
- notifyOnAgentApproved=True,
- notifyOnAgentRejected=True,
+ briefingFrequency=prisma.enums.BriefingFrequency.WEEKLY, # type: ignore[reportCallIssue,reportAttributeAccessIssue]
+ alertsEnabled=True,
+ notifyOnStoreVerdict=True,
timezone="Europe/Delft",
subscriptionTier=prisma.enums.SubscriptionTier.BASIC, # type: ignore[reportCallIssue,reportAttributeAccessIssue]
)
diff --git a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
index 8849fe2c59..0dc296ec2d 100644
--- a/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/subscription_routes_test.py
@@ -47,6 +47,26 @@ def _configure_frontend_origin(mocker: pytest_mock.MockFixture) -> None:
)
[email protected](autouse=True)
+def _stub_lifecycle_emails(mocker: pytest_mock.MockFixture) -> None:
+ """The billing emails hang off the Stripe webhook. Stub them here so the
+ dispatch tests in this module stay about routing, not about mail."""
+ for handler in (
+ "on_checkout_completed",
+ "on_payment_failed",
+ "on_subscription_updated",
+ "on_subscription_deleted",
+ ):
+ mocker.patch(
+ f"backend.api.features.v1.lifecycle.{handler}", new_callable=AsyncMock
+ )
+ mocker.patch(
+ "stripe.Subscription.retrieve_async",
+ new_callable=AsyncMock,
+ return_value={"id": "sub_stub"},
+ )
+
+
@pytest.fixture(autouse=True)
def _stub_pending_subscription_change(mocker: pytest_mock.MockFixture) -> None:
"""Default pending-change lookup to None so tests don't hit Stripe/DB.
diff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.py
index a134fa748b..7d5b29d16f 100644
--- a/autogpt_platform/backend/backend/api/features/v1.py
+++ b/autogpt_platform/backend/backend/api/features/v1.py
@@ -27,7 +27,7 @@ from fastapi import (
UploadFile,
)
from fastapi.concurrency import run_in_threadpool
-from prisma.enums import SubscriptionTier
+from prisma.enums import BriefingFrequency, SubscriptionTier
from pydantic import BaseModel, Field
from starlette.status import (
HTTP_204_NO_CONTENT,
@@ -106,7 +106,12 @@ from backend.data.execution_cost_summary import (
)
from backend.data.graph import GraphSettings
from backend.data.model import CredentialsMetaInput, UserOnboarding
-from backend.data.notifications import NotificationPreference, NotificationPreferenceDTO
+from backend.data.notifications import (
+ NotificationPreference,
+ NotificationPreferenceDTO,
+ PassWorkEvent,
+ PassWorkKind,
+)
from backend.data.onboarding import (
FrontendOnboardingStep,
OnboardingStep,
@@ -134,6 +139,7 @@ from backend.data.user import (
update_user_email,
update_user_notification_preference,
update_user_timezone,
+ verify_preference_token,
)
from backend.data.workspace import get_workspace_file_by_id
from backend.executor import scheduler
@@ -147,6 +153,8 @@ from backend.monitoring.instrumentation import (
record_graph_execution,
record_graph_operation,
)
+from backend.notifications import lifecycle
+from backend.notifications.queue import queue_pass_work
from backend.util.cache import cached
from backend.util.clients import get_scheduler_client
from backend.util.cloud_storage import get_cloud_storage_handler
@@ -304,6 +312,59 @@ async def update_preferences(
return output
+@v1_router.post(
+ "/auth/user/preferences/from-email",
+ summary="Apply a volume-knob choice from a Briefing footer link",
+ tags=["auth"],
+)
+async def apply_email_preference_choice(
+ choice: Annotated[str, Query()],
+ token: Annotated[str, Query()],
+) -> NotificationPreference:
+ """Apply one footer choice, authorised by the token in the link.
+
+ Deliberately not `Security(requires_user)`. The session is the wrong
+ authority here: the settings page applies this on arrival, so a
+ session-authenticated write would let any third party change a logged-in
+ reader's preferences just by getting them to follow a link. The HMAC binds
+ the choice to the recipient we sent it to, exactly as the unsubscribe link
+ does, and works whether or not they happen to be signed in.
+ """
+ user_id = verify_preference_token(token, choice)
+ if user_id is None:
+ raise HTTPException(status_code=400, detail="Invalid or expired link")
+
+ current = await get_user_notification_preference(user_id)
+ updated = _preference_with_choice(current, choice)
+ if updated is None:
+ raise HTTPException(status_code=400, detail="Unknown preference choice")
+ return await update_user_notification_preference(user_id, updated)
+
+
+def _preference_with_choice(
+ current: NotificationPreference, choice: str
+) -> NotificationPreferenceDTO | None:
+ """The volume knob, server-side. "alerts" and "off" both stop the digest;
+ they differ in whether alerts survive."""
+ mapping: dict[str, tuple[BriefingFrequency, bool]] = {
+ "daily": (BriefingFrequency.DAILY, current.alerts_enabled),
+ "weekly": (BriefingFrequency.WEEKLY, current.alerts_enabled),
+ "monthly": (BriefingFrequency.MONTHLY, current.alerts_enabled),
+ "alerts": (BriefingFrequency.OFF, True),
+ "off": (BriefingFrequency.OFF, False),
+ }
+ if choice not in mapping:
+ return None
+ frequency, alerts = mapping[choice]
+ return NotificationPreferenceDTO(
+ email=current.email,
+ briefing_frequency=frequency,
+ alerts_enabled=alerts,
+ store_verdicts_enabled=current.store_verdicts_enabled,
+ daily_limit=current.daily_limit,
+ )
+
+
########################################################
##################### Onboarding #######################
########################################################
@@ -1396,6 +1457,46 @@ async def _claim_stripe_event(event_id: str) -> bool:
return True
+async def _notify_checkout_completed(session: dict) -> None:
+ """Hand the completed checkout to the lifecycle emails.
+
+ Failures here must not fail the webhook: the customer has paid, and Stripe
+ retrying the whole event would re-run `fulfill_checkout`, which grants
+ credits. But swallowing the failure lost the welcome permanently — Stripe
+ does not retry a 200, and `customer.subscription.created` deliberately does
+ not send it either.
+
+ So the work is queued rather than done here. The consumer re-reads the
+ session and subscription from Stripe and sends the welcome, with the same
+ retry-with-backoff and dead-letter queue every other notification gets.
+ Publishing is one small call that either succeeds or is logged; the Stripe
+ API round-trip and the email now sit behind a retry instead of a warning.
+ """
+ if session.get("mode") != "subscription":
+ return
+ if not session.get("subscription"):
+ return
+ session_id = session.get("id")
+ if not session_id:
+ return
+ result = await queue_pass_work(
+ PassWorkKind.WELCOME.value,
+ str(session_id),
+ PassWorkEvent(
+ kind=PassWorkKind.WELCOME,
+ user_id="",
+ scheduled_for=datetime.now(tz=timezone.utc),
+ context={"session_id": str(session_id)},
+ ).model_dump_json(),
+ )
+ if not result.success:
+ logger.warning(
+ "stripe_webhook: could not queue the welcome email for session %s: %s",
+ session_id,
+ result.message,
+ )
+
+
async def _release_stripe_event(event_id: str) -> None:
"""Release a previously-claimed dedup key so Stripe's retry can rerun."""
if not event_id:
@@ -1484,6 +1585,11 @@ async def stripe_webhook(request: Request):
return Response(status_code=200)
await UserCredit().fulfill_checkout(session_id=session_id)
await sync_tier_from_checkout_session(data_object)
+ # Only `checkout.session.completed` drives the welcome email.
+ # `customer.subscription.created` fires at signup too; listening to
+ # both would double-send.
+ if event_type == "checkout.session.completed":
+ await _notify_checkout_completed(data_object)
if event_type in (
"customer.subscription.created",
@@ -1491,6 +1597,12 @@ async def stripe_webhook(request: Request):
"customer.subscription.deleted",
):
await sync_subscription_from_stripe(data_object)
+ if event_type == "customer.subscription.updated":
+ await lifecycle.on_subscription_updated(
+ data_object, event_data.get("previous_attributes") or {}
+ )
+ elif event_type == "customer.subscription.deleted":
+ await lifecycle.on_subscription_deleted(data_object)
# `subscription_schedule.updated` is deliberately omitted: our own
# `SubscriptionSchedule.create` + `.modify` calls in
@@ -1509,6 +1621,7 @@ async def stripe_webhook(request: Request):
if event_type == "invoice.payment_failed":
await handle_subscription_payment_failure(data_object)
+ await lifecycle.on_payment_failed(data_object)
# New Stripe API (≥2025-04-01) split the per-payment events off the
# Invoice resource. data.object is an InvoicePayment, not an Invoice,
@@ -1526,6 +1639,7 @@ async def stripe_webhook(request: Request):
await handle_subscription_payment_success(invoice_payload)
else:
await handle_subscription_payment_failure(invoice_payload)
+ await lifecycle.on_payment_failed(invoice_payload)
# `handle_dispute` and `deduct_credits` expect Stripe SDK typed objects
# (Dispute/Refund). The Stripe webhook payload's `data.object` is a
diff --git a/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py b/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py
index ac12310e6c..db55dd5c2f 100644
--- a/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py
+++ b/autogpt_platform/backend/backend/api/features/v1_stripe_webhook_test.py
@@ -14,6 +14,7 @@ from backend.data.credit import (
reconcile_stripe_tier_for_user,
sync_tier_from_checkout_session,
)
+from backend.data.notifications import NotificationResult, PassWorkEvent, PassWorkKind
from .v1 import _claim_stripe_event, _release_stripe_event, v1_router
@@ -22,6 +23,43 @@ app.include_router(v1_router)
client = fastapi.testclient.TestClient(app)
[email protected](autouse=True)
+def stub_lifecycle_emails(mocker: pytest_mock.MockFixture):
+ """The billing emails are wired into this webhook. Stub them by default so
+ unrelated dispatch tests neither hit Stripe nor queue mail; the tests that
+ care about the wiring assert on these mocks."""
+ # The welcome email needs the subscription itself for its plan slots; keep
+ # that lookup off the network in tests.
+ mocker.patch(
+ "stripe.Subscription.retrieve_async",
+ new_callable=AsyncMock,
+ return_value={"id": "sub_stub"},
+ )
+ return {
+ # The welcome is queued rather than sent inline: the customer has
+ # already paid, and retrying the whole event to re-send a welcome would
+ # re-run `fulfill_checkout`. The consumer re-reads the session from
+ # Stripe and sends it, with retries and a DLQ.
+ "checkout": mocker.patch(
+ "backend.api.features.v1.queue_pass_work",
+ new_callable=AsyncMock,
+ return_value=NotificationResult(success=True),
+ ),
+ "payment_failed": mocker.patch(
+ "backend.api.features.v1.lifecycle.on_payment_failed",
+ new_callable=AsyncMock,
+ ),
+ "updated": mocker.patch(
+ "backend.api.features.v1.lifecycle.on_subscription_updated",
+ new_callable=AsyncMock,
+ ),
+ "deleted": mocker.patch(
+ "backend.api.features.v1.lifecycle.on_subscription_deleted",
+ new_callable=AsyncMock,
+ ),
+ }
+
+
def _make_checkout_event(mode: str, sub_id: str | None = None) -> dict:
return {
"type": "checkout.session.completed",
@@ -687,3 +725,128 @@ async def test_reconcile_stripe_tier_active_sub_unchanged_returns_false(
)
assert await reconcile_stripe_tier_for_user("user_abc") is False
+
+
+# ---------------------------------------------------------------------------
+# The billing emails hang off this webhook, so the dispatch is part of its
+# contract: exactly one trigger per email, and no trial listener at all.
+# ---------------------------------------------------------------------------
+
+
+def _post_event(mocker: pytest_mock.MockFixture, event: dict) -> None:
+ mocker.patch("stripe.Webhook.construct_event", return_value=event)
+ mocker.patch(
+ "backend.api.features.v1.settings.secrets.stripe_webhook_secret",
+ new="whsec_test",
+ )
+ response = client.post(
+ "/credits/stripe_webhook",
+ content=b"{}",
+ headers={"stripe-signature": "t=1,v1=sig"},
+ )
+ assert response.status_code == 200
+
+
+def test_welcome_email_hangs_off_checkout_not_subscription_created(
+ mocker: pytest_mock.MockFixture, stub_lifecycle_emails
+) -> None:
+ """Both events fire at signup; listening to both would double-send."""
+ mocker.patch(
+ "backend.api.features.v1.UserCredit.fulfill_checkout", new_callable=AsyncMock
+ )
+ mocker.patch(
+ "backend.api.features.v1.sync_tier_from_checkout_session",
+ new_callable=AsyncMock,
+ )
+ _post_event(mocker, _make_checkout_event("subscription", "sub_123"))
+ stub_lifecycle_emails["checkout"].assert_awaited_once()
+ queued = stub_lifecycle_emails["checkout"].await_args
+ assert queued.args[0] == PassWorkKind.WELCOME.value
+ assert (
+ PassWorkEvent.model_validate_json(queued.args[2]).context["session_id"]
+ == "cs_test_123"
+ )
+
+ stub_lifecycle_emails["checkout"].reset_mock()
+ mocker.patch(
+ "backend.api.features.v1.sync_subscription_from_stripe", new_callable=AsyncMock
+ )
+ _post_event(
+ mocker,
+ {
+ "type": "customer.subscription.created",
+ "data": {"object": {"id": "sub_123", "customer": "cus_1"}},
+ },
+ )
+ stub_lifecycle_emails["checkout"].assert_not_awaited()
+
+
+def test_subscription_updated_passes_previous_attributes_through(
+ mocker: pytest_mock.MockFixture, stub_lifecycle_emails
+) -> None:
+ """The cancel/resume emails fire on the flip, which is only visible in
+ previous_attributes."""
+ mocker.patch(
+ "backend.api.features.v1.sync_subscription_from_stripe", new_callable=AsyncMock
+ )
+ _post_event(
+ mocker,
+ {
+ "type": "customer.subscription.updated",
+ "data": {
+ "object": {"id": "sub_1", "customer": "cus_1"},
+ "previous_attributes": {"cancel_at_period_end": False},
+ },
+ },
+ )
+ subscription, previous = stub_lifecycle_emails["updated"].await_args.args
+ assert subscription["id"] == "sub_1"
+ assert previous == {"cancel_at_period_end": False}
+
+
+def test_subscription_deleted_triggers_the_plan_ended_email(
+ mocker: pytest_mock.MockFixture, stub_lifecycle_emails
+) -> None:
+ mocker.patch(
+ "backend.api.features.v1.sync_subscription_from_stripe", new_callable=AsyncMock
+ )
+ _post_event(
+ mocker,
+ {
+ "type": "customer.subscription.deleted",
+ "data": {"object": {"id": "sub_1", "customer": "cus_1"}},
+ },
+ )
+ stub_lifecycle_emails["deleted"].assert_awaited_once()
+
+
+def test_payment_failure_triggers_the_payment_email(
+ mocker: pytest_mock.MockFixture, stub_lifecycle_emails
+) -> None:
+ mocker.patch(
+ "backend.api.features.v1.handle_subscription_payment_failure",
+ new_callable=AsyncMock,
+ )
+ _post_event(
+ mocker,
+ {
+ "type": "invoice.payment_failed",
+ "data": {"object": {"id": "in_1", "customer": "cus_1"}},
+ },
+ )
+ stub_lifecycle_emails["payment_failed"].assert_awaited_once()
+
+
+def test_a_trial_ending_event_is_not_listened_for(
+ mocker: pytest_mock.MockFixture, stub_lifecycle_emails
+) -> None:
+ """The platform does not offer a trial, so this event does nothing."""
+ _post_event(
+ mocker,
+ {
+ "type": "customer.subscription.trial_will_end",
+ "data": {"object": {"id": "sub_1", "customer": "cus_1"}},
+ },
+ )
+ for mock in stub_lifecycle_emails.values():
+ mock.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/app.py b/autogpt_platform/backend/backend/app.py
index 68eac98ff7..e545a23931 100644
--- a/autogpt_platform/backend/backend/app.py
+++ b/autogpt_platform/backend/backend/app.py
@@ -43,7 +43,7 @@ def main(**kwargs):
from backend.data.db_manager import DatabaseManager
from backend.executor import ExecutionManager, Scheduler
from backend.executor.batch_executor import BatchExecutor
- from backend.notifications import NotificationManager
+ from backend.notifications.notifications import NotificationManager
from backend.platform_linking.manager import PlatformLinkingManager
run_processes(
diff --git a/autogpt_platform/backend/backend/data/alerts.py b/autogpt_platform/backend/backend/data/alerts.py
new file mode 100644
index 0000000000..012f3a2316
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/alerts.py
@@ -0,0 +1,314 @@
+"""Persistence for live alert conditions.
+
+One row per condition that needs the user's attention. `cause_key` identifies
+the condition, so re-raising the same problem updates the existing row instead
+of adding a duplicate, and resolving it can find the row by key alone.
+
+The lifecycle the alert engine drives off this table:
+
+ PENDING ── debounce window elapses, under the daily cap ──▶ SENT
+ │ │
+ │ condition clears first │ re-raised
+ ▼ ▼ within 24h
+ RESOLVED DEFERRED
+ │
+ folded into the next
+ Briefing's attention block
+"""
+
+import logging
+from datetime import datetime, timedelta, timezone
+
+from prisma.enums import AlertCause, AlertConditionStatus
+from prisma.models import AlertCondition
+from prisma.types import AlertConditionWhereInput
+from pydantic import BaseModel
+
+from backend.util.exceptions import DatabaseError
+from backend.util.json import SafeJson
+from backend.util.logging import TruncatedLogger
+
+logger = TruncatedLogger(logging.getLogger(__name__), prefix="[Alerts]")
+
+# The same cause never re-alerts inside this window; if it persists it
+# escalates into the next Briefing's attention block.
+ALERT_DEDUPE_WINDOW = timedelta(hours=24)
+
+# Only ever used to bound a counting read; well above the real daily cap so the
+# count is never silently truncated below it.
+MAX_ALERT_EMAILS_PER_DAY_CEILING = 100
+
+# Statuses that still describe a live problem, in the sense that the Briefing
+# should tell the user about it.
+LIVE_STATUSES = [
+ AlertConditionStatus.PENDING,
+ AlertConditionStatus.SENT,
+ AlertConditionStatus.DEFERRED,
+]
+
+
+class AlertConditionDTO(BaseModel):
+ id: str
+ user_id: str
+ cause: AlertCause
+ cause_key: str
+ data: dict
+ status: AlertConditionStatus
+ created_at: datetime
+ sent_at: datetime | None
+ briefed_at: datetime | None
+
+ @staticmethod
+ def from_db(model: AlertCondition) -> "AlertConditionDTO":
+ return AlertConditionDTO(
+ id=model.id,
+ user_id=model.userId,
+ cause=model.cause,
+ cause_key=model.causeKey,
+ data=dict(model.data),
+ status=model.status,
+ created_at=model.createdAt,
+ sent_at=model.sentAt,
+ briefed_at=model.briefedAt,
+ )
+
+
+async def raise_alert_condition(
+ user_id: str,
+ cause: AlertCause,
+ cause_key: str,
+ data: dict,
+) -> AlertConditionDTO:
+ """Record a live condition.
+
+ A condition alerted on within the last 24 hours does not re-alert: it
+ becomes DEFERRED and escalates into the next Briefing's attention block
+ instead of re-pinging the inbox.
+ """
+ dedupe_since = datetime.now(tz=timezone.utc) - ALERT_DEDUPE_WINDOW
+ try:
+ existing = await AlertCondition.prisma().find_unique(
+ where={"userId_causeKey": {"userId": user_id, "causeKey": cause_key}}
+ )
+ payload = SafeJson(data)
+ if existing is None:
+ created = await AlertCondition.prisma().create(
+ data={
+ "userId": user_id,
+ "cause": cause,
+ "causeKey": cause_key,
+ "data": payload,
+ }
+ )
+ return AlertConditionDTO.from_db(created)
+
+ recently_alerted = (
+ existing.sentAt is not None and existing.sentAt > dedupe_since
+ )
+ status = (
+ AlertConditionStatus.DEFERRED
+ if recently_alerted
+ else AlertConditionStatus.PENDING
+ )
+ # Keep a DEFERRED row deferred until a Briefing consumes it; promoting
+ # it back to PENDING would re-alert inside the 24h window.
+ if existing.status is AlertConditionStatus.DEFERRED:
+ status = AlertConditionStatus.DEFERRED
+
+ updated = await AlertCondition.prisma().update(
+ where={"id": existing.id},
+ data={
+ "cause": cause,
+ "data": payload,
+ "status": status,
+ "resolvedAt": None,
+ # A re-raise after a Briefing already reported it is news
+ # again, so let the next Briefing carry it.
+ "briefedAt": None,
+ },
+ )
+ if updated is None:
+ raise DatabaseError(f"Alert condition {existing.id} vanished mid-update")
+ return AlertConditionDTO.from_db(updated)
+ except DatabaseError:
+ raise
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to raise alert condition {cause_key} for user {user_id}: {e}"
+ ) from e
+
+
+async def resolve_alert_condition(user_id: str, cause_key: str) -> bool:
+ """Mark a condition fixed. Returns whether a live row was cleared.
+
+ Called when the underlying problem goes away — including during the
+ debounce window, which cancels the send outright, because an alert about a
+ solved problem trains people to ignore alerts.
+ """
+ try:
+ cleared = await AlertCondition.prisma().update_many(
+ where={
+ "userId": user_id,
+ "causeKey": cause_key,
+ "status": {"in": LIVE_STATUSES},
+ },
+ data={
+ "status": AlertConditionStatus.RESOLVED,
+ "resolvedAt": datetime.now(tz=timezone.utc),
+ },
+ )
+ return cleared > 0
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to resolve alert condition {cause_key} for user {user_id}: {e}"
+ ) from e
+
+
+class MaturedAlertPage(BaseModel):
+ """One keyset page of users with matured alerts.
+
+ `exhausted` is set from the row count rather than the user count,
+ because de-duplication shrinks the page.
+ """
+
+ user_ids: list[str]
+ exhausted: bool
+
+
+async def get_users_with_matured_alerts(
+ matured_before: datetime, after_user_id: str | None = None, limit: int = 1000
+) -> MaturedAlertPage:
+ """Users holding at least one PENDING condition older than the debounce
+ window, i.e. whose pending alerts are ready to go out as one email.
+
+ Bounded and keyset-paged on `userId`. This runs every minute against every
+ PENDING row on the platform; an unbounded `find_many` would pull each row's
+ full JSONB payload across the wire once a minute forever.
+
+ `distinct` is applied by the query engine after the take, so the page is
+ requested by ordered `userId` and de-duplicated here. That makes the
+ returned user count smaller than the rows read, so `exhausted` reports
+ whether the *raw* page was short — the caller cannot infer it from the
+ number of users, which is the normal case for anyone holding more than
+ one condition.
+ """
+ try:
+ where: AlertConditionWhereInput = {
+ "status": AlertConditionStatus.PENDING,
+ "createdAt": {"lt": matured_before},
+ }
+ if after_user_id:
+ where["userId"] = {"gt": after_user_id}
+ rows = await AlertCondition.prisma().find_many(
+ where=where,
+ order={"userId": "asc"},
+ take=limit,
+ )
+ seen: list[str] = []
+ for row in rows:
+ if not seen or seen[-1] != row.userId:
+ seen.append(row.userId)
+ return MaturedAlertPage(user_ids=seen, exhausted=len(rows) < limit)
+ except Exception as e:
+ raise DatabaseError(f"Failed to list users with matured alerts: {e}") from e
+
+
+# One user cannot have more distinct live causes than this before the email
+# stops being readable; the rest stay PENDING for the next flush.
+MAX_CONDITIONS_PER_EMAIL = 50
+
+
+async def get_pending_alert_conditions(user_id: str) -> list[AlertConditionDTO]:
+ try:
+ rows = await AlertCondition.prisma().find_many(
+ where={"userId": user_id, "status": AlertConditionStatus.PENDING},
+ order={"createdAt": "asc"},
+ take=MAX_CONDITIONS_PER_EMAIL,
+ )
+ return [AlertConditionDTO.from_db(row) for row in rows]
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to get pending alert conditions for user {user_id}: {e}"
+ ) from e
+
+
+async def count_alerts_sent_since(user_id: str, since: datetime) -> int:
+ """How many Alert *emails* this user has already had since `since`.
+
+ Every condition coalesced into one email is stamped with the same `sentAt`
+ (one `update_many` with one timestamp), so counting distinct timestamps
+ counts emails, not conditions — which is what the daily cap is about.
+ """
+ try:
+ rows = await AlertCondition.prisma().find_many(
+ where={"userId": user_id, "sentAt": {"gte": since}},
+ distinct=["sentAt"],
+ take=MAX_ALERT_EMAILS_PER_DAY_CEILING,
+ )
+ return len(rows)
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to count alerts sent for user {user_id}: {e}"
+ ) from e
+
+
+async def mark_alert_conditions_sent(condition_ids: list[str]) -> None:
+ if not condition_ids:
+ return
+ try:
+ await AlertCondition.prisma().update_many(
+ where={"id": {"in": condition_ids}},
+ data={
+ "status": AlertConditionStatus.SENT,
+ "sentAt": datetime.now(tz=timezone.utc),
+ },
+ )
+ except Exception as e:
+ raise DatabaseError(f"Failed to mark alert conditions sent: {e}") from e
+
+
+async def mark_alert_conditions_deferred(condition_ids: list[str]) -> None:
+ """Overflow past the daily cap folds into the Briefing rather than being
+ dropped — nothing actionable is ever silently lost."""
+ if not condition_ids:
+ return
+ try:
+ await AlertCondition.prisma().update_many(
+ where={"id": {"in": condition_ids}},
+ data={"status": AlertConditionStatus.DEFERRED},
+ )
+ except Exception as e:
+ raise DatabaseError(f"Failed to defer alert conditions: {e}") from e
+
+
+async def get_briefing_alert_conditions(user_id: str) -> list[AlertConditionDTO]:
+ """Everything the next Briefing's attention block must absorb: conditions
+ capped or deduped during the period, plus any still unresolved, minus the
+ ones a previous Briefing already reported."""
+ try:
+ rows = await AlertCondition.prisma().find_many(
+ where={
+ "userId": user_id,
+ "status": {"in": LIVE_STATUSES},
+ "briefedAt": None,
+ },
+ order={"createdAt": "asc"},
+ take=MAX_CONDITIONS_PER_EMAIL,
+ )
+ return [AlertConditionDTO.from_db(row) for row in rows]
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to get briefing alert conditions for user {user_id}: {e}"
+ ) from e
+
+
+async def mark_alert_conditions_briefed(condition_ids: list[str]) -> None:
+ if not condition_ids:
+ return
+ try:
+ await AlertCondition.prisma().update_many(
+ where={"id": {"in": condition_ids}},
+ data={"briefedAt": datetime.now(tz=timezone.utc)},
+ )
+ except Exception as e:
+ raise DatabaseError(f"Failed to mark alert conditions briefed: {e}") from e
diff --git a/autogpt_platform/backend/backend/data/briefing_data.py b/autogpt_platform/backend/backend/data/briefing_data.py
new file mode 100644
index 0000000000..20b4d08796
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/briefing_data.py
@@ -0,0 +1,202 @@
+"""Aggregation for the Briefing.
+
+The unit of aggregation is the **agent**, never the run. Runs are scored at
+completion, agents are ranked here, and the email is assembled top-down under a
+hard length budget — so ten thousand runs is a legitimate week without ten
+thousand of anything landing in an inbox.
+
+Everything below is one grouped read per user per period. Nothing walks the
+individual executions.
+"""
+
+import logging
+from datetime import datetime
+
+from prisma.models import AgentPreset, UserBalance
+from pydantic import BaseModel
+
+from backend.data.db import query_raw_with_schema
+from backend.util.exceptions import DatabaseError
+from backend.util.logging import TruncatedLogger
+
+logger = TruncatedLogger(logging.getLogger(__name__), prefix="[BriefingData]")
+
+
+class AgentPeriodStats(BaseModel):
+ """One agent's whole period, which is one ledger row."""
+
+ graph_id: str
+ agent: str
+ runs: int
+ failed: int
+ credits: float
+ top_score: float
+
+
+class ScoredRun(BaseModel):
+ """A candidate for the highlights block."""
+
+ execution_id: str
+ graph_id: str
+ agent: str
+ interestingness: float
+ activity_status: str | None
+
+
+async def get_agent_period_stats(
+ user_id: str, start: datetime, end: datetime
+) -> list[AgentPeriodStats]:
+ """Per-agent totals for the period, ranked by interestingness.
+
+ Ordering here is what the ledger's "six rows sorted by interestingness,
+ then + N more agents" rule reads off, so it is part of the contract rather
+ than a detail of the query.
+ """
+ try:
+ rows = await query_raw_with_schema(
+ """
+ SELECT
+ e."agentGraphId" AS graph_id,
+ COALESCE(MAX(g."name"), '') AS agent,
+ COUNT(*) AS runs,
+ COUNT(*) FILTER (
+ WHERE e."executionStatus" IN ('FAILED', 'TERMINATED')
+ ) AS failed,
+ COALESCE(SUM((e."stats"::jsonb->>'cost')::numeric), 0) AS cost_cents,
+ COALESCE(MAX(e."interestingness"), 0) AS top_score
+ FROM {schema_prefix}"AgentGraphExecution" e
+ LEFT JOIN {schema_prefix}"AgentGraph" g
+ ON g."id" = e."agentGraphId"
+ AND g."version" = e."agentGraphVersion"
+ WHERE e."userId" = $1
+ AND e."isDeleted" = false
+ -- `endedAt` is `timestamp without time zone` holding UTC, and the
+ -- driver binds these bounds as `timestamptz`. A bare `::timestamp`
+ -- cast converts using the session's TimeZone, so a non-UTC session
+ -- silently shifts the whole period window.
+ AND e."endedAt" >= ($2::timestamptz AT TIME ZONE 'UTC')
+ AND e."endedAt" < ($3::timestamptz AT TIME ZONE 'UTC')
+ GROUP BY e."agentGraphId"
+ ORDER BY top_score DESC, runs DESC, graph_id
+ """,
+ user_id,
+ start,
+ end,
+ )
+ return [_to_agent_stats(row) for row in rows]
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to aggregate briefing stats for user {user_id}: {e}"
+ ) from e
+
+
+async def get_top_scored_runs(
+ user_id: str, start: datetime, end: datetime, limit: int
+) -> list[ScoredRun]:
+ """The period's best candidates for highlights, straight off the score
+ written at completion time."""
+ try:
+ rows = await query_raw_with_schema(
+ """
+ SELECT
+ e."id" AS execution_id,
+ e."agentGraphId" AS graph_id,
+ COALESCE(g."name", '') AS agent,
+ COALESCE(e."interestingness", 0) AS interestingness,
+ e."stats"::jsonb->>'activity_status' AS activity_status
+ FROM {schema_prefix}"AgentGraphExecution" e
+ LEFT JOIN {schema_prefix}"AgentGraph" g
+ ON g."id" = e."agentGraphId"
+ AND g."version" = e."agentGraphVersion"
+ WHERE e."userId" = $1
+ AND e."isDeleted" = false
+ -- `endedAt` is `timestamp without time zone` holding UTC, and the
+ -- driver binds these bounds as `timestamptz`. A bare `::timestamp`
+ -- cast converts using the session's TimeZone, so a non-UTC session
+ -- silently shifts the whole period window.
+ AND e."endedAt" >= ($2::timestamptz AT TIME ZONE 'UTC')
+ AND e."endedAt" < ($3::timestamptz AT TIME ZONE 'UTC')
+ AND e."executionStatus" = 'COMPLETED'
+ ORDER BY e."interestingness" DESC NULLS LAST, e."endedAt" DESC
+ LIMIT $4
+ """,
+ user_id,
+ start,
+ end,
+ limit,
+ )
+ return [
+ ScoredRun(
+ execution_id=row["execution_id"],
+ graph_id=row["graph_id"],
+ agent=row["agent"] or _fallback_name(row["graph_id"]),
+ interestingness=float(row["interestingness"] or 0),
+ activity_status=row["activity_status"],
+ )
+ for row in rows
+ ]
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to read top-scored runs for user {user_id}: {e}"
+ ) from e
+
+
+async def count_active_agents(user_id: str) -> int:
+ """Every agent the user has switched on, counted once across its versions.
+
+ The Briefing subtracts the agents that actually ran from this to get the
+ "on standby" figure, rather than passing a list of IDs into SQL.
+ """
+ try:
+ rows = await query_raw_with_schema(
+ """
+ SELECT COUNT(DISTINCT "id") AS total
+ FROM {schema_prefix}"AgentGraph"
+ WHERE "userId" = $1
+ AND "isActive" = true
+ """,
+ user_id,
+ )
+ return int(rows[0]["total"]) if rows else 0
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to count active agents for user {user_id}: {e}"
+ ) from e
+
+
+async def count_scheduled_agents(user_id: str) -> int:
+ """Agents configured to run on their own — the ones that would silently
+ stop if the credits ran out."""
+ try:
+ return await AgentPreset.prisma().count(
+ where={"userId": user_id, "isActive": True, "isDeleted": False}
+ )
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to count scheduled agents for user {user_id}: {e}"
+ ) from e
+
+
+async def get_briefing_credit_balance(user_id: str) -> float:
+ """Balance in credits (the stored figure is cents)."""
+ try:
+ balance = await UserBalance.prisma().find_unique(where={"userId": user_id})
+ return (balance.balance if balance else 0) / 100
+ except Exception as e:
+ raise DatabaseError(f"Failed to read balance for user {user_id}: {e}") from e
+
+
+def _to_agent_stats(row: dict) -> AgentPeriodStats:
+ graph_id = row["graph_id"]
+ return AgentPeriodStats(
+ graph_id=graph_id,
+ agent=row["agent"] or _fallback_name(graph_id),
+ runs=int(row["runs"]),
+ failed=int(row["failed"]),
+ credits=float(row["cost_cents"]) / 100,
+ top_score=float(row["top_score"] or 0),
+ )
+
+
+def _fallback_name(graph_id: str) -> str:
+ return f"Agent {graph_id[:8]}"
diff --git a/autogpt_platform/backend/backend/data/credit.py b/autogpt_platform/backend/backend/data/credit.py
index 98533fbb43..5a39bfd4ed 100644
--- a/autogpt_platform/backend/backend/data/credit.py
+++ b/autogpt_platform/backend/backend/data/credit.py
@@ -37,9 +37,9 @@ from backend.data.model import (
)
from backend.data.model import User as AppUser
from backend.data.model import UserTransaction
-from backend.data.notifications import NotificationEventModel, RefundRequestData
+from backend.data.notifications import NotificationEventModel, OpsData
from backend.data.user import get_user_by_id, get_user_email_by_id
-from backend.notifications.notifications import queue_notification_async
+from backend.notifications.queue import queue_notification_async
from backend.util.cache import cached
from backend.util.exceptions import InsufficientBalanceError
from backend.util.feature_flag import Flag, get_feature_flag_value
@@ -731,14 +731,45 @@ class UserCreditBase(ABC):
class UserCredit(UserCreditBase):
async def _send_refund_notification(
self,
- notification_request: RefundRequestData,
- notification_type: NotificationType,
- ):
+ kind: Literal["request", "processed"],
+ user: AppUser,
+ transaction_id: str,
+ refund_request_id: str,
+ reason: str,
+ amount_cents: int,
+ balance_cents: int,
+ ) -> None:
+ """Internal mail to the refunds team. The amount leads, because it is
+ what the person on call triages by, and every timestamp is absolute —
+ the email is read hours later."""
+ now = datetime.now(tz=timezone.utc)
+ stamp = f"{now.day} {now.strftime('%B')} at {now.strftime('%H:%M')}"
await queue_notification_async(
- NotificationEventModel(
- user_id=notification_request.user_id,
- type=notification_type,
- data=notification_request,
+ NotificationEventModel[OpsData](
+ user_id=user.id,
+ type=NotificationType.OPS,
+ data=OpsData(
+ kind=kind,
+ user_name=user.name or "AutoGPT Platform User",
+ user_email=user.email,
+ user_id=user.id,
+ transaction_id=transaction_id,
+ refund_request_id=refund_request_id,
+ amount_cents=amount_cents,
+ balance_cents=balance_cents,
+ reason=reason,
+ recipient=settings.config.refund_notification_email,
+ stripe_url=(
+ f"https://dashboard.stripe.com/payments/{transaction_id}"
+ ),
+ admin_url=(
+ f"{settings.config.admin_panel_base_url}/refunds/"
+ f"{refund_request_id}"
+ ),
+ age_label=stamp if kind == "request" else None,
+ requested_at_label=stamp if kind == "request" else None,
+ processed_at_label=stamp if kind == "processed" else None,
+ ),
)
)
@@ -868,17 +899,13 @@ class UserCredit(UserCreditBase):
if amount - balance > settings.config.refund_credit_tolerance_threshold:
user_data = await get_user_by_id(user_id)
await self._send_refund_notification(
- RefundRequestData(
- user_id=user_id,
- user_name=user_data.name or "AutoGPT Platform User",
- user_email=user_data.email,
- transaction_id=transaction_key,
- refund_request_id=refund_request.id,
- reason=refund_request.reason,
- amount=amount,
- balance=balance,
- ),
- NotificationType.REFUND_REQUEST,
+ kind="request",
+ user=user_data,
+ transaction_id=transaction_key,
+ refund_request_id=refund_request.id,
+ reason=refund_request.reason,
+ amount_cents=amount,
+ balance_cents=balance,
)
return 0 # Register the refund request for manual approval.
@@ -935,17 +962,13 @@ class UserCredit(UserCreditBase):
user_data = await get_user_by_id(transaction.userId)
await self._send_refund_notification(
- RefundRequestData(
- user_id=user_data.id,
- user_name=user_data.name or "AutoGPT Platform User",
- user_email=user_data.email,
- transaction_id=transaction.transactionKey,
- refund_request_id=request.id,
- reason=str(request.reason or "-"),
- amount=transaction.amount,
- balance=balance,
- ),
- NotificationType.REFUND_PROCESSED,
+ kind="processed",
+ user=user_data,
+ transaction_id=transaction.transactionKey,
+ refund_request_id=request.id,
+ reason=str(request.reason or ""),
+ amount_cents=transaction.amount,
+ balance_cents=balance,
)
async def handle_dispute(self, dispute: stripe.Dispute):
@@ -3433,3 +3456,46 @@ async def admin_export_user_history(
)
)
return history
+
+
+# A forecast needs enough history to mean anything; below this the alert says
+# the balance is low without inventing a run-out date.
+SPEND_WINDOW_DAYS = 7
+MIN_SPEND_TRANSACTIONS = 3
+
+
+async def get_recent_daily_spend(user_id: str, days: int = SPEND_WINDOW_DAYS) -> float:
+ """Mean daily spend in credit-cents over the last `days`, or 0.0.
+
+ The runway forecast used to divide the balance by the cost of the single
+ transaction that happened to cross the threshold, so a one-cent charge
+ against a five-credit balance produced a run-out date more than a year
+ out — inside an email whose whole point is that the balance is nearly
+ gone. This reads what the account actually spends.
+
+ Returns 0.0 when there is too little history to forecast from; the caller
+ omits the forecast rather than publishing one built from noise.
+ """
+ since = datetime.now(tz=timezone.utc) - timedelta(days=days)
+ try:
+ rows = await query_raw_with_schema(
+ """
+ SELECT COALESCE(SUM(ABS("amount")), 0) AS spent, COUNT(*) AS txns
+ FROM {schema_prefix}"CreditTransaction"
+ WHERE "userId" = $1
+ AND "type" = 'USAGE'
+ AND "createdAt" >= ($2::timestamptz AT TIME ZONE 'UTC')
+ """,
+ user_id,
+ since,
+ )
+ except Exception:
+ logger.warning(
+ "Could not read recent spend for user %s; omitting the forecast",
+ user_id,
+ exc_info=True,
+ )
+ return 0.0
+ if not rows or int(rows[0]["txns"] or 0) < MIN_SPEND_TRANSACTIONS:
+ return 0.0
+ return float(rows[0]["spent"] or 0) / days
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index 7d540af090..40813dfade 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -52,6 +52,17 @@ from backend.copilot.sharing.db import link_new_execution_to_chat_share
from backend.data import bot_analytics as bot_analytics_db
from backend.data import bot_installs as bot_installs_db
from backend.data import db
+from backend.data.alerts import (
+ count_alerts_sent_since,
+ get_briefing_alert_conditions,
+ get_pending_alert_conditions,
+ get_users_with_matured_alerts,
+ mark_alert_conditions_briefed,
+ mark_alert_conditions_deferred,
+ mark_alert_conditions_sent,
+ raise_alert_condition,
+ resolve_alert_condition,
+)
from backend.data.analytics import (
get_accuracy_trends_and_alerts,
get_marketplace_graphs_for_monitoring,
@@ -68,8 +79,16 @@ from backend.data.briefing import (
mark_briefing_delivered,
update_briefing_content,
)
+from backend.data.briefing_data import (
+ count_active_agents,
+ count_scheduled_agents,
+ get_agent_period_stats,
+ get_briefing_credit_balance,
+ get_top_scored_runs,
+)
from backend.data.credit import (
UsageTransactionMetadata,
+ get_recent_daily_spend,
get_user_credit_model,
reconcile_stripe_tier_for_user,
)
@@ -95,7 +114,6 @@ from backend.data.execution import (
upsert_execution_input,
upsert_execution_output,
)
-from backend.data.generate_data import get_user_execution_summary_data
from backend.data.graph import (
get_connected_output_nodes,
get_graph,
@@ -116,15 +134,6 @@ from backend.data.human_review import (
has_pending_reviews_for_graph_exec,
update_review_processed_status,
)
-from backend.data.notifications import (
- clear_all_user_notification_batches,
- create_or_add_to_user_notification_batch,
- empty_user_notification_batch,
- get_all_batches_by_type,
- get_user_notification_batch,
- get_user_notification_oldest_message_in_batch,
- remove_notifications_from_batch,
-)
from backend.data.onboarding import increment_onboarding_runs
from backend.data.org_credit import get_org_credits as _get_org_credits_raw
from backend.data.org_credit import get_personal_org_owner
@@ -142,8 +151,12 @@ from backend.data.understanding import (
upsert_business_understanding,
)
from backend.data.user import (
+ claim_welcome_email,
get_active_user_ids_in_timerange,
get_auth_user_flag_fields,
+ get_billing_email_recipient,
+ get_briefing_candidate,
+ get_briefing_candidates,
get_user_by_id,
get_user_credentials,
get_user_email_by_id,
@@ -151,6 +164,8 @@ from backend.data.user import (
get_user_integrations,
get_user_notification_preference,
get_user_subscription_tier,
+ release_welcome_email,
+ set_last_briefing_at,
set_user_credentials,
update_user_integrations,
)
@@ -345,19 +360,6 @@ class DatabaseManager(AppService):
has_pending_reviews_for_graph_exec = _(has_pending_reviews_for_graph_exec)
update_review_processed_status = _(update_review_processed_status)
- # ============ Notifications ============ #
- clear_all_user_notification_batches = _(clear_all_user_notification_batches)
- create_or_add_to_user_notification_batch = _(
- create_or_add_to_user_notification_batch
- )
- empty_user_notification_batch = _(empty_user_notification_batch)
- remove_notifications_from_batch = _(remove_notifications_from_batch)
- get_all_batches_by_type = _(get_all_batches_by_type)
- get_user_notification_batch = _(get_user_notification_batch)
- get_user_notification_oldest_message_in_batch = _(
- get_user_notification_oldest_message_in_batch
- )
-
# ============ Library ============ #
list_library_agents = _(list_library_agents)
add_store_agent_to_library = _(add_store_agent_to_library)
@@ -406,8 +408,20 @@ class DatabaseManager(AppService):
cleanup_orphaned_embeddings = _(cleanup_orphaned_embeddings)
unified_hybrid_search = _(unified_hybrid_search)
- # ============ Summary Data ============ #
- get_user_execution_summary_data = _(get_user_execution_summary_data)
+ # ============ Alerts ============ #
+ raise_alert_condition = _(raise_alert_condition)
+ resolve_alert_condition = _(resolve_alert_condition)
+ # The notification service drives the Alert and Briefing passes from here;
+ # it owns no Prisma connection of its own.
+ get_users_with_matured_alerts = _(get_users_with_matured_alerts)
+ get_pending_alert_conditions = _(get_pending_alert_conditions)
+ count_alerts_sent_since = _(count_alerts_sent_since)
+ mark_alert_conditions_sent = _(mark_alert_conditions_sent)
+ mark_alert_conditions_deferred = _(mark_alert_conditions_deferred)
+ get_briefing_alert_conditions = _(get_briefing_alert_conditions)
+ mark_alert_conditions_briefed = _(mark_alert_conditions_briefed)
+ count_scheduled_agents = _(count_scheduled_agents)
+ get_recent_daily_spend = _(get_recent_daily_spend)
# ============ Chat Sharing ============ #
# Exposed so the run_agent tool (running in the CoPilotExecutor
@@ -556,6 +570,25 @@ class DatabaseManager(AppService):
get_briefing_for_date = _(get_briefing_for_date)
get_latest_briefings = _(get_latest_briefings)
mark_briefing_delivered = _(mark_briefing_delivered)
+
+ # ============ Briefing / Alert engine (notification service) ============ #
+ # These run in the NotificationManager process, which owns no Prisma
+ # connection, so every read goes through this RPC surface.
+ get_agent_period_stats = _(get_agent_period_stats)
+ get_top_scored_runs = _(get_top_scored_runs)
+ count_active_agents = _(count_active_agents)
+ get_briefing_credit_balance = _(get_briefing_credit_balance)
+ get_briefing_candidates = _(get_briefing_candidates)
+ get_briefing_candidate = _(get_briefing_candidate)
+ set_last_briefing_at = _(set_last_briefing_at)
+
+ # ============ Billing emails ============ #
+ # The lifecycle handlers run in the REST API on a Stripe webhook *and* in
+ # the notification service when the welcome comes off the work queue. That
+ # second process has no Prisma connection, so these cross the RPC.
+ get_billing_email_recipient = _(get_billing_email_recipient)
+ claim_welcome_email = _(claim_welcome_email)
+ release_welcome_email = _(release_welcome_email)
update_briefing_content = _(update_briefing_content)
@@ -600,6 +633,12 @@ class DatabaseManagerClient(AppServiceClient):
# User Emails
get_user_email_by_id = _(d.get_user_email_by_id)
+ # Alerts
+ raise_alert_condition = _(d.raise_alert_condition)
+ resolve_alert_condition = _(d.resolve_alert_condition)
+ count_scheduled_agents = _(d.count_scheduled_agents)
+ get_recent_daily_spend = _(d.get_recent_daily_spend)
+
# Library
list_library_agents = _(d.list_library_agents)
add_store_agent_to_library = _(d.add_store_agent_to_library)
@@ -690,18 +729,32 @@ class DatabaseManagerAsyncClient(AppServiceClient):
get_user_email_verification = d.get_user_email_verification
get_user_notification_preference = d.get_user_notification_preference
- # ============ Notifications ============ #
- clear_all_user_notification_batches = d.clear_all_user_notification_batches
- create_or_add_to_user_notification_batch = (
- d.create_or_add_to_user_notification_batch
- )
- empty_user_notification_batch = d.empty_user_notification_batch
- remove_notifications_from_batch = d.remove_notifications_from_batch
- get_all_batches_by_type = d.get_all_batches_by_type
- get_user_notification_batch = d.get_user_notification_batch
- get_user_notification_oldest_message_in_batch = (
- d.get_user_notification_oldest_message_in_batch
- )
+ # ============ Alerts ============ #
+ raise_alert_condition = d.raise_alert_condition
+ resolve_alert_condition = d.resolve_alert_condition
+ count_scheduled_agents = d.count_scheduled_agents
+ get_recent_daily_spend = d.get_recent_daily_spend
+
+ # ============ Briefing / Alert engine (notification service) ============ #
+ # The NotificationManager owns no Prisma connection, so its scheduled
+ # passes read and write exclusively through these.
+ get_users_with_matured_alerts = d.get_users_with_matured_alerts
+ get_pending_alert_conditions = d.get_pending_alert_conditions
+ count_alerts_sent_since = d.count_alerts_sent_since
+ mark_alert_conditions_sent = d.mark_alert_conditions_sent
+ mark_alert_conditions_deferred = d.mark_alert_conditions_deferred
+ get_briefing_alert_conditions = d.get_briefing_alert_conditions
+ mark_alert_conditions_briefed = d.mark_alert_conditions_briefed
+ get_agent_period_stats = d.get_agent_period_stats
+ get_top_scored_runs = d.get_top_scored_runs
+ count_active_agents = d.count_active_agents
+ get_briefing_credit_balance = d.get_briefing_credit_balance
+ get_briefing_candidates = d.get_briefing_candidates
+ get_briefing_candidate = d.get_briefing_candidate
+ set_last_briefing_at = d.set_last_briefing_at
+ get_billing_email_recipient = d.get_billing_email_recipient
+ claim_welcome_email = d.claim_welcome_email
+ release_welcome_email = d.release_welcome_email
# ============ Morning Briefing ============ #
append_plain_session_message = d.append_plain_session_message
@@ -756,9 +809,6 @@ class DatabaseManagerAsyncClient(AppServiceClient):
# ============ Search ============ #
unified_hybrid_search = d.unified_hybrid_search
- # ============ Summary Data ============ #
- get_user_execution_summary_data = d.get_user_execution_summary_data
-
# ============ Chat Sharing ============ #
link_new_execution_to_chat_share = d.link_new_execution_to_chat_share
diff --git a/autogpt_platform/backend/backend/data/diagnostics.py b/autogpt_platform/backend/backend/data/diagnostics.py
index 35c39bf490..70bd967c59 100644
--- a/autogpt_platform/backend/backend/data/diagnostics.py
+++ b/autogpt_platform/backend/backend/data/diagnostics.py
@@ -33,8 +33,8 @@ SYSTEM_JOB_IDS = {
"cleanup_expired_files",
"report_late_executions",
"report_block_error_rates",
- "process_existing_batches",
- "process_weekly_summary",
+ "flush_matured_alerts",
+ "send_due_briefings",
}
diff --git a/autogpt_platform/backend/backend/data/execution.py b/autogpt_platform/backend/backend/data/execution.py
index 6b8d31bedb..a1ec649ffb 100644
--- a/autogpt_platform/backend/backend/data/execution.py
+++ b/autogpt_platform/backend/backend/data/execution.py
@@ -49,6 +49,7 @@ from backend.blocks import get_block, get_io_block_ids, get_webhook_block_ids
from backend.blocks._base import BlockType
from backend.data.expert_run_output import reconstruct_run_outputs
from backend.data.tenancy import get_user_team_ids, visibility_filter
+from backend.notifications.scoring import score_completed_run
from backend.util import type as type_utils
from backend.util.exceptions import (
DatabaseError,
@@ -1217,6 +1218,11 @@ async def update_graph_execution_stats(
data=update_data,
)
+ if status in TERMINAL_GRAPH_EXECUTION_STATUSES:
+ # Score the finished run for the Briefing while its stats are fresh.
+ # Never raises — a scoring failure must not fail the run.
+ await score_completed_run(graph_exec_id)
+
if cascade_running_children and status in TERMINAL_GRAPH_EXECUTION_STATUSES:
# Sweep any child node_execs that are still RUNNING. Without this,
# an in-flight node task whose asyncio cancel didn't propagate
diff --git a/autogpt_platform/backend/backend/data/execution_cascade_test.py b/autogpt_platform/backend/backend/data/execution_cascade_test.py
index ee52c17866..326a150df0 100644
--- a/autogpt_platform/backend/backend/data/execution_cascade_test.py
+++ b/autogpt_platform/backend/backend/data/execution_cascade_test.py
@@ -1,3 +1,4 @@
+from collections.abc import Iterator
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -8,6 +9,14 @@ from backend.blocks.autopilot import AutoPilotBlock
from backend.data.execution import ExecutionStatus, update_graph_execution_stats
[email protected](autouse=True)
+def mock_score_completed_run() -> Iterator[AsyncMock]:
+ with patch(
+ "backend.data.execution.score_completed_run", new_callable=AsyncMock
+ ) as mock:
+ yield mock
+
+
def test_default_block_has_execution_timeout():
"""Leaf compute blocks inherit the default wall-clock cap."""
diff --git a/autogpt_platform/backend/backend/data/generate_data.py b/autogpt_platform/backend/backend/data/generate_data.py
deleted file mode 100644
index 94f649ac1e..0000000000
--- a/autogpt_platform/backend/backend/data/generate_data.py
+++ /dev/null
@@ -1,137 +0,0 @@
-import asyncio
-import logging
-from datetime import datetime
-
-from pydantic import BaseModel, Field
-
-from backend.data.db import query_raw_with_schema
-from backend.data.graph import get_graph_metadata
-from backend.data.model import UserExecutionSummaryStats
-from backend.util.exceptions import DatabaseError
-from backend.util.logging import TruncatedLogger
-
-logger = TruncatedLogger(logging.getLogger(__name__), prefix="[SummaryData]")
-
-
-class _ExecutionAggregates(BaseModel):
- total_executions: int = 0
- successful_runs: int = 0
- failed_runs: int = 0
- total_cost_cents: float = 0.0
- total_walltime: float = 0.0
- walltime_count: int = 0
- cost_by_graph_id: dict[str, float] = Field(default_factory=dict)
- usage_by_graph_id: dict[str, int] = Field(default_factory=dict)
-
-
-async def get_user_execution_summary_data(
- user_id: str, start_time: datetime, end_time: datetime
-) -> UserExecutionSummaryStats:
- """Aggregate per-graph execution stats for a user via grouped SQL.
-
- Pulls only one summary row per agentGraphId instead of every individual
- AgentGraphExecution: heavy users had thousands of executions per call,
- making this the dominant row-egress query in the prior implementation.
- """
- try:
- rows = await _fetch_execution_aggregate_rows(user_id, start_time, end_time)
- agg = _reduce_execution_rows(rows)
- name_by_graph_id = await _resolve_agent_names(list(agg.cost_by_graph_id))
- return _assemble_summary(agg, name_by_graph_id)
- except Exception as e:
- logger.error(f"Failed to get user summary data: {e}")
- raise DatabaseError(f"Failed to get user summary data: {e}") from e
-
-
-async def _fetch_execution_aggregate_rows(
- user_id: str, start_time: datetime, end_time: datetime
-) -> list[dict]:
- return await query_raw_with_schema(
- """
- SELECT
- "agentGraphId" AS graph_id,
- COUNT(*) AS total,
- COUNT(*) FILTER (WHERE "executionStatus" = 'COMPLETED') AS successful,
- COUNT(*) FILTER (WHERE "executionStatus" IN ('FAILED', 'TERMINATED')) AS failed,
- COALESCE(SUM(("stats"::jsonb->>'cost')::numeric), 0) AS total_cost_cents,
- COALESCE(SUM(("stats"::jsonb->>'walltime')::numeric), 0) AS total_walltime,
- COUNT(*) FILTER (WHERE ("stats"::jsonb->>'walltime') IS NOT NULL) AS walltime_count
- FROM {schema_prefix}"AgentGraphExecution"
- WHERE "userId" = $1
- AND "isDeleted" = false
- AND "createdAt" >= $2::timestamp
- AND "createdAt" <= $3::timestamp
- GROUP BY "agentGraphId"
- """,
- user_id,
- start_time,
- end_time,
- )
-
-
-def _reduce_execution_rows(rows: list[dict]) -> _ExecutionAggregates:
- agg = _ExecutionAggregates()
- for row in rows:
- graph_id = row["graph_id"]
- count = int(row["total"])
- cost_cents = float(row["total_cost_cents"])
-
- agg.total_executions += count
- agg.successful_runs += int(row["successful"])
- agg.failed_runs += int(row["failed"])
- agg.total_cost_cents += cost_cents
- agg.total_walltime += float(row["total_walltime"])
- agg.walltime_count += int(row["walltime_count"])
- agg.usage_by_graph_id[graph_id] = count
- agg.cost_by_graph_id[graph_id] = cost_cents / 100
- return agg
-
-
-async def _resolve_agent_names(graph_ids: list[str]) -> dict[str, str]:
- resolved = await asyncio.gather(*(_resolve_agent_name(gid) for gid in graph_ids))
- return dict(zip(graph_ids, resolved))
-
-
-def _assemble_summary(
- agg: _ExecutionAggregates, name_by_graph_id: dict[str, str]
-) -> UserExecutionSummaryStats:
- most_used_agent = "No agents used"
- if agg.usage_by_graph_id:
- # Tuple key gives a deterministic tie-break by graph_id when execution
- # counts match, instead of relying on dict insertion order.
- most_used_agent_id = max(
- agg.usage_by_graph_id,
- key=lambda k: (agg.usage_by_graph_id[k], k),
- )
- most_used_agent = name_by_graph_id[most_used_agent_id]
-
- # Sum on name collisions (two distinct graphs can resolve to the same
- # display name); a plain assign would silently drop one bucket.
- cost_breakdown: dict[str, float] = {}
- for graph_id, cost in agg.cost_by_graph_id.items():
- name = name_by_graph_id[graph_id]
- cost_breakdown[name] = cost_breakdown.get(name, 0.0) + cost
-
- average_execution_time = (
- agg.total_walltime / agg.walltime_count if agg.walltime_count else 0
- )
-
- return UserExecutionSummaryStats(
- total_credits_used=agg.total_cost_cents / 100,
- total_executions=agg.total_executions,
- successful_runs=agg.successful_runs,
- failed_runs=agg.failed_runs,
- most_used_agent=most_used_agent,
- total_execution_time=agg.total_walltime,
- average_execution_time=average_execution_time,
- cost_breakdown=cost_breakdown,
- )
-
-
-async def _resolve_agent_name(graph_id: str) -> str:
- try:
- graph_meta = await get_graph_metadata(graph_id=graph_id)
- return graph_meta.name if graph_meta else f"Agent {graph_id[:8]}"
- except Exception:
- logger.warning(f"Could not get metadata for graph {graph_id}", exc_info=True)
- return f"Agent {graph_id[:8]}"
diff --git a/autogpt_platform/backend/backend/data/generate_data_test.py b/autogpt_platform/backend/backend/data/generate_data_test.py
deleted file mode 100644
index 7f144bc59b..0000000000
--- a/autogpt_platform/backend/backend/data/generate_data_test.py
+++ /dev/null
@@ -1,293 +0,0 @@
-"""Tests for the SQL-aggregated user execution summary."""
-
-import logging
-from datetime import datetime, timedelta, timezone
-from uuid import uuid4
-
-import pytest
-from prisma.enums import AgentExecutionStatus
-from prisma.errors import UniqueViolationError
-from prisma.models import AgentGraph, AgentGraphExecution, User
-
-from backend.data import generate_data
-from backend.data.generate_data import (
- _resolve_agent_name,
- get_user_execution_summary_data,
-)
-from backend.util.json import SafeJson
-from backend.util.test import SpinTestServer
-
-logger = logging.getLogger(__name__)
-
-
-async def _create_test_user(user_id: str) -> None:
- try:
- await User.prisma().create(
- data={
- "id": user_id,
- "email": f"test-{user_id}@example.com",
- "name": f"Test User {user_id[:8]}",
- }
- )
- except UniqueViolationError:
- # Idempotent test setup: row already exists from a prior run.
- pass
-
-
-async def _create_graph(graph_id: str, user_id: str, name: str) -> None:
- try:
- await AgentGraph.prisma().create(
- data={
- "id": graph_id,
- "version": 1,
- "name": name,
- "description": "test",
- "userId": user_id,
- "isActive": True,
- }
- )
- except UniqueViolationError:
- # Idempotent test setup: row already exists from a prior run.
- pass
-
-
-async def _create_exec(
- exec_id: str,
- user_id: str,
- graph_id: str,
- status: AgentExecutionStatus,
- cost_cents: int,
- walltime_s: float,
- created_at: datetime,
-) -> None:
- await AgentGraphExecution.prisma().create(
- data={
- "id": exec_id,
- "agentGraphId": graph_id,
- "agentGraphVersion": 1,
- "executionStatus": status,
- "userId": user_id,
- "createdAt": created_at,
- "stats": SafeJson({"cost": cost_cents, "walltime": walltime_s}),
- }
- )
-
-
-async def _cleanup(user_id: str, graph_ids: list[str]) -> None:
- try:
- await AgentGraphExecution.prisma().delete_many(where={"userId": user_id})
- for gid in graph_ids:
- await AgentGraph.prisma().delete_many(where={"id": gid})
- await User.prisma().delete_many(where={"id": user_id})
- except Exception as exc:
- logger.warning("cleanup for %s failed: %s", user_id, exc)
-
-
[email protected](loop_scope="session")
-async def test_summary_empty_returns_zero_stats(server: SpinTestServer):
- user_id = f"sum-empty-{uuid4()}"
- await _create_test_user(user_id)
- try:
- now = datetime.now(timezone.utc)
- stats = await get_user_execution_summary_data(
- user_id, now - timedelta(days=1), now
- )
- assert stats.total_executions == 0
- assert stats.successful_runs == 0
- assert stats.failed_runs == 0
- assert stats.total_credits_used == 0
- assert stats.total_execution_time == 0
- assert stats.average_execution_time == 0
- assert stats.cost_breakdown == {}
- assert stats.most_used_agent == "No agents used"
- finally:
- await _cleanup(user_id, [])
-
-
[email protected](loop_scope="session")
-async def test_summary_aggregates_by_status_and_graph(server: SpinTestServer):
- user_id = f"sum-agg-{uuid4()}"
- graph_a = f"graph-a-{uuid4()}"
- graph_b = f"graph-b-{uuid4()}"
- await _create_test_user(user_id)
- await _create_graph(graph_a, user_id, "Alpha")
- await _create_graph(graph_b, user_id, "Beta")
-
- now = datetime.now(timezone.utc)
- in_window = now - timedelta(hours=1)
-
- try:
- # Graph A: 2 successful (50 + 75 cents), 1 failed (25 cents)
- await _create_exec(
- f"a1-{uuid4()}",
- user_id,
- graph_a,
- AgentExecutionStatus.COMPLETED,
- 50,
- 1.5,
- in_window,
- )
- await _create_exec(
- f"a2-{uuid4()}",
- user_id,
- graph_a,
- AgentExecutionStatus.COMPLETED,
- 75,
- 2.5,
- in_window,
- )
- await _create_exec(
- f"a3-{uuid4()}",
- user_id,
- graph_a,
- AgentExecutionStatus.FAILED,
- 25,
- 0.5,
- in_window,
- )
- # Graph B: 1 terminated (10 cents) — counted as failed
- await _create_exec(
- f"b1-{uuid4()}",
- user_id,
- graph_b,
- AgentExecutionStatus.TERMINATED,
- 10,
- 0.1,
- in_window,
- )
-
- stats = await get_user_execution_summary_data(
- user_id, now - timedelta(hours=2), now
- )
-
- assert stats.total_executions == 4
- assert stats.successful_runs == 2
- assert stats.failed_runs == 2 # 1 FAILED + 1 TERMINATED
- assert stats.total_credits_used == pytest.approx((50 + 75 + 25 + 10) / 100)
- assert stats.total_execution_time == pytest.approx(1.5 + 2.5 + 0.5 + 0.1)
- assert stats.average_execution_time == pytest.approx(
- (1.5 + 2.5 + 0.5 + 0.1) / 4
- )
- # Most-used agent is Graph A (3 executions vs Graph B's 1)
- assert stats.most_used_agent == "Alpha"
- # Cost breakdown keyed by agent name
- assert stats.cost_breakdown == {
- "Alpha": pytest.approx((50 + 75 + 25) / 100),
- "Beta": pytest.approx(10 / 100),
- }
- finally:
- await _cleanup(user_id, [graph_a, graph_b])
-
-
[email protected](loop_scope="session")
-async def test_summary_sums_costs_on_agent_name_collision(server: SpinTestServer):
- # Two distinct agentGraphIds resolving to the same display name must sum
- # into the same cost_breakdown bucket, not overwrite each other.
- user_id = f"sum-collide-{uuid4()}"
- graph_a = f"graph-c1-{uuid4()}"
- graph_b = f"graph-c2-{uuid4()}"
- await _create_test_user(user_id)
- await _create_graph(graph_a, user_id, "Scraper")
- await _create_graph(graph_b, user_id, "Scraper")
-
- now = datetime.now(timezone.utc)
- in_window = now - timedelta(hours=1)
-
- try:
- await _create_exec(
- f"c1-{uuid4()}",
- user_id,
- graph_a,
- AgentExecutionStatus.COMPLETED,
- 30,
- 1.0,
- in_window,
- )
- await _create_exec(
- f"c2-{uuid4()}",
- user_id,
- graph_b,
- AgentExecutionStatus.COMPLETED,
- 70,
- 2.0,
- in_window,
- )
-
- stats = await get_user_execution_summary_data(
- user_id, now - timedelta(hours=2), now
- )
-
- assert stats.cost_breakdown == {
- "Scraper": pytest.approx((30 + 70) / 100),
- }
- assert stats.total_credits_used == pytest.approx(100 / 100)
- finally:
- await _cleanup(user_id, [graph_a, graph_b])
-
-
[email protected](loop_scope="session")
-async def test_summary_excludes_out_of_window(server: SpinTestServer):
- user_id = f"sum-window-{uuid4()}"
- graph_a = f"graph-w-{uuid4()}"
- await _create_test_user(user_id)
- await _create_graph(graph_a, user_id, "InWindow")
-
- now = datetime.now(timezone.utc)
- in_window = now - timedelta(hours=1)
- out_of_window = now - timedelta(days=10)
-
- try:
- await _create_exec(
- f"in-{uuid4()}",
- user_id,
- graph_a,
- AgentExecutionStatus.COMPLETED,
- 100,
- 1.0,
- in_window,
- )
- await _create_exec(
- f"out-{uuid4()}",
- user_id,
- graph_a,
- AgentExecutionStatus.COMPLETED,
- 200,
- 2.0,
- out_of_window,
- )
-
- stats = await get_user_execution_summary_data(
- user_id, now - timedelta(hours=2), now
- )
- assert stats.total_executions == 1
- assert stats.total_credits_used == pytest.approx(100 / 100)
- finally:
- await _cleanup(user_id, [graph_a])
-
-
-async def test_resolve_agent_name_falls_back_on_exception(
- monkeypatch: pytest.MonkeyPatch,
-):
- # Direct unit test: when get_graph_metadata raises, _resolve_agent_name
- # logs and returns the short-id fallback.
- async def boom(graph_id: str, version=None):
- raise RuntimeError("simulated DB blip")
-
- monkeypatch.setattr(generate_data, "get_graph_metadata", boom)
- name = await _resolve_agent_name("abcdef0123456789")
- assert name == "Agent abcdef01"
-
-
-async def test_resolve_agent_name_falls_back_when_metadata_missing(
- monkeypatch: pytest.MonkeyPatch,
-):
- # When get_graph_metadata returns None (e.g. graph not found),
- # _resolve_agent_name must produce a short-id label.
- async def returns_none(graph_id: str, version=None):
- return None
-
- monkeypatch.setattr(generate_data, "get_graph_metadata", returns_none)
- name = await _resolve_agent_name("abcdef0123456789")
- assert name == "Agent abcdef01"
diff --git a/autogpt_platform/backend/backend/data/human_review.py b/autogpt_platform/backend/backend/data/human_review.py
index bf697d2a5c..2a356d8ac2 100644
--- a/autogpt_platform/backend/backend/data/human_review.py
+++ b/autogpt_platform/backend/backend/data/human_review.py
@@ -29,6 +29,7 @@ from backend.copilot.constants import (
parse_node_id_from_exec_id,
)
from backend.data.execution import get_graph_execution_meta
+from backend.notifications.review_alerts import sync_awaiting_review
from backend.util.json import SafeJson
if TYPE_CHECKING:
@@ -47,6 +48,24 @@ class ReviewResult(BaseModel):
node_exec_id: str
+async def _sync_awaiting_review_safely(user_id: str, graph_id: str) -> None:
+ """Keep the awaiting-review alert from deciding whether a review succeeds.
+
+ The alert is a notification side effect. Raising here would report failure
+ for a review that was actually recorded — the node is already paused, or
+ the rows are already marked REJECTED by the time this runs — and would roll
+ the caller back over a notification problem.
+ """
+ try:
+ await sync_awaiting_review(user_id, graph_id)
+ except Exception:
+ logger.warning(
+ "Could not sync the awaiting-review alert for graph %s",
+ graph_id,
+ exc_info=True,
+ )
+
+
def get_auto_approve_key(graph_exec_id: str, node_id: str) -> str:
"""Generate the special nodeExecId key for auto-approval records."""
return f"auto_approve_{graph_exec_id}_{node_id}"
@@ -237,6 +256,9 @@ async def get_or_create_human_review(
# If pending, return None to continue waiting, otherwise return the review result
if review.status == ReviewStatus.WAITING:
+ # Nothing sends until a human acts, which is exactly the shape of an
+ # Alert. The engine debounces and coalesces from here.
+ await _sync_awaiting_review_safely(user_id, graph_id)
return None
else:
return ReviewResult(
@@ -652,6 +674,11 @@ async def process_all_reviews_for_execution(
# Execute all updates in parallel and get updated reviews
updated_reviews = await asyncio.gather(*update_tasks) if update_tasks else []
+ # Re-derive the "waiting on your review" alert from the live queue, so
+ # clearing the last item resolves it rather than leaving a stale alert.
+ for review in {(r.userId, r.graphId) for r in reviews_to_process}:
+ await _sync_awaiting_review_safely(review[0], review[1])
+
# Note: Execution resumption is now handled at the API layer after ALL reviews
# for an execution are processed (both approved and rejected)
@@ -722,6 +749,7 @@ async def cancel_pending_reviews_for_execution(graph_exec_id: str, user_id: str)
"reviewedAt": datetime.now(timezone.utc),
},
)
+ await sync_awaiting_review(user_id, graph_exec.graph_id)
return result
diff --git a/autogpt_platform/backend/backend/data/model.py b/autogpt_platform/backend/backend/data/model.py
index 714c9afe1c..8ea0869039 100644
--- a/autogpt_platform/backend/backend/data/model.py
+++ b/autogpt_platform/backend/backend/data/model.py
@@ -21,7 +21,7 @@ from typing import (
)
from uuid import uuid4
-from prisma.enums import CreditTransactionType, SubscriptionTier
+from prisma.enums import BriefingFrequency, CreditTransactionType, SubscriptionTier
from pydantic import (
BaseModel,
ConfigDict,
@@ -78,29 +78,17 @@ class User(BaseModel):
default=SubscriptionTier.NO_TIER, description="User subscription tier"
)
- # Notification preferences
+ # Notification preferences: the volume knob, not a checkbox list.
max_emails_per_day: int = Field(default=3, description="Maximum emails per day")
- notify_on_agent_run: bool = Field(default=True, description="Notify on agent run")
- notify_on_zero_balance: bool = Field(
- default=True, description="Notify on zero balance"
+ briefing_frequency: BriefingFrequency = Field(
+ default=BriefingFrequency.WEEKLY,
+ description="How often the Briefing digest is delivered (OFF = alerts only)",
)
- notify_on_low_balance: bool = Field(
- default=True, description="Notify on low balance"
+ alerts_enabled: bool = Field(
+ default=True, description="Send Alerts when something is blocked on the user"
)
- notify_on_block_execution_failed: bool = Field(
- default=True, description="Notify on block execution failure"
- )
- notify_on_continuous_agent_error: bool = Field(
- default=True, description="Notify on continuous agent error"
- )
- notify_on_daily_summary: bool = Field(
- default=True, description="Notify on daily summary"
- )
- notify_on_weekly_summary: bool = Field(
- default=True, description="Notify on weekly summary"
- )
- notify_on_monthly_summary: bool = Field(
- default=True, description="Notify on monthly summary"
+ notify_on_store_verdict: bool = Field(
+ default=True, description="Notify when a store submission is reviewed"
)
# User timezone for scheduling and time display
@@ -152,17 +140,10 @@ class User(BaseModel):
stripe_customer_id=prisma_user.stripeCustomerId,
top_up_config=top_up_config,
subscription_tier=prisma_user.subscriptionTier or SubscriptionTier.NO_TIER,
- max_emails_per_day=prisma_user.maxEmailsPerDay or 3,
- notify_on_agent_run=prisma_user.notifyOnAgentRun or True,
- notify_on_zero_balance=prisma_user.notifyOnZeroBalance or True,
- notify_on_low_balance=prisma_user.notifyOnLowBalance or True,
- notify_on_block_execution_failed=prisma_user.notifyOnBlockExecutionFailed
- or True,
- notify_on_continuous_agent_error=prisma_user.notifyOnContinuousAgentError
- or True,
- notify_on_daily_summary=prisma_user.notifyOnDailySummary or True,
- notify_on_weekly_summary=prisma_user.notifyOnWeeklySummary or True,
- notify_on_monthly_summary=prisma_user.notifyOnMonthlySummary or True,
+ max_emails_per_day=prisma_user.maxEmailsPerDay,
+ briefing_frequency=BriefingFrequency(prisma_user.briefingFrequency),
+ alerts_enabled=prisma_user.alertsEnabled,
+ notify_on_store_verdict=prisma_user.notifyOnStoreVerdict,
timezone=prisma_user.timezone or USER_TIMEZONE_NOT_SET,
)
diff --git a/autogpt_platform/backend/backend/data/notifications.py b/autogpt_platform/backend/backend/data/notifications.py
index 183838d3cf..d0769b0621 100644
--- a/autogpt_platform/backend/backend/data/notifications.py
+++ b/autogpt_platform/backend/backend/data/notifications.py
@@ -1,319 +1,387 @@
+"""Payloads for every email the platform sends.
+
+Four product-notification families (Briefing, Alert, Verdict, Ops) plus the
+account/billing service messages. Each model is exactly the render context its
+Jinja template expects, minus the per-recipient values (`user_email`, `urls`)
+which the renderer injects — so a payload can be queued, persisted and replayed
+without carrying a copy of our own URLs around.
+
+There is deliberately no per-run notification type. A finished run is evidence
+for the Briefing's highlights, not a message of its own.
+"""
+
import logging
-from datetime import datetime, timedelta, timezone
+from datetime import datetime, timezone
from enum import Enum
-from typing import Annotated, Any, Generic, Optional, TypeVar, Union
-
-from prisma import Json
-from prisma.enums import NotificationType
-from prisma.errors import UniqueViolationError
-from prisma.models import NotificationEvent, UserNotificationBatch
-from prisma.types import (
- NotificationEventCreateInput,
- UserNotificationBatchCreateInput,
- UserNotificationBatchWhereInput,
-)
+from typing import Generic, Literal, Optional, TypeVar, Union
-# from backend.notifications.models import NotificationEvent
-from pydantic import (
- BaseModel,
- ConfigDict,
- EmailStr,
- Field,
- field_validator,
- model_validator,
-)
+from prisma.enums import BriefingFrequency, NotificationType
+from pydantic import BaseModel, ConfigDict, EmailStr, Field, field_validator
-from backend.util.exceptions import DatabaseError
-from backend.util.json import SafeJson
from backend.util.logging import TruncatedLogger
-from .db import transaction
-
logger = TruncatedLogger(logging.getLogger(__name__), prefix="[NotificationService]")
-
NotificationDataType_co = TypeVar(
"NotificationDataType_co", bound="BaseNotificationData", covariant=True
)
-SummaryParamsType_co = TypeVar(
- "SummaryParamsType_co", bound="BaseSummaryParams", covariant=True
-)
-class QueueType(Enum):
- IMMEDIATE = "immediate" # Send right away (errors, critical notifications)
- BATCH = "batch" # Batch for up to an hour (usage reports)
- SUMMARY = "summary" # Daily digest (summary notifications)
- BACKOFF = "backoff" # Backoff strategy (exponential backoff)
- ADMIN = "admin" # Admin notifications (errors, critical notifications)
+class BaseNotificationData(BaseModel):
+ model_config = ConfigDict(extra="forbid")
-class BaseNotificationData(BaseModel):
- model_config = ConfigDict(extra="allow")
+# ─────────────────────────── The Briefing ───────────────────────────
-class AgentRunData(BaseNotificationData):
- agent_name: str
+class BriefingPeriod(BaseModel):
+ label: str = Field(
+ description='Range shown in the eyebrow, "Mon 27 Jul – Sun 2 Aug"'
+ )
+ noun: str = Field(description='"this week" / "yesterday" / "in July"')
+ adjective: str = Field(description='"week" / "day" / "month"')
+ frequency: Literal["daily", "weekly", "monthly"]
+
+
+class BriefingTotals(BaseModel):
+ """Server-side invariants: `runs` equals the sum of the ledger's runs, and
+ `agents_active` equals `len(ledger)` — the lede counts the agents that ran
+ and the ledger lists exactly those."""
+
+ runs: int
+ agents_active: int
+ agents_idle: int = 0
+ failed: int = 0
credits_used: float
- execution_time: float
- node_count: int = Field(..., description="Number of nodes executed")
- graph_id: str
- outputs: list[dict[str, Any]] = Field(..., description="Outputs of the agent")
+ credits_balance: float
+ usd_estimate: float | None = None
+
+
+class BriefingAttentionItem(BaseModel):
+ agent: str
+ title: str
+ tag: str | None = None
+ body: str
+ cta_label: str
+ cta_url: str
+
+
+class BriefingHighlight(BaseModel):
+ agent: str
+ gist: str
+ link_label: str
+ url: str
+
+
+class BriefingLedgerRow(BaseModel):
+ agent: str
+ runs: int
+ credits: float
+ issues_label: str | None = None
+ issues_kind: Literal["fail", "warn"] | None = None
+
+
+class BriefingData(BaseNotificationData):
+ mode: Literal["standard", "quiet"] = "standard"
+ period: BriefingPeriod
+ totals: BriefingTotals
+ standout: str | None = None
+ subject_note: str | None = None
+ # Order is load-bearing: sorted by severity, because the first card gets
+ # the strong amber rule and the rest a lighter one.
+ attention: list[BriefingAttentionItem] = Field(default_factory=list)
+ highlights: list[BriefingHighlight] = Field(default_factory=list)
+ # Arrives pre-sorted by interestingness, and already capped: the payload
+ # carries what the email shows plus a count of what it does not, rather
+ # than every row a busy account produced.
+ ledger: list[BriefingLedgerRow] = Field(default_factory=list)
+ # Pre-aggregated so the "+ N quieter agents ran M times" line survives the
+ # cap: the rows themselves are dropped, their totals are not.
+ ledger_overflow: int = 0
+ ledger_overflow_runs: int = 0
+ ledger_overflow_issues: int = 0
+ only_agent: str | None = None
+ quiet_summary: str | None = None
+
+
+# ───────────────────────────── The Alert ─────────────────────────────
+
+
+class AlertFact(BaseModel):
+ label: str
+ value: str
+
+
+class AlertPrimary(BaseModel):
+ headline: str
+ body: str
+ cta_label: str
+ cta_url: str
+ # Written from the cause catalog, not left to the template to guess: the
+ # subject states the blockage and its cause, and the preheader carries the
+ # detail that decides whether this needs opening now.
+ subject: str
+ preheader: str
+ microcopy: str | None = None
+ facts: list[AlertFact] = Field(default_factory=list)
+
+
+class AlertAlsoItem(BaseModel):
+ agent: str
+ text: str
+ link_label: str
+ url: str
+
+
+class AlertData(BaseNotificationData):
+ timestamp_label: str
+ primary: AlertPrimary
+ also: list[AlertAlsoItem] = Field(default_factory=list)
+ also_label: str | None = None
+
+
+# ──────────────────────────── The Verdict ────────────────────────────
+
+
+class VerdictData(BaseNotificationData):
+ """A store submission was reviewed. `changes` is the preferred shape — the
+ review UI should collect discrete items — with free-text `comments` as the
+ fallback. Empty and whitespace-only feedback are both handled by the
+ template rather than papered over here."""
+
+ outcome: Literal["approved", "changes"]
+ agent_name: str
+ version: int = 1
+ reviewer_name: str
+ reviewed_at_label: str
+ comments: str = ""
+ changes: list[str] = Field(default_factory=list)
+ closing_note: str | None = None
+ store_url: str | None = None
+ share_url: str | None = None
+ resubmit_url: str | None = None
-class ZeroBalanceData(BaseNotificationData):
- agent_name: str = Field(..., description="Name of the agent")
- current_balance: float = Field(
- ..., description="Current balance in credits (100 = $1)"
- )
- billing_page_link: str = Field(..., description="Link to billing page")
- shortfall: float = Field(..., description="Amount of credits needed to continue")
+# ────────────────────────── Ops (internal) ──────────────────────────
-class LowBalanceData(BaseNotificationData):
- current_balance: float = Field(
- ..., description="Current balance in credits (100 = $1)"
- )
- billing_page_link: str = Field(..., description="Link to billing page")
+class OpsData(BaseNotificationData):
+ """Internal refunds-team mail. Not customer-facing, and the only family
+ that must NOT carry List-Unsubscribe headers."""
+ kind: Literal["request", "processed"]
+ user_name: str
+ user_email: str
+ user_id: str
+ transaction_id: str
+ refund_request_id: str
+ amount_cents: int
+ balance_cents: int
+ reason: str = ""
+ recipient: str
+ stripe_url: str
+ admin_url: str
+ # Absolute, never a duration — the email is read hours later.
+ age_label: str | None = None
+ requested_at_label: str | None = None
+ processed_at_label: str | None = None
-class BlockExecutionFailedData(BaseNotificationData):
- block_name: str
- block_id: str
- error_message: str
- graph_id: str
- node_id: str
- execution_id: str
+# ───────────────────── Account & billing messages ─────────────────────
-class ContinuousAgentErrorData(BaseNotificationData):
- agent_name: str
- error_message: str
- graph_id: str
- execution_id: str
- start_time: datetime
- error_time: datetime
- attempts: int = Field(..., description="Number of retry attempts made")
-
- @field_validator("start_time", "error_time")
- @classmethod
- def validate_timezone(cls, value: datetime):
- if value.tzinfo is None:
- raise ValueError("datetime must have timezone information")
- return value
+class SubscriptionPlan(BaseModel):
+ name: str = Field(description='"Pro" / "Max"')
+ cycle: Literal["monthly", "yearly"]
+ cycle_noun: Literal["month", "year"]
+ label: str = Field(description='"Pro — monthly"')
+ price_display: str = Field(description='"$50.00 / month"')
-class BaseSummaryData(BaseNotificationData):
- total_credits_used: float
- total_executions: int
- most_used_agent: str
- total_execution_time: float
- successful_runs: int
- failed_runs: int
- average_execution_time: float
- cost_breakdown: dict[str, float]
+class CardDetails(BaseModel):
+ brand: str
+ last4: str
-class BaseSummaryParams(BaseModel):
- start_date: datetime
- end_date: datetime
- @field_validator("start_date", "end_date")
- def validate_timezone(cls, value):
- if value.tzinfo is None:
- raise ValueError("datetime must have timezone information")
- return value
+class LifecycleData(BaseNotificationData):
+ """Shared shape for the billing emails. `user_name` is the greeting name;
+ every other sentence is assembled from the slots below by the template."""
+ user_name: str
+ plan: SubscriptionPlan
-class DailySummaryParams(BaseSummaryParams):
- date: datetime
- @field_validator("date")
- def validate_timezone(cls, value):
- if value.tzinfo is None:
- raise ValueError("datetime must have timezone information")
- return value
+class SubscriptionWelcomeData(LifecycleData):
+ renews_label: str
-class WeeklySummaryParams(BaseSummaryParams):
- start_date: datetime
- end_date: datetime
+class PaymentFailedData(LifecycleData):
+ amount_display: str
+ card: CardDetails
+ next_retry_label: str
- @field_validator("start_date", "end_date")
- def validate_timezone(cls, value):
- if value.tzinfo is None:
- raise ValueError("datetime must have timezone information")
- return value
+class PaymentFinalNoticeData(LifecycleData):
+ amount_display: str
+ pauses_label: str
-class DailySummaryData(BaseSummaryData):
- date: datetime
- @field_validator("date")
- def validate_timezone(cls, value):
- if value.tzinfo is None:
- raise ValueError("datetime must have timezone information")
- return value
+class SubscriptionCancelledData(LifecycleData):
+ access_until_label: str
-class WeeklySummaryData(BaseSummaryData):
- start_date: datetime
- end_date: datetime
+class SubscriptionResumedData(LifecycleData):
+ renews_label: str
- @field_validator("start_date", "end_date")
- def validate_timezone(cls, value):
- if value.tzinfo is None:
- raise ValueError("datetime must have timezone information")
- return value
+class SubscriptionEndedData(LifecycleData):
+ ended_label: str
+ due_to_payment: bool
-class MonthlySummaryData(BaseNotificationData):
- month: int
- year: int
+NotificationData = Union[
+ BriefingData,
+ AlertData,
+ VerdictData,
+ OpsData,
+ SubscriptionWelcomeData,
+ PaymentFailedData,
+ PaymentFinalNoticeData,
+ SubscriptionCancelledData,
+ SubscriptionResumedData,
+ SubscriptionEndedData,
+]
-class RefundRequestData(BaseNotificationData):
- user_id: str
- user_name: str
- user_email: str
- transaction_id: str
- refund_request_id: str
- reason: str
- amount: float
- balance: int
+_DATA_TYPES: dict[NotificationType, type[BaseNotificationData]] = {
+ NotificationType.BRIEFING: BriefingData,
+ NotificationType.ALERT: AlertData,
+ NotificationType.VERDICT: VerdictData,
+ NotificationType.OPS: OpsData,
+ NotificationType.SUBSCRIPTION_WELCOME: SubscriptionWelcomeData,
+ NotificationType.PAYMENT_FAILED: PaymentFailedData,
+ NotificationType.PAYMENT_FINAL_NOTICE: PaymentFinalNoticeData,
+ NotificationType.SUBSCRIPTION_CANCELLED: SubscriptionCancelledData,
+ NotificationType.SUBSCRIPTION_RESUMED: SubscriptionResumedData,
+ NotificationType.SUBSCRIPTION_ENDED: SubscriptionEndedData,
+}
+
+# Which Jinja template family renders each type. The billing messages all share
+# `lifecycle`, branching internally on `kind`.
+_TEMPLATES: dict[NotificationType, str] = {
+ NotificationType.BRIEFING: "briefing",
+ NotificationType.ALERT: "alert",
+ NotificationType.VERDICT: "verdict",
+ NotificationType.OPS: "ops",
+ NotificationType.SUBSCRIPTION_WELCOME: "lifecycle",
+ NotificationType.PAYMENT_FAILED: "lifecycle",
+ NotificationType.PAYMENT_FINAL_NOTICE: "lifecycle",
+ NotificationType.SUBSCRIPTION_CANCELLED: "lifecycle",
+ NotificationType.SUBSCRIPTION_RESUMED: "lifecycle",
+ NotificationType.SUBSCRIPTION_ENDED: "lifecycle",
+}
+
+# The `kind` slot the lifecycle template branches on.
+_LIFECYCLE_KINDS: dict[NotificationType, str] = {
+ NotificationType.SUBSCRIPTION_WELCOME: "welcome",
+ NotificationType.PAYMENT_FAILED: "payment_failed",
+ NotificationType.PAYMENT_FINAL_NOTICE: "final_notice",
+ NotificationType.SUBSCRIPTION_CANCELLED: "cancel_confirmed",
+ NotificationType.SUBSCRIPTION_RESUMED: "cancel_reversed",
+ NotificationType.SUBSCRIPTION_ENDED: "ended",
+}
-class _LegacyAgentFieldsMixin:
- """Temporary patch to handle existing queued payloads"""
+def get_notif_data_type(
+ notification_type: NotificationType,
+) -> type[BaseNotificationData]:
+ return _DATA_TYPES[notification_type]
- # FIXME: remove in next release
- @model_validator(mode="before")
- @classmethod
- def _map_legacy_agent_fields(cls, values: Any):
- if isinstance(values, dict):
- if "graph_id" not in values and "agent_id" in values:
- values["graph_id"] = values.pop("agent_id")
- if "graph_version" not in values and "agent_version" in values:
- values["graph_version"] = values.pop("agent_version")
- return values
+def get_template_family(notification_type: NotificationType) -> str:
+ return _TEMPLATES[notification_type]
-class AgentApprovalData(_LegacyAgentFieldsMixin, BaseNotificationData):
- agent_name: str
- graph_id: str
- graph_version: int
- reviewer_name: str
- reviewer_email: str
- comments: str
- reviewed_at: datetime
- store_url: str
+def get_lifecycle_kind(notification_type: NotificationType) -> str | None:
+ """The `kind` the shared lifecycle template branches on, or None for the
+ four product-notification families, which have a template each."""
+ return _LIFECYCLE_KINDS.get(notification_type)
- @field_validator("reviewed_at")
- @classmethod
- def validate_timezone(cls, value: datetime):
- if value.tzinfo is None:
- raise ValueError("datetime must have timezone information")
- return value
+class DeliveryStream(Enum):
+ """Which sender identity and reputation the message goes out on. Marketing
+ mail (the onboarding tour, the monthly changelog) is not here: it is sent
+ from MailerLite, and the backend only manages who is in its audience."""
-class AgentRejectionData(_LegacyAgentFieldsMixin, BaseNotificationData):
- agent_name: str
- graph_id: str
- graph_version: int
- reviewer_name: str
- reviewer_email: str
- comments: str
- reviewed_at: datetime
- resubmit_url: str
+ BILLING = "billing"
+ PRODUCT = "product"
+ OPS = "ops"
- @field_validator("reviewed_at")
- @classmethod
- def validate_timezone(cls, value: datetime):
- if value.tzinfo is None:
- raise ValueError("datetime must have timezone information")
- return value
-
-
-NotificationData = Annotated[
- Union[
- AgentRunData,
- ZeroBalanceData,
- LowBalanceData,
- BlockExecutionFailedData,
- ContinuousAgentErrorData,
- MonthlySummaryData,
- WeeklySummaryData,
- DailySummaryData,
- RefundRequestData,
- BaseSummaryData,
- ],
- Field(discriminator="type"),
-]
+_STREAMS: dict[NotificationType, DeliveryStream] = {
+ NotificationType.BRIEFING: DeliveryStream.PRODUCT,
+ NotificationType.ALERT: DeliveryStream.PRODUCT,
+ NotificationType.VERDICT: DeliveryStream.PRODUCT,
+ NotificationType.OPS: DeliveryStream.OPS,
+ NotificationType.SUBSCRIPTION_WELCOME: DeliveryStream.BILLING,
+ NotificationType.PAYMENT_FAILED: DeliveryStream.BILLING,
+ NotificationType.PAYMENT_FINAL_NOTICE: DeliveryStream.BILLING,
+ NotificationType.SUBSCRIPTION_CANCELLED: DeliveryStream.BILLING,
+ NotificationType.SUBSCRIPTION_RESUMED: DeliveryStream.BILLING,
+ NotificationType.SUBSCRIPTION_ENDED: DeliveryStream.BILLING,
+}
-class BaseEventModel(BaseModel):
- type: NotificationType
- user_id: str
- created_at: datetime = Field(default_factory=lambda: datetime.now(tz=timezone.utc))
+def get_delivery_stream(notification_type: NotificationType) -> DeliveryStream:
+ return _STREAMS[notification_type]
-class NotificationEventModel(BaseEventModel, Generic[NotificationDataType_co]):
- id: Optional[str] = None # None when creating, populated when reading from DB
- data: NotificationDataType_co
- @property
- def strategy(self) -> QueueType:
- return NotificationTypeOverride(self.type).strategy
+# Product mail only. Billing is service mail that `wants_notification` always
+# allows, so advertising an opt-out we do not honour would be a broken
+# unsubscribe under Gmail/Yahoo bulk-sender rules.
+def supports_list_unsubscribe(notification_type: NotificationType) -> bool:
+ return get_delivery_stream(notification_type) is DeliveryStream.PRODUCT
- @field_validator("type", mode="before")
- def uppercase_type(cls, v):
- if isinstance(v, str):
- return v.upper()
- return v
- @property
- def template(self) -> str:
- return NotificationTypeOverride(self.type).template
+class PassWorkKind(str, Enum):
+ """Which scheduled pass produced a unit of per-user work."""
+ BRIEFING = "briefing"
+ ALERT_FLUSH = "alert_flush"
+ WELCOME = "welcome"
-class SummaryParamsEventModel(BaseEventModel, Generic[SummaryParamsType_co]):
- data: SummaryParamsType_co
+class PassWorkEvent(BaseModel):
+ """One user's share of a scheduled pass.
-def get_notif_data_type(
- notification_type: NotificationType,
-) -> type[BaseNotificationData]:
- return {
- NotificationType.AGENT_RUN: AgentRunData,
- NotificationType.ZERO_BALANCE: ZeroBalanceData,
- NotificationType.LOW_BALANCE: LowBalanceData,
- NotificationType.BLOCK_EXECUTION_FAILED: BlockExecutionFailedData,
- NotificationType.CONTINUOUS_AGENT_ERROR: ContinuousAgentErrorData,
- NotificationType.DAILY_SUMMARY: DailySummaryData,
- NotificationType.WEEKLY_SUMMARY: WeeklySummaryData,
- NotificationType.MONTHLY_SUMMARY: MonthlySummaryData,
- NotificationType.REFUND_REQUEST: RefundRequestData,
- NotificationType.REFUND_PROCESSED: RefundRequestData,
- NotificationType.AGENT_APPROVED: AgentApprovalData,
- NotificationType.AGENT_REJECTED: AgentRejectionData,
- }[notification_type]
-
-
-def get_summary_params_type(
- notification_type: NotificationType,
-) -> type[BaseSummaryParams]:
- return {
- NotificationType.DAILY_SUMMARY: DailySummaryParams,
- NotificationType.WEEKLY_SUMMARY: WeeklySummaryParams,
- }[notification_type]
+ Carries the pass's own notion of "now" rather than letting the consumer
+ read the clock: a message that waits in the queue must still be assembled
+ for the period it was scheduled for, and the dedupe key has to be stable
+ across a redelivery.
+ """
+
+ kind: PassWorkKind
+ user_id: str
+ scheduled_for: datetime
+ # Only the identifier, never the payload: a checkout session that sat in
+ # the queue is re-read from Stripe so the work acts on current state.
+ # Empty for the scheduled kinds, which key off `user_id` alone.
+ context: dict[str, str] = Field(default_factory=dict)
-class NotificationBatch(BaseModel):
+class BaseEventModel(BaseModel):
+ type: NotificationType
user_id: str
- events: list[NotificationEvent]
- strategy: QueueType
- last_update: datetime = Field(default_factory=lambda: datetime.now(tz=timezone.utc))
+ created_at: datetime = Field(default_factory=lambda: datetime.now(tz=timezone.utc))
+
+
+class NotificationEventModel(BaseEventModel, Generic[NotificationDataType_co]):
+ id: Optional[str] = None
+ data: NotificationDataType_co
+
+ @field_validator("type", mode="before")
+ @classmethod
+ def uppercase_type(cls, v: object) -> object:
+ return v.upper() if isinstance(v, str) else v
class NotificationResult(BaseModel):
@@ -321,368 +389,48 @@ class NotificationResult(BaseModel):
message: Optional[str] = None
-class NotificationTypeOverride:
- def __init__(self, notification_type: NotificationType):
- self.notification_type = notification_type
-
- @property
- def strategy(self) -> QueueType:
- BATCHING_RULES = {
- # These are batched by the notification service
- NotificationType.AGENT_RUN: QueueType.BATCH,
- # These are batched by the notification service, but with a backoff strategy
- NotificationType.ZERO_BALANCE: QueueType.IMMEDIATE,
- NotificationType.LOW_BALANCE: QueueType.IMMEDIATE,
- NotificationType.BLOCK_EXECUTION_FAILED: QueueType.BACKOFF,
- NotificationType.CONTINUOUS_AGENT_ERROR: QueueType.BACKOFF,
- NotificationType.DAILY_SUMMARY: QueueType.SUMMARY,
- NotificationType.WEEKLY_SUMMARY: QueueType.SUMMARY,
- NotificationType.MONTHLY_SUMMARY: QueueType.SUMMARY,
- NotificationType.REFUND_REQUEST: QueueType.ADMIN,
- NotificationType.REFUND_PROCESSED: QueueType.ADMIN,
- NotificationType.AGENT_APPROVED: QueueType.IMMEDIATE,
- NotificationType.AGENT_REJECTED: QueueType.IMMEDIATE,
- }
- return BATCHING_RULES.get(self.notification_type, QueueType.IMMEDIATE)
+class AudienceAction(Enum):
+ """Membership changes the backend owns. The tour → changelog handoff is
+ deliberately absent: MailerLite's automation owns that edge."""
- @property
- def template(self) -> str:
- """Returns template name for this notification type"""
- return {
- NotificationType.AGENT_RUN: "agent_run.html",
- NotificationType.ZERO_BALANCE: "zero_balance.html",
- NotificationType.LOW_BALANCE: "low_balance.html",
- NotificationType.BLOCK_EXECUTION_FAILED: "block_failed.html",
- NotificationType.CONTINUOUS_AGENT_ERROR: "agent_error.html",
- NotificationType.DAILY_SUMMARY: "daily_summary.html",
- NotificationType.WEEKLY_SUMMARY: "weekly_summary.html",
- NotificationType.MONTHLY_SUMMARY: "monthly_summary.html",
- NotificationType.REFUND_REQUEST: "refund_request.html",
- NotificationType.REFUND_PROCESSED: "refund_processed.html",
- NotificationType.AGENT_APPROVED: "agent_approved.html",
- NotificationType.AGENT_REJECTED: "agent_rejected.html",
- }[self.notification_type]
+ ENROLL_TOUR = "enroll_tour"
+ ADD_CHANGELOG = "add_changelog"
+ REMOVE_CHANGELOG = "remove_changelog"
- @property
- def subject(self) -> str:
- return {
- NotificationType.AGENT_RUN: "Agent Run Report",
- NotificationType.ZERO_BALANCE: "You're out of credits!",
- NotificationType.LOW_BALANCE: "Low Balance Warning!",
- NotificationType.BLOCK_EXECUTION_FAILED: "Uh oh! Block Execution Failed",
- NotificationType.CONTINUOUS_AGENT_ERROR: "Shoot! Continuous Agent Error",
- NotificationType.DAILY_SUMMARY: "Here's your daily summary!",
- NotificationType.WEEKLY_SUMMARY: "Look at all the cool stuff you did last week!",
- NotificationType.MONTHLY_SUMMARY: "We did a lot this month!",
- NotificationType.REFUND_REQUEST: "[ACTION REQUIRED] You got a ${{data.amount / 100}} refund request from {{data.user_name}}",
- NotificationType.REFUND_PROCESSED: "Refund for ${{data.amount / 100}} to {{data.user_name}} has been processed",
- NotificationType.AGENT_APPROVED: "🎉 Your agent '{{data.agent_name}}' has been approved!",
- NotificationType.AGENT_REJECTED: "Your agent '{{data.agent_name}}' needs some updates",
- }[self.notification_type]
+class AudienceEventModel(BaseModel):
+ """A MailerLite audience change, queued rather than called inline so a
+ MailerLite outage can never fail payment processing."""
-class NotificationPreferenceDTO(BaseModel):
- email: EmailStr = Field(..., description="User's email address")
- preferences: dict[NotificationType, bool] = Field(
- ..., description="Which notifications the user wants"
- )
- daily_limit: int = Field(..., description="Max emails per day")
+ action: AudienceAction
+ email: EmailStr
+ user_id: str
class NotificationPreference(BaseModel):
- user_id: str
- email: EmailStr
- preferences: dict[NotificationType, bool] = Field(
- default_factory=dict, description="Which notifications the user wants"
- )
- daily_limit: int = 10 # Max emails per day
- emails_sent_today: int = 0
- last_reset_date: datetime = Field(
- default_factory=lambda: datetime.now(timezone.utc)
- )
-
+ """The volume knob from the Briefing footer, not a checkbox list. Billing
+ and account messages are service mail and are not represented here — they
+ are sent regardless of these settings."""
-class UserNotificationEventDTO(BaseModel):
- id: str # Added to track notifications for removal
- type: NotificationType
- data: dict
- created_at: datetime
- updated_at: datetime
-
- @staticmethod
- def from_db(model: NotificationEvent) -> "UserNotificationEventDTO":
- return UserNotificationEventDTO(
- id=model.id,
- type=model.type,
- data=dict(model.data),
- created_at=model.createdAt,
- updated_at=model.updatedAt,
- )
-
-
-class UserNotificationBatchDTO(BaseModel):
user_id: str
- type: NotificationType
- notifications: list[UserNotificationEventDTO]
- created_at: datetime
- updated_at: datetime
-
- @staticmethod
- def from_db(model: UserNotificationBatch) -> "UserNotificationBatchDTO":
- return UserNotificationBatchDTO(
- user_id=model.userId,
- type=model.type,
- notifications=[
- UserNotificationEventDTO.from_db(notification)
- for notification in model.Notifications or []
- ],
- created_at=model.createdAt,
- updated_at=model.updatedAt,
- )
-
-
-def get_batch_delay(notification_type: NotificationType) -> timedelta:
- return {
- NotificationType.AGENT_RUN: timedelta(days=1),
- NotificationType.ZERO_BALANCE: timedelta(minutes=60),
- NotificationType.LOW_BALANCE: timedelta(minutes=60),
- NotificationType.BLOCK_EXECUTION_FAILED: timedelta(minutes=60),
- NotificationType.CONTINUOUS_AGENT_ERROR: timedelta(minutes=60),
- }[notification_type]
-
-
-async def create_or_add_to_user_notification_batch(
- user_id: str,
- notification_type: NotificationType,
- notification_data: NotificationEventModel,
- organization_id: Optional[str] = None,
- team_id: Optional[str] = None,
-) -> UserNotificationBatchDTO:
- try:
- if not notification_data.data:
- raise ValueError("Notification data must be provided")
-
- json_data: Json = SafeJson(notification_data.data.model_dump())
-
- # Stamp the batch with the user's default org/team at creation.
- # Resolve a default only when the caller supplied NEITHER field (never
- # overwrite an explicit team_id). resolve_default_tenancy is
- # best-effort — an unresolvable org or a raised lookup both leave the
- # batch untenanted rather than crash a notification.
- if organization_id is None and team_id is None:
- from backend.api.features.orgs.db import resolve_default_tenancy
-
- organization_id, team_id = await resolve_default_tenancy(user_id)
-
- # Prisma's upsert is find→INSERT/UPDATE under the hood, not a true
- # SQL ON CONFLICT, so two concurrent calls on a missing row can both
- # take the INSERT branch and one loses to @@unique([userId, type]).
- # Retry once on UniqueViolationError: the row now exists, so the
- # second pass takes the UPDATE branch. Avoids a write-skipping
- # find_unique pre-check on the hot path. Skips the eager
- # `Notifications` include that loaded thousands of rows for heavy
- # AGENT_RUN users and tripped Postgres statement_timeout.
- for attempt in range(2):
- try:
- resp = await UserNotificationBatch.prisma().upsert(
- where={
- "userId_type": {
- "userId": user_id,
- "type": notification_type,
- }
- },
- data={
- "create": UserNotificationBatchCreateInput(
- userId=user_id,
- type=notification_type,
- **(
- {"organizationId": organization_id}
- if organization_id
- else {}
- ),
- **({"teamId": team_id} if team_id else {}),
- Notifications={
- "create": [
- NotificationEventCreateInput(
- type=notification_type,
- data=json_data,
- )
- ]
- },
- ),
- "update": {
- "Notifications": {
- "create": [
- NotificationEventCreateInput(
- type=notification_type,
- data=json_data,
- )
- ]
- }
- },
- },
- )
- return UserNotificationBatchDTO.from_db(resp)
- except UniqueViolationError:
- if attempt == 0:
- continue
- raise
- raise RuntimeError("unreachable") # for type-checkers
- except Exception as e:
- raise DatabaseError(
- f"Failed to create or add to notification batch for user {user_id} and type {notification_type}: {e}"
- ) from e
-
-
-async def get_user_notification_oldest_message_in_batch(
- user_id: str,
- notification_type: NotificationType,
-) -> UserNotificationEventDTO | None:
- try:
- oldest = await NotificationEvent.prisma().find_first(
- where={
- "UserNotificationBatch": {
- "is": {"userId": user_id, "type": notification_type}
- }
- },
- order={"createdAt": "asc"},
- )
- return UserNotificationEventDTO.from_db(oldest) if oldest else None
- except Exception as e:
- raise DatabaseError(
- f"Failed to get user notification last message in batch for user {user_id} and type {notification_type}: {e}"
- ) from e
-
-
-async def empty_user_notification_batch(
- user_id: str, notification_type: NotificationType
-) -> None:
- try:
- async with transaction() as tx:
- await tx.notificationevent.delete_many(
- where={
- "UserNotificationBatch": {
- "is": {"userId": user_id, "type": notification_type}
- }
- }
- )
-
- await tx.usernotificationbatch.delete_many(
- where=UserNotificationBatchWhereInput(
- userId=user_id,
- type=notification_type,
- )
- )
- except Exception as e:
- raise DatabaseError(
- f"Failed to empty user notification batch for user {user_id} and type {notification_type}: {e}"
- ) from e
-
-
-async def clear_all_user_notification_batches(user_id: str) -> None:
- """Clear ALL notification batches for a user across all types.
-
- Used when user's email is bounced/inactive and we should stop
- trying to send them ANY emails.
- """
- try:
- # Delete all notification events for this user
- await NotificationEvent.prisma().delete_many(
- where={"UserNotificationBatch": {"is": {"userId": user_id}}}
- )
-
- # Delete all batches for this user
- await UserNotificationBatch.prisma().delete_many(where={"userId": user_id})
-
- logger.info(f"Cleared all notification batches for user {user_id}")
- except Exception as e:
- raise DatabaseError(
- f"Failed to clear all notification batches for user {user_id}: {e}"
- ) from e
+ email: EmailStr
+ briefing_frequency: BriefingFrequency = BriefingFrequency.WEEKLY
+ alerts_enabled: bool = True
+ store_verdicts_enabled: bool = True
+ daily_limit: int = 3
+ @property
+ def wants_briefing(self) -> bool:
+ return self.briefing_frequency is not BriefingFrequency.OFF
-async def remove_notifications_from_batch(
- user_id: str, notification_type: NotificationType, notification_ids: list[str]
-) -> None:
- """Remove specific notifications from a user's batch by their IDs.
- This is used after successful sending to remove only the
- sent notifications, preventing duplicates on retry.
- """
- if not notification_ids:
- return
-
- try:
- # Delete the specific notification events
- deleted_count = await NotificationEvent.prisma().delete_many(
- where={
- "id": {"in": notification_ids},
- "UserNotificationBatch": {
- "is": {"userId": user_id, "type": notification_type}
- },
- }
- )
-
- logger.info(
- f"Removed {deleted_count} notifications from batch for user {user_id}"
- )
-
- # Check if batch is now empty and delete it if so
- remaining = await NotificationEvent.prisma().count(
- where={
- "UserNotificationBatch": {
- "is": {"userId": user_id, "type": notification_type}
- }
- }
- )
-
- if remaining == 0:
- await UserNotificationBatch.prisma().delete_many(
- where=UserNotificationBatchWhereInput(
- userId=user_id,
- type=notification_type,
- )
- )
- logger.info(
- f"Deleted empty batch for user {user_id} and type {notification_type}"
- )
- except Exception as e:
- raise DatabaseError(
- f"Failed to remove notifications from batch for user {user_id} and type {notification_type}: {e}"
- ) from e
-
-
-async def get_user_notification_batch(
- user_id: str,
- notification_type: NotificationType,
-) -> UserNotificationBatchDTO | None:
- try:
- batch = await UserNotificationBatch.prisma().find_first(
- where={"userId": user_id, "type": notification_type},
- include={"Notifications": True},
- )
- return UserNotificationBatchDTO.from_db(batch) if batch else None
- except Exception as e:
- raise DatabaseError(
- f"Failed to get user notification batch for user {user_id} and type {notification_type}: {e}"
- ) from e
-
-
-async def get_all_batches_by_type(
- notification_type: NotificationType,
-) -> list[UserNotificationBatchDTO]:
- # Caller re-fetches events per batch when actually sending; no eager include here.
- try:
- batches = await UserNotificationBatch.prisma().find_many(
- where={
- "type": notification_type,
- "Notifications": {
- "some": {} # Only return batches with at least one notification
- },
- },
- )
- return [UserNotificationBatchDTO.from_db(batch) for batch in batches]
- except Exception as e:
- raise DatabaseError(
- f"Failed to get all batches by type {notification_type}: {e}"
- ) from e
+class NotificationPreferenceDTO(BaseModel):
+ email: EmailStr
+ briefing_frequency: BriefingFrequency
+ alerts_enabled: bool
+ store_verdicts_enabled: bool
+ daily_limit: int = Field(
+ default=3,
+ description="Max product emails per day; 0 sends none. Account and "
+ "billing messages are service mail and ignore it.",
+ )
diff --git a/autogpt_platform/backend/backend/data/notifications_test.py b/autogpt_platform/backend/backend/data/notifications_test.py
deleted file mode 100644
index e99fe8e79a..0000000000
--- a/autogpt_platform/backend/backend/data/notifications_test.py
+++ /dev/null
@@ -1,596 +0,0 @@
-"""Tests for notification data models and batch helpers."""
-
-import asyncio
-import logging
-from datetime import datetime, timezone
-from unittest.mock import AsyncMock
-from uuid import uuid4
-
-import pytest
-from prisma.actions import UserNotificationBatchActions
-from prisma.enums import NotificationType
-from prisma.errors import UniqueViolationError
-from prisma.models import NotificationEvent, User, UserNotificationBatch
-from pydantic import ValidationError
-
-from backend.data.notifications import (
- AgentApprovalData,
- AgentRejectionData,
- AgentRunData,
- NotificationEventModel,
- create_or_add_to_user_notification_batch,
- empty_user_notification_batch,
- get_all_batches_by_type,
- get_user_notification_oldest_message_in_batch,
-)
-from backend.util.test import SpinTestServer
-
-logger = logging.getLogger(__name__)
-
-
-class TestAgentApprovalData:
- """Test cases for AgentApprovalData model."""
-
- def test_valid_agent_approval_data(self):
- """Test creating valid AgentApprovalData."""
- data = AgentApprovalData(
- agent_name="Test Agent",
- graph_id="test-agent-123",
- graph_version=1,
- reviewer_name="John Doe",
- reviewer_email="[email protected]",
- comments="Great agent, approved!",
- reviewed_at=datetime.now(timezone.utc),
- store_url="https://app.autogpt.com/store/test-agent-123",
- )
-
- assert data.agent_name == "Test Agent"
- assert data.graph_id == "test-agent-123"
- assert data.graph_version == 1
- assert data.reviewer_name == "John Doe"
- assert data.reviewer_email == "[email protected]"
- assert data.comments == "Great agent, approved!"
- assert data.store_url == "https://app.autogpt.com/store/test-agent-123"
- assert data.reviewed_at.tzinfo is not None
-
- def test_agent_approval_data_without_timezone_raises_error(self):
- """Test that AgentApprovalData raises error without timezone."""
- with pytest.raises(
- ValidationError, match="datetime must have timezone information"
- ):
- AgentApprovalData(
- agent_name="Test Agent",
- graph_id="test-agent-123",
- graph_version=1,
- reviewer_name="John Doe",
- reviewer_email="[email protected]",
- comments="Great agent, approved!",
- reviewed_at=datetime.now(), # No timezone
- store_url="https://app.autogpt.com/store/test-agent-123",
- )
-
- def test_agent_approval_data_with_empty_comments(self):
- """Test AgentApprovalData with empty comments."""
- data = AgentApprovalData(
- agent_name="Test Agent",
- graph_id="test-agent-123",
- graph_version=1,
- reviewer_name="John Doe",
- reviewer_email="[email protected]",
- comments="", # Empty comments
- reviewed_at=datetime.now(timezone.utc),
- store_url="https://app.autogpt.com/store/test-agent-123",
- )
-
- assert data.comments == ""
-
-
-class TestAgentRejectionData:
- """Test cases for AgentRejectionData model."""
-
- def test_valid_agent_rejection_data(self):
- """Test creating valid AgentRejectionData."""
- data = AgentRejectionData(
- agent_name="Test Agent",
- graph_id="test-agent-123",
- graph_version=1,
- reviewer_name="Jane Doe",
- reviewer_email="[email protected]",
- comments="Please fix the security issues before resubmitting.",
- reviewed_at=datetime.now(timezone.utc),
- resubmit_url="https://app.autogpt.com/build/test-agent-123",
- )
-
- assert data.agent_name == "Test Agent"
- assert data.graph_id == "test-agent-123"
- assert data.graph_version == 1
- assert data.reviewer_name == "Jane Doe"
- assert data.reviewer_email == "[email protected]"
- assert data.comments == "Please fix the security issues before resubmitting."
- assert data.resubmit_url == "https://app.autogpt.com/build/test-agent-123"
- assert data.reviewed_at.tzinfo is not None
-
- def test_agent_rejection_data_without_timezone_raises_error(self):
- """Test that AgentRejectionData raises error without timezone."""
- with pytest.raises(
- ValidationError, match="datetime must have timezone information"
- ):
- AgentRejectionData(
- agent_name="Test Agent",
- graph_id="test-agent-123",
- graph_version=1,
- reviewer_name="Jane Doe",
- reviewer_email="[email protected]",
- comments="Please fix the security issues.",
- reviewed_at=datetime.now(), # No timezone
- resubmit_url="https://app.autogpt.com/build/test-agent-123",
- )
-
- def test_agent_rejection_data_with_long_comments(self):
- """Test AgentRejectionData with long comments."""
- long_comment = "A" * 1000 # Very long comment
- data = AgentRejectionData(
- agent_name="Test Agent",
- graph_id="test-agent-123",
- graph_version=1,
- reviewer_name="Jane Doe",
- reviewer_email="[email protected]",
- comments=long_comment,
- reviewed_at=datetime.now(timezone.utc),
- resubmit_url="https://app.autogpt.com/build/test-agent-123",
- )
-
- assert data.comments == long_comment
-
- def test_model_serialization(self):
- """Test that models can be serialized and deserialized."""
- original_data = AgentRejectionData(
- agent_name="Test Agent",
- graph_id="test-agent-123",
- graph_version=1,
- reviewer_name="Jane Doe",
- reviewer_email="[email protected]",
- comments="Please fix the issues.",
- reviewed_at=datetime.now(timezone.utc),
- resubmit_url="https://app.autogpt.com/build/test-agent-123",
- )
-
- # Serialize to dict
- data_dict = original_data.model_dump()
-
- # Deserialize back
- restored_data = AgentRejectionData.model_validate(data_dict)
-
- assert restored_data.agent_name == original_data.agent_name
- assert restored_data.graph_id == original_data.graph_id
- assert restored_data.graph_version == original_data.graph_version
- assert restored_data.reviewer_name == original_data.reviewer_name
- assert restored_data.reviewer_email == original_data.reviewer_email
- assert restored_data.comments == original_data.comments
- assert restored_data.reviewed_at == original_data.reviewed_at
- assert restored_data.resubmit_url == original_data.resubmit_url
-
-
-def _make_agent_run_event(user_id: str, agent_name: str = "Test Agent"):
- return NotificationEventModel[AgentRunData](
- type=NotificationType.AGENT_RUN,
- user_id=user_id,
- data=AgentRunData(
- agent_name=agent_name,
- credits_used=10.0,
- execution_time=5.0,
- node_count=3,
- graph_id="graph-" + agent_name,
- outputs=[],
- ),
- )
-
-
-async def _create_test_user(user_id: str) -> None:
- try:
- await User.prisma().create(
- data={
- "id": user_id,
- "email": f"test-{user_id}@example.com",
- "name": f"Test User {user_id[:8]}",
- }
- )
- except UniqueViolationError:
- pass
-
-
-async def _cleanup_test_user(user_id: str) -> None:
- try:
- await empty_user_notification_batch(user_id, NotificationType.AGENT_RUN)
- except Exception as exc:
- logger.warning("notification cleanup for %s failed: %s", user_id, exc)
- try:
- await User.prisma().delete_many(where={"id": user_id})
- except Exception as exc:
- logger.warning("user cleanup for %s failed: %s", user_id, exc)
-
-
[email protected](loop_scope="session")
-async def test_upsert_creates_empty_batch_then_appends(server: SpinTestServer):
- """Empty batch path creates a batch. Existing-batch path appends without
- loading the existing notification rows."""
- user_id = f"notif-create-{uuid4()}"
- await _create_test_user(user_id)
-
- try:
- # First call → create path.
- first = await create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id, agent_name="first"),
- )
- assert first.user_id == user_id
- assert first.type == NotificationType.AGENT_RUN
- # The returned DTO no longer eagerly loads notifications — callers
- # that need them must fetch separately.
- assert first.notifications == []
-
- row_count = await NotificationEvent.prisma().count(
- where={"UserNotificationBatch": {"is": {"userId": user_id}}}
- )
- assert row_count == 1
-
- # Second call → update path.
- second = await create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id, agent_name="second"),
- )
- assert second.user_id == user_id
- # Still no eager include, even when the batch has rows.
- assert second.notifications == []
-
- row_count = await NotificationEvent.prisma().count(
- where={"UserNotificationBatch": {"is": {"userId": user_id}}}
- )
- assert row_count == 2
-
- # Exactly one batch for (user_id, AGENT_RUN).
- batch_count = await UserNotificationBatch.prisma().count(
- where={"userId": user_id, "type": NotificationType.AGENT_RUN}
- )
- assert batch_count == 1
- finally:
- await _cleanup_test_user(user_id)
-
-
[email protected](loop_scope="session")
-async def test_upsert_does_not_load_existing_notifications(server: SpinTestServer):
- """Pre-seeding 25 notifications into the batch and then upserting one more
- must not trip on the eager include that used to load every row."""
- user_id = f"notif-bigbatch-{uuid4()}"
- await _create_test_user(user_id)
-
- try:
- # Seed the batch by issuing 25 upserts. The first creates, the rest
- # append.
- for i in range(25):
- await create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id, agent_name=f"a{i}"),
- )
-
- pre_count = await NotificationEvent.prisma().count(
- where={"UserNotificationBatch": {"is": {"userId": user_id}}}
- )
- assert pre_count == 25
-
- # The 26th upsert: must succeed and must NOT return the 25 prior rows.
- resp = await create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id, agent_name="final"),
- )
- assert resp.notifications == [], (
- "Upsert must not eagerly include Notifications; that is the "
- "statement_timeout regression we are guarding against."
- )
-
- post_count = await NotificationEvent.prisma().count(
- where={"UserNotificationBatch": {"is": {"userId": user_id}}}
- )
- assert post_count == 26
- finally:
- await _cleanup_test_user(user_id)
-
-
[email protected](loop_scope="session")
-async def test_upsert_concurrent_invocations_no_unique_violation(
- server: SpinTestServer,
-):
- """Two concurrent invocations on an empty batch must both succeed: one
- creates, one appends. Neither loses its event, and no
- @@unique([userId, type]) violation leaks out of the helper.
-
- Prisma's upsert is find→INSERT/UPDATE, not a true SQL ON CONFLICT, so
- two concurrent calls can both miss the existing row and both attempt
- INSERT. The helper retries on UniqueViolationError so the loser
- converges on the UPDATE path."""
- user_id = f"notif-race-{uuid4()}"
- await _create_test_user(user_id)
-
- try:
- results = await asyncio.gather(
- create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id, agent_name="left"),
- ),
- create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id, agent_name="right"),
- ),
- return_exceptions=True,
- )
-
- assert all(not isinstance(r, Exception) for r in results), results
-
- batch_count = await UserNotificationBatch.prisma().count(
- where={"userId": user_id, "type": NotificationType.AGENT_RUN}
- )
- assert batch_count == 1
-
- event_count = await NotificationEvent.prisma().count(
- where={"UserNotificationBatch": {"is": {"userId": user_id}}}
- )
- assert event_count == 2, "both concurrent notifications must persist"
- finally:
- await _cleanup_test_user(user_id)
-
-
[email protected](loop_scope="session")
-async def test_upsert_retries_on_unique_violation(
- server: SpinTestServer, monkeypatch: pytest.MonkeyPatch
-):
- """Deterministic coverage for the retry path: when the first upsert
- raises UniqueViolationError (the loser of a concurrent INSERT race),
- the helper retries and the second attempt succeeds via UPDATE.
-
- Async gather + a shared connection pool can serialize concurrent calls
- in some test setups, so we patch the actions class to inject a unique
- violation on the first call and prove the retry actually runs."""
- user_id = f"notif-retry-{uuid4()}"
- await _create_test_user(user_id)
-
- try:
- # Pre-create the batch so the retry's UPDATE path has a row to hit.
- await create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id, agent_name="seed"),
- )
-
- original_upsert = UserNotificationBatchActions.upsert
- call_count = {"n": 0}
-
- async def flaky_upsert(self, *args, **kwargs):
- call_count["n"] += 1
- if call_count["n"] == 1:
- raise UniqueViolationError(
- {
- "error": (
- "Unique constraint failed on the fields: (`userId`,`type`)"
- ),
- "user_facing_error": {},
- }
- )
- return await original_upsert(self, *args, **kwargs)
-
- monkeypatch.setattr(UserNotificationBatchActions, "upsert", flaky_upsert)
-
- resp = await create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id, agent_name="retry"),
- )
- assert resp.user_id == user_id
- assert call_count["n"] == 2, "retry path must run exactly once"
-
- event_count = await NotificationEvent.prisma().count(
- where={"UserNotificationBatch": {"is": {"userId": user_id}}}
- )
- assert event_count == 2
- finally:
- await _cleanup_test_user(user_id)
-
-
[email protected](loop_scope="session")
-async def test_get_oldest_message_returns_single_event(server: SpinTestServer):
- # Hot-path egress fix: must return a single oldest event without dragging
- # the whole batch back through Prisma's eager-include path.
- user_id = f"notif-oldest-{uuid4()}"
- await _create_test_user(user_id)
-
- try:
- for i in range(5):
- await create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id, agent_name=f"e{i}"),
- )
-
- oldest = await get_user_notification_oldest_message_in_batch(
- user_id, NotificationType.AGENT_RUN
- )
- assert oldest is not None
- all_events = await NotificationEvent.prisma().find_many(
- where={"UserNotificationBatch": {"is": {"userId": user_id}}},
- order={"createdAt": "asc"},
- )
- assert oldest.created_at == all_events[0].createdAt
- finally:
- await _cleanup_test_user(user_id)
-
-
[email protected](loop_scope="session")
-async def test_get_oldest_message_returns_none_when_empty(server: SpinTestServer):
- user_id = f"notif-oldest-empty-{uuid4()}"
- await _create_test_user(user_id)
- try:
- oldest = await get_user_notification_oldest_message_in_batch(
- user_id, NotificationType.AGENT_RUN
- )
- assert oldest is None
- finally:
- await _cleanup_test_user(user_id)
-
-
[email protected](loop_scope="session")
-async def test_get_all_batches_does_not_eager_load_events(server: SpinTestServer):
- # Caller iterates batches and re-fetches events per batch when actually
- # sending; loading them here was the egress hot path.
- user_id = f"notif-allbatches-{uuid4()}"
- await _create_test_user(user_id)
-
- try:
- for i in range(3):
- await create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id, agent_name=f"e{i}"),
- )
-
- batches = await get_all_batches_by_type(NotificationType.AGENT_RUN)
- mine = [b for b in batches if b.user_id == user_id]
- assert len(mine) == 1
- assert mine[0].notifications == []
- finally:
- await _cleanup_test_user(user_id)
-
-
-async def test_create_batch_born_tenanted_stamps_default_team(mocker):
- """The create branch of the upsert stamps the batch with the user's default
- org/team at creation; the update branch must not, so re-batching never
- overwrites an existing batch's tenant. Mocked at the Prisma boundary."""
- mock_upsert = AsyncMock(return_value=object())
- mocker.patch(
- "backend.data.notifications.UserNotificationBatch.prisma"
- ).return_value.upsert = mock_upsert
- mocker.patch(
- "backend.data.notifications.UserNotificationBatchDTO.from_db",
- return_value="dto-sentinel",
- )
- mock_get_default_team = mocker.patch(
- "backend.api.features.orgs.db.get_user_default_team",
- new=AsyncMock(return_value=("org-notif", "team-notif")),
- )
-
- user_id = "notif-tenancy-user"
- result = await create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id),
- )
-
- assert result == "dto-sentinel"
- mock_get_default_team.assert_awaited_once_with(user_id)
- create_input = mock_upsert.call_args.kwargs["data"]["create"]
- assert create_input["organizationId"] == "org-notif"
- assert create_input["teamId"] == "team-notif"
- # Re-batch (update) must leave tenancy alone — an existing batch keeps its
- # tenant; only the create branch tenants.
- update_input = mock_upsert.call_args.kwargs["data"]["update"]
- assert "organizationId" not in update_input
- assert "teamId" not in update_input
-
-
-async def test_create_batch_explicit_tenancy_not_overridden(mocker):
- """An explicit org/team passed by a caller is used as-is; the default-team
- resolver is not consulted."""
- mock_upsert = AsyncMock(return_value=object())
- mocker.patch(
- "backend.data.notifications.UserNotificationBatch.prisma"
- ).return_value.upsert = mock_upsert
- mocker.patch(
- "backend.data.notifications.UserNotificationBatchDTO.from_db",
- return_value="dto-sentinel",
- )
- mock_get_default_team = mocker.patch(
- "backend.api.features.orgs.db.get_user_default_team",
- new=AsyncMock(return_value=("fallback-org", "fallback-team")),
- )
-
- user_id = "notif-explicit-user"
- await create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id),
- organization_id="explicit-org",
- team_id="explicit-team",
- )
-
- mock_get_default_team.assert_not_called()
- create_input = mock_upsert.call_args.kwargs["data"]["create"]
- assert create_input["organizationId"] == "explicit-org"
- assert create_input["teamId"] == "explicit-team"
-
-
-async def test_create_batch_default_team_lookup_failure_stays_untenanted(mocker):
- """The default-team lookup is best-effort: if it RAISES, the batch is still
- created (untenanted) rather than crashing the notification."""
- mock_upsert = AsyncMock(return_value=object())
- mocker.patch(
- "backend.data.notifications.UserNotificationBatch.prisma"
- ).return_value.upsert = mock_upsert
- mocker.patch(
- "backend.data.notifications.UserNotificationBatchDTO.from_db",
- return_value="dto-sentinel",
- )
- mocker.patch(
- "backend.api.features.orgs.db.get_user_default_team",
- new=AsyncMock(side_effect=RuntimeError("bootstrap unavailable")),
- )
-
- user_id = "notif-lookup-fail-user"
- result = await create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id),
- )
-
- assert result == "dto-sentinel"
- create_input = mock_upsert.call_args.kwargs["data"]["create"]
- assert create_input.get("organizationId") is None
- assert create_input.get("teamId") is None
-
-
-async def test_create_batch_explicit_team_id_preserved_when_org_absent(mocker):
- """An explicit team_id with no org must NOT be clobbered by the default-
- team lookup — the guard only fires when BOTH fields are unset (mirrors the
- executor-path guard)."""
- mock_upsert = AsyncMock(return_value=object())
- mocker.patch(
- "backend.data.notifications.UserNotificationBatch.prisma"
- ).return_value.upsert = mock_upsert
- mocker.patch(
- "backend.data.notifications.UserNotificationBatchDTO.from_db",
- return_value="dto-sentinel",
- )
- mock_get_default_team = mocker.patch(
- "backend.api.features.orgs.db.get_user_default_team",
- new=AsyncMock(return_value=("fallback-org", "fallback-team")),
- )
-
- user_id = "notif-team-only-user"
- await create_or_add_to_user_notification_batch(
- user_id=user_id,
- notification_type=NotificationType.AGENT_RUN,
- notification_data=_make_agent_run_event(user_id),
- team_id="explicit-team",
- )
-
- mock_get_default_team.assert_not_called()
- create_input = mock_upsert.call_args.kwargs["data"]["create"]
- assert create_input["teamId"] == "explicit-team"
- assert create_input.get("organizationId") is None
diff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.py
index 84724da52d..80a3951fdf 100644
--- a/autogpt_platform/backend/backend/data/user.py
+++ b/autogpt_platform/backend/backend/data/user.py
@@ -5,13 +5,13 @@ import hmac
import logging
import random
import uuid
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Optional, cast
from urllib.parse import quote_plus
from autogpt_libs.auth.models import DEFAULT_USER_ID
from fastapi import HTTPException
-from prisma.enums import NotificationType, SubscriptionTier
+from prisma.enums import BriefingFrequency, SubscriptionTier
from prisma.errors import UniqueViolationError
from prisma.models import AuthUser
from prisma.models import User as PrismaUser
@@ -20,6 +20,7 @@ from prisma.types import (
ProfileCreateInput,
UserCreateInput,
UserUpdateInput,
+ UserWhereInput,
)
from pydantic import BaseModel, ConfigDict
@@ -517,41 +518,14 @@ async def get_active_users_ids() -> list[str]:
async def get_user_notification_preference(user_id: str) -> NotificationPreference:
+ """The volume knob: a Briefing frequency plus two switches. Billing and
+ account messages are service mail and are not gated by any of it."""
try:
- user = await PrismaUser.prisma().find_unique_or_raise(
- where={"id": user_id},
- )
-
- # enable notifications by default if user has no notification preference (shouldn't ever happen though)
- preferences: dict[NotificationType, bool] = {
- NotificationType.AGENT_RUN: user.notifyOnAgentRun or False,
- NotificationType.ZERO_BALANCE: user.notifyOnZeroBalance or False,
- NotificationType.LOW_BALANCE: user.notifyOnLowBalance or False,
- NotificationType.BLOCK_EXECUTION_FAILED: user.notifyOnBlockExecutionFailed
- or False,
- NotificationType.CONTINUOUS_AGENT_ERROR: user.notifyOnContinuousAgentError
- or False,
- NotificationType.DAILY_SUMMARY: user.notifyOnDailySummary or False,
- NotificationType.WEEKLY_SUMMARY: user.notifyOnWeeklySummary or False,
- NotificationType.MONTHLY_SUMMARY: user.notifyOnMonthlySummary or False,
- NotificationType.AGENT_APPROVED: user.notifyOnAgentApproved or False,
- NotificationType.AGENT_REJECTED: user.notifyOnAgentRejected or False,
- }
- daily_limit = user.maxEmailsPerDay or 3
- notification_preference = NotificationPreference(
- user_id=user.id,
- email=user.email,
- preferences=preferences,
- daily_limit=daily_limit,
- # TODO with other changes later, for now we just will email them
- emails_sent_today=0,
- last_reset_date=datetime.now(),
- )
- return NotificationPreference.model_validate(notification_preference)
-
+ user = await PrismaUser.prisma().find_unique_or_raise(where={"id": user_id})
+ return _preference_from_user(user)
except Exception as e:
raise DatabaseError(
- f"Failed to upsert user notification preference for user {user_id}: {e}"
+ f"Failed to get user notification preference for user {user_id}: {e}"
) from e
@@ -559,93 +533,47 @@ async def update_user_notification_preference(
user_id: str, data: NotificationPreferenceDTO
) -> NotificationPreference:
try:
- update_data: UserUpdateInput = {}
+ update_data: UserUpdateInput = {
+ "briefingFrequency": data.briefing_frequency,
+ "alertsEnabled": data.alerts_enabled,
+ "notifyOnStoreVerdict": data.store_verdicts_enabled,
+ }
if data.email:
update_data["email"] = data.email
- if NotificationType.AGENT_RUN in data.preferences:
- update_data["notifyOnAgentRun"] = data.preferences[
- NotificationType.AGENT_RUN
- ]
- if NotificationType.ZERO_BALANCE in data.preferences:
- update_data["notifyOnZeroBalance"] = data.preferences[
- NotificationType.ZERO_BALANCE
- ]
- if NotificationType.LOW_BALANCE in data.preferences:
- update_data["notifyOnLowBalance"] = data.preferences[
- NotificationType.LOW_BALANCE
- ]
- if NotificationType.BLOCK_EXECUTION_FAILED in data.preferences:
- update_data["notifyOnBlockExecutionFailed"] = data.preferences[
- NotificationType.BLOCK_EXECUTION_FAILED
- ]
- if NotificationType.CONTINUOUS_AGENT_ERROR in data.preferences:
- update_data["notifyOnContinuousAgentError"] = data.preferences[
- NotificationType.CONTINUOUS_AGENT_ERROR
- ]
- if NotificationType.DAILY_SUMMARY in data.preferences:
- update_data["notifyOnDailySummary"] = data.preferences[
- NotificationType.DAILY_SUMMARY
- ]
- if NotificationType.WEEKLY_SUMMARY in data.preferences:
- update_data["notifyOnWeeklySummary"] = data.preferences[
- NotificationType.WEEKLY_SUMMARY
- ]
- if NotificationType.MONTHLY_SUMMARY in data.preferences:
- update_data["notifyOnMonthlySummary"] = data.preferences[
- NotificationType.MONTHLY_SUMMARY
- ]
- if NotificationType.AGENT_APPROVED in data.preferences:
- update_data["notifyOnAgentApproved"] = data.preferences[
- NotificationType.AGENT_APPROVED
- ]
- if NotificationType.AGENT_REJECTED in data.preferences:
- update_data["notifyOnAgentRejected"] = data.preferences[
- NotificationType.AGENT_REJECTED
- ]
- if data.daily_limit:
+ # `is not None`, not truthiness: 0 is the documented "send nothing"
+ # value that one-click unsubscribe writes, and a falsy check silently
+ # kept the previous limit instead.
+ if data.daily_limit is not None:
update_data["maxEmailsPerDay"] = data.daily_limit
- user = await PrismaUser.prisma().update(
- where={"id": user_id},
- data=update_data,
- )
+ user = await PrismaUser.prisma().update(where={"id": user_id}, data=update_data)
if not user:
raise ValueError(f"User not found with ID: {user_id}")
- # Invalidate cache for this user since notification preferences are part of user data
+ # Invalidate cache for this user since notification preferences are
+ # part of user data
get_user_by_id.cache_delete(user_id)
-
- preferences: dict[NotificationType, bool] = {
- NotificationType.AGENT_RUN: user.notifyOnAgentRun or True,
- NotificationType.ZERO_BALANCE: user.notifyOnZeroBalance or True,
- NotificationType.LOW_BALANCE: user.notifyOnLowBalance or True,
- NotificationType.BLOCK_EXECUTION_FAILED: user.notifyOnBlockExecutionFailed
- or True,
- NotificationType.CONTINUOUS_AGENT_ERROR: user.notifyOnContinuousAgentError
- or True,
- NotificationType.DAILY_SUMMARY: user.notifyOnDailySummary or True,
- NotificationType.WEEKLY_SUMMARY: user.notifyOnWeeklySummary or True,
- NotificationType.MONTHLY_SUMMARY: user.notifyOnMonthlySummary or True,
- NotificationType.AGENT_APPROVED: user.notifyOnAgentApproved or True,
- NotificationType.AGENT_REJECTED: user.notifyOnAgentRejected or True,
- }
- notification_preference = NotificationPreference(
- user_id=user.id,
- email=user.email,
- preferences=preferences,
- daily_limit=user.maxEmailsPerDay or 3,
- # TODO with other changes later, for now we just will email them
- emails_sent_today=0,
- last_reset_date=datetime.now(),
- )
- return NotificationPreference.model_validate(notification_preference)
-
+ return _preference_from_user(user)
except Exception as e:
raise DatabaseError(
f"Failed to update user notification preference for user {user_id}: {e}"
) from e
+def _preference_from_user(user: PrismaUser) -> NotificationPreference:
+ return NotificationPreference(
+ user_id=user.id,
+ email=user.email,
+ briefing_frequency=BriefingFrequency(user.briefingFrequency),
+ alerts_enabled=user.alertsEnabled,
+ store_verdicts_enabled=user.notifyOnStoreVerdict,
+ # Not `or 3`: the column is non-nullable, so the only value that
+ # coalesce would catch is 0 — which is precisely what a one-click
+ # unsubscribe sets, and means "send nothing".
+ daily_limit=user.maxEmailsPerDay,
+ )
+
+
async def set_user_email_verification(user_id: str, verified: bool) -> None:
"""Set the email verification status for a user."""
try:
@@ -662,24 +590,18 @@ async def set_user_email_verification(user_id: str, verified: bool) -> None:
async def disable_all_user_notifications(user_id: str) -> None:
- """Disable all notification preferences for a user.
+ """Turn the volume knob all the way down.
- Used when user's email bounces/is inactive to prevent any future notifications.
+ Used when a user's email bounces or is marked inactive, so we stop trying
+ to reach an address that cannot receive mail.
"""
try:
await PrismaUser.prisma().update(
where={"id": user_id},
data={
- "notifyOnAgentRun": False,
- "notifyOnZeroBalance": False,
- "notifyOnLowBalance": False,
- "notifyOnBlockExecutionFailed": False,
- "notifyOnContinuousAgentError": False,
- "notifyOnDailySummary": False,
- "notifyOnWeeklySummary": False,
- "notifyOnMonthlySummary": False,
- "notifyOnAgentApproved": False,
- "notifyOnAgentRejected": False,
+ "briefingFrequency": BriefingFrequency.OFF,
+ "alertsEnabled": False,
+ "notifyOnStoreVerdict": False,
},
)
# Invalidate cache for this user
@@ -739,21 +661,17 @@ async def unsubscribe_user_by_token(token: str) -> None:
raise ValueError("Invalid token signature")
user = await get_user_by_id(user_id)
+ # One-click unsubscribe turns everything off, including store
+ # verdicts — this is the trapdoor, and the volume knob in the Briefing
+ # footer is what most people should be using instead.
await update_user_notification_preference(
user.id,
NotificationPreferenceDTO(
email=user.email,
+ briefing_frequency=BriefingFrequency.OFF,
+ alerts_enabled=False,
+ store_verdicts_enabled=False,
daily_limit=0,
- preferences={
- NotificationType.AGENT_RUN: False,
- NotificationType.ZERO_BALANCE: False,
- NotificationType.LOW_BALANCE: False,
- NotificationType.BLOCK_EXECUTION_FAILED: False,
- NotificationType.CONTINUOUS_AGENT_ERROR: False,
- NotificationType.DAILY_SUMMARY: False,
- NotificationType.WEEKLY_SUMMARY: False,
- NotificationType.MONTHLY_SUMMARY: False,
- },
),
)
except Exception as e:
@@ -875,3 +793,222 @@ async def update_user_timezone(user_id: str, timezone: str) -> User:
return User.from_db(user)
except Exception as e:
raise DatabaseError(f"Failed to update timezone for user {user_id}: {e}") from e
+
+
+class BriefingCandidate(BaseModel):
+ """The fields the briefing pass needs to decide whether a user is due.
+
+ A narrow model rather than the full `User`, because this crosses the
+ DatabaseManager RPC boundary once per page of candidates.
+ """
+
+ id: str
+ email: str
+ timezone: str
+ briefing_frequency: BriefingFrequency
+ last_briefing_at: datetime | None
+ alerts_enabled: bool
+
+
+async def get_briefing_candidates(
+ timezones: list[str], after_id: str | None, limit: int
+) -> list[BriefingCandidate]:
+ """One page of users for whom it is currently the local briefing hour.
+
+ Keyset-paged on `id` so the caller can walk the whole set: a single capped
+ read would strand every user past the cap behind the same first page,
+ because the ordering never changes and the filter does not exclude users
+ already briefed.
+ """
+ try:
+ where: UserWhereInput = {
+ "briefingFrequency": {"not": BriefingFrequency.OFF},
+ "timezone": {"in": timezones},
+ }
+ if after_id:
+ where["id"] = {"gt": after_id}
+ rows = await prisma.user.find_many(where=where, take=limit, order={"id": "asc"})
+ return [
+ BriefingCandidate(
+ id=row.id,
+ email=row.email,
+ timezone=row.timezone,
+ briefing_frequency=BriefingFrequency(row.briefingFrequency),
+ last_briefing_at=row.lastBriefingAt,
+ alerts_enabled=row.alertsEnabled,
+ )
+ for row in rows
+ ]
+ except Exception as e:
+ raise DatabaseError(f"Failed to list briefing candidates: {e}") from e
+
+
+async def get_briefing_candidate(user_id: str) -> BriefingCandidate | None:
+ """One user's briefing settings, for work picked up off the queue.
+
+ The pass publishes only a user id, so the consumer re-reads rather than
+ trusting settings captured a tick earlier — a user who switched the
+ briefing off in between must not receive one.
+ """
+ try:
+ row = await prisma.user.find_unique(where={"id": user_id})
+ if row is None:
+ return None
+ return BriefingCandidate(
+ id=row.id,
+ email=row.email,
+ timezone=row.timezone,
+ briefing_frequency=BriefingFrequency(row.briefingFrequency),
+ last_briefing_at=row.lastBriefingAt,
+ alerts_enabled=row.alertsEnabled,
+ )
+ except Exception as e:
+ raise DatabaseError(f"Failed to load briefing candidate {user_id}: {e}") from e
+
+
+async def set_last_briefing_at(user_id: str, sent_at: datetime) -> None:
+ """Advance the cadence clock, once the briefing is safely on the queue."""
+ try:
+ await prisma.user.update(
+ where={"id": user_id}, data={"lastBriefingAt": sent_at}
+ )
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to record briefing time for user {user_id}: {e}"
+ ) from e
+
+
+class BillingEmailRecipient(BaseModel):
+ """The four fields the billing emails need about a customer.
+
+ A narrow model rather than the Prisma `User`, because this crosses the
+ DatabaseManager RPC boundary: the lifecycle handlers run in the REST API
+ when a Stripe webhook arrives, and in the notification service when the
+ welcome is picked up off the work queue. That second process has no Prisma
+ connection.
+ """
+
+ id: str
+ email: str
+ name: str | None = None
+ welcome_email_sent_at: datetime | None = None
+
+
+async def get_billing_email_recipient(
+ stripe_customer_id: str,
+) -> BillingEmailRecipient | None:
+ """The account behind a Stripe customer, or None for a deleted or unknown
+ one — better to skip than to email into the void."""
+ try:
+ row = await prisma.user.find_first(
+ where={"stripeCustomerId": stripe_customer_id}
+ )
+ if row is None:
+ return None
+ return BillingEmailRecipient(
+ id=row.id,
+ email=row.email,
+ name=row.name,
+ welcome_email_sent_at=row.welcomeEmailSentAt,
+ )
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to look up the account for Stripe customer "
+ f"{stripe_customer_id}: {e}"
+ ) from e
+
+
+async def claim_welcome_email(user_id: str) -> bool:
+ """Take the one-shot welcome claim. True only for the caller that set it.
+
+ Conditional on the column still being null, so two webhook deliveries
+ racing each other cannot both send.
+ """
+ try:
+ claimed = await prisma.user.update_many(
+ where={"id": user_id, "welcomeEmailSentAt": None},
+ data={"welcomeEmailSentAt": datetime.now(tz=timezone.utc)},
+ )
+ return claimed > 0
+ except Exception as e:
+ raise DatabaseError(
+ f"Failed to claim the welcome email for user {user_id}: {e}"
+ ) from e
+
+
+async def release_welcome_email(user_id: str) -> None:
+ """Give the claim back when the send fails.
+
+ This is a column, not a key with a TTL: left set after a failed publish it
+ marks the customer welcomed forever, and every retry takes the
+ returning-customer branch instead.
+ """
+ try:
+ await prisma.user.update_many(
+ where={"id": user_id}, data={"welcomeEmailSentAt": None}
+ )
+ except Exception:
+ logger.warning(
+ "Could not release the welcome claim for user %s; they will not be "
+ "greeted on a retry",
+ user_id,
+ exc_info=True,
+ )
+
+
+# The volume-knob choices a Briefing footer can carry.
+FOOTER_CHOICES = frozenset({"daily", "weekly", "monthly", "alerts", "off"})
+
+
+def generate_preference_link(user_id: str, choice: str) -> str:
+ """A footer link that changes one setting in one click.
+
+ The choice is bound to the recipient by an HMAC, for the same reason the
+ unsubscribe link is: the settings page applies it on arrival, so a bare
+ `?f=off` would let any third party change an authenticated reader's
+ preferences simply by getting them to follow a link. Signing it means only
+ a link we generated, for that person, for that choice, is honoured.
+ """
+ if choice not in FOOTER_CHOICES:
+ raise ValueError(f"Unknown footer choice: {choice}")
+ token = _sign_preference_choice(user_id, choice)
+ base_url = settings.config.frontend_base_url or settings.config.platform_base_url
+ return f"{base_url}/settings/account?f={choice}&t={quote_plus(token)}"
+
+
+def verify_preference_token(token: str, choice: str) -> str | None:
+ """The user id this token authorises for this choice, or None.
+
+ Returns None rather than raising: a bad token means the link is ignored and
+ the page loads normally, which is the right outcome for a stale forward or
+ a tampered URL.
+ """
+ try:
+ decoded = base64.urlsafe_b64decode(token).decode("utf-8")
+ user_id, received = decoded.rsplit(":", 1)
+ except Exception:
+ return None
+ expected = _sign_preference_choice(user_id, choice)
+ try:
+ expected_sig = (
+ base64.urlsafe_b64decode(expected).decode("utf-8").rsplit(":", 1)[1]
+ )
+ except Exception:
+ return None
+ if not hmac.compare_digest(expected_sig, received):
+ return None
+ return user_id
+
+
+def _sign_preference_choice(user_id: str, choice: str) -> str:
+ secret_key = settings.secrets.unsubscribe_secret_key
+ # The choice is inside the signed payload, so a token minted for "daily"
+ # cannot be replayed as "off".
+ signature = hmac.new(
+ secret_key.encode("utf-8"),
+ f"{user_id}:{choice}".encode("utf-8"),
+ hashlib.sha256,
+ ).digest()
+ return base64.urlsafe_b64encode(
+ f"{user_id}:{signature.hex()}".encode("utf-8")
+ ).decode("utf-8")
diff --git a/autogpt_platform/backend/backend/executor/billing.py b/autogpt_platform/backend/backend/executor/billing.py
index 4bf38fc6f6..4bcc3bad08 100644
--- a/autogpt_platform/backend/backend/executor/billing.py
+++ b/autogpt_platform/backend/backend/executor/billing.py
@@ -1,23 +1,18 @@
import asyncio
import logging
+from datetime import datetime, timedelta, timezone
from typing import TYPE_CHECKING, Any
+from prisma.enums import AlertCause
+
from backend.blocks import get_block
from backend.blocks._base import Block
-from backend.blocks.io import AgentOutputBlock
from backend.data import redis_client as redis
from backend.data.credit import UsageTransactionMetadata
-from backend.data.execution import GraphExecutionEntry, NodeExecutionEntry
+from backend.data.execution import NodeExecutionEntry
from backend.data.expert_spend import add_weekly_spend, add_weekly_spend_sync
-from backend.data.model import GraphExecutionStats, NodeExecutionStats
-from backend.data.notifications import (
- AgentRunData,
- LowBalanceData,
- NotificationEventModel,
- NotificationType,
- ZeroBalanceData,
-)
-from backend.notifications.notifications import queue_notification
+from backend.data.model import NodeExecutionStats
+from backend.notifications.alert_causes import LowBalanceCause, ZeroBalanceCause
from backend.util.clients import (
get_database_manager_async_client,
get_database_manager_client,
@@ -394,43 +389,6 @@ async def try_send_insufficient_funds_notif(
)
-def handle_agent_run_notif(
- db_client: "DatabaseManagerClient",
- graph_exec: GraphExecutionEntry,
- exec_stats: GraphExecutionStats,
-) -> None:
- metadata = db_client.get_graph_metadata(
- graph_exec.graph_id, graph_exec.graph_version
- )
- outputs = db_client.get_node_executions(
- graph_exec.graph_exec_id,
- block_ids=[AgentOutputBlock().id],
- )
-
- named_outputs = [
- {
- key: value[0] if key == "name" else value
- for key, value in output.output_data.items()
- }
- for output in outputs
- ]
-
- queue_notification(
- NotificationEventModel(
- user_id=graph_exec.user_id,
- type=NotificationType.AGENT_RUN,
- data=AgentRunData(
- outputs=named_outputs,
- agent_name=metadata.name if metadata else "Unknown Agent",
- credits_used=exec_stats.cost,
- execution_time=exec_stats.walltime,
- graph_id=graph_exec.graph_id,
- node_count=exec_stats.node_count,
- ),
- )
- )
-
-
def handle_insufficient_funds_notif(
db_client: "DatabaseManagerClient",
user_id: str,
@@ -468,18 +426,19 @@ def handle_insufficient_funds_notif(
metadata = db_client.get_graph_metadata(graph_id)
base_url = settings.config.frontend_base_url or settings.config.platform_base_url
- # Queue user email notification
- queue_notification(
- NotificationEventModel(
- user_id=user_id,
- type=NotificationType.ZERO_BALANCE,
- data=ZeroBalanceData(
- current_balance=e.balance,
- billing_page_link=f"{base_url}/settings/billing",
- shortfall=shortfall,
- agent_name=metadata.name if metadata else "Unknown Agent",
- ),
- )
+ # Raise the alert condition rather than sending: the alert engine owns
+ # debouncing, coalescing and the daily cap, and folds anything it can't
+ # send into the next Briefing.
+ agent_name = metadata.name if metadata else "Unknown Agent"
+ db_client.raise_alert_condition(
+ user_id=user_id,
+ cause=AlertCause.ZERO_BALANCE,
+ cause_key=f"zero_balance:{graph_id}",
+ data=ZeroBalanceCause(
+ cta_path="/settings/billing",
+ agent=agent_name,
+ shortfall_display=f"{shortfall / 100:,.2f}",
+ ).model_dump(mode="json"),
)
# Send Discord system alert
@@ -521,15 +480,13 @@ def handle_low_balance(
base_url = (
settings.config.frontend_base_url or settings.config.platform_base_url
)
- queue_notification(
- NotificationEventModel(
- user_id=user_id,
- type=NotificationType.LOW_BALANCE,
- data=LowBalanceData(
- current_balance=current_balance,
- billing_page_link=f"{base_url}/settings/billing",
- ),
- )
+ db_client.raise_alert_condition(
+ user_id=user_id,
+ cause=AlertCause.LOW_BALANCE,
+ cause_key="low_balance",
+ data=_low_balance_cause(
+ current_balance, transaction_cost, db_client, user_id
+ ).model_dump(mode="json"),
)
try:
@@ -547,3 +504,43 @@ def handle_low_balance(
)
except Exception as e:
logger.warning(f"Failed to send low balance Discord alert: {e}")
+
+
+def _low_balance_cause(
+ current_balance: int,
+ transaction_cost: int,
+ db_client: "DatabaseManagerClient",
+ user_id: str,
+) -> LowBalanceCause:
+ """Forecast the runway from what the account actually spends.
+
+ The rate used to be the cost of the single transaction that crossed the
+ threshold, which is not a rate at all: a one-cent charge against a
+ five-credit balance forecast a run-out date over a year away, inside an
+ email whose entire point is that the balance is nearly gone. Both the date
+ and the "per day" figure reached the customer.
+
+ With too little history to average, the forecast slots are left unset and
+ the alert says the balance is low without naming a date.
+ """
+ daily_rate = db_client.get_recent_daily_spend(user_id)
+ balance_display = f"{current_balance / 100:,.2f} credits"
+ scheduled_agents = db_client.count_scheduled_agents(user_id)
+
+ if daily_rate <= 0:
+ return LowBalanceCause(
+ cta_path="/settings/billing",
+ balance_display=balance_display,
+ scheduled_agents=scheduled_agents,
+ )
+
+ days_left = max(int(current_balance / daily_rate), 0)
+ runs_out = datetime.now(tz=timezone.utc) + timedelta(days=days_left)
+ return LowBalanceCause(
+ cta_path="/settings/billing",
+ days_left=days_left,
+ daily_rate_display=f"{daily_rate / 100:,.2f} credits",
+ balance_display=balance_display,
+ runs_out_label=f"{runs_out.day} {runs_out.strftime('%b')}",
+ scheduled_agents=scheduled_agents,
+ )
diff --git a/autogpt_platform/backend/backend/executor/billing_test.py b/autogpt_platform/backend/backend/executor/billing_test.py
new file mode 100644
index 0000000000..44ab922db8
--- /dev/null
+++ b/autogpt_platform/backend/backend/executor/billing_test.py
@@ -0,0 +1,41 @@
+"""The low-balance alert's runway forecast."""
+
+from types import SimpleNamespace
+
+from backend.executor.billing import _low_balance_cause
+
+
+def test_a_low_balance_alert_never_forecasts_from_a_single_charge():
+ """The rate must be a rate.
+
+ Using the threshold-crossing transaction's own cost meant a 1-credit charge
+ against a 5-credit balance forecast 500 days of runway — inside an email
+ whose subject says the credits are about to run out. Both the date and the
+ "per day" figure reached the customer.
+ """
+ client = SimpleNamespace(
+ get_recent_daily_spend=lambda _uid: 250.0, # 2.50 credits/day
+ count_scheduled_agents=lambda _uid: 2,
+ )
+ cause = _low_balance_cause(
+ current_balance=1000, transaction_cost=1, db_client=client, user_id="u1"
+ )
+ # 1000 cents at 250 cents/day is 4 days, not 1000.
+ assert cause.days_left == 4
+ assert "2.50 credits" in (cause.daily_rate_display or "")
+
+
+def test_no_spend_history_means_no_invented_date():
+ """A wrong run-out date in this email is worse than no date."""
+ client = SimpleNamespace(
+ get_recent_daily_spend=lambda _uid: 0.0,
+ count_scheduled_agents=lambda _uid: 2,
+ )
+ cause = _low_balance_cause(
+ current_balance=1000, transaction_cost=1, db_client=client, user_id="u1"
+ )
+ assert cause.days_left is None
+ assert cause.runs_out_label is None
+ assert cause.headline == "Your credits are running low"
+ assert "2 scheduled agents would stop" in cause.body
+ assert cause.tag == "low balance"
diff --git a/autogpt_platform/backend/backend/executor/manager.py b/autogpt_platform/backend/backend/executor/manager.py
index 08126e9500..0680749f2a 100644
--- a/autogpt_platform/backend/backend/executor/manager.py
+++ b/autogpt_platform/backend/backend/executor/manager.py
@@ -1069,8 +1069,10 @@ class ExecutionProcessor:
"Activity status generation disabled, not setting fields"
)
finally:
- # Communication handling
- billing.handle_agent_run_notif(db_client, graph_exec, exec_stats)
+ # No per-run email: a successful run is the system working as
+ # designed, and its evidence belongs in the Briefing's highlights
+ # or behind a deep link. The run is scored for the Briefing when
+ # its terminal stats are written, just below.
expert_posts.handle_expert_run_post(
db_client, graph_exec, exec_meta.status, exec_stats
)
diff --git a/autogpt_platform/backend/backend/executor/manager_activity_status_test.py b/autogpt_platform/backend/backend/executor/manager_activity_status_test.py
index c4b49d4080..d082a77d63 100644
--- a/autogpt_platform/backend/backend/executor/manager_activity_status_test.py
+++ b/autogpt_platform/backend/backend/executor/manager_activity_status_test.py
@@ -53,7 +53,6 @@ def test_continued_execution_clears_prior_terminal_analysis():
patch("backend.executor.manager.get_db_client", return_value=db_client),
patch("backend.executor.manager.send_execution_update"),
patch("backend.executor.manager.update_graph_execution_state"),
- patch("backend.executor.manager.billing.handle_agent_run_notif"),
patch("backend.executor.manager.expert_posts.handle_expert_run_post"),
):
processor.on_graph_execution(
diff --git a/autogpt_platform/backend/backend/executor/manager_insufficient_funds_test.py b/autogpt_platform/backend/backend/executor/manager_insufficient_funds_test.py
index 64cab1507a..79db8e3d88 100644
--- a/autogpt_platform/backend/backend/executor/manager_insufficient_funds_test.py
+++ b/autogpt_platform/backend/backend/executor/manager_insufficient_funds_test.py
@@ -1,9 +1,8 @@
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
-from prisma.enums import NotificationType
+from prisma.enums import AlertCause
-from backend.data.notifications import ZeroBalanceData
from backend.executor import billing
from backend.executor.billing import (
INSUFFICIENT_FUNDS_NOTIFIED_PREFIX,
@@ -35,8 +34,6 @@ async def test_handle_insufficient_funds_sends_discord_alert_first_time(
)
with patch(
- "backend.executor.billing.queue_notification"
- ) as mock_queue_notif, patch(
"backend.executor.billing.get_notification_manager_client"
) as mock_get_client, patch(
"backend.executor.billing.settings"
@@ -69,13 +66,14 @@ async def test_handle_insufficient_funds_sends_discord_alert_first_time(
e=error,
)
- # Verify notification was queued
- mock_queue_notif.assert_called_once()
- notification_call = mock_queue_notif.call_args[0][0]
- assert notification_call.type == NotificationType.ZERO_BALANCE
- assert notification_call.user_id == user_id
- assert isinstance(notification_call.data, ZeroBalanceData)
- assert notification_call.data.current_balance == 72
+ # Billing raises an alert condition; the alert engine decides whether
+ # it becomes an email, a coalesced line, or a Briefing attention card.
+ mock_db_client.raise_alert_condition.assert_called_once()
+ raised = mock_db_client.raise_alert_condition.call_args.kwargs
+ assert raised["cause"] == AlertCause.ZERO_BALANCE
+ assert raised["user_id"] == user_id
+ assert raised["cause_key"] == f"zero_balance:{graph_id}"
+ assert raised["data"]["agent"] == "Test Agent"
# Verify Redis was checked with correct key pattern
expected_key = f"{INSUFFICIENT_FUNDS_NOTIFIED_PREFIX}:{user_id}:{graph_id}"
@@ -108,8 +106,6 @@ async def test_handle_insufficient_funds_skips_duplicate_notifications(
)
with patch(
- "backend.executor.billing.queue_notification"
- ) as mock_queue_notif, patch(
"backend.executor.billing.get_notification_manager_client"
) as mock_get_client, patch(
"backend.executor.billing.settings"
@@ -139,8 +135,8 @@ async def test_handle_insufficient_funds_skips_duplicate_notifications(
e=error,
)
- # Verify email notification was NOT queued (deduplication worked)
- mock_queue_notif.assert_not_called()
+ # Verify no alert condition was raised (deduplication worked)
+ mock_db_client.raise_alert_condition.assert_not_called()
# Verify Discord alert was NOT sent (deduplication worked)
mock_client.discord_system_alert.assert_not_called()
@@ -163,7 +159,7 @@ async def test_handle_insufficient_funds_different_agents_get_separate_alerts(
amount=-714,
)
- with patch("backend.executor.billing.queue_notification"), patch(
+ with patch(
"backend.executor.billing.get_notification_manager_client"
) as mock_get_client, patch(
"backend.executor.billing.settings"
@@ -321,8 +317,6 @@ async def test_handle_insufficient_funds_continues_on_redis_error(
)
with patch(
- "backend.executor.billing.queue_notification"
- ) as mock_queue_notif, patch(
"backend.executor.billing.get_notification_manager_client"
) as mock_get_client, patch(
"backend.executor.billing.settings"
@@ -353,8 +347,8 @@ async def test_handle_insufficient_funds_continues_on_redis_error(
e=error,
)
- # Verify email notification was still queued despite Redis error
- mock_queue_notif.assert_called_once()
+ # Verify the alert condition was still raised despite the Redis error
+ mock_db_client.raise_alert_condition.assert_called_once()
# Verify Discord alert was still sent despite Redis error
mock_client.discord_system_alert.assert_called_once()
diff --git a/autogpt_platform/backend/backend/executor/manager_low_balance_test.py b/autogpt_platform/backend/backend/executor/manager_low_balance_test.py
index fe99379782..23bc2a24f6 100644
--- a/autogpt_platform/backend/backend/executor/manager_low_balance_test.py
+++ b/autogpt_platform/backend/backend/executor/manager_low_balance_test.py
@@ -1,9 +1,8 @@
from unittest.mock import MagicMock, patch
import pytest
-from prisma.enums import NotificationType
+from prisma.enums import AlertCause
-from backend.data.notifications import LowBalanceData
from backend.executor import billing
from backend.util.test import SpinTestServer
@@ -18,12 +17,8 @@ async def test_handle_low_balance_threshold_crossing(server: SpinTestServer):
# Mock dependencies
with patch(
- "backend.executor.billing.queue_notification"
- ) as mock_queue_notif, patch(
"backend.executor.billing.get_notification_manager_client"
- ) as mock_get_client, patch(
- "backend.executor.billing.settings"
- ) as mock_settings:
+ ) as mock_get_client, patch("backend.executor.billing.settings") as mock_settings:
# Setup mocks
mock_client = MagicMock()
@@ -34,6 +29,10 @@ async def test_handle_low_balance_threshold_crossing(server: SpinTestServer):
# Create mock database client
mock_db_client = MagicMock()
mock_db_client.get_user_email_by_id.return_value = "[email protected]"
+ # The forecast is derived from the account's real recent spend, not
+ # from the single transaction that crossed the threshold.
+ mock_db_client.get_recent_daily_spend.return_value = 100.0 # 1.00/day
+ mock_db_client.count_scheduled_agents.return_value = 2
# Test the low balance handler
billing.handle_low_balance(
@@ -43,15 +42,14 @@ async def test_handle_low_balance_threshold_crossing(server: SpinTestServer):
transaction_cost=transaction_cost,
)
- # Verify notification was queued
- mock_queue_notif.assert_called_once()
- notification_call = mock_queue_notif.call_args[0][0]
-
- # Verify notification details
- assert notification_call.type == NotificationType.LOW_BALANCE
- assert notification_call.user_id == user_id
- assert isinstance(notification_call.data, LowBalanceData)
- assert notification_call.data.current_balance == current_balance
+ # The alert engine owns debouncing and the daily cap, so billing
+ # raises a condition rather than sending anything.
+ mock_db_client.raise_alert_condition.assert_called_once()
+ raised = mock_db_client.raise_alert_condition.call_args.kwargs
+ assert raised["cause"] == AlertCause.LOW_BALANCE
+ assert raised["user_id"] == user_id
+ assert raised["cause_key"] == "low_balance"
+ assert raised["data"]["balance_display"] == "4.00 credits"
# Verify Discord alert was sent
mock_client.discord_system_alert.assert_called_once()
@@ -76,12 +74,8 @@ async def test_handle_low_balance_no_notification_when_not_crossing(
# Mock dependencies
with patch(
- "backend.executor.billing.queue_notification"
- ) as mock_queue_notif, patch(
"backend.executor.billing.get_notification_manager_client"
- ) as mock_get_client, patch(
- "backend.executor.billing.settings"
- ) as mock_settings:
+ ) as mock_get_client, patch("backend.executor.billing.settings") as mock_settings:
# Setup mocks
mock_client = MagicMock()
@@ -90,6 +84,8 @@ async def test_handle_low_balance_no_notification_when_not_crossing(
# Create mock database client
mock_db_client = MagicMock()
+ mock_db_client.get_recent_daily_spend.return_value = 100.0
+ mock_db_client.count_scheduled_agents.return_value = 2
# Test the low balance handler
billing.handle_low_balance(
@@ -99,8 +95,8 @@ async def test_handle_low_balance_no_notification_when_not_crossing(
transaction_cost=transaction_cost,
)
- # Verify no notification was sent
- mock_queue_notif.assert_not_called()
+ # Verify no alert was raised
+ mock_db_client.raise_alert_condition.assert_not_called()
mock_client.discord_system_alert.assert_not_called()
@@ -118,12 +114,8 @@ async def test_handle_low_balance_no_duplicate_when_already_below(
# Mock dependencies
with patch(
- "backend.executor.billing.queue_notification"
- ) as mock_queue_notif, patch(
"backend.executor.billing.get_notification_manager_client"
- ) as mock_get_client, patch(
- "backend.executor.billing.settings"
- ) as mock_settings:
+ ) as mock_get_client, patch("backend.executor.billing.settings") as mock_settings:
# Setup mocks
mock_client = MagicMock()
@@ -132,6 +124,8 @@ async def test_handle_low_balance_no_duplicate_when_already_below(
# Create mock database client
mock_db_client = MagicMock()
+ mock_db_client.get_recent_daily_spend.return_value = 100.0
+ mock_db_client.count_scheduled_agents.return_value = 2
# Test the low balance handler
billing.handle_low_balance(
@@ -141,6 +135,6 @@ async def test_handle_low_balance_no_duplicate_when_already_below(
transaction_cost=transaction_cost,
)
- # Verify no notification was sent (user was already below threshold)
- mock_queue_notif.assert_not_called()
+ # Verify no alert was raised (user was already below threshold)
+ mock_db_client.raise_alert_condition.assert_not_called()
mock_client.discord_system_alert.assert_not_called()
diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.py
index 88f4a7ad4d..b3cd099197 100644
--- a/autogpt_platform/backend/backend/executor/scheduler.py
+++ b/autogpt_platform/backend/backend/executor/scheduler.py
@@ -43,12 +43,11 @@ from backend.data.execution import GraphExecutionWithNodes
from backend.data.model import CredentialsMetaInput, GraphInput
from backend.executor import utils as execution_utils
from backend.monitoring import (
- NotificationJobArgs,
- process_existing_batches,
- process_weekly_summary,
+ flush_matured_alerts,
report_block_error_rates,
report_execution_accuracy_alerts,
report_late_executions,
+ send_due_briefings,
)
from backend.util.clients import (
get_database_manager_async_client,
@@ -1634,23 +1633,6 @@ def _job_to_info(
return None
-class NotificationJobInfo(NotificationJobArgs):
- id: str
- name: str
- next_run_time: str
-
- @staticmethod
- def from_db(
- job_args: NotificationJobArgs, job_obj: JobObj
- ) -> "NotificationJobInfo":
- return NotificationJobInfo(
- id=job_obj.id,
- name=job_obj.name,
- next_run_time=job_obj.next_run_time.isoformat(),
- **job_args.model_dump(),
- )
-
-
class Scheduler(AppService):
scheduler: BackgroundScheduler
@@ -1743,26 +1725,35 @@ class Scheduler(AppService):
)
if self.register_system_tasks:
- # Notification PROCESS WEEKLY SUMMARY
- # Runs every Monday at 9 AM UTC
+ # ALERTS — empty the ten-minute debounce window. Runs every
+ # minute so a condition raised at :01 goes out at :11, not at the
+ # next quarter hour.
self.scheduler.add_job(
- process_weekly_summary,
- CronTrigger.from_crontab("0 9 * * 1"),
- id="process_weekly_summary",
+ flush_matured_alerts,
+ id="flush_matured_alerts",
+ trigger="interval",
+ replace_existing=True,
+ seconds=60,
+ # Belt and braces. This only stops APScheduler double-firing
+ # the RPC; the RPC returns as soon as the pass is spawned, so
+ # the real guards are the in-process one in NotificationManager
+ # and the per-user claim the work itself takes.
+ max_instances=1,
+ jobstore=Jobstores.BATCHED_NOTIFICATIONS.value,
+ )
+
+ # BRIEFINGS — hourly, because "07:30 in the user's own timezone"
+ # is a different UTC hour for each of them.
+ self.scheduler.add_job(
+ send_due_briefings,
+ CronTrigger.from_crontab("30 * * * *"),
+ id="send_due_briefings",
kwargs={},
replace_existing=True,
+ max_instances=1,
jobstore=Jobstores.WEEKLY_NOTIFICATIONS.value,
)
- # Notification PROCESS EXISTING BATCHES
- # self.scheduler.add_job(
- # process_existing_batches,
- # id="process_existing_batches",
- # CronTrigger.from_crontab("0 12 * * 5"),
- # replace_existing=True,
- # jobstore=Jobstores.BATCHED_NOTIFICATIONS.value,
- # )
-
# Notification LATE EXECUTIONS ALERT
self.scheduler.add_job(
report_late_executions,
@@ -2302,12 +2293,12 @@ class Scheduler(AppService):
return results
@expose
- def execute_process_existing_batches(self, kwargs: dict):
- process_existing_batches(**kwargs)
+ def execute_flush_matured_alerts(self):
+ flush_matured_alerts()
@expose
- def execute_process_weekly_summary(self):
- process_weekly_summary()
+ def execute_send_due_briefings(self):
+ send_due_briefings()
@expose
def execute_report_late_executions(self):
diff --git a/autogpt_platform/backend/backend/monitoring/__init__.py b/autogpt_platform/backend/backend/monitoring/__init__.py
index f2d22f5af7..d7cb576b28 100644
--- a/autogpt_platform/backend/backend/monitoring/__init__.py
+++ b/autogpt_platform/backend/backend/monitoring/__init__.py
@@ -7,21 +7,16 @@ from .late_execution_monitor import (
LateExecutionMonitor,
report_late_executions,
)
-from .notification_monitor import (
- NotificationJobArgs,
- process_existing_batches,
- process_weekly_summary,
-)
+from .notification_monitor import flush_matured_alerts, send_due_briefings
__all__ = [
"AccuracyMonitor",
"BlockErrorMonitor",
- "LateExecutionMonitor",
"LateExecutionException",
- "NotificationJobArgs",
- "report_execution_accuracy_alerts",
+ "LateExecutionMonitor",
+ "flush_matured_alerts",
"report_block_error_rates",
+ "report_execution_accuracy_alerts",
"report_late_executions",
- "process_existing_batches",
- "process_weekly_summary",
+ "send_due_briefings",
]
diff --git a/autogpt_platform/backend/backend/monitoring/notification_monitor.py b/autogpt_platform/backend/backend/monitoring/notification_monitor.py
index db69b4d9fb..a002c87f70 100644
--- a/autogpt_platform/backend/backend/monitoring/notification_monitor.py
+++ b/autogpt_platform/backend/backend/monitoring/notification_monitor.py
@@ -1,38 +1,28 @@
-"""Notification processing monitoring module."""
+"""Scheduled passes for the email system.
-import logging
+Two jobs, matching the two families that are not purely event-driven: the
+Alert's debounce window has to be emptied on a timer, and the Briefing has to
+catch each user's local morning.
+"""
-from prisma.enums import NotificationType
-from pydantic import BaseModel
+import logging
from backend.util.clients import get_notification_manager_client
logger = logging.getLogger(__name__)
-class NotificationJobArgs(BaseModel):
- notification_types: list[NotificationType]
- cron: str
+def flush_matured_alerts() -> None:
+ """Send everything that has sat out the ten-minute debounce window."""
+ try:
+ get_notification_manager_client().flush_matured_alerts()
+ except Exception:
+ logger.exception("Error flushing matured alerts")
-def process_existing_batches(**kwargs):
- """Process existing notification batches."""
- args = NotificationJobArgs(**kwargs)
- try:
- logging.info(
- f"Processing existing batches for notification type {args.notification_types}"
- )
- get_notification_manager_client().process_existing_batches(
- args.notification_types
- )
- except Exception as e:
- logger.exception(f"Error processing existing batches: {e}")
-
-
-def process_weekly_summary(**kwargs):
- """Process weekly summary notifications."""
+def send_due_briefings() -> None:
+ """Assemble briefings for the users whose local ~07:30 this hour is."""
try:
- logging.info("Processing weekly summary")
- get_notification_manager_client().queue_weekly_summary()
- except Exception as e:
- logger.exception(f"Error processing weekly summary: {e}")
+ get_notification_manager_client().send_due_briefings()
+ except Exception:
+ logger.exception("Error sending due briefings")
diff --git a/autogpt_platform/backend/backend/notifications/__init__.py b/autogpt_platform/backend/backend/notifications/__init__.py
index 804449e106..cfccf50d3f 100644
--- a/autogpt_platform/backend/backend/notifications/__init__.py
+++ b/autogpt_platform/backend/backend/notifications/__init__.py
@@ -1,6 +1,6 @@
-from .notifications import NotificationManager, NotificationManagerClient
+"""Email notifications.
-__all__ = [
- "NotificationManager",
- "NotificationManagerClient",
-]
+Deliberately empty of re-exports: `backend.data.execution` imports the run
+scorer from here, so an eager import of the service would close an import
+cycle. Import the concrete module you need.
+"""
diff --git a/autogpt_platform/backend/backend/notifications/alert_causes.py b/autogpt_platform/backend/backend/notifications/alert_causes.py
new file mode 100644
index 0000000000..d62d2cd0a4
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/alert_causes.py
@@ -0,0 +1,465 @@
+"""The alert cause catalog.
+
+An Alert fires only for states where the platform is blocked on the human. Each
+cause carries exactly the slots its sentences need, and knows how to render
+itself three ways: as the primary block of an Alert, as a secondary "also
+waiting" line when several alerts coalesce into one email, and as an attention
+card in the Briefing when it was deduped, capped or has persisted.
+
+Every sentence is assembled from those slots — there is no hand-written copy
+per condition — and the CTA verb is always the fix, never "View dashboard".
+"""
+
+from typing import Annotated, Generic, Literal, TypeVar, Union
+
+from prisma.enums import AlertCause
+from pydantic import BaseModel, Field
+
+from backend.data.notifications import AlertAlsoItem, AlertFact, BriefingAttentionItem
+
+# Blocked-on-everything first, forecasts last. The order is load-bearing: it
+# picks which condition leads a coalesced Alert, and the Briefing's first
+# attention card gets the strong amber rule.
+SEVERITY: dict[AlertCause, int] = {
+ AlertCause.ZERO_BALANCE: 0,
+ AlertCause.AUTH_EXPIRED: 1,
+ AlertCause.PAUSED_FAILURES: 2,
+ AlertCause.CONTINUOUS_ERROR: 3,
+ AlertCause.BLOCK_FAILED: 4,
+ AlertCause.GUARDRAIL: 5,
+ AlertCause.AWAITING_INPUT: 6,
+ AlertCause.AWAITING_REVIEW: 7,
+ AlertCause.LOW_BALANCE: 8,
+}
+
+AlertCauseT = TypeVar("AlertCauseT", bound=AlertCause)
+
+
+class BaseCause(BaseModel, Generic[AlertCauseT]):
+ """Slots plus the four renderings every cause owes the email system."""
+
+ cause: AlertCauseT
+ # Relative path into the platform; the base URL is applied at render time
+ # so a stored condition still links correctly after a domain change.
+ cta_path: str
+
+ @property
+ def subject_line(self) -> str:
+ return self.headline
+
+ @property
+ def headline(self) -> str:
+ raise NotImplementedError
+
+ @property
+ def body(self) -> str:
+ raise NotImplementedError
+
+ @property
+ def cta_label(self) -> str:
+ raise NotImplementedError
+
+ @property
+ def agent_label(self) -> str:
+ """Name shown in bold on a coalesced line and in the Briefing card."""
+ raise NotImplementedError
+
+ @property
+ def tag(self) -> str | None:
+ """Short all-caps chip on the Briefing attention card."""
+ return None
+
+ @property
+ def facts(self) -> list[AlertFact]:
+ """Used when the load-bearing detail is data rather than prose."""
+ return []
+
+ @property
+ def microcopy(self) -> str | None:
+ return None
+
+ def also_item(self, base_url: str) -> AlertAlsoItem:
+ return AlertAlsoItem(
+ agent=self.agent_label,
+ text=self.body,
+ link_label=self.cta_label,
+ url=f"{base_url}{self.cta_path}",
+ )
+
+ def attention_item(self, base_url: str) -> BriefingAttentionItem:
+ return BriefingAttentionItem(
+ agent=self.agent_label,
+ title=self.headline,
+ tag=self.tag,
+ body=self.body,
+ cta_label=self.cta_label,
+ cta_url=f"{base_url}{self.cta_path}",
+ )
+
+
+class AuthExpiredCause(BaseCause[Literal[AlertCause.AUTH_EXPIRED]]):
+ cause: Literal[AlertCause.AUTH_EXPIRED] = AlertCause.AUTH_EXPIRED
+ agent: str
+ provider: str
+ expired_at_label: str
+ runs_skipped: int
+ next_try_label: str
+
+ @property
+ def headline(self) -> str:
+ return f"{self.agent} is stuck"
+
+ @property
+ def subject_line(self) -> str:
+ return f"{self.agent} is stuck — {self.provider} needs a reconnect"
+
+ @property
+ def body(self) -> str:
+ runs = (
+ "1 scheduled run has"
+ if self.runs_skipped == 1
+ else f"{self.runs_skipped} scheduled runs have"
+ )
+ return (
+ f"{self.provider}’s connection expired at {self.expired_at_label}, so "
+ f"{self.agent} can’t run. {runs} been skipped; the next try is at "
+ f"{self.next_try_label}. Until then, its schedule is on hold."
+ )
+
+ @property
+ def cta_label(self) -> str:
+ return f"Reconnect {self.provider}"
+
+ @property
+ def agent_label(self) -> str:
+ return self.agent
+
+ @property
+ def tag(self) -> str | None:
+ return f"{self.runs_skipped} runs skipped" if self.runs_skipped else None
+
+ @property
+ def microcopy(self) -> str | None:
+ return "Usually takes under a minute"
+
+
+class PausedFailuresCause(BaseCause[Literal[AlertCause.PAUSED_FAILURES]]):
+ cause: Literal[AlertCause.PAUSED_FAILURES] = AlertCause.PAUSED_FAILURES
+ agent: str
+ step: str
+ consecutive_failures: int
+
+ @property
+ def headline(self) -> str:
+ return f"{self.agent} paused itself"
+
+ @property
+ def body(self) -> str:
+ return (
+ f"The step “{self.step}” failed on {self.consecutive_failures} "
+ "consecutive runs. It stays paused until you take a look."
+ )
+
+ @property
+ def cta_label(self) -> str:
+ return "See the failing step"
+
+ @property
+ def agent_label(self) -> str:
+ return self.agent
+
+ @property
+ def tag(self) -> str | None:
+ return f"{self.consecutive_failures} fails on one step"
+
+
+class BlockFailedCause(BaseCause[Literal[AlertCause.BLOCK_FAILED]]):
+ cause: Literal[AlertCause.BLOCK_FAILED] = AlertCause.BLOCK_FAILED
+ agent: str
+ step: str
+ failure_count: int
+ error: str
+
+ @property
+ def headline(self) -> str:
+ return f"{self.agent} keeps failing on one step"
+
+ @property
+ def body(self) -> str:
+ return (
+ f"Every run gets as far as “{self.step}” and stops there. The rest of "
+ f"{self.agent} is fine — this one step needs a look."
+ )
+
+ @property
+ def cta_label(self) -> str:
+ return "See the failing step"
+
+ @property
+ def agent_label(self) -> str:
+ return self.agent
+
+ @property
+ def tag(self) -> str | None:
+ return f"{self.failure_count} failures"
+
+ @property
+ def facts(self) -> list[AlertFact]:
+ return [
+ AlertFact(label="Failing step", value=self.step),
+ AlertFact(label="Failures", value=str(self.failure_count)),
+ AlertFact(label="Error", value=self.error),
+ ]
+
+
+class ContinuousErrorCause(BaseCause[Literal[AlertCause.CONTINUOUS_ERROR]]):
+ cause: Literal[AlertCause.CONTINUOUS_ERROR] = AlertCause.CONTINUOUS_ERROR
+ agent: str
+ days: int
+ failing_since_label: str
+ consecutive_failures: int
+ error: str
+ credits_spent: float
+ fix_label: str = "See what’s failing"
+
+ @property
+ def headline(self) -> str:
+ day_word = "day" if self.days == 1 else "days"
+ return f"{self.agent} has been failing for {self.days} {day_word}"
+
+ @property
+ def body(self) -> str:
+ return (
+ f"Every scheduled run since {self.failing_since_label} has ended the same "
+ "way, and each attempt still costs credits."
+ )
+
+ @property
+ def cta_label(self) -> str:
+ return self.fix_label
+
+ @property
+ def agent_label(self) -> str:
+ return self.agent
+
+ @property
+ def tag(self) -> str | None:
+ return f"failing {self.days}d"
+
+ @property
+ def facts(self) -> list[AlertFact]:
+ return [
+ AlertFact(label="Failing since", value=self.failing_since_label),
+ AlertFact(
+ label="Consecutive failures", value=str(self.consecutive_failures)
+ ),
+ AlertFact(label="Error", value=self.error),
+ AlertFact(
+ label="Credits spent retrying", value=f"{self.credits_spent:,.2f}"
+ ),
+ ]
+
+
+class AwaitingReviewCause(BaseCause[Literal[AlertCause.AWAITING_REVIEW]]):
+ cause: Literal[AlertCause.AWAITING_REVIEW] = AlertCause.AWAITING_REVIEW
+ agent: str
+ count: int
+ since_label: str
+
+ @property
+ def headline(self) -> str:
+ return f"{self.agent} is waiting on your review"
+
+ @property
+ def body(self) -> str:
+ output = "1 output" if self.count == 1 else f"{self.count} outputs"
+ return (
+ f"{output} waiting since {self.since_label}. Nothing sends until you "
+ "approve or dismiss."
+ )
+
+ @property
+ def cta_label(self) -> str:
+ return f"Review {self.count} output" + ("" if self.count == 1 else "s")
+
+ @property
+ def agent_label(self) -> str:
+ return self.agent
+
+ @property
+ def tag(self) -> str | None:
+ return f"{self.count} waiting"
+
+
+class AwaitingInputCause(BaseCause[Literal[AlertCause.AWAITING_INPUT]]):
+ cause: Literal[AlertCause.AWAITING_INPUT] = AlertCause.AWAITING_INPUT
+ agent: str
+ field_name: str
+
+ @property
+ def headline(self) -> str:
+ return f"{self.agent} needs an input from you"
+
+ @property
+ def body(self) -> str:
+ return f"Its current run is waiting for a value for “{self.field_name}”."
+
+ @property
+ def cta_label(self) -> str:
+ return "Provide the input"
+
+ @property
+ def agent_label(self) -> str:
+ return self.agent
+
+ @property
+ def tag(self) -> str | None:
+ return "waiting on input"
+
+
+class LowBalanceCause(BaseCause[Literal[AlertCause.LOW_BALANCE]]):
+ """The forecast slots are optional on purpose.
+
+ A run-out date is only worth stating when it is derived from what the
+ account actually spends. With too little history the alert still says the
+ balance is low — it just does not invent a date, because a wrong date in
+ this email is worse than no date.
+ """
+
+ cause: Literal[AlertCause.LOW_BALANCE] = AlertCause.LOW_BALANCE
+ days_left: int | None = None
+ daily_rate_display: str | None = None
+ balance_display: str
+ runs_out_label: str | None = None
+ scheduled_agents: int
+
+ @property
+ def headline(self) -> str:
+ if self.days_left is None:
+ return "Your credits are running low"
+ day_word = "day" if self.days_left == 1 else "days"
+ return f"Your credits run out in about {self.days_left} {day_word}"
+
+ @property
+ def body(self) -> str:
+ agents = (
+ "1 scheduled agent would stop"
+ if self.scheduled_agents == 1
+ else f"{self.scheduled_agents} scheduled agents would stop"
+ )
+ if self.days_left is None:
+ # No usable spend history: state the balance and the stake, and
+ # stop short of a date we cannot stand behind.
+ return f"{self.balance_display} remaining. {agents} when it runs out."
+ return (
+ f"At {self.daily_rate_display}/day the {self.balance_display} remaining "
+ f"run out around {self.runs_out_label}. {agents}."
+ )
+
+ @property
+ def cta_label(self) -> str:
+ return "Top up credits"
+
+ @property
+ def agent_label(self) -> str:
+ return "Your balance"
+
+ @property
+ def tag(self) -> str | None:
+ if self.days_left is None:
+ return "low balance"
+ day_word = "day" if self.days_left == 1 else "days"
+ return f"~{self.days_left} {day_word} left"
+
+
+class ZeroBalanceCause(BaseCause[Literal[AlertCause.ZERO_BALANCE]]):
+ cause: Literal[AlertCause.ZERO_BALANCE] = AlertCause.ZERO_BALANCE
+ agent: str
+ shortfall_display: str
+
+ @property
+ def headline(self) -> str:
+ return f"{self.agent} stopped — you are out of credits"
+
+ @property
+ def body(self) -> str:
+ return (
+ f"{self.agent} needs {self.shortfall_display} more credits to finish. It "
+ "stays stopped until you top up."
+ )
+
+ @property
+ def cta_label(self) -> str:
+ return "Top up credits"
+
+ @property
+ def agent_label(self) -> str:
+ return self.agent
+
+ @property
+ def tag(self) -> str | None:
+ return "out of credits"
+
+
+class GuardrailCause(BaseCause[Literal[AlertCause.GUARDRAIL]]):
+ cause: Literal[AlertCause.GUARDRAIL] = AlertCause.GUARDRAIL
+ agent: str
+ limit_display: str
+ period_noun: str
+ reset_label: str
+
+ @property
+ def headline(self) -> str:
+ return f"{self.agent} hit its spend limit"
+
+ @property
+ def body(self) -> str:
+ return (
+ f"Reached its {self.limit_display}-credit limit for this "
+ f"{self.period_noun} and stopped mid-run. Resumes {self.reset_label}."
+ )
+
+ @property
+ def cta_label(self) -> str:
+ return "Review spend limit"
+
+ @property
+ def agent_label(self) -> str:
+ return self.agent
+
+ @property
+ def tag(self) -> str | None:
+ return "spend limit hit"
+
+
+AlertCausePayload = Annotated[
+ Union[
+ AuthExpiredCause,
+ PausedFailuresCause,
+ BlockFailedCause,
+ ContinuousErrorCause,
+ AwaitingReviewCause,
+ AwaitingInputCause,
+ LowBalanceCause,
+ ZeroBalanceCause,
+ GuardrailCause,
+ ],
+ Field(discriminator="cause"),
+]
+
+_BY_CAUSE: dict[AlertCause, type[BaseCause]] = {
+ AlertCause.AUTH_EXPIRED: AuthExpiredCause,
+ AlertCause.PAUSED_FAILURES: PausedFailuresCause,
+ AlertCause.BLOCK_FAILED: BlockFailedCause,
+ AlertCause.CONTINUOUS_ERROR: ContinuousErrorCause,
+ AlertCause.AWAITING_REVIEW: AwaitingReviewCause,
+ AlertCause.AWAITING_INPUT: AwaitingInputCause,
+ AlertCause.LOW_BALANCE: LowBalanceCause,
+ AlertCause.ZERO_BALANCE: ZeroBalanceCause,
+ AlertCause.GUARDRAIL: GuardrailCause,
+}
+
+
+def parse_cause(cause: AlertCause, data: dict) -> BaseCause:
+ """Rebuild a stored condition into its cause model."""
+ return _BY_CAUSE[cause].model_validate(data)
diff --git a/autogpt_platform/backend/backend/notifications/alerts.py b/autogpt_platform/backend/backend/notifications/alerts.py
new file mode 100644
index 0000000000..ee9fcd7c24
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/alerts.py
@@ -0,0 +1,162 @@
+"""The Alert engine.
+
+Alerts fire only when the platform is blocked on the human, and the rules that
+keep them worth reading live here:
+
+* **Debounce and coalesce.** New conditions are held for ten minutes, then
+ everything pending goes out as one email.
+* **Never twice in 24 hours.** The same cause does not re-alert within a day;
+ if it persists it escalates into the next Briefing's attention block.
+* **Two per day, hard cap.** Overflow folds into the Briefing. An alert channel
+ that can flood is an alert channel people mute.
+* **Cancel solved problems.** A condition that clears during the debounce
+ window cancels the send.
+"""
+
+import logging
+from datetime import datetime, timedelta, timezone
+
+from prisma.enums import NotificationType
+from pydantic import BaseModel
+
+from backend.data.alerts import MaturedAlertPage
+from backend.data.notifications import AlertData, AlertPrimary, NotificationEventModel
+from backend.notifications.alert_causes import SEVERITY, BaseCause, parse_cause
+from backend.util.clients import get_database_manager_async_client
+from backend.util.logging import TruncatedLogger
+from backend.util.settings import Settings
+
+logger = TruncatedLogger(logging.getLogger(__name__), prefix="[Alerts]")
+settings = Settings()
+
+ALERT_DEBOUNCE = timedelta(minutes=10)
+MAX_ALERT_EMAILS_PER_DAY = 2
+# How many users one flush tick pulls per page.
+MATURED_PAGE_SIZE = 1000
+
+
+def _db():
+ """The notification service owns no Prisma connection; every read and
+ write goes through the DatabaseManager."""
+ return get_database_manager_async_client()
+
+
+async def raise_alert(user_id: str, cause_key: str, cause: BaseCause) -> None:
+ """Record that the platform is blocked on this user for `cause_key`.
+
+ Emitters call this instead of sending anything: whether it becomes an
+ email, a line in a coalesced email, or an attention card in the next
+ Briefing is the engine's decision, not the caller's.
+ """
+ await _db().raise_alert_condition(
+ user_id=user_id,
+ cause=cause.cause,
+ cause_key=cause_key,
+ data=cause.model_dump(mode="json"),
+ )
+
+
+async def resolve_alert(user_id: str, cause_key: str) -> None:
+ """The problem went away. During the debounce window this cancels the send
+ outright — the user reconnected Gmail from their phone and never needs to
+ hear that it was disconnected."""
+ if await _db().resolve_alert_condition(user_id, cause_key):
+ logger.info(f"Alert condition {cause_key} resolved for user {user_id}")
+
+
+async def matured_alert_user_ids(
+ after_user_id: str | None = None,
+) -> MaturedAlertPage:
+ """One page of users whose pending conditions have sat out the debounce
+ window. Paged because this runs every minute over a platform-wide table."""
+ return await _db().get_users_with_matured_alerts(
+ datetime.now(tz=timezone.utc) - ALERT_DEBOUNCE,
+ after_user_id,
+ MATURED_PAGE_SIZE,
+ )
+
+
+class BuiltAlert(BaseModel):
+ """The email plus the conditions it covers, so the caller can mark them
+ sent only once the message is safely on the queue."""
+
+ data: AlertData
+ condition_ids: list[str]
+
+
+async def build_alert_email(user_id: str, alerts_enabled: bool) -> BuiltAlert | None:
+ """Assemble one coalesced Alert for a user, or defer everything into the
+ Briefing when the cap is hit or alerts are switched off.
+
+ Returns None when nothing should be emailed; in that case the conditions
+ have already been marked deferred, so the Briefing will carry them.
+ """
+ pending = await _db().get_pending_alert_conditions(user_id)
+ if not pending:
+ return None
+
+ condition_ids = [row.id for row in pending]
+
+ if not alerts_enabled:
+ await _db().mark_alert_conditions_deferred(condition_ids)
+ return None
+
+ sent_today = await _db().count_alerts_sent_since(user_id, _start_of_day())
+ if sent_today >= MAX_ALERT_EMAILS_PER_DAY:
+ logger.info(
+ f"User {user_id} hit the {MAX_ALERT_EMAILS_PER_DAY}-alert daily cap; "
+ f"folding {len(condition_ids)} conditions into the next briefing"
+ )
+ await _db().mark_alert_conditions_deferred(condition_ids)
+ return None
+
+ causes = sorted(
+ (parse_cause(row.cause, row.data) for row in pending),
+ key=lambda c: SEVERITY[c.cause],
+ )
+ primary, rest = causes[0], causes[1:]
+ base_url = settings.config.frontend_base_url or settings.config.platform_base_url
+
+ data = AlertData(
+ timestamp_label=_timestamp_label(),
+ primary=AlertPrimary(
+ headline=primary.headline,
+ subject=primary.subject_line,
+ preheader=primary.body,
+ body=primary.body,
+ cta_label=primary.cta_label,
+ cta_url=f"{base_url}{primary.cta_path}",
+ microcopy=primary.microcopy,
+ facts=primary.facts,
+ ),
+ also=[c.also_item(base_url) for c in rest],
+ also_label="Also waiting" if rest else None,
+ )
+ return BuiltAlert(data=data, condition_ids=condition_ids)
+
+
+async def mark_alert_sent(condition_ids: list[str]) -> None:
+ """Called once the email is on the queue. Marking earlier would lose the
+ conditions if the publish failed; marking later is the reason the same
+ cause can't re-alert for 24 hours."""
+ await _db().mark_alert_conditions_sent(condition_ids)
+
+
+def alert_event(user_id: str, data: AlertData) -> NotificationEventModel[AlertData]:
+ return NotificationEventModel[AlertData](
+ user_id=user_id, type=NotificationType.ALERT, data=data
+ )
+
+
+def _start_of_day() -> datetime:
+ now = datetime.now(tz=timezone.utc)
+ return now.replace(hour=0, minute=0, second=0, microsecond=0)
+
+
+def _timestamp_label() -> str:
+ """Absolute, never a duration: the email is read hours later, and a stale
+ relative time is a wrong time."""
+ now = datetime.now(tz=timezone.utc)
+ return (
+ f"{now.strftime('%a')} {now.day} {now.strftime('%b')}, {now.strftime('%H:%M')}"
+ )
diff --git a/autogpt_platform/backend/backend/notifications/alerts_test.py b/autogpt_platform/backend/backend/notifications/alerts_test.py
new file mode 100644
index 0000000000..4d81707c3a
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/alerts_test.py
@@ -0,0 +1,171 @@
+"""The rules that keep the Alert channel worth reading.
+
+Debounce and coalesce, never twice in 24 hours, two per day, and cancel
+anything that solved itself — with everything that can't be sent folded into
+the Briefing rather than dropped.
+"""
+
+from datetime import datetime, timedelta, timezone
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from prisma.enums import AlertCause, AlertConditionStatus
+
+from backend.data.alerts import ALERT_DEDUPE_WINDOW, AlertConditionDTO
+from backend.notifications.alert_causes import (
+ AuthExpiredCause,
+ LowBalanceCause,
+ ZeroBalanceCause,
+)
+from backend.notifications.alerts import (
+ ALERT_DEBOUNCE,
+ MAX_ALERT_EMAILS_PER_DAY,
+ build_alert_email,
+ raise_alert,
+ resolve_alert,
+)
+from backend.notifications.conftest import make_db_client
+
+USER = "user-1"
+
+
+def _condition(cause: AlertCause, payload) -> AlertConditionDTO:
+ return AlertConditionDTO(
+ id=f"c-{cause.value}",
+ user_id=USER,
+ cause=cause,
+ cause_key=f"{cause.value.lower()}:x",
+ data=payload.model_dump(mode="json"),
+ status=AlertConditionStatus.PENDING,
+ created_at=datetime.now(tz=timezone.utc) - ALERT_DEBOUNCE,
+ sent_at=None,
+ briefed_at=None,
+ )
+
+
+AUTH = AuthExpiredCause(
+ cta_path="/integrations/gmail/reconnect",
+ agent="Invoice Chaser",
+ provider="Gmail",
+ expired_at_label="9:14",
+ runs_skipped=2,
+ next_try_label="16:00",
+)
+ZERO = ZeroBalanceCause(
+ cta_path="/settings/billing", agent="Price Watch", shortfall_display="4.00"
+)
+LOW = LowBalanceCause(
+ cta_path="/settings/billing",
+ days_left=3,
+ daily_rate_display="2.00 credits",
+ balance_display="6.00 credits",
+ runs_out_label="9 Aug",
+ scheduled_agents=4,
+)
+
+
+async def test_pending_alerts_coalesce_into_one_email():
+ pending = [
+ _condition(AlertCause.LOW_BALANCE, LOW),
+ _condition(AlertCause.ZERO_BALANCE, ZERO),
+ ]
+ client = make_db_client(
+ get_pending_alert_conditions=AsyncMock(return_value=pending)
+ )
+ with patch("backend.notifications.alerts._db", return_value=client):
+ built = await build_alert_email(USER, alerts_enabled=True)
+
+ assert built is not None
+ # Severity decides which condition leads: being out of credits outranks a
+ # forecast of running low.
+ assert built.data.primary.headline == ZERO.headline
+ assert [item.agent for item in built.data.also] == ["Your balance"]
+ assert built.data.also_label == "Also waiting"
+ assert sorted(built.condition_ids) == sorted(c.id for c in pending)
+
+
+async def test_the_cta_verb_is_the_fix_not_view_dashboard():
+ client = make_db_client(
+ get_pending_alert_conditions=AsyncMock(
+ return_value=[_condition(AlertCause.AUTH_EXPIRED, AUTH)]
+ )
+ )
+ with patch("backend.notifications.alerts._db", return_value=client):
+ built = await build_alert_email(USER, alerts_enabled=True)
+
+ assert built is not None
+ assert built.data.primary.cta_label == "Reconnect Gmail"
+ assert (
+ built.data.primary.subject
+ == "Invoice Chaser is stuck — Gmail needs a reconnect"
+ )
+
+
+async def test_overflow_past_the_daily_cap_folds_into_the_briefing():
+ pending = [_condition(AlertCause.AUTH_EXPIRED, AUTH)]
+ client = make_db_client(
+ get_pending_alert_conditions=AsyncMock(return_value=pending),
+ count_alerts_sent_since=AsyncMock(return_value=MAX_ALERT_EMAILS_PER_DAY),
+ )
+ mark_deferred = client.mark_alert_conditions_deferred
+ mark_sent = client.mark_alert_conditions_sent
+ with patch("backend.notifications.alerts._db", return_value=client):
+ built = await build_alert_email(USER, alerts_enabled=True)
+
+ assert built is None
+ mark_deferred.assert_awaited_once_with([pending[0].id])
+ # Nothing is marked sent, so the 24h dedupe window never opens on an email
+ # that was never sent.
+ mark_sent.assert_not_awaited()
+
+
+async def test_alerts_switched_off_still_reach_the_briefing():
+ pending = [_condition(AlertCause.AUTH_EXPIRED, AUTH)]
+ client = make_db_client(
+ get_pending_alert_conditions=AsyncMock(return_value=pending)
+ )
+ mark_deferred = client.mark_alert_conditions_deferred
+ with patch("backend.notifications.alerts._db", return_value=client):
+ built = await build_alert_email(USER, alerts_enabled=False)
+
+ assert built is None
+ mark_deferred.assert_awaited_once_with([pending[0].id])
+
+
+async def test_nothing_pending_sends_nothing():
+ with patch("backend.notifications.alerts._db", return_value=make_db_client()):
+ assert await build_alert_email(USER, alerts_enabled=True) is None
+
+
+async def test_raising_a_condition_carries_its_cause_and_payload():
+ client = make_db_client()
+ with patch("backend.notifications.alerts._db", return_value=client):
+ await raise_alert(USER, "auth_expired:gmail:g1", AUTH)
+
+ kwargs = client.raise_alert_condition.await_args.kwargs
+ assert kwargs["cause"] is AlertCause.AUTH_EXPIRED
+ assert kwargs["cause_key"] == "auth_expired:gmail:g1"
+ assert kwargs["data"]["provider"] == "Gmail"
+
+
+async def test_a_condition_that_clears_cancels_the_send():
+ client = make_db_client()
+ with patch("backend.notifications.alerts._db", return_value=client):
+ await resolve_alert(USER, "auth_expired:gmail:g1")
+
+ client.resolve_alert_condition.assert_awaited_once_with(
+ USER, "auth_expired:gmail:g1"
+ )
+
+
+def test_the_debounce_and_dedupe_windows_match_the_design():
+ assert ALERT_DEBOUNCE == timedelta(minutes=10)
+ assert ALERT_DEDUPE_WINDOW == timedelta(hours=24)
+ assert MAX_ALERT_EMAILS_PER_DAY == 2
diff --git a/autogpt_platform/backend/backend/notifications/boundary_test.py b/autogpt_platform/backend/backend/notifications/boundary_test.py
new file mode 100644
index 0000000000..29ede18134
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/boundary_test.py
@@ -0,0 +1,115 @@
+"""The notification service owns no database connection.
+
+`AppService.lifespan` connects Redis and leaves Prisma to subclasses; only
+`rest_api`, `ws_api` and `db_manager` call `db.connect()`. Everything the
+NotificationManager process runs therefore has to reach the database through
+the DatabaseManager RPC.
+
+A grep is a blunt instrument, but it fails at the moment the boundary is
+crossed rather than the first time the service is deployed.
+"""
+
+import ast
+import pathlib
+
+import pytest
+
+# Modules in this package that do NOT run inside the notification service, and
+# so are allowed their own Prisma access. Each is called from a process that
+# owns a connection; adding to this list means asserting the same.
+_RUNS_ELSEWHERE = {
+ # Called from data/execution.py, which is exposed on the DatabaseManager and
+ # therefore runs inside it.
+ "scoring.py",
+ # Called from data/human_review.py, likewise inside the DatabaseManager.
+ "review_alerts.py",
+}
+
+_FORBIDDEN_CALLS = {"prisma"}
+_FORBIDDEN_IMPORTS = {
+ "backend.data.db": {"prisma", "query_raw_with_schema", "connect"},
+}
+
+_PACKAGE = pathlib.Path(__file__).parent
+
+
+def _modules() -> list[pathlib.Path]:
+ return sorted(
+ p
+ for p in _PACKAGE.glob("*.py")
+ if not p.name.endswith("_test.py") and p.name not in _RUNS_ELSEWHERE
+ )
+
+
[email protected]("module", _modules(), ids=lambda p: p.name)
+def test_no_direct_prisma_access_in_the_notification_service(module: pathlib.Path):
+ tree = ast.parse(module.read_text(), filename=str(module))
+
+ for node in ast.walk(tree):
+ # `Something.prisma()` — the Prisma model accessor.
+ if (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr in _FORBIDDEN_CALLS
+ ):
+ pytest.fail(
+ f"{module.name}:{node.lineno} calls .prisma() directly. The "
+ "notification service has no Prisma connection — go through "
+ "get_database_manager_async_client() instead."
+ )
+
+ if isinstance(node, ast.ImportFrom) and node.module in _FORBIDDEN_IMPORTS:
+ banned = _FORBIDDEN_IMPORTS[node.module] & {a.name for a in node.names}
+ if banned:
+ pytest.fail(
+ f"{module.name}:{node.lineno} imports {sorted(banned)} from "
+ f"{node.module}. The notification service has no Prisma "
+ "connection — go through the DatabaseManager RPC instead."
+ )
+
+
+def test_the_allowlist_only_names_modules_that_exist():
+ """A stale allowlist entry would silently exempt nothing, or worse, mask a
+ module that later moved into the service."""
+ for name in _RUNS_ELSEWHERE:
+ assert (_PACKAGE / name).exists(), f"{name} is allowlisted but does not exist"
+
+
+def test_the_service_does_not_connect_a_database_itself():
+ """If this ever needs changing, the RPC boundary has been abandoned and
+ every module above is free to query Prisma again — which is the state that
+ shipped the outage."""
+ source = (_PACKAGE / "notifications.py").read_text()
+ assert "db.connect()" not in source, (
+ "NotificationManager must not open its own Prisma connection; its "
+ "database access belongs behind the DatabaseManager RPC."
+ )
+
+
+def test_no_rpc_endpoint_is_aliased():
+ """A renamed RPC endpoint is a 404 waiting to happen.
+
+ `AppService` registers routes by *attribute* name
+ (``route_path = f"/{attr_name}"``) while the client builds its URL from the
+ underlying function's ``__name__`` (``rpc_name = original_func.__name__``).
+ Alias one and the server exposes `/get_pending_alert_conditions` while the
+ client POSTs `/get_pending_conditions`.
+
+ This is silent until something actually calls the endpoint: the two aliases
+ the email redesign introduced were dead for as long as its callers used
+ Prisma directly, and only 404'd once they went through the RPC.
+ """
+ from backend.data.db_manager import DatabaseManager
+
+ aliased = []
+ for name, attr in vars(DatabaseManager).items():
+ if name.startswith("_"):
+ continue
+ func = getattr(attr, "__wrapped__", attr)
+ real = getattr(func, "__name__", None)
+ if real and real not in (name, "_stub"):
+ aliased.append(f"/{name} is served, but clients POST /{real}")
+
+ assert not aliased, "aliased RPC endpoints 404 at runtime:\n " + "\n ".join(
+ aliased
+ )
diff --git a/autogpt_platform/backend/backend/notifications/briefing.py b/autogpt_platform/backend/backend/notifications/briefing.py
new file mode 100644
index 0000000000..f93bfb2562
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/briefing.py
@@ -0,0 +1,252 @@
+"""Assembling the Briefing.
+
+An inverted pyramid under a hard length budget: the lede, anything that needs
+the user, at most three highlights, a six-row ledger, and a footer with the
+volume knob. It is never sent empty — a period with nothing to say produces no
+email, and a period with only a whisper of activity produces a deliberately
+tiny email rather than a padded one.
+"""
+
+import logging
+
+from prisma.enums import BriefingFrequency, NotificationType
+from pydantic import BaseModel
+
+from backend.data.alerts import AlertConditionDTO
+from backend.data.briefing_data import AgentPeriodStats, ScoredRun
+from backend.data.notifications import (
+ BriefingAttentionItem,
+ BriefingData,
+ BriefingHighlight,
+ BriefingLedgerRow,
+ BriefingTotals,
+ NotificationEventModel,
+)
+from backend.notifications.alert_causes import SEVERITY, parse_cause
+from backend.notifications.briefing_period import period_window
+from backend.notifications.gist import build_gist, fallback_gist
+from backend.util.clients import get_database_manager_async_client
+from backend.util.logging import TruncatedLogger
+from backend.util.settings import Settings
+
+logger = TruncatedLogger(logging.getLogger(__name__), prefix="[Briefing]")
+settings = Settings()
+
+MAX_HIGHLIGHTS = 3
+# The email shows six rows and a "+ N quieter agents" line. Capping here
+# rather than in the template keeps the queued payload the size of the email
+# instead of the size of the account.
+MAX_LEDGER_ROWS = 6
+# Likewise for the attention block: everything beyond this stays unbriefed and
+# is carried by the next period rather than bloating this one.
+MAX_ATTENTION_ITEMS = 6
+# Under this much activity the digest shrinks instead of padding.
+QUIET_RUN_THRESHOLD = 3
+# Roughly what a credit costs, used only for the parenthetical dollar estimate
+# under the ledger.
+CREDITS_PER_USD = 100
+
+
+def _db():
+ """No Prisma connection in the notification service; go via the RPC."""
+ return get_database_manager_async_client()
+
+
+class BuiltBriefing(BaseModel):
+ """The briefing plus the alert conditions its attention block reported, so
+ only those are marked once the email is safely on the queue."""
+
+ data: BriefingData
+ attention_condition_ids: list[str]
+
+
+async def build_briefing(
+ user_id: str, frequency: BriefingFrequency, timezone_name: str, now
+) -> BuiltBriefing | None:
+ """Assemble one user's briefing, or None when there is nothing to send."""
+ window = period_window(frequency, timezone_name, now)
+ agents = await _db().get_agent_period_stats(user_id, window.start, window.end)
+ conditions = await _db().get_briefing_alert_conditions(user_id)
+
+ if not agents and not conditions:
+ # Never send empty — but a period with no runs can still carry an
+ # unresolved condition, and the Briefing is the only place those show.
+ return None
+ attention, reported_condition_ids = _attention_block(conditions)
+ highlights = await _highlights(user_id, window.start, window.end, agents)
+ all_rows = [_ledger_row(agent, attention) for agent in agents]
+ ledger, overflow = all_rows[:MAX_LEDGER_ROWS], all_rows[MAX_LEDGER_ROWS:]
+
+ runs = sum(agent.runs for agent in agents)
+ failed = sum(agent.failed for agent in agents)
+ credits_used = sum(agent.credits for agent in agents)
+ totals = BriefingTotals(
+ # Invariants: runs is the sum over every active agent, and
+ # agents_active counts them all — the ledger is the displayed slice,
+ # so the totals are taken before the cap.
+ runs=runs,
+ agents_active=len(all_rows),
+ agents_idle=max(await _db().count_active_agents(user_id) - len(agents), 0),
+ failed=failed,
+ credits_used=credits_used,
+ credits_balance=await _db().get_briefing_credit_balance(user_id),
+ usd_estimate=round(credits_used / CREDITS_PER_USD, 2) if credits_used else None,
+ )
+
+ quiet = _is_quiet(totals, attention)
+ return BuiltBriefing(
+ data=BriefingData(
+ mode="quiet" if quiet else "standard",
+ period=window.period,
+ totals=totals,
+ standout=None if quiet else _standout(agents, totals),
+ subject_note=_subject_note(highlights),
+ attention=attention,
+ highlights=highlights,
+ ledger=ledger,
+ ledger_overflow=len(overflow),
+ ledger_overflow_runs=sum(row.runs for row in overflow),
+ ledger_overflow_issues=sum(1 for row in overflow if row.issues_label),
+ only_agent=all_rows[0].agent if quiet and len(all_rows) == 1 else None,
+ quiet_summary=_quiet_summary(totals) if quiet else None,
+ ),
+ attention_condition_ids=reported_condition_ids,
+ )
+
+
+def briefing_event(
+ user_id: str, data: BriefingData
+) -> NotificationEventModel[BriefingData]:
+ return NotificationEventModel[BriefingData](
+ user_id=user_id, type=NotificationType.BRIEFING, data=data
+ )
+
+
+async def mark_attention_reported(condition_ids: list[str]) -> None:
+ """Called once the briefing is actually queued, so the same conditions are
+ not reported again next period."""
+ await _db().mark_alert_conditions_briefed(condition_ids)
+
+
+def _attention_block(
+ conditions: list[AlertConditionDTO],
+) -> tuple[list[BriefingAttentionItem], list[str]]:
+ """Absorbs every alert condition that was capped or deduped during the
+ period, plus anything still unresolved. Sorted by severity, because the
+ first card gets the strong amber rule.
+
+ Returns the items alongside the ids of exactly the conditions they came
+ from. The block is capped, and marking the overflow briefed would retire
+ conditions the reader never saw — they are filtered out of the next
+ period's candidates, so they would never surface in any briefing.
+ """
+ base_url = settings.config.frontend_base_url or settings.config.platform_base_url
+ ranked = sorted(
+ ((parse_cause(c.cause, c.data), c) for c in conditions),
+ key=lambda pair: SEVERITY[pair[0].cause],
+ )[:MAX_ATTENTION_ITEMS]
+ return (
+ [cause.attention_item(base_url) for cause, _ in ranked],
+ [condition.id for _, condition in ranked],
+ )
+
+
+async def _highlights(
+ user_id: str, start, end, agents: list[AgentPeriodStats]
+) -> list[BriefingHighlight]:
+ """At most three notable outputs from the whole period, each a gist and a
+ deep link. This is what replaces the old per-run email."""
+ base_url = settings.config.frontend_base_url or settings.config.platform_base_url
+ runs = await _db().get_top_scored_runs(user_id, start, end, limit=MAX_HIGHLIGHTS)
+ runs_by_graph = {agent.graph_id: agent.runs for agent in agents}
+ return [
+ BriefingHighlight(
+ agent=run.agent,
+ gist=await _gist_for(user_id, run, runs_by_graph.get(run.graph_id, 1)),
+ link_label="See the run",
+ url=f"{base_url}/library/agents/{run.graph_id}/runs/{run.execution_id}",
+ )
+ for run in runs
+ ]
+
+
+async def _gist_for(user_id: str, run: ScoredRun, agent_runs: int) -> str:
+ """Summarisation pass, then a truncated first line, then counts — but never
+ a raw output. The inbox gets the gist and the link; the platform is where
+ outputs live."""
+ outputs = await _run_outputs(user_id, run.execution_id)
+ return build_gist(outputs, run.activity_status) or fallback_gist(agent_runs)
+
+
+async def _run_outputs(user_id: str, execution_id: str) -> dict[str, list]:
+ try:
+ execution = await _db().get_graph_execution(user_id, execution_id)
+ except Exception:
+ logger.warning(
+ f"Could not load outputs for run {execution_id}; falling back to counts",
+ exc_info=True,
+ )
+ return {}
+ return dict(execution.outputs) if execution else {}
+
+
+def _ledger_row(
+ agent: AgentPeriodStats, attention: list[BriefingAttentionItem]
+) -> BriefingLedgerRow:
+ if agent.failed:
+ return BriefingLedgerRow(
+ agent=agent.agent,
+ runs=agent.runs,
+ credits=agent.credits,
+ issues_label=f"{agent.failed} failed",
+ issues_kind="fail",
+ )
+ # An agent with no failures can still be blocked — a skipped schedule shows
+ # as amber, not red.
+ waiting = next((item for item in attention if item.agent == agent.agent), None)
+ return BriefingLedgerRow(
+ agent=agent.agent,
+ runs=agent.runs,
+ credits=agent.credits,
+ issues_label=waiting.tag if waiting and waiting.tag else None,
+ issues_kind="warn" if waiting and waiting.tag else None,
+ )
+
+
+def _is_quiet(totals: BriefingTotals, attention: list[BriefingAttentionItem]) -> bool:
+ return totals.runs <= QUIET_RUN_THRESHOLD and totals.failed == 0 and not attention
+
+
+def _quiet_summary(totals: BriefingTotals) -> str:
+ times = "once" if totals.runs == 1 else f"{totals.runs} times"
+ return f"It ran {times}, and nothing needed your attention."
+
+
+def _standout(agents: list[AgentPeriodStats], totals: BriefingTotals) -> str | None:
+ """One rule-built sentence of colour, or nothing. A standout that has to be
+ invented is worse than no standout."""
+ if len(agents) < 3 or totals.runs == 0:
+ return None
+
+ busiest = max(agents, key=lambda a: a.runs)
+ if busiest.runs * 2 >= totals.runs:
+ return (
+ f"{busiest.agent} did most of the work — {busiest.runs:,} of "
+ f"{totals.runs:,} runs."
+ )
+
+ if totals.credits_used > 0:
+ costliest = max(agents, key=lambda a: a.credits)
+ if costliest.credits * 2 >= totals.credits_used:
+ return f"{costliest.agent} accounted for most of your credits."
+ return None
+
+
+def _subject_note(highlights: list[BriefingHighlight]) -> str | None:
+ """A short phrase for the subject, taken from the top highlight — the
+ subject is the email for most people, so it carries the payload."""
+ if not highlights:
+ return None
+ top = highlights[0]
+ note = f"{top.agent} {top.gist.rstrip('.')}"
+ return note if len(note) <= 60 else f"{note[:59].rstrip()}…"
diff --git a/autogpt_platform/backend/backend/notifications/briefing_period.py b/autogpt_platform/backend/backend/notifications/briefing_period.py
new file mode 100644
index 0000000000..d6e95970bf
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/briefing_period.py
@@ -0,0 +1,121 @@
+"""Which period a Briefing covers, and when it is due.
+
+Briefings land at ~07:30 in the user's own local time — a digest that arrives
+at 3am reads as a machine talking, not a chief of staff. The scheduler runs
+hourly and this module decides, per user, whether this is their hour.
+"""
+
+from datetime import date, datetime, time, timedelta, timezone
+from typing import Literal
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+
+from prisma.enums import BriefingFrequency
+from pydantic import BaseModel
+
+from backend.data.notifications import BriefingPeriod
+
+# The hour, in the user's local time, that briefings go out.
+BRIEFING_HOUR = 7
+BRIEFING_MINUTE = 30
+
+BriefingFrequencyLabel = Literal["daily", "weekly", "monthly"]
+
+_FREQUENCY_LABELS: dict[BriefingFrequency, tuple[BriefingFrequencyLabel, str]] = {
+ BriefingFrequency.DAILY: ("daily", "day"),
+ BriefingFrequency.WEEKLY: ("weekly", "week"),
+ BriefingFrequency.MONTHLY: ("monthly", "month"),
+}
+
+
+class PeriodWindow(BaseModel):
+ """The UTC window a briefing covers, plus the words that describe it."""
+
+ start: datetime
+ end: datetime
+ period: BriefingPeriod
+
+
+def resolve_zone(timezone_name: str) -> ZoneInfo:
+ """Users who never set a timezone get UTC rather than no briefing."""
+ if not timezone_name or timezone_name == "not-set":
+ return ZoneInfo("UTC")
+ try:
+ return ZoneInfo(timezone_name)
+ except (ZoneInfoNotFoundError, ValueError):
+ return ZoneInfo("UTC")
+
+
+def is_briefing_due(
+ frequency: BriefingFrequency,
+ timezone_name: str,
+ now: datetime,
+ last_sent: datetime | None,
+) -> bool:
+ """Whether `now` is this user's briefing moment for their frequency.
+
+ Daily fires every local morning, weekly on Mondays, monthly on the 1st.
+ `last_sent` guards against a re-run of the hourly job sending the same
+ period twice.
+ """
+ if frequency is BriefingFrequency.OFF:
+ return False
+
+ local_now = now.astimezone(resolve_zone(timezone_name))
+ if local_now.hour != BRIEFING_HOUR:
+ return False
+ if frequency is BriefingFrequency.WEEKLY and local_now.weekday() != 0:
+ return False
+ if frequency is BriefingFrequency.MONTHLY and local_now.day != 1:
+ return False
+
+ if last_sent is None:
+ return True
+ # One send per period: anything inside the window we are about to report on
+ # means this user already has it.
+ window = period_window(frequency, timezone_name, now)
+ return last_sent < window.end
+
+
+def period_window(
+ frequency: BriefingFrequency, timezone_name: str, now: datetime
+) -> PeriodWindow:
+ """The window to report on, in UTC, with its plain-English labels."""
+ zone = resolve_zone(timezone_name)
+ local_now = now.astimezone(zone)
+ today = local_now.date()
+
+ if frequency is BriefingFrequency.DAILY:
+ start_date, end_date = today - timedelta(days=1), today
+ label = _format_day(start_date)
+ noun = "yesterday"
+ elif frequency is BriefingFrequency.MONTHLY:
+ end_date = today.replace(day=1)
+ start_date = (end_date - timedelta(days=1)).replace(day=1)
+ label = start_date.strftime("%B %Y")
+ noun = f"in {start_date.strftime('%B')}"
+ else:
+ start_date, end_date = today - timedelta(days=7), today
+ label = (
+ f"{_format_day(start_date)} – {_format_day(end_date - timedelta(days=1))}"
+ )
+ noun = "last week"
+
+ frequency_word, adjective = _FREQUENCY_LABELS[frequency]
+ return PeriodWindow(
+ start=_utc_midnight(start_date, zone),
+ end=_utc_midnight(end_date, zone),
+ period=BriefingPeriod(
+ label=label,
+ noun=noun,
+ adjective=adjective,
+ frequency=frequency_word,
+ ),
+ )
+
+
+def _utc_midnight(day: date, zone: ZoneInfo) -> datetime:
+ return datetime.combine(day, time.min, tzinfo=zone).astimezone(timezone.utc)
+
+
+def _format_day(day: date) -> str:
+ return f"{day.strftime('%a')} {day.day} {day.strftime('%b')}"
diff --git a/autogpt_platform/backend/backend/notifications/briefing_period_test.py b/autogpt_platform/backend/backend/notifications/briefing_period_test.py
new file mode 100644
index 0000000000..f449d82833
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/briefing_period_test.py
@@ -0,0 +1,89 @@
+"""A briefing lands at ~07:30 in the reader's own morning, not ours."""
+
+from datetime import datetime, timezone
+
+from prisma.enums import BriefingFrequency
+
+from backend.notifications.briefing_period import (
+ BRIEFING_HOUR,
+ is_briefing_due,
+ period_window,
+ resolve_zone,
+)
+
+# 07:30 in New York is 11:30 UTC in August.
+NY_MORNING = datetime(2026, 8, 3, 11, 30, tzinfo=timezone.utc) # a Monday
+
+
+def test_due_in_the_users_own_morning_not_ours():
+ assert is_briefing_due(
+ BriefingFrequency.DAILY, "America/New_York", NY_MORNING, None
+ )
+ # Same instant is mid-afternoon in Berlin, so nothing is due there.
+ assert not is_briefing_due(
+ BriefingFrequency.DAILY, "Europe/Berlin", NY_MORNING, None
+ )
+
+
+def test_weekly_only_fires_on_a_monday():
+ tuesday = datetime(2026, 8, 4, 11, 30, tzinfo=timezone.utc)
+ assert is_briefing_due(
+ BriefingFrequency.WEEKLY, "America/New_York", NY_MORNING, None
+ )
+ assert not is_briefing_due(
+ BriefingFrequency.WEEKLY, "America/New_York", tuesday, None
+ )
+
+
+def test_monthly_only_fires_on_the_first():
+ first = datetime(2026, 9, 1, 11, 30, tzinfo=timezone.utc)
+ assert is_briefing_due(BriefingFrequency.MONTHLY, "America/New_York", first, None)
+ assert not is_briefing_due(
+ BriefingFrequency.MONTHLY, "America/New_York", NY_MORNING, None
+ )
+
+
+def test_off_is_never_due():
+ assert not is_briefing_due(
+ BriefingFrequency.OFF, "America/New_York", NY_MORNING, None
+ )
+
+
+def test_a_period_is_never_briefed_twice():
+ window = period_window(BriefingFrequency.WEEKLY, "America/New_York", NY_MORNING)
+ already_sent = window.end
+ assert not is_briefing_due(
+ BriefingFrequency.WEEKLY, "America/New_York", NY_MORNING, already_sent
+ )
+
+
+def test_an_unset_timezone_is_treated_as_utc_rather_than_skipped():
+ utc_morning = datetime(2026, 8, 3, BRIEFING_HOUR, 30, tzinfo=timezone.utc)
+ assert is_briefing_due(BriefingFrequency.DAILY, "not-set", utc_morning, None)
+ assert resolve_zone("Nowhere/Fictional").key == "UTC"
+
+
+def test_daily_window_covers_yesterday_in_local_time():
+ window = period_window(BriefingFrequency.DAILY, "America/New_York", NY_MORNING)
+ assert window.period.noun == "yesterday"
+ assert window.period.frequency == "daily"
+ assert (window.end - window.start).days == 1
+
+
+def test_monthly_window_covers_the_previous_calendar_month():
+ first = datetime(2026, 9, 1, 11, 30, tzinfo=timezone.utc)
+ window = period_window(BriefingFrequency.MONTHLY, "America/New_York", first)
+ assert window.period.label == "August 2026"
+ assert window.period.noun == "in August"
+
+
+def test_the_weekly_noun_describes_the_window_it_actually_covers():
+ """The weekly window is the seven days *before* today, matching how daily
+ says "yesterday" and monthly names the previous month."""
+ window = period_window(
+ BriefingFrequency.WEEKLY,
+ "UTC",
+ datetime(2026, 8, 3, 7, 30, tzinfo=timezone.utc),
+ )
+ assert window.period.noun == "last week"
+ assert (window.end - window.start).days == 7
diff --git a/autogpt_platform/backend/backend/notifications/briefing_runner.py b/autogpt_platform/backend/backend/notifications/briefing_runner.py
new file mode 100644
index 0000000000..8a55d937bc
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/briefing_runner.py
@@ -0,0 +1,248 @@
+"""The two scheduled passes, and the per-user work they fan out.
+
+`flush_matured_alerts` runs every minute and empties the debounce window;
+`send_due_briefings` runs hourly and catches each user's local ~07:30.
+
+**A pass decides who is due and publishes; it never assembles.** Each due user
+becomes one message on the work queue, and a consumer does the reading and
+rendering. That keeps a tick O(1) in the number of users, so a pass physically
+cannot run past its own interval no matter how many users are due — which is
+what the previous shape got wrong, silently falling further behind as the user
+base grew. It also buys per-user retry, failure isolation and a dead-letter
+queue from the same machinery the emails already use.
+
+The work is claimed before it is acted on, because queue delivery is
+at-least-once and the service can run more than one replica.
+"""
+
+import logging
+from collections.abc import AsyncIterator
+from datetime import datetime, timezone
+from zoneinfo import available_timezones
+
+from backend.data.notifications import PassWorkEvent, PassWorkKind
+from backend.data.user import BriefingCandidate
+from backend.notifications import alerts, briefing, lifecycle
+from backend.notifications.briefing_period import (
+ BRIEFING_HOUR,
+ is_briefing_due,
+ resolve_zone,
+)
+from backend.notifications.dedupe import (
+ PASS_CLAIM_TTL_SECONDS,
+ claim_once,
+ release_claim,
+)
+from backend.notifications.queue import queue_notification_async, queue_pass_work
+from backend.util.clients import get_database_manager_async_client
+from backend.util.logging import TruncatedLogger
+
+logger = TruncatedLogger(logging.getLogger(__name__), prefix="[NotificationRunner]")
+
+
+def _db():
+ """This service owns no Prisma connection; the DatabaseManager does."""
+ return get_database_manager_async_client()
+
+
+# Page size for the candidate walk. Bounds how many users are held in memory
+# at once; it does not bound how many are considered.
+CANDIDATE_PAGE_SIZE = 5000
+
+
+async def flush_matured_alerts() -> None:
+ """Publish one flush job per user whose conditions have matured."""
+ now = datetime.now(tz=timezone.utc)
+ published = 0
+
+ async for user_id in _matured_alert_user_ids():
+ published += 1
+ await queue_pass_work(
+ PassWorkKind.ALERT_FLUSH.value,
+ user_id,
+ PassWorkEvent(
+ kind=PassWorkKind.ALERT_FLUSH, user_id=user_id, scheduled_for=now
+ ).model_dump_json(),
+ )
+
+ if published:
+ logger.info(f"Fanned out {published} alert flushes")
+
+
+async def send_due_briefings() -> None:
+ """Publish one briefing job per user whose local briefing hour this is.
+
+ The cadence check stays here because it is cheap and needs no extra read:
+ the candidate row already carries the frequency and the last send. Only
+ users that pass it become messages.
+ """
+ now = datetime.now(tz=timezone.utc)
+ zones = _briefing_hour_timezones(now)
+ considered = published = 0
+
+ async for user in _briefing_candidates(zones):
+ considered += 1
+ if not is_briefing_due(
+ user.briefing_frequency, user.timezone, now, user.last_briefing_at
+ ):
+ continue
+ published += 1
+ await queue_pass_work(
+ PassWorkKind.BRIEFING.value,
+ user.id,
+ PassWorkEvent(
+ kind=PassWorkKind.BRIEFING, user_id=user.id, scheduled_for=now
+ ).model_dump_json(),
+ )
+
+ logger.info(f"Considered {considered} users, fanned out {published} briefings")
+
+
+# ── the work itself, run by the queue consumer ──────────────────────────
+
+
+async def run_pass_work(event: PassWorkEvent) -> None:
+ """Do one user's share of a scheduled pass.
+
+ Claimed first: delivery is at-least-once and there may be several
+ replicas, so without this a redelivery is a second email. The claim key
+ carries the period, so the next period is never suppressed by this one.
+ """
+ key = _claim_key(event)
+ if not await claim_once(key, ttl_seconds=PASS_CLAIM_TTL_SECONDS):
+ logger.debug(f"{event.kind.value} for {event.user_id} already claimed")
+ return
+
+ try:
+ if event.kind is PassWorkKind.ALERT_FLUSH:
+ await _flush_user_alerts(event.user_id)
+ elif event.kind is PassWorkKind.WELCOME:
+ await lifecycle.send_welcome_for_session(event.context["session_id"])
+ else:
+ await _build_and_queue_briefing(event.user_id, event.scheduled_for)
+ except Exception:
+ # The consumer retries this message. Holding the claim would make the
+ # retry find its own claim, return early, and drop the work for the
+ # whole period — the claim outlives the retries by design.
+ await release_claim(key)
+ raise
+
+
+def _claim_key(event: PassWorkEvent) -> str:
+ """Identify the work's slot, not the moment it was published.
+
+ Every publisher of one slot has to arrive at the same key or the claim
+ stops being a claim: two schedulers reading the clock a microsecond apart
+ would each get their own key and both send. WELCOME has no slot — Stripe
+ redelivers at a fresh timestamp, so it keys on the checkout session, which
+ is also the only identifier it carries (`user_id` is empty).
+ """
+ if event.kind is PassWorkKind.WELCOME:
+ return f"{event.kind.value}:{event.context['session_id']}"
+ slot = event.scheduled_for.replace(second=0, microsecond=0)
+ if event.kind is PassWorkKind.BRIEFING:
+ # Briefings are scheduled by the hour; alert flushes run every minute.
+ slot = slot.replace(minute=0)
+ return f"{event.kind.value}:{event.user_id}:{slot.isoformat()}"
+
+
+async def _flush_user_alerts(user_id: str) -> None:
+ # Raises for an unknown user rather than returning None, and that is left
+ # to propagate — a transient database failure is what the retry is for.
+ preference = await _db().get_user_notification_preference(user_id)
+ built = await alerts.build_alert_email(user_id, preference.alerts_enabled)
+ if built is None:
+ # Deferred into the next briefing, or nothing left to say.
+ return
+ result = await queue_notification_async(alerts.alert_event(user_id, built.data))
+ if not result.success:
+ raise RuntimeError(f"Could not queue the alert for user {user_id}")
+ await alerts.mark_alert_sent(built.condition_ids)
+
+
+async def _build_and_queue_briefing(user_id: str, now: datetime) -> None:
+ # No preference read here: `send_due_briefings` already gated on frequency
+ # via `is_briefing_due`, and a user who has since vanished falls out on the
+ # candidate lookup below rather than raising.
+ user = await _db().get_briefing_candidate(user_id)
+ if user is None:
+ return
+
+ built = await briefing.build_briefing(
+ user_id, user.briefing_frequency, user.timezone, now
+ )
+ if built is None:
+ # Never sent empty: a period with nothing to say produces no email.
+ logger.debug(f"Nothing to brief for user {user_id}")
+ return
+
+ result = await queue_notification_async(
+ briefing.briefing_event(user_id, built.data)
+ )
+ if not result.success:
+ # Raise so the consumer retries; the claim is period-scoped, so a
+ # redelivery inside the same period is still suppressed and only a
+ # genuine retry of *this* message gets through.
+ raise RuntimeError(f"Could not queue the briefing for user {user_id}")
+
+ # Only the conditions this briefing actually reported are marked, so one
+ # raised while it was being built still gets its turn next period.
+ await briefing.mark_attention_reported(built.attention_condition_ids)
+ await _db().set_last_briefing_at(user_id, now)
+
+
+async def _matured_alert_user_ids() -> AsyncIterator[str]:
+ """Every user with a matured PENDING condition, paged.
+
+ The underlying table holds one row per live condition for the whole
+ platform and this runs every minute, so the read is bounded and walked
+ rather than taken in one go.
+ """
+ cursor: str | None = None
+ while True:
+ page = await alerts.matured_alert_user_ids(after_user_id=cursor)
+ for user_id in page.user_ids:
+ yield user_id
+ # Deduplication makes `user_ids` shorter than the rows read, so only
+ # the page itself can say whether the walk is done.
+ if page.exhausted or not page.user_ids:
+ return
+ cursor = page.user_ids[-1]
+
+
+async def _briefing_candidates(zones: list[str]) -> AsyncIterator[BriefingCandidate]:
+ """Users for whom it is currently the briefing hour, locally.
+
+ Filtering on timezone in SQL keeps each hourly pass to roughly a
+ twenty-fourth of the user base; `is_briefing_due` then applies the weekly
+ and monthly cadence rules.
+
+ Walks the whole set one page at a time, keyed on the last id seen, so the
+ pass is bounded in memory without being bounded in coverage.
+ """
+ cursor: str | None = None
+ while True:
+ page = await _db().get_briefing_candidates(zones, cursor, CANDIDATE_PAGE_SIZE)
+ if not page:
+ return
+ for user in page:
+ yield user
+ if len(page) < CANDIDATE_PAGE_SIZE:
+ return
+ cursor = page[-1].id
+
+
+def _briefing_hour_timezones(now: datetime) -> list[str]:
+ """Every timezone whose local clock currently reads the briefing hour.
+
+ Users who never set one are treated as UTC, matching `resolve_zone`, so
+ they are included when it is the briefing hour in UTC.
+ """
+ zones = [
+ name
+ for name in available_timezones()
+ if now.astimezone(resolve_zone(name)).hour == BRIEFING_HOUR
+ ]
+ if now.astimezone(timezone.utc).hour == BRIEFING_HOUR:
+ zones.append("not-set")
+ return zones
diff --git a/autogpt_platform/backend/backend/notifications/briefing_runner_test.py b/autogpt_platform/backend/backend/notifications/briefing_runner_test.py
new file mode 100644
index 0000000000..ba3b15c97f
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/briefing_runner_test.py
@@ -0,0 +1,522 @@
+"""Scheduling and queue hand-off tests for alerts and Briefings."""
+
+from collections.abc import Iterator
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from prisma.enums import BriefingFrequency
+
+from backend.data.alerts import MaturedAlertPage
+from backend.data.notifications import NotificationResult, PassWorkEvent, PassWorkKind
+from backend.notifications import briefing_runner
+from backend.notifications.conftest import make_db_client
+
+NOW = datetime(2026, 8, 3, 7, 30, tzinfo=timezone.utc)
+
+
[email protected](scope="session")
+def server() -> None:
+ return None
+
+
[email protected](scope="session", autouse=True)
+def graph_cleanup() -> Iterator[None]:
+ yield
+
+
+def _candidates(users: list) -> object:
+ """Stand-in for the paged async generator `_briefing_candidates` returns."""
+
+ def _generator(*_args, **_kwargs):
+ async def _iter():
+ for user in users:
+ yield user
+
+ return _iter()
+
+ return _generator
+
+
+def _user(user_id: str = "user-1") -> SimpleNamespace:
+ """Shaped like `BriefingCandidate`, which is what the RPC returns."""
+ return SimpleNamespace(
+ id=user_id,
+ briefing_frequency=BriefingFrequency.DAILY,
+ timezone="UTC",
+ last_briefing_at=None,
+ alertsEnabled=True,
+ )
+
+
+def _result(success: bool) -> NotificationResult:
+ return NotificationResult(success=success)
+
+
+# ── the passes: publish, never assemble ─────────────────────────────────
+
+
+async def test_no_matured_alerts_publishes_nothing():
+ with patch.object(
+ briefing_runner.alerts,
+ "matured_alert_user_ids",
+ AsyncMock(return_value=MaturedAlertPage(user_ids=[], exhausted=True)),
+ ), patch.object(briefing_runner, "queue_pass_work", AsyncMock()) as publish:
+ await briefing_runner.flush_matured_alerts()
+
+ publish.assert_not_awaited()
+
+
+async def test_the_alert_pass_publishes_one_message_per_user():
+ """The tick must stay O(1) in work: it fans out and returns, so a slow
+ user cannot hold the next tick open."""
+ with patch.object(
+ briefing_runner.alerts,
+ "matured_alert_user_ids",
+ AsyncMock(
+ return_value=MaturedAlertPage(user_ids=["user-1", "user-2"], exhausted=True)
+ ),
+ ), patch.object(briefing_runner, "queue_pass_work", AsyncMock()) as publish:
+ await briefing_runner.flush_matured_alerts()
+
+ assert [c.args[1] for c in publish.await_args_list] == ["user-1", "user-2"]
+ for call in publish.await_args_list:
+ event = PassWorkEvent.model_validate_json(call.args[2])
+ assert event.kind is PassWorkKind.ALERT_FLUSH
+
+
+async def test_the_alert_walk_keeps_going_past_a_deduplicated_page():
+ """A full page of rows collapses to a handful of users once duplicates are
+ dropped, and anyone holding two conditions produces exactly that. Treating
+ the short user list as the end of the table would strand every user after
+ the first page."""
+ pages = [
+ MaturedAlertPage(user_ids=["user-1", "user-2"], exhausted=False),
+ MaturedAlertPage(user_ids=["user-3"], exhausted=True),
+ ]
+ with patch.object(
+ briefing_runner.alerts,
+ "matured_alert_user_ids",
+ AsyncMock(side_effect=pages),
+ ), patch.object(briefing_runner, "queue_pass_work", AsyncMock()) as publish:
+ await briefing_runner.flush_matured_alerts()
+
+ assert [c.args[1] for c in publish.await_args_list] == [
+ "user-1",
+ "user-2",
+ "user-3",
+ ]
+
+
+async def test_no_briefing_candidates_publishes_nothing():
+ with patch.object(
+ briefing_runner, "_briefing_candidates", _candidates([])
+ ), patch.object(briefing_runner, "queue_pass_work", AsyncMock()) as publish:
+ await briefing_runner.send_due_briefings()
+
+ publish.assert_not_awaited()
+
+
+async def test_the_briefing_pass_publishes_only_users_that_are_due():
+ users = [_user("user-1"), _user("user-2")]
+ with patch.object(
+ briefing_runner, "_briefing_candidates", _candidates(users)
+ ), patch.object(
+ briefing_runner, "is_briefing_due", side_effect=[True, False]
+ ), patch.object(
+ briefing_runner, "queue_pass_work", AsyncMock()
+ ) as publish:
+ await briefing_runner.send_due_briefings()
+
+ assert [c.args[1] for c in publish.await_args_list] == ["user-1"]
+
+
+async def test_every_message_carries_the_passes_own_clock():
+ """The consumer must not read the clock itself: a message that waits in the
+ queue still belongs to the period it was scheduled for, and the dedupe key
+ is built from that timestamp."""
+ users = [_user("user-1"), _user("user-2")]
+ with patch.object(
+ briefing_runner, "_briefing_candidates", _candidates(users)
+ ), patch.object(
+ briefing_runner, "is_briefing_due", return_value=True
+ ), patch.object(
+ briefing_runner, "queue_pass_work", AsyncMock()
+ ) as publish:
+ await briefing_runner.send_due_briefings()
+
+ stamps = {
+ PassWorkEvent.model_validate_json(c.args[2]).scheduled_for
+ for c in publish.await_args_list
+ }
+ assert len(stamps) == 1
+
+
+# ── the work: claimed exactly once ──────────────────────────────────────
+
+
+async def test_work_is_claimed_before_anything_is_sent():
+ """Queue delivery is at-least-once and there may be several replicas, so
+ an unclaimed redelivery would be a second email."""
+ event = PassWorkEvent(
+ kind=PassWorkKind.ALERT_FLUSH, user_id="user-1", scheduled_for=NOW
+ )
+ with patch.object(
+ briefing_runner, "claim_once", AsyncMock(return_value=False)
+ ) as claim, patch.object(
+ briefing_runner, "_flush_user_alerts", AsyncMock()
+ ) as flush:
+ await briefing_runner.run_pass_work(event)
+
+ claim.assert_awaited_once()
+ flush.assert_not_awaited()
+
+
+async def test_the_claim_key_is_scoped_to_the_period():
+ """A month-long key would suppress the *next* period's legitimate send."""
+ first = PassWorkEvent(
+ kind=PassWorkKind.BRIEFING, user_id="user-1", scheduled_for=NOW
+ )
+ later = PassWorkEvent(
+ kind=PassWorkKind.BRIEFING,
+ user_id="user-1",
+ scheduled_for=NOW + timedelta(days=1),
+ )
+ seen = []
+
+ async def record(key, **_kw):
+ seen.append(key)
+ return True
+
+ with patch.object(
+ briefing_runner, "claim_once", AsyncMock(side_effect=record)
+ ), patch.object(briefing_runner, "_build_and_queue_briefing", AsyncMock()):
+ await briefing_runner.run_pass_work(first)
+ await briefing_runner.run_pass_work(later)
+
+ assert len(set(seen)) == 2, "each period must claim its own key"
+ assert all("user-1" in k for k in seen)
+
+
+async def test_two_publishers_of_one_slot_share_a_claim_key():
+ """The claim exists to stop a second replica sending a second email, so it
+ has to key on the slot rather than the instant the message was published."""
+ seen = []
+
+ async def record(key, **_kw):
+ seen.append(key)
+ return True
+
+ same_slot = [
+ PassWorkEvent(
+ kind=PassWorkKind.BRIEFING,
+ user_id="user-1",
+ scheduled_for=NOW.replace(minute=m, second=s, microsecond=us),
+ )
+ for m, s, us in ((0, 0, 0), (17, 42, 987654))
+ ]
+ with patch.object(
+ briefing_runner, "claim_once", AsyncMock(side_effect=record)
+ ), patch.object(briefing_runner, "_build_and_queue_briefing", AsyncMock()):
+ for event in same_slot:
+ await briefing_runner.run_pass_work(event)
+
+ assert len(set(seen)) == 1, f"one slot must be one key, got {seen}"
+
+
+async def test_welcome_is_claimed_by_checkout_session():
+ """A Stripe redelivery arrives at a new timestamp, so a timestamp key would
+ never suppress it — and every welcome carries an empty user_id, so the key
+ has to come from the session."""
+ seen = []
+
+ async def record(key, **_kw):
+ seen.append(key)
+ return True
+
+ with patch.object(
+ briefing_runner, "claim_once", AsyncMock(side_effect=record)
+ ), patch.object(briefing_runner.lifecycle, "send_welcome_for_session", AsyncMock()):
+ for offset in (0, 90):
+ await briefing_runner.run_pass_work(
+ PassWorkEvent(
+ kind=PassWorkKind.WELCOME,
+ user_id="",
+ scheduled_for=NOW + timedelta(seconds=offset),
+ context={"session_id": "cs_test_123"},
+ )
+ )
+
+ assert len(set(seen)) == 1, f"one session must be one key, got {seen}"
+ assert "cs_test_123" in seen[0]
+
+
+async def test_a_failed_pass_releases_its_claim():
+ """Otherwise the consumer's retry finds the claim it made itself, returns
+ early, and the user's briefing is dropped for the whole period."""
+ event = PassWorkEvent(
+ kind=PassWorkKind.BRIEFING, user_id="user-1", scheduled_for=NOW
+ )
+ with patch.object(
+ briefing_runner, "claim_once", AsyncMock(return_value=True)
+ ), patch.object(
+ briefing_runner, "release_claim", AsyncMock()
+ ) as release, patch.object(
+ briefing_runner,
+ "_build_and_queue_briefing",
+ AsyncMock(side_effect=RuntimeError("postmark exploded")),
+ ):
+ with pytest.raises(RuntimeError):
+ await briefing_runner.run_pass_work(event)
+
+ release.assert_awaited_once()
+
+
+async def test_each_kind_routes_to_its_own_work():
+ with patch.object(
+ briefing_runner, "claim_once", AsyncMock(return_value=True)
+ ), patch.object(
+ briefing_runner, "_flush_user_alerts", AsyncMock()
+ ) as flush, patch.object(
+ briefing_runner, "_build_and_queue_briefing", AsyncMock()
+ ) as build:
+ await briefing_runner.run_pass_work(
+ PassWorkEvent(kind=PassWorkKind.ALERT_FLUSH, user_id="u", scheduled_for=NOW)
+ )
+ await briefing_runner.run_pass_work(
+ PassWorkEvent(kind=PassWorkKind.BRIEFING, user_id="u", scheduled_for=NOW)
+ )
+
+ flush.assert_awaited_once()
+ build.assert_awaited_once()
+
+
[email protected]("queued", [True, False])
+async def test_alerts_are_marked_sent_only_after_queue_success(queued: bool):
+ user = _user()
+ built = SimpleNamespace(data=object(), condition_ids=["condition-1"])
+ event = object()
+ client = make_db_client(
+ get_user_notification_preference=AsyncMock(
+ return_value=SimpleNamespace(alerts_enabled=user.alertsEnabled)
+ )
+ )
+
+ with patch.object(briefing_runner, "_db", return_value=client), patch.object(
+ briefing_runner.alerts,
+ "build_alert_email",
+ AsyncMock(return_value=built),
+ ), patch.object(
+ briefing_runner.alerts, "alert_event", return_value=event
+ ), patch.object(
+ briefing_runner,
+ "queue_notification_async",
+ AsyncMock(return_value=_result(queued)),
+ ), patch.object(
+ briefing_runner.alerts, "mark_alert_sent", AsyncMock()
+ ) as mark_sent:
+ if queued:
+ await briefing_runner._flush_user_alerts(user.id)
+ else:
+ # A failed publish must reach the consumer so its retry can run;
+ # swallowing it would drop the alert silently.
+ with pytest.raises(RuntimeError):
+ await briefing_runner._flush_user_alerts(user.id)
+
+ if queued:
+ mark_sent.assert_awaited_once_with(["condition-1"])
+ else:
+ mark_sent.assert_not_awaited()
+
+
+async def test_an_empty_alert_build_queues_nothing():
+ """Everything was deferred or resolved, so there is nothing to say."""
+ user = _user()
+ build_alert = AsyncMock(return_value=None)
+ queue = AsyncMock()
+ client = make_db_client(
+ get_user_notification_preference=AsyncMock(
+ return_value=SimpleNamespace(alerts_enabled=True)
+ )
+ )
+
+ with patch.object(briefing_runner, "_db", return_value=client), patch.object(
+ briefing_runner.alerts, "build_alert_email", build_alert
+ ), patch.object(briefing_runner, "queue_notification_async", queue):
+ await briefing_runner._flush_user_alerts(user.id)
+
+ build_alert.assert_awaited_once_with(user.id, True)
+ queue.assert_not_awaited()
+
+
+async def test_a_database_failure_propagates_so_the_consumer_retries():
+ """`get_user_notification_preference` raises for an unknown user rather
+ than returning None. Swallowing that would drop the alert silently."""
+ client = make_db_client(
+ get_user_notification_preference=AsyncMock(side_effect=RuntimeError("db down"))
+ )
+ with patch.object(briefing_runner, "_db", return_value=client):
+ with pytest.raises(RuntimeError):
+ await briefing_runner._flush_user_alerts("user-1")
+
+
+async def test_empty_briefing_is_not_queued():
+ user = _user()
+ queue = AsyncMock()
+ client = make_db_client(get_briefing_candidate=AsyncMock(return_value=user))
+
+ with patch.object(briefing_runner, "_db", return_value=client), patch.object(
+ briefing_runner.briefing,
+ "build_briefing",
+ AsyncMock(return_value=None),
+ ), patch.object(briefing_runner, "queue_notification_async", queue):
+ await briefing_runner._build_and_queue_briefing(user.id, NOW)
+
+ queue.assert_not_awaited()
+
+
+async def test_failed_briefing_queue_does_not_mark_or_advance():
+ user = _user()
+ built = SimpleNamespace(data=object(), attention_condition_ids=["condition-1"])
+ event = object()
+ client = make_db_client(get_briefing_candidate=AsyncMock(return_value=user))
+
+ with patch.object(
+ briefing_runner.briefing,
+ "build_briefing",
+ AsyncMock(return_value=built),
+ ), patch.object(
+ briefing_runner.briefing, "briefing_event", return_value=event
+ ), patch.object(
+ briefing_runner,
+ "queue_notification_async",
+ AsyncMock(return_value=_result(False)),
+ ), patch.object(
+ briefing_runner.briefing, "mark_attention_reported", AsyncMock()
+ ) as mark_reported, patch.object(
+ briefing_runner, "_db", return_value=client
+ ):
+ # A failed publish raises so the consumer retries rather than
+ # advancing the cadence clock on an email that never went out.
+ with pytest.raises(RuntimeError):
+ await briefing_runner._build_and_queue_briefing(user.id, NOW)
+
+ mark_reported.assert_not_awaited()
+ client.set_last_briefing_at.assert_not_awaited()
+
+
+async def test_queued_briefing_marks_conditions_and_advances_last_sent():
+ user = _user()
+ built = SimpleNamespace(
+ data=object(), attention_condition_ids=["condition-1", "condition-2"]
+ )
+ event = object()
+ client = make_db_client(get_briefing_candidate=AsyncMock(return_value=user))
+
+ with patch.object(
+ briefing_runner.briefing,
+ "build_briefing",
+ AsyncMock(return_value=built),
+ ), patch.object(
+ briefing_runner.briefing, "briefing_event", return_value=event
+ ) as briefing_event, patch.object(
+ briefing_runner,
+ "queue_notification_async",
+ AsyncMock(return_value=_result(True)),
+ ) as queue, patch.object(
+ briefing_runner.briefing, "mark_attention_reported", AsyncMock()
+ ) as mark_reported, patch.object(
+ briefing_runner, "_db", return_value=client
+ ):
+ await briefing_runner._build_and_queue_briefing(user.id, NOW)
+
+ briefing_event.assert_called_once_with(user.id, built.data)
+ queue.assert_awaited_once_with(event)
+ mark_reported.assert_awaited_once_with(["condition-1", "condition-2"])
+ client.set_last_briefing_at.assert_awaited_once_with(user.id, NOW)
+
+
+async def test_candidate_query_uses_timezones_in_their_local_briefing_hour():
+ user = _user()
+ client = make_db_client(get_briefing_candidates=AsyncMock(return_value=[user]))
+ zones = ["UTC", "not-set"]
+
+ with patch.object(briefing_runner, "_db", return_value=client):
+ candidates = [u async for u in briefing_runner._briefing_candidates(zones)]
+
+ assert candidates == [user]
+ # The timezone filter lives in the DatabaseManager, not here; this asserts
+ # the runner hands it the zones and pages from the start.
+ client.get_briefing_candidates.assert_awaited_once_with(
+ zones, None, briefing_runner.CANDIDATE_PAGE_SIZE
+ )
+
+
+async def test_every_candidate_is_considered_not_just_the_first_page():
+ """A capped read strands everyone past the cap behind the same low-id page.
+
+ The ordering is stable and the query does not exclude users already
+ briefed, so a bounded single read returns the *same* users every hour and
+ the tail of the table never receives a briefing at all.
+ """
+ page_size = briefing_runner.CANDIDATE_PAGE_SIZE
+ all_users = [_user(f"user-{i:05d}") for i in range(page_size * 2 + 7)]
+
+ async def paged(_zones, after, limit):
+ remaining = [u for u in all_users if after is None or u.id > after]
+ return remaining[:limit]
+
+ client = make_db_client(get_briefing_candidates=AsyncMock(side_effect=paged))
+ with patch.object(briefing_runner, "_db", return_value=client):
+ seen = [u async for u in briefing_runner._briefing_candidates(["UTC"])]
+
+ assert len(seen) == len(all_users)
+ assert [u.id for u in seen] == [u.id for u in all_users]
+
+
+async def test_candidate_walk_stops_once_a_short_page_comes_back():
+ """The walk must terminate rather than spin on an exhausted table."""
+ client = make_db_client(get_briefing_candidates=AsyncMock(return_value=[_user()]))
+ with patch.object(briefing_runner, "_db", return_value=client):
+ seen = [u async for u in briefing_runner._briefing_candidates(["UTC"])]
+
+ assert len(seen) == 1
+ assert client.get_briefing_candidates.await_count == 1
+
+
+def test_timezone_selection_follows_each_users_local_clock():
+ utc_morning = datetime(2026, 8, 3, 7, 30, tzinfo=timezone.utc)
+ new_york_morning = datetime(2026, 8, 3, 11, 30, tzinfo=timezone.utc)
+ zones = {"UTC", "America/New_York", "Asia/Tokyo"}
+
+ with patch.object(briefing_runner, "available_timezones", return_value=zones):
+ assert set(briefing_runner._briefing_hour_timezones(utc_morning)) == {
+ "UTC",
+ "not-set",
+ }
+ assert briefing_runner._briefing_hour_timezones(new_york_morning) == [
+ "America/New_York"
+ ]
diff --git a/autogpt_platform/backend/backend/notifications/briefing_test.py b/autogpt_platform/backend/backend/notifications/briefing_test.py
new file mode 100644
index 0000000000..24ec2d7c70
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/briefing_test.py
@@ -0,0 +1,227 @@
+"""The Briefing's load-bearing invariants.
+
+Never sent empty, totals equal the ledger's sums, the attention block absorbs
+everything the alert engine deferred, and a whisper of activity shrinks the
+email instead of padding it.
+"""
+
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from prisma.enums import AlertCause, AlertConditionStatus, BriefingFrequency
+
+from backend.data.alerts import AlertConditionDTO
+from backend.data.briefing_data import AgentPeriodStats, ScoredRun
+from backend.notifications.alert_causes import AuthExpiredCause
+from backend.notifications.briefing import (
+ MAX_ATTENTION_ITEMS,
+ MAX_HIGHLIGHTS,
+ build_briefing,
+)
+from backend.notifications.conftest import make_db_client
+
+USER = "user-1"
+NOW = datetime(2026, 8, 3, 11, 30, tzinfo=timezone.utc)
+
+AUTH = AuthExpiredCause(
+ cta_path="/integrations/gmail/reconnect",
+ agent="Invoice Chaser",
+ provider="Gmail",
+ expired_at_label="9:14",
+ runs_skipped=5,
+ next_try_label="16:00",
+)
+
+
+def _agents(*specs: tuple[str, int, int, float]) -> list[AgentPeriodStats]:
+ return [
+ AgentPeriodStats(
+ graph_id=f"g-{name}",
+ agent=name,
+ runs=runs,
+ failed=failed,
+ credits=credits,
+ top_score=1.0,
+ )
+ for name, runs, failed, credits in specs
+ ]
+
+
+def _deferred_condition(condition_id: str = "c1") -> AlertConditionDTO:
+ return AlertConditionDTO(
+ id=condition_id,
+ user_id=USER,
+ cause=AlertCause.AUTH_EXPIRED,
+ cause_key="auth_expired:gmail:g1",
+ data=AUTH.model_dump(mode="json"),
+ status=AlertConditionStatus.DEFERRED,
+ created_at=NOW,
+ sent_at=None,
+ briefed_at=None,
+ )
+
+
+def _db_client(agents, conditions=None, runs=None, balance=100.0, idle=0):
+ """Patch the Briefing's RPC client.
+
+ `idle` is the user's total active-agent count; the Briefing subtracts the
+ ones that ran.
+ """
+ client = make_db_client(
+ get_agent_period_stats=AsyncMock(return_value=agents),
+ get_top_scored_runs=AsyncMock(return_value=runs or []),
+ count_active_agents=AsyncMock(return_value=idle),
+ get_briefing_credit_balance=AsyncMock(return_value=balance),
+ get_briefing_alert_conditions=AsyncMock(return_value=conditions or []),
+ )
+ return patch("backend.notifications.briefing._db", return_value=client)
+
+
+async def _built(agents, **kwargs):
+ with _db_client(agents, **kwargs):
+ return await build_briefing(USER, BriefingFrequency.WEEKLY, "UTC", NOW)
+
+
+async def _build(agents, **kwargs):
+ built = await _built(agents, **kwargs)
+ return built.data if built else None
+
+
+async def test_a_period_with_no_runs_sends_nothing_at_all():
+ assert await _build([]) is None
+
+
+async def test_totals_equal_the_ledgers_sums():
+ data = await _build(_agents(("A", 10, 1, 2.0), ("B", 5, 0, 1.0)))
+ assert data is not None
+ assert data.totals.runs == sum(row.runs for row in data.ledger)
+ assert data.totals.agents_active == len(data.ledger)
+ assert data.totals.failed == 1
+
+
+async def test_a_whisper_of_activity_shrinks_instead_of_padding():
+ data = await _build(_agents(("Lead Scout", 2, 0, 0.1)))
+ assert data is not None
+ assert data.mode == "quiet"
+ assert data.only_agent == "Lead Scout"
+ assert data.quiet_summary is not None
+
+
+async def test_a_failure_keeps_the_standard_form():
+ data = await _build(_agents(("Lead Scout", 2, 1, 0.1)))
+ assert data is not None
+ assert data.mode == "standard"
+
+
+async def test_attention_absorbs_what_the_alert_engine_deferred():
+ data = await _build(
+ _agents(("Invoice Chaser", 6, 0, 0.25)),
+ conditions=[_deferred_condition()],
+ )
+ assert data is not None
+ assert [item.title for item in data.attention] == ["Invoice Chaser is stuck"]
+ assert data.attention[0].cta_label == "Reconnect Gmail"
+ # A blocked agent with no failures reads amber, not red.
+ row = next(r for r in data.ledger if r.agent == "Invoice Chaser")
+ assert row.issues_kind == "warn"
+ assert row.issues_label == "5 runs skipped"
+
+
+async def test_a_failing_agent_reads_red():
+ data = await _build(_agents(("Price Watch", 42, 3, 2.6)))
+ assert data is not None
+ row = data.ledger[0]
+ assert row.issues_kind == "fail"
+ assert row.issues_label == "3 failed"
+
+
+async def test_highlights_are_capped_and_carry_a_gist_and_a_link():
+ scored = [
+ ScoredRun(
+ execution_id=f"x{i}",
+ graph_id="g-A",
+ agent="A",
+ interestingness=1.0,
+ activity_status=f"Did thing {i}.",
+ )
+ for i in range(MAX_HIGHLIGHTS)
+ ]
+ data = await _build(_agents(("A", 30, 0, 1.0)), runs=scored)
+ assert data is not None
+ assert len(data.highlights) == MAX_HIGHLIGHTS
+ assert all(h.gist and h.url for h in data.highlights)
+ # The subject carries the payload, taken from the top highlight.
+ assert data.subject_note is not None and data.subject_note.startswith("A ")
+
+
+async def test_the_briefing_reports_exactly_the_conditions_it_carried():
+ built = await _built(
+ _agents(("Invoice Chaser", 6, 0, 0.25)),
+ conditions=[_deferred_condition()],
+ )
+ assert built is not None
+ # Only these are marked briefed, so a condition raised while the email was
+ # being built still gets its turn next period.
+ assert built.attention_condition_ids == ["c1"]
+
+
+async def test_conditions_past_the_display_cap_keep_their_turn():
+ """Only what the attention block actually showed is marked briefed.
+
+ Marking the overflow too would retire conditions the reader never saw:
+ they are filtered out of the next period's candidates, so they would never
+ appear in any briefing.
+ """
+ conditions = [_deferred_condition(f"c{i}") for i in range(1, 9)]
+ built = await _built(_agents(("Invoice Chaser", 6, 0, 0.25)), conditions=conditions)
+ assert built is not None
+ assert len(built.data.attention) == MAX_ATTENTION_ITEMS
+ assert built.attention_condition_ids == [f"c{i}" for i in range(1, 7)]
+
+
+async def test_a_run_with_nothing_to_say_still_gets_an_honest_gist():
+ scored = [
+ ScoredRun(
+ execution_id="x1",
+ graph_id="g-A",
+ agent="A",
+ interestingness=1.0,
+ activity_status=None,
+ )
+ ]
+ data = await _build(_agents(("A", 7, 0, 1.0)), runs=scored)
+ assert data is not None
+ assert data.highlights[0].gist == "completed 7 runs."
+
+
+async def test_a_quiet_period_still_reports_what_is_waiting():
+ """A deferred condition is reported by the Briefing and nowhere else.
+
+ Returning early on a zero-run period read the conditions *after* the
+ return, so anything the Alert engine had capped or deduped was stranded:
+ never emailed, and never marked briefed, so it could sit unreported
+ indefinitely. Nothing actionable is silently dropped is the whole promise.
+ """
+ built = await _built([], conditions=[_deferred_condition()])
+
+ assert built is not None
+ assert [item.agent for item in built.data.attention] == ["Invoice Chaser"]
+ assert built.attention_condition_ids == ["c1"]
+ assert built.data.totals.runs == 0
+
+
+async def test_a_period_with_neither_runs_nor_conditions_sends_nothing():
+ assert await _built([], conditions=[]) is None
diff --git a/autogpt_platform/backend/backend/notifications/conftest.py b/autogpt_platform/backend/backend/notifications/conftest.py
new file mode 100644
index 0000000000..0e19555d56
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/conftest.py
@@ -0,0 +1,94 @@
+"""Shared fixtures for the notification service's tests.
+
+The important one is `db_client`. Everything this service reads or writes goes
+through the DatabaseManager RPC, so that client is the boundary these tests
+should mock — and mocking it is what keeps them honest.
+
+The suite previously mocked `User.prisma()` directly. That looked equivalent
+and was not: it meant the tests supplied a working database to a process that
+has no connection to one, so a hundred-plus green tests sat on top of a service
+whose scheduled passes failed on every single tick. Mocking here instead means
+a module that reaches past the RPC fails its test rather than passing it.
+"""
+
+from datetime import datetime, timezone
+from types import SimpleNamespace
+from typing import Iterator
+from unittest.mock import AsyncMock
+
+import pytest
+from prisma.enums import BriefingFrequency
+
+from backend.data.alerts import MaturedAlertPage
+from backend.data.notifications import NotificationPreference
+
+NOW = datetime(2026, 8, 3, 7, 30, tzinfo=timezone.utc)
+
+
[email protected](scope="session")
+def server() -> None:
+ """The notification suite is pure logic; it needs no live stack."""
+ return None
+
+
[email protected](scope="session", autouse=True)
+def graph_cleanup() -> Iterator[None]:
+ yield
+
+
+def make_db_client(**overrides) -> SimpleNamespace:
+ """A stand-in `DatabaseManagerAsyncClient`.
+
+ Defaults are the empty/no-op answer for every method the notification
+ service calls, so a test overrides only what it is actually about. Passing
+ an unknown name is deliberately allowed — a new RPC method should not
+ require touching every test that predates it.
+ """
+ client = SimpleNamespace(
+ # Preferences and users
+ # The whole model, not just the fields one test happened to read:
+ # the consumer gates on `daily_limit` and `wants_notification` reads
+ # the frequency and the verdict switch, so a partial stub turns a real
+ # regression into an AttributeError somewhere unrelated.
+ get_user_notification_preference=AsyncMock(
+ return_value=NotificationPreference(
+ user_id="user-1",
+ briefing_frequency=BriefingFrequency.WEEKLY,
+ alerts_enabled=True,
+ store_verdicts_enabled=True,
+ daily_limit=3,
+ )
+ ),
+ get_user_by_id=AsyncMock(return_value=None),
+ get_user_email_verification=AsyncMock(return_value=True),
+ # Alert conditions
+ get_users_with_matured_alerts=AsyncMock(
+ return_value=MaturedAlertPage(user_ids=[], exhausted=True)
+ ),
+ get_pending_alert_conditions=AsyncMock(return_value=[]),
+ count_alerts_sent_since=AsyncMock(return_value=0),
+ mark_alert_conditions_sent=AsyncMock(),
+ mark_alert_conditions_deferred=AsyncMock(),
+ get_briefing_alert_conditions=AsyncMock(return_value=[]),
+ mark_alert_conditions_briefed=AsyncMock(),
+ raise_alert_condition=AsyncMock(),
+ resolve_alert_condition=AsyncMock(return_value=True),
+ # Briefing assembly
+ get_agent_period_stats=AsyncMock(return_value=[]),
+ get_top_scored_runs=AsyncMock(return_value=[]),
+ count_active_agents=AsyncMock(return_value=0),
+ get_briefing_credit_balance=AsyncMock(return_value=0.0),
+ get_briefing_candidates=AsyncMock(return_value=[]),
+ get_briefing_candidate=AsyncMock(return_value=None),
+ set_last_briefing_at=AsyncMock(),
+ get_graph_execution=AsyncMock(return_value=None),
+ )
+ for name, value in overrides.items():
+ setattr(client, name, value)
+ return client
+
+
+def db_client() -> SimpleNamespace:
+ return make_db_client()
diff --git a/autogpt_platform/backend/backend/notifications/daily_cap_test.py b/autogpt_platform/backend/backend/notifications/daily_cap_test.py
new file mode 100644
index 0000000000..823a573209
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/daily_cap_test.py
@@ -0,0 +1,119 @@
+"""The volume knob's daily ceiling.
+
+`daily_limit` was persisted and returned by the API but nothing consumed it,
+so the number the settings page showed had no effect — and the `0` that a
+one-click unsubscribe writes did nothing at all.
+"""
+
+from datetime import date
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from backend.notifications.dedupe import claim_daily_send
+
+DAY = date(2026, 8, 3)
+
+
+def _redis(counts=None):
+ """A Redis stand-in whose INCR actually counts."""
+ state = {"n": 0}
+ counts = counts if counts is not None else state
+
+ async def incr(_key):
+ counts["n"] += 1
+ return counts["n"]
+
+ return SimpleNamespace(incr=incr, expire=AsyncMock())
+
+
+async def test_sends_are_allowed_up_to_the_limit_then_refused():
+ client = _redis()
+ with patch(
+ "backend.notifications.dedupe.get_redis_async", AsyncMock(return_value=client)
+ ):
+ allowed = [await claim_daily_send("u1", 3, DAY) for _ in range(5)]
+
+ assert allowed == [True, True, True, False, False]
+
+
+async def test_a_limit_of_zero_sends_nothing():
+ """This is what one-click unsubscribe writes, so it has to mean it."""
+ client = _redis()
+ with patch(
+ "backend.notifications.dedupe.get_redis_async", AsyncMock(return_value=client)
+ ):
+ assert await claim_daily_send("u1", 0, DAY) is False
+
+
+async def test_each_day_gets_its_own_allowance():
+ keys = []
+
+ async def incr(key):
+ keys.append(key)
+ return 1
+
+ client = SimpleNamespace(incr=incr, expire=AsyncMock())
+ with patch(
+ "backend.notifications.dedupe.get_redis_async", AsyncMock(return_value=client)
+ ):
+ await claim_daily_send("u1", 3, DAY)
+ await claim_daily_send("u1", 3, date(2026, 8, 4))
+
+ assert len(set(keys)) == 2
+
+
+async def test_the_counter_expires_so_it_never_needs_resetting():
+ client = _redis()
+ with patch(
+ "backend.notifications.dedupe.get_redis_async", AsyncMock(return_value=client)
+ ):
+ await claim_daily_send("u1", 3, DAY)
+
+ client.expire.assert_awaited_once()
+
+
+async def test_a_redis_outage_lets_the_email_through():
+ """Fails open, like `claim_once`: a rare extra email beats silently
+ swallowing someone's briefing because a counter was unreachable."""
+ with patch(
+ "backend.notifications.dedupe.get_redis_async",
+ AsyncMock(side_effect=RuntimeError("redis down")),
+ ):
+ assert await claim_daily_send("u1", 3, DAY) is True
+
+
+async def test_service_mail_is_never_capped():
+ """Billing messages ignore the volume knob for the same reason they ignore
+ every other preference: a payment failure has to arrive."""
+ from prisma.enums import NotificationType
+
+ from backend.notifications.preferences import SERVICE_MESSAGES
+
+ assert NotificationType.PAYMENT_FAILED in SERVICE_MESSAGES
+ assert NotificationType.SUBSCRIPTION_ENDED in SERVICE_MESSAGES
+ # ...and the product families are not exempt.
+ assert NotificationType.BRIEFING not in SERVICE_MESSAGES
+ assert NotificationType.ALERT not in SERVICE_MESSAGES
+ assert NotificationType.VERDICT not in SERVICE_MESSAGES
+
+
+def test_zero_survives_the_read_back_from_the_database():
+ """`maxEmailsPerDay or 3` turned the unsubscribe's 0 into 3.
+
+ The column is non-nullable with its own default, so the coalesce could only
+ ever catch the one value that carries meaning.
+ """
+ import inspect
+
+ from backend.data import user as user_db
+
+ source = inspect.getsource(user_db)
+ assert "maxEmailsPerDay or 3" not in source
diff --git a/autogpt_platform/backend/backend/notifications/dedupe.py b/autogpt_platform/backend/backend/notifications/dedupe.py
new file mode 100644
index 0000000000..8da997ae8e
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/dedupe.py
@@ -0,0 +1,104 @@
+"""One-shot claims for anything that must email a person exactly once.
+
+Two independent sources of duplicates:
+
+* **Stripe replays webhooks.** Several billing events legitimately arrive more
+ than once (a retried delivery, an out-of-order subscription update), so each
+ billing email claims a key derived from the resource it is about.
+* **Scheduled passes fan out over a queue.** Delivery is at-least-once and the
+ service can run more than one replica, so the per-user work published by a
+ pass claims the user plus the period it covers.
+
+Both need the same primitive: the first caller wins, everyone else no-ops.
+
+Falls open on a Redis failure. A rare duplicate is a better outcome than
+dropping a payment-failed notice — or a whole briefing — entirely.
+"""
+
+import logging
+from datetime import date
+
+from backend.data.redis_client import get_redis_async
+
+logger = logging.getLogger(__name__)
+
+# Comfortably longer than Stripe's retry window, and long enough that an
+# out-of-order redelivery days later still finds the claim.
+CLAIM_TTL_SECONDS = 60 * 60 * 24 * 30
+# A scheduled pass only has to dedupe within the period it covers; holding the
+# key for a month would suppress the *next* period's legitimate send.
+PASS_CLAIM_TTL_SECONDS = 60 * 60 * 36
+_PREFIX = "notification_claim"
+
+
+async def claim_once(key: str, ttl_seconds: int = CLAIM_TTL_SECONDS) -> bool:
+ """Returns True for the first caller with this key, False afterwards."""
+ try:
+ redis_client = await get_redis_async()
+ claimed = await redis_client.set(
+ f"{_PREFIX}:{key}", "1", nx=True, ex=ttl_seconds
+ )
+ return bool(claimed)
+ except Exception:
+ logger.warning(
+ "Dedupe claim failed for %s; proceeding anyway", key, exc_info=True
+ )
+ return True
+
+
+async def release_claim(key: str) -> None:
+ """Give a claim back after the work it guarded failed.
+
+ A claim is taken *before* the send so a replay cannot double-send. That
+ ordering has a cost: if the send then fails, the key is spent and every
+ retry is deduped away, so the email is lost permanently rather than
+ retried. Releasing on failure keeps the replay protection while letting a
+ genuine retry through.
+ """
+ try:
+ redis_client = await get_redis_async()
+ await redis_client.delete(f"{_PREFIX}:{key}")
+ except Exception:
+ logger.warning(
+ "Could not release the dedupe claim for %s; a retry of this "
+ "message will be suppressed until the key expires",
+ key,
+ exc_info=True,
+ )
+
+
+# Counters outlive the day they cover so a late send is still counted against
+# the right day, and are dropped well before they could be reused.
+_DAILY_COUNTER_TTL_SECONDS = 60 * 60 * 48
+
+
+async def claim_daily_send(user_id: str, limit: int, on_day: date) -> bool:
+ """Take one of the user's sends for `on_day`, or refuse.
+
+ The volume knob's `daily_limit` is the user's own ceiling across every
+ product notification. It is counted here rather than in the database
+ because it is ephemeral per-day state: a counter with a TTL needs no table,
+ no reset job, and no migration to change.
+
+ `limit <= 0` refuses everything, which is what a one-click unsubscribe
+ means when it sets the limit to zero.
+
+ Fails *open* on a Redis error, matching `claim_once`: a rare extra email is
+ a better outcome than silently swallowing someone's briefing.
+ """
+ if limit <= 0:
+ return False
+ key = f"{_PREFIX}:daily_send:{user_id}:{on_day.isoformat()}"
+ try:
+ redis_client = await get_redis_async()
+ sent = await redis_client.incr(key)
+ if sent == 1:
+ await redis_client.expire(key, _DAILY_COUNTER_TTL_SECONDS)
+ return sent <= limit
+ except Exception:
+ logger.warning(
+ "Daily-send counter unavailable for %s; allowing the send",
+ user_id,
+ exc_info=True,
+ )
+ return True
diff --git a/autogpt_platform/backend/backend/notifications/email.py b/autogpt_platform/backend/backend/notifications/email.py
index 17858fd034..ecf0637e74 100644
--- a/autogpt_platform/backend/backend/notifications/email.py
+++ b/autogpt_platform/backend/backend/notifications/email.py
@@ -1,137 +1,94 @@
+"""Postmark delivery for the notification families.
+
+Everything goes out on a transactional stream, separate from marketing mail
+(which the platform does not send at all — the onboarding tour and the monthly
+changelog are MailerLite's). Every message carries a plain-text MIME part built
+from the same data model, and one-click List-Unsubscribe headers on every
+family except Ops, which is internal mail and deliberately not opt-in.
+"""
+
+import asyncio
import logging
-import pathlib
from postmarker.core import PostmarkClient
from postmarker.models.emails import EmailManager
from prisma.enums import NotificationType
-from pydantic import BaseModel
from backend.data.notifications import (
- NotificationDataType_co,
- NotificationEventModel,
- NotificationTypeOverride,
+ BaseNotificationData,
+ DeliveryStream,
+ get_delivery_stream,
+ supports_list_unsubscribe,
)
+from backend.notifications.renderer import EmailUrls, RenderedEmail, build_urls, render
from backend.util.settings import Settings
-from backend.util.text import TextFormatter
logger = logging.getLogger(__name__)
settings = Settings()
+# Bounds how long one send can hold a thread-pool worker.
+POSTMARK_TIMEOUT_SECONDS = 30
-# The following is a workaround to get the type checker to recognize the EmailManager type
-# This is a temporary solution and should be removed once the Postmark library is updated
-# to support type annotations.
-class TypedPostmarkClient(PostmarkClient):
- emails: EmailManager
+class TypedPostmarkClient(PostmarkClient):
+ """Workaround so the type checker sees `emails`; the Postmark library ships
+ no annotations."""
-class Template(BaseModel):
- subject_template: str
- body_template: str
- base_template: str
+ emails: EmailManager
class EmailSender:
def __init__(self):
if settings.secrets.postmark_server_api_token:
self.postmark = TypedPostmarkClient(
- server_token=settings.secrets.postmark_server_api_token
+ server_token=settings.secrets.postmark_server_api_token,
+ # postmarker defaults to no timeout, which hands `requests` an
+ # unbounded wait. Every send occupies a thread-pool worker, so a
+ # hung Postmark call would otherwise exhaust the pool.
+ timeout=POSTMARK_TIMEOUT_SECONDS,
)
else:
logger.warning(
"Postmark server API token not found, email sending disabled"
)
self.postmark = None
- self.formatter = TextFormatter()
-
- MAX_EMAIL_CHARS = 5_000_000 # ~5MB buffer
- async def send_templated(
+ async def send_notification(
self,
- notification: NotificationType,
+ notification_type: NotificationType,
user_email: str,
- data: (
- NotificationEventModel[NotificationDataType_co]
- | list[NotificationEventModel[NotificationDataType_co]]
- ),
- user_unsub_link: str | None = None,
- ):
- """Send an email to a user using a template pulled from the notification type, or fallback"""
- if not self.postmark:
- logger.warning("Postmark client not initialized, email not sent")
- return
-
- template = self._get_template(notification)
-
- base_url = (
- settings.config.frontend_base_url or settings.config.platform_base_url
+ data: BaseNotificationData,
+ unsubscribe_link: str,
+ volume_links: dict[str, str] | None = None,
+ ) -> None:
+ """Render and send one notification. Raises on delivery failure so the
+ queue consumer's retry-with-backoff can recover."""
+ urls = build_urls(unsubscribe_link, volume_links)
+ email = render(notification_type, data, user_email, urls)
+ await self._deliver(notification_type, user_email, email, urls)
+
+ async def _deliver(
+ self,
+ notification_type: NotificationType,
+ user_email: str,
+ email: RenderedEmail,
+ urls: EmailUrls,
+ ) -> None:
+ headers = (
+ {
+ "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
+ "List-Unsubscribe": f"<{urls.unsubscribe}>",
+ }
+ if supports_list_unsubscribe(notification_type)
+ else None
)
-
- # Normalize data
- template_data = {"notifications": data} if isinstance(data, list) else data
-
- try:
- subject, full_message = await self.formatter.format_email(
- base_template=template.base_template,
- subject_template=template.subject_template,
- content_template=template.body_template,
- data=template_data,
- unsubscribe_link=f"{base_url}/profile/settings",
- )
- except Exception as e:
- logger.error(f"Error formatting full message: {e}")
- raise e
-
- # Check email size & send summary if too large
- email_size = len(full_message)
- if email_size > self.MAX_EMAIL_CHARS:
- logger.warning(
- f"Email size ({email_size} chars) exceeds safe limit. "
- "Sending summary email instead."
- )
-
- # Create lightweight summary
- summary_message = (
- f"⚠️ Your agent '{getattr(data, 'agent_name', 'Unknown')}' "
- f"generated a very large output ({email_size / 1_000_000:.2f} MB).\n\n"
- f"Execution time: {getattr(data, 'execution_time', 'N/A')}\n"
- f"Credits used: {getattr(data, 'credits_used', 'N/A')}\n"
- f"View full results: {base_url}/executions/{getattr(data, 'id', 'N/A')}"
- )
-
- self._send_email(
- user_email=user_email,
- subject=f"{subject} (Output Too Large)",
- body=summary_message,
- user_unsubscribe_link=user_unsub_link,
- )
- return # Skip sending full email
-
- logger.debug(f"Sending email with size: {email_size} characters")
- self._send_email(
+ await self._send(
user_email=user_email,
- subject=subject,
- body=full_message,
- user_unsubscribe_link=user_unsub_link,
- )
-
- def _get_template(self, notification: NotificationType):
- # convert the notification type to a notification type override
- notification_type_override = NotificationTypeOverride(notification)
- # find the template in templates/name.html (the .template returns with the .html)
- template_path = f"templates/{notification_type_override.template}.jinja2"
- logger.debug(
- f"Template full path: {pathlib.Path(__file__).parent / template_path}"
- )
- base_template_path = "templates/base.html.jinja2"
- with open(pathlib.Path(__file__).parent / base_template_path, "r") as file:
- base_template = file.read()
- with open(pathlib.Path(__file__).parent / template_path, "r") as file:
- template = file.read()
- return Template(
- subject_template=notification_type_override.subject,
- body_template=template,
- base_template=base_template,
+ sender=_sender_for(get_delivery_stream(notification_type)),
+ subject=email.subject,
+ html_body=email.html,
+ text_body=email.text,
+ headers=headers,
)
def send_email_or_raise(self, user_email: str, subject: str, body: str) -> None:
@@ -141,30 +98,44 @@ class EmailSender:
surface the failure instead of silently dropping an auth email."""
if not self.postmark:
raise RuntimeError("Postmark is not configured; cannot send email")
- self._send_email(user_email, subject, body)
+ self.postmark.emails.send(
+ From=settings.config.postmark_sender_email,
+ To=user_email,
+ Subject=subject,
+ HtmlBody=body,
+ MessageStream=settings.config.postmark_transactional_stream,
+ )
- def _send_email(
+ async def _send(
self,
user_email: str,
+ sender: str,
subject: str,
- body: str,
- user_unsubscribe_link: str | None = None,
- ):
+ html_body: str,
+ text_body: str,
+ headers: dict[str, str] | None,
+ ) -> None:
if not self.postmark:
- logger.warning("Email tried to send without postmark configured")
+ logger.warning("Email tried to send without Postmark configured")
return
- logger.debug(f"Sending email to {user_email} with subject {subject}")
- self.postmark.emails.send(
- From=settings.config.postmark_sender_email,
+ logger.debug("Sending email to %s with subject %s", user_email, subject)
+ # postmarker's send is a blocking HTTP call; keep it off the event loop
+ # so a slow Postmark response can't stall the notification service.
+ await asyncio.to_thread(
+ self.postmark.emails.send,
+ From=sender,
To=user_email,
Subject=subject,
- HtmlBody=body,
- Headers=(
- {
- "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
- "List-Unsubscribe": f"<{user_unsubscribe_link}>",
- }
- if user_unsubscribe_link
- else None
- ),
+ HtmlBody=html_body,
+ TextBody=text_body,
+ MessageStream=settings.config.postmark_transactional_stream,
+ Headers=headers,
)
+
+
+def _sender_for(stream: DeliveryStream) -> str:
+ return {
+ DeliveryStream.BILLING: settings.config.billing_sender_email,
+ DeliveryStream.PRODUCT: settings.config.product_sender_email,
+ DeliveryStream.OPS: settings.config.ops_sender_email,
+ }[stream]
diff --git a/autogpt_platform/backend/backend/notifications/gist.py b/autogpt_platform/backend/backend/notifications/gist.py
new file mode 100644
index 0000000000..18c3e6de78
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/gist.py
@@ -0,0 +1,128 @@
+"""Turning a run's outputs into one sentence for the Briefing's highlights.
+
+Strict rules, because this is what replaces dumping raw output into the inbox:
+
+* a hard character limit
+* text outputs get one sentence
+* structured outputs get counted and characterised
+* binary and file outputs get named, never embedded
+* on failure, fall back to a truncated first line, then to "Completed N runs."
+
+Never inline a raw output. The inbox gets the gist and the link; the platform
+is where outputs live.
+"""
+
+import re
+from typing import Any
+
+GIST_MAX_CHARS = 150
+
+# Output names that read as files rather than prose, so they are named by kind
+# and count instead of being quoted.
+# Whole words only: "profile" contains "file" and "document" contains "doc",
+# and either would route a text output into the file-describing branch.
+_FILE_HINT = re.compile(r"\b(file|image|video|audio|clip|pdf|doc|csv|sheet)s?\b", re.I)
+_DATA_URI = re.compile(r"^data:([\w.+-]+)/")
+_URL = re.compile(r"^https?://")
+
+
+def build_gist(
+ outputs: dict[str, list[Any]], activity_status: str | None
+) -> str | None:
+ """One sentence describing what a run produced, or None when there is
+ nothing honest to say — the caller then falls back to counts and links."""
+ if activity_status and activity_status.strip():
+ return _one_sentence(activity_status)
+
+ parts = [
+ p for p in (_describe(name, values) for name, values in outputs.items()) if p
+ ]
+ if not parts:
+ return None
+ return _truncate(_join(parts))
+
+
+def fallback_gist(run_count: int) -> str:
+ """The last fallback. Says only what we actually know."""
+ runs = "1 run" if run_count == 1 else f"{run_count} runs"
+ return f"completed {runs}."
+
+
+def _describe(name: str, values: list[Any]) -> str | None:
+ if not values:
+ return None
+ if _looks_like_files(name, values):
+ return _describe_files(name, values)
+ if len(values) == 1 and isinstance(values[0], (dict, list)):
+ return _describe_structured(name, values[0])
+ if len(values) > 1:
+ return f"produced {len(values)} {_plural(name)}"
+ return _describe_text(values[0])
+
+
+def _describe_files(name: str, values: list[Any]) -> str:
+ """Named, never embedded."""
+ count = len(values)
+ kind = _plural(name) if count != 1 else name
+ return f"produced {count} {kind}"
+
+
+def _describe_structured(name: str, value: dict | list) -> str:
+ """Counted and characterised, not pasted."""
+ if isinstance(value, list):
+ return f"produced {len(value)} {_plural(name)}"
+ keys = len(value)
+ field_word = "field" if keys == 1 else "fields"
+ return f"produced a {name} with {keys} {field_word}"
+
+
+def _describe_text(value: Any) -> str | None:
+ text = str(value).strip()
+ if not text:
+ return None
+ words = len(text.split())
+ if words > 60:
+ return f"wrote a {words:,}-word result"
+ return _one_sentence(text)
+
+
+def _one_sentence(text: str) -> str:
+ """First sentence only, collapsed onto one line and length-capped."""
+ flat = " ".join(text.split())
+ match = re.search(r"(?<=[.!?])\s", flat)
+ sentence = flat[: match.start()] if match else flat
+ return _truncate(sentence)
+
+
+def _join(parts: list[str]) -> str:
+ if len(parts) == 1:
+ return _finish(parts[0])
+ return _finish(", ".join(parts[:-1]) + f" and {parts[-1]}")
+
+
+def _finish(text: str) -> str:
+ return text if text.endswith((".", "!", "?")) else text + "."
+
+
+def _truncate(text: str) -> str:
+ if len(text) <= GIST_MAX_CHARS:
+ return _finish(text)
+ cut = text[: GIST_MAX_CHARS - 1]
+ if " " in cut:
+ cut = cut[: cut.rfind(" ")]
+ return cut.rstrip(" ,;:-") + "…"
+
+
+def _plural(name: str) -> str:
+ word = name.replace("_", " ").strip() or "result"
+ if word.endswith("s"):
+ return word
+ return word + "s"
+
+
+def _looks_like_files(name: str, values: list[Any]) -> bool:
+ if _FILE_HINT.search(name):
+ return True
+ return any(
+ isinstance(v, str) and (_DATA_URI.match(v) or _URL.match(v)) for v in values
+ )
diff --git a/autogpt_platform/backend/backend/notifications/gist_test.py b/autogpt_platform/backend/backend/notifications/gist_test.py
new file mode 100644
index 0000000000..9da29755bd
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/gist_test.py
@@ -0,0 +1,53 @@
+"""The gist rules are what stop raw output landing in an inbox."""
+
+from backend.notifications.gist import GIST_MAX_CHARS, build_gist, fallback_gist
+
+
+def test_activity_status_wins_and_is_one_sentence():
+ gist = build_gist(
+ {},
+ "Matched 41 new leads to the saved search. It also refreshed the cache.",
+ )
+ assert gist == "Matched 41 new leads to the saved search."
+
+
+def test_structured_output_is_counted_not_pasted():
+ leads = [{"name": f"lead {i}"} for i in range(41)]
+ gist = build_gist({"leads": leads}, None)
+ assert gist is not None
+ assert "41 leads" in gist
+ assert "lead 0" not in gist
+
+
+def test_file_outputs_are_named_never_embedded():
+ gist = build_gist(
+ {"clips": ["data:video/mp4;base64,AAAA", "data:video/mp4;base64,BBBB"]},
+ None,
+ )
+ assert gist == "produced 2 clips."
+ assert "base64" not in gist
+
+
+def test_long_text_is_described_not_reproduced():
+ draft = " ".join(["word"] * 1200)
+ gist = build_gist({"draft": [draft]}, None)
+ assert gist is not None
+ assert gist == "wrote a 1,200-word result."
+ assert len(gist) <= GIST_MAX_CHARS + 1
+
+
+def test_gist_is_length_capped():
+ gist = build_gist({}, "x" * 500)
+ assert gist is not None
+ assert len(gist) <= GIST_MAX_CHARS + 1
+ assert gist.endswith("…")
+
+
+def test_no_output_and_no_summary_has_nothing_to_say():
+ assert build_gist({}, None) is None
+ assert build_gist({"result": [""]}, " ") is None
+
+
+def test_final_fallback_only_claims_what_we_know():
+ assert fallback_gist(1) == "completed 1 run."
+ assert fallback_gist(14) == "completed 14 runs."
diff --git a/autogpt_platform/backend/backend/notifications/lifecycle.py b/autogpt_platform/backend/backend/notifications/lifecycle.py
new file mode 100644
index 0000000000..f93086ac15
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/lifecycle.py
@@ -0,0 +1,331 @@
+"""The account and billing emails, triggered from Stripe.
+
+Each handler listens for exactly one signal and does one thing. The rules that
+keep them from misfiring — first subscription only, first failed charge only,
+the false→true flip rather than every subscription update — live here rather
+than in the webhook router, so the webhook stays a dispatcher.
+
+There is deliberately no trial handler: the platform does not offer a trial, so
+`customer.subscription.trial_will_end` is not listened for.
+"""
+
+import logging
+from datetime import datetime, timezone
+
+import stripe
+from prisma.enums import NotificationType
+
+from backend.data.notifications import (
+ AudienceAction,
+ AudienceEventModel,
+ NotificationEventModel,
+ PaymentFailedData,
+ PaymentFinalNoticeData,
+ SubscriptionCancelledData,
+ SubscriptionEndedData,
+ SubscriptionResumedData,
+ SubscriptionWelcomeData,
+)
+from backend.data.user import BillingEmailRecipient
+from backend.notifications.dedupe import claim_once, release_claim
+from backend.notifications.lifecycle_plan import (
+ card_from_invoice,
+ format_amount,
+ format_date,
+ plan_from_invoice,
+ plan_from_subscription,
+)
+from backend.notifications.queue import queue_audience_change, queue_notification_async
+from backend.util.clients import get_database_manager_async_client
+from backend.util.logging import TruncatedLogger
+from backend.util.settings import Settings
+
+logger = TruncatedLogger(logging.getLogger(__name__), prefix="[Lifecycle]")
+settings = Settings()
+
+
+def _db():
+ """These handlers run in two processes — the REST API on a Stripe webhook,
+ and the notification service when the welcome is picked up off the work
+ queue. Only one of them owns a Prisma connection, so both go via the RPC."""
+ return get_database_manager_async_client()
+
+
+async def _publish(event, claim_key: str | None = None) -> None:
+ """Publish a billing email, or give its claim back and fail loudly.
+
+ Every one of these is claimed before it is published so a Stripe replay
+ cannot double-send. Ignoring a failed publish turns that safety into a
+ liability: the key is spent, the webhook still returns 200, Stripe never
+ retries, and the customer simply never hears that their payment failed.
+
+ Raising instead lets the webhook dispatcher release its own event claim and
+ return 5xx, and releasing this key first means the retry actually gets
+ through rather than being deduped.
+ """
+ result = await queue_notification_async(event)
+ if result.success:
+ return
+ if claim_key:
+ await release_claim(claim_key)
+ raise RuntimeError(f"Could not queue {event.type.value}: {result.message}")
+
+
+async def send_welcome_for_session(session_id: str) -> None:
+ """Re-read the checkout from Stripe and send the welcome.
+
+ Called from the work queue rather than the webhook, so the Stripe round
+ trip and the email are covered by retry-with-backoff and a dead-letter
+ queue. Re-reading rather than carrying the payload means a message that
+ waited acts on current state.
+
+ Raises on failure so the consumer retries; `on_checkout_completed` is
+ idempotent via the `welcomeEmailSentAt` claim.
+ """
+ session = dict(await stripe.checkout.Session.retrieve_async(session_id))
+ subscription_id = session.get("subscription")
+ if not subscription_id:
+ logger.info(f"Checkout {session_id} has no subscription; nothing to welcome")
+ return
+ subscription = dict(await stripe.Subscription.retrieve_async(str(subscription_id)))
+ await on_checkout_completed(session, subscription)
+
+
+async def on_checkout_completed(session: dict, subscription: dict) -> None:
+ """First subscription → welcome email and the onboarding tour. A returning
+ customer is not greeted like a stranger: they go straight into the
+ changelog audience instead."""
+ user = await _user_for(session.get("customer"))
+ if user is None:
+ return
+
+ if user.welcome_email_sent_at is not None:
+ await queue_audience_change(
+ AudienceEventModel(
+ action=AudienceAction.ADD_CHANGELOG, email=user.email, user_id=user.id
+ )
+ )
+ return
+
+ # Claim before queueing: Stripe retries webhooks, and two welcomes is worse
+ # than none.
+ if not await _claim_welcome(user):
+ return
+
+ plan = await plan_from_subscription(subscription)
+ try:
+ await _publish(
+ NotificationEventModel[SubscriptionWelcomeData](
+ user_id=user.id,
+ type=NotificationType.SUBSCRIPTION_WELCOME,
+ data=SubscriptionWelcomeData(
+ user_name=_greeting_name(user),
+ plan=plan,
+ renews_label=format_date(subscription.get("current_period_end")),
+ ),
+ )
+ )
+ except Exception:
+ # The claim is a database flag, not a Redis key with a TTL, so a failed
+ # publish would otherwise mark this customer as welcomed forever and
+ # every retry would take the returning-customer branch instead.
+ await _release_welcome(user)
+ raise
+
+ # Must not propagate: the welcome is already out and the claim is durable,
+ # so a Stripe retry would take the returning-customer branch and enrol them
+ # in the changelog instead of the tour. Report it rather than fail.
+ enrolled = await queue_audience_change(
+ AudienceEventModel(
+ action=AudienceAction.ENROLL_TOUR, email=user.email, user_id=user.id
+ )
+ )
+ if not enrolled.success:
+ logger.error(
+ f"Welcomed user {user.id} but could not queue the onboarding tour: "
+ f"{enrolled.message}"
+ )
+
+
+async def on_payment_failed(invoice: dict) -> None:
+ """First failed charge → a calm heads-up. Retries exhausted → the final
+ notice. Nothing at all during Stripe's automatic retries, which re-fire
+ this same event."""
+ user = await _user_for(invoice.get("customer"))
+ if user is None:
+ return
+
+ invoice_id = str(invoice.get("id") or "")
+ plan = await plan_from_invoice(invoice)
+ amount = format_amount(invoice.get("amount_due"), invoice.get("currency", "usd"))
+
+ if invoice.get("next_payment_attempt"):
+ if int(invoice.get("attempt_count") or 0) != 1:
+ # Automatic retries stay silent: four "payment failed" emails in
+ # two weeks reads as a billing crisis.
+ return
+ claim_key = f"payment_failed:{invoice_id}"
+ if not await claim_once(claim_key):
+ return
+ await _publish(
+ NotificationEventModel[PaymentFailedData](
+ user_id=user.id,
+ type=NotificationType.PAYMENT_FAILED,
+ data=PaymentFailedData(
+ user_name=_greeting_name(user),
+ plan=plan,
+ amount_display=amount,
+ card=card_from_invoice(invoice),
+ next_retry_label=format_date(invoice.get("next_payment_attempt")),
+ ),
+ ),
+ claim_key,
+ )
+ return
+
+ claim_key = f"final_notice:{invoice_id}"
+ if not await claim_once(claim_key):
+ return
+ await _publish(
+ NotificationEventModel[PaymentFinalNoticeData](
+ user_id=user.id,
+ type=NotificationType.PAYMENT_FINAL_NOTICE,
+ data=PaymentFinalNoticeData(
+ user_name=_greeting_name(user),
+ plan=plan,
+ amount_display=amount,
+ # Matches Stripe's automatic-collection configuration; see the
+ # deployment notes for the setting this must agree with.
+ pauses_label=format_date(invoice.get("period_end")),
+ ),
+ ),
+ claim_key,
+ )
+
+
+async def on_subscription_updated(subscription: dict, previous: dict) -> None:
+ """Only the cancel_at_period_end flip matters here; this event fires for
+ many unrelated changes."""
+ if "cancel_at_period_end" not in previous:
+ return
+ user = await _user_for(subscription.get("customer"))
+ if user is None:
+ return
+
+ was_cancelling = bool(previous.get("cancel_at_period_end"))
+ is_cancelling = bool(subscription.get("cancel_at_period_end"))
+ if was_cancelling == is_cancelling:
+ return
+
+ sub_id = str(subscription.get("id") or "")
+ period_end = subscription.get("current_period_end")
+ plan = await plan_from_subscription(subscription)
+
+ # The cancellation episode, not the billing period: cancel → resume →
+ # cancel inside one period is two real cancellations. Stripe stamps
+ # `canceled_at` on request and clears it on resume, so it names the episode.
+ episode = (
+ subscription.get("canceled_at")
+ if is_cancelling
+ else previous.get("canceled_at")
+ ) or period_end
+
+ if is_cancelling:
+ claim_key = f"cancelled:{sub_id}:{episode}"
+ if not await claim_once(claim_key):
+ return
+ await _publish(
+ NotificationEventModel[SubscriptionCancelledData](
+ user_id=user.id,
+ type=NotificationType.SUBSCRIPTION_CANCELLED,
+ data=SubscriptionCancelledData(
+ user_name=_greeting_name(user),
+ plan=plan,
+ access_until_label=format_date(period_end),
+ ),
+ ),
+ claim_key,
+ )
+ return
+
+ claim_key = f"resumed:{sub_id}:{episode}"
+ if not await claim_once(claim_key):
+ return
+ await _publish(
+ NotificationEventModel[SubscriptionResumedData](
+ user_id=user.id,
+ type=NotificationType.SUBSCRIPTION_RESUMED,
+ data=SubscriptionResumedData(
+ user_name=_greeting_name(user),
+ plan=plan,
+ renews_label=format_date(period_end),
+ ),
+ ),
+ claim_key,
+ )
+
+
+async def on_subscription_deleted(subscription: dict) -> None:
+ """Two roads lead here — a cancellation reaching period end, and dunning
+ exhaustion — so the copy branches on which one the customer took."""
+ user = await _user_for(subscription.get("customer"))
+ if user is None:
+ return
+
+ sub_id = str(subscription.get("id") or "")
+ claim_key = f"ended:{sub_id}"
+ if not await claim_once(claim_key):
+ return
+
+ reason = (subscription.get("cancellation_details") or {}).get("reason")
+ plan = await plan_from_subscription(subscription)
+ await _publish(
+ NotificationEventModel[SubscriptionEndedData](
+ user_id=user.id,
+ type=NotificationType.SUBSCRIPTION_ENDED,
+ data=SubscriptionEndedData(
+ user_name=_greeting_name(user),
+ plan=plan,
+ ended_label=format_date(subscription.get("ended_at")),
+ due_to_payment=reason == "payment_failed",
+ ),
+ ),
+ claim_key,
+ )
+ # Churned users get win-back only, never the monthly update.
+ await queue_audience_change(
+ AudienceEventModel(
+ action=AudienceAction.REMOVE_CHANGELOG, email=user.email, user_id=user.id
+ )
+ )
+
+
+async def _user_for(customer_id: object) -> BillingEmailRecipient | None:
+ """Skip deleted or unknown accounts rather than emailing into the void."""
+ if not customer_id or not isinstance(customer_id, str):
+ return None
+ user = await _db().get_billing_email_recipient(customer_id)
+ if user is None:
+ logger.warning(f"No user for Stripe customer {customer_id}; skipping email")
+ return user
+
+
+async def _claim_welcome(user: BillingEmailRecipient) -> bool:
+ """Set the "welcome sent" flag, and only send if this call is the one that
+ set it."""
+ return await _db().claim_welcome_email(user.id)
+
+
+async def _release_welcome(user: BillingEmailRecipient) -> None:
+ """Give the welcome claim back so a retry can actually send."""
+ await _db().release_welcome_email(user.id)
+
+
+def _greeting_name(user: BillingEmailRecipient) -> str:
+ if user.name and user.name.strip():
+ return user.name.strip().split()[0]
+ return user.email.split("@")[0]
+
+
+def _now() -> datetime:
+ return datetime.now(tz=timezone.utc)
diff --git a/autogpt_platform/backend/backend/notifications/lifecycle_plan.py b/autogpt_platform/backend/backend/notifications/lifecycle_plan.py
new file mode 100644
index 0000000000..5d0defbb65
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/lifecycle_plan.py
@@ -0,0 +1,120 @@
+"""Turning a Stripe subscription payload into the plan slots the billing
+emails are written from.
+
+Every sentence in those emails is assembled from these values — "this month's
+renewal" vs "this year's renewal", the plan name, the amount — so getting them
+from Stripe rather than from our own copy is what keeps the copy honest.
+"""
+
+import logging
+from datetime import datetime, timezone
+from typing import Literal
+
+from backend.data.credit import build_price_to_tier_map
+from backend.data.notifications import CardDetails, SubscriptionPlan
+from backend.notifications.stripe_payloads import StripeInvoice
+from backend.util.logging import TruncatedLogger
+
+logger = TruncatedLogger(logging.getLogger(__name__), prefix="[Lifecycle]")
+
+_ZERO_DECIMAL_CURRENCIES = {
+ "bif",
+ "clp",
+ "djf",
+ "gnf",
+ "jpy",
+ "kmf",
+ "krw",
+ "mga",
+ "pyg",
+ "rwf",
+ "ugx",
+ "vnd",
+ "vuv",
+ "xaf",
+ "xof",
+ "xpf",
+}
+
+
+async def plan_from_subscription(subscription: dict) -> SubscriptionPlan:
+ """Read the plan the customer is actually on out of a Stripe subscription."""
+ price = _first_price(subscription)
+ cycle = _cycle(price)
+ name = await _tier_name(price.get("id"))
+ return SubscriptionPlan(
+ name=name,
+ cycle=cycle,
+ cycle_noun="month" if cycle == "monthly" else "year",
+ label=f"{name} — {cycle}",
+ price_display=f"{format_amount(price.get('unit_amount'), price.get('currency', 'usd'))} / {'month' if cycle == 'monthly' else 'year'}",
+ )
+
+
+async def plan_from_invoice(invoice: dict) -> SubscriptionPlan:
+ """Same, from the invoice shape the payment events carry."""
+ lines = (invoice.get("lines") or {}).get("data") or []
+ price = (lines[0].get("price") or {}) if lines else {}
+ cycle = _cycle(price)
+ name = await _tier_name(price.get("id"))
+ return SubscriptionPlan(
+ name=name,
+ cycle=cycle,
+ cycle_noun="month" if cycle == "monthly" else "year",
+ label=f"{name} — {cycle}",
+ price_display=f"{format_amount(price.get('unit_amount'), price.get('currency', 'usd'))} / {'month' if cycle == 'monthly' else 'year'}",
+ )
+
+
+def card_from_invoice(invoice: dict) -> CardDetails:
+ """Card brand and last four for the "Card ···· 4242" row.
+
+ Falls back to neutral wording rather than inventing digits — and, because
+ it reads through `StripeInvoice`, never raises on an unexpanded webhook
+ payload where the nested objects are ID strings.
+ """
+ card = StripeInvoice.parse(invoice).card
+ return CardDetails(
+ brand=str((card.brand if card else None) or "Card").title(),
+ last4=str((card.last4 if card else None) or "••••"),
+ )
+
+
+def format_amount(minor_units: int | None, currency: str) -> str:
+ """Stripe amounts are in the currency's minor unit, except where they
+ aren't."""
+ if minor_units is None:
+ return "—"
+ symbol = {"usd": "$", "eur": "€", "gbp": "£"}.get(currency.lower(), "")
+ if currency.lower() in _ZERO_DECIMAL_CURRENCIES:
+ return f"{symbol}{minor_units:,}"
+ return f"{symbol}{minor_units / 100:,.2f}"
+
+
+def format_date(timestamp: int | None) -> str:
+ """The one fact these emails exist to state, so it is never relative."""
+ if not timestamp:
+ return "—"
+ moment = datetime.fromtimestamp(timestamp, tz=timezone.utc)
+ return f"{moment.day} {moment.strftime('%b %Y')}"
+
+
+def _first_price(subscription: dict) -> dict:
+ items = (subscription.get("items") or {}).get("data") or []
+ return (items[0].get("price") or {}) if items else {}
+
+
+def _cycle(price: dict) -> Literal["monthly", "yearly"]:
+ interval = ((price.get("recurring") or {}).get("interval")) or "month"
+ return "yearly" if interval == "year" else "monthly"
+
+
+async def _tier_name(price_id: str | None) -> str:
+ if not price_id:
+ return "AutoGPT"
+ try:
+ tier = (await build_price_to_tier_map()).get(price_id)
+ except Exception:
+ logger.warning(f"Could not resolve tier for price {price_id}", exc_info=True)
+ return "AutoGPT"
+ return tier.value.title() if tier else "AutoGPT"
diff --git a/autogpt_platform/backend/backend/notifications/lifecycle_test.py b/autogpt_platform/backend/backend/notifications/lifecycle_test.py
new file mode 100644
index 0000000000..d97917a4bd
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/lifecycle_test.py
@@ -0,0 +1,434 @@
+"""The billing emails fire on exactly one signal each.
+
+The failure modes these guard against are the classic ones: greeting a
+returning customer like a stranger, emailing on every Stripe retry, sending the
+cancellation confirmation weeks late off `subscription.deleted`, and treating
+every `subscription.updated` as a cancellation.
+"""
+
+import logging
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from prisma.enums import NotificationType
+
+from backend.data.notifications import NotificationResult, SubscriptionPlan
+from backend.notifications import lifecycle
+from backend.notifications.lifecycle_plan import card_from_invoice
+
+CUSTOMER = "cus_1"
+PLAN_PATCH = "backend.notifications.lifecycle.plan_from_subscription"
+INVOICE_PLAN_PATCH = "backend.notifications.lifecycle.plan_from_invoice"
+
+
+class _User:
+ """Shaped like `BillingEmailRecipient`, which is what the RPC returns."""
+
+ def __init__(self, welcome_sent_at=None):
+ self.id = "user-1"
+ self.email = "[email protected]"
+ self.name = "Sam Carter"
+ self.welcome_email_sent_at = welcome_sent_at
+
+
+def _subscription(**over) -> dict:
+ sub = {
+ "id": "sub_1",
+ "customer": CUSTOMER,
+ "current_period_end": 1789200000,
+ "cancel_at_period_end": False,
+ "ended_at": 1789200000,
+ "items": {
+ "data": [
+ {
+ "price": {
+ "id": "price_1",
+ "unit_amount": 5000,
+ "currency": "usd",
+ "recurring": {"interval": "month"},
+ }
+ }
+ ]
+ },
+ }
+ sub.update(over)
+ return sub
+
+
+def _invoice(**over) -> dict:
+ invoice = {
+ "id": "in_1",
+ "customer": CUSTOMER,
+ "amount_due": 5000,
+ "currency": "usd",
+ "attempt_count": 1,
+ "next_payment_attempt": 1789200000,
+ "period_end": 1789200000,
+ "lines": {
+ "data": [
+ {
+ "price": {
+ "id": "price_1",
+ "unit_amount": 5000,
+ "currency": "usd",
+ "recurring": {"interval": "month"},
+ }
+ }
+ ]
+ },
+ }
+ invoice.update(over)
+ return invoice
+
+
+def _context(user, claim=True, audience_ok=True):
+
+ plan = SubscriptionPlan(
+ name="Pro",
+ cycle="monthly",
+ cycle_noun="month",
+ label="Pro — monthly",
+ price_display="$50.00 / month",
+ )
+ return [
+ patch(
+ "backend.notifications.lifecycle._user_for", AsyncMock(return_value=user)
+ ),
+ patch(PLAN_PATCH, AsyncMock(return_value=plan)),
+ patch(INVOICE_PLAN_PATCH, AsyncMock(return_value=plan)),
+ patch(
+ "backend.notifications.lifecycle.claim_once",
+ AsyncMock(return_value=claim),
+ ),
+ patch("backend.notifications.lifecycle.queue_notification_async", AsyncMock()),
+ patch(
+ "backend.notifications.lifecycle.queue_audience_change",
+ AsyncMock(
+ return_value=NotificationResult(success=audience_ok, message="test")
+ ),
+ ),
+ ]
+
+
+async def _run(coro_factory, user, claim=True, audience_ok=True):
+ patches = _context(user, claim, audience_ok)
+ started = [p.start() for p in patches]
+ try:
+ await coro_factory()
+ return {"notify": started[4], "audience": started[5], "claim": started[3]}
+ finally:
+ for p in patches:
+ p.stop()
+
+
+async def test_first_subscription_gets_the_welcome_and_the_tour():
+ user = _User(welcome_sent_at=None)
+ with patch(
+ "backend.notifications.lifecycle._claim_welcome",
+ AsyncMock(return_value=True),
+ ):
+ calls = await _run(
+ lambda: lifecycle.on_checkout_completed(
+ {"customer": CUSTOMER}, _subscription()
+ ),
+ user,
+ )
+ queued = calls["notify"].await_args.args[0]
+ assert queued.type is NotificationType.SUBSCRIPTION_WELCOME
+ assert queued.data.user_name == "Sam"
+ calls["audience"].assert_awaited_once()
+ assert calls["audience"].await_args.args[0].action.value == "enroll_tour"
+
+
+async def test_a_returning_customer_is_not_greeted_like_a_stranger():
+ user = _User(welcome_sent_at=datetime(2026, 1, 1, tzinfo=timezone.utc))
+ calls = await _run(
+ lambda: lifecycle.on_checkout_completed(
+ {"customer": CUSTOMER}, _subscription()
+ ),
+ user,
+ )
+ calls["notify"].assert_not_awaited()
+ assert calls["audience"].await_args.args[0].action.value == "add_changelog"
+
+
+async def test_only_the_first_failed_charge_emails():
+ calls = await _run(
+ lambda: lifecycle.on_payment_failed(_invoice(attempt_count=1)), _User()
+ )
+ assert calls["notify"].await_args.args[0].type is NotificationType.PAYMENT_FAILED
+
+ calls = await _run(
+ lambda: lifecycle.on_payment_failed(_invoice(attempt_count=3)), _User()
+ )
+ calls["notify"].assert_not_awaited()
+
+
+async def test_no_retries_left_is_the_final_notice_not_another_heads_up():
+ calls = await _run(
+ lambda: lifecycle.on_payment_failed(_invoice(next_payment_attempt=None)),
+ _User(),
+ )
+ queued = calls["notify"].await_args.args[0]
+ assert queued.type is NotificationType.PAYMENT_FINAL_NOTICE
+
+
+async def test_a_replayed_webhook_does_not_send_twice():
+ calls = await _run(
+ lambda: lifecycle.on_payment_failed(_invoice()), _User(), claim=False
+ )
+ calls["notify"].assert_not_awaited()
+
+
+async def test_cancellation_fires_on_the_flip_not_on_every_update():
+ calls = await _run(
+ lambda: lifecycle.on_subscription_updated(
+ _subscription(cancel_at_period_end=True),
+ {"cancel_at_period_end": False},
+ ),
+ _User(),
+ )
+ queued = calls["notify"].await_args.args[0]
+ assert queued.type is NotificationType.SUBSCRIPTION_CANCELLED
+
+ # An unrelated update carries no cancel_at_period_end in previous_attributes.
+ calls = await _run(
+ lambda: lifecycle.on_subscription_updated(
+ _subscription(), {"default_payment_method": "pm_old"}
+ ),
+ _User(),
+ )
+ calls["notify"].assert_not_awaited()
+
+
+async def test_a_failed_tour_enrolment_still_welcomes_the_customer(caplog):
+ """The publish helper swallows its own errors and returns a result, so an
+ unchecked call drops the enrolment in silence. The welcome is already out
+ and the claim is durable, so this cannot undo it — Stripe would retry and
+ take the returning-customer branch. It gets reported instead."""
+ user = _User(welcome_sent_at=None)
+ with patch(
+ "backend.notifications.lifecycle._claim_welcome",
+ AsyncMock(return_value=True),
+ ), caplog.at_level(logging.ERROR):
+ calls = await _run(
+ lambda: lifecycle.on_checkout_completed(
+ {"customer": CUSTOMER}, _subscription()
+ ),
+ user,
+ audience_ok=False,
+ )
+
+ assert (
+ calls["notify"].await_args.args[0].type is NotificationType.SUBSCRIPTION_WELCOME
+ )
+ assert "onboarding tour" in caplog.text
+
+
+async def test_a_second_cancellation_in_one_period_is_its_own_email():
+ """Cancel → resume → cancel inside one billing period is two real
+ cancellations. Keying the claim on the period alone swallows the second
+ confirmation, so the customer cancels and hears nothing back."""
+ episodes = (
+ (
+ _subscription(cancel_at_period_end=True, canceled_at=1789100000),
+ {"cancel_at_period_end": False},
+ ),
+ (
+ _subscription(cancel_at_period_end=False),
+ {"cancel_at_period_end": True, "canceled_at": 1789100000},
+ ),
+ (
+ _subscription(cancel_at_period_end=True, canceled_at=1789150000),
+ {"cancel_at_period_end": False},
+ ),
+ )
+ keys = []
+ for sub, previous in episodes:
+ calls = await _run(
+ lambda s=sub, p=previous: lifecycle.on_subscription_updated(s, p),
+ _User(),
+ )
+ keys.append(calls["claim"].await_args.args[0])
+
+ assert keys[0].startswith("cancelled:") and keys[1].startswith("resumed:")
+ assert keys[0] != keys[2], f"each cancellation needs its own key: {keys}"
+
+
+async def test_resuming_closes_the_loop_on_the_cancellation_email():
+ calls = await _run(
+ lambda: lifecycle.on_subscription_updated(
+ _subscription(cancel_at_period_end=False),
+ {"cancel_at_period_end": True},
+ ),
+ _User(),
+ )
+ assert (
+ calls["notify"].await_args.args[0].type is NotificationType.SUBSCRIPTION_RESUMED
+ )
+
+
+async def test_the_ended_email_branches_on_which_road_they_took():
+ calls = await _run(
+ lambda: lifecycle.on_subscription_deleted(
+ _subscription(cancellation_details={"reason": "payment_failed"})
+ ),
+ _User(),
+ )
+ queued = calls["notify"].await_args.args[0]
+ assert queued.type is NotificationType.SUBSCRIPTION_ENDED
+ assert queued.data.due_to_payment is True
+ # Churned users get win-back only, never the monthly update.
+ assert calls["audience"].await_args.args[0].action.value == "remove_changelog"
+
+ calls = await _run(
+ lambda: lifecycle.on_subscription_deleted(
+ _subscription(cancellation_details={"reason": "cancellation_requested"})
+ ),
+ _User(),
+ )
+ assert calls["notify"].await_args.args[0].data.due_to_payment is False
+
+
+def test_the_platform_does_not_listen_for_trials():
+ assert not hasattr(lifecycle, "on_trial_will_end")
+ assert not any(name.endswith("TRIAL_ENDING") for name in dir(NotificationType))
+
+
+# ── the shape Stripe actually delivers ──────────────────────────────────
+#
+# Webhook payloads do not expand nested objects: `payment_intent` and
+# `default_payment_method` arrive as ID *strings*, not dicts. The fixtures
+# above omit both keys entirely, so `None or {}` masks it.
+
+
+def test_card_details_survive_an_unexpanded_webhook_invoice():
+ card = card_from_invoice(
+ {"id": "in_1", "payment_intent": "pi_3ABC", "default_payment_method": "pm_1XYZ"}
+ )
+ assert card.brand == "Card"
+ assert card.last4 == "••••"
+
+
+async def test_the_payment_failed_email_still_sends_for_a_real_invoice():
+ """The crash lands *after* `claim_once` has already taken the key, so
+ Stripe's retry is deduped away and the email never sends at all."""
+ calls = await _run(
+ lambda: lifecycle.on_payment_failed(
+ _invoice(payment_intent="pi_3ABC", default_payment_method="pm_1XYZ")
+ ),
+ _User(),
+ )
+ queued = calls["notify"].await_args.args[0]
+ assert queued.type is NotificationType.PAYMENT_FAILED
+
+
+async def test_a_failed_publish_gives_the_claim_back():
+ """The claim is taken before the send so a Stripe replay cannot
+ double-send. If the send then fails and the key stays spent, every retry is
+ deduped away and the customer never learns their payment failed — the same
+ permanent loss the unexpanded-invoice crash used to cause.
+ """
+ plan = SubscriptionPlan(
+ name="Pro",
+ cycle="monthly",
+ cycle_noun="month",
+ label="Pro — monthly",
+ price_display="$50.00 / month",
+ )
+ with patch(
+ "backend.notifications.lifecycle._user_for", AsyncMock(return_value=_User())
+ ), patch(INVOICE_PLAN_PATCH, AsyncMock(return_value=plan)), patch(
+ "backend.notifications.lifecycle.claim_once", AsyncMock(return_value=True)
+ ), patch(
+ "backend.notifications.lifecycle.queue_notification_async",
+ AsyncMock(
+ return_value=NotificationResult(success=False, message="broker down")
+ ),
+ ), patch(
+ "backend.notifications.lifecycle.release_claim", AsyncMock()
+ ) as released:
+ # Raises so the webhook dispatcher releases its own event claim and
+ # returns 5xx, which is what makes Stripe retry at all.
+ with pytest.raises(RuntimeError):
+ await lifecycle.on_payment_failed(_invoice())
+
+ released.assert_awaited_once_with("payment_failed:in_1")
+
+
+async def test_a_successful_publish_keeps_the_claim():
+ plan = SubscriptionPlan(
+ name="Pro",
+ cycle="monthly",
+ cycle_noun="month",
+ label="Pro — monthly",
+ price_display="$50.00 / month",
+ )
+ with patch(
+ "backend.notifications.lifecycle._user_for", AsyncMock(return_value=_User())
+ ), patch(INVOICE_PLAN_PATCH, AsyncMock(return_value=plan)), patch(
+ "backend.notifications.lifecycle.claim_once", AsyncMock(return_value=True)
+ ), patch(
+ "backend.notifications.lifecycle.queue_notification_async",
+ AsyncMock(return_value=NotificationResult(success=True)),
+ ), patch(
+ "backend.notifications.lifecycle.release_claim", AsyncMock()
+ ) as released:
+ await lifecycle.on_payment_failed(_invoice())
+
+ released.assert_not_awaited()
+
+
+async def test_a_failed_welcome_publish_gives_the_claim_back():
+ """`welcomeEmailSentAt` is a database flag, not a key with a TTL.
+
+ Marking it before the publish is what stops a Stripe replay double-sending.
+ If the publish then fails and the flag stays set, this customer is marked
+ welcomed forever: every retry takes the returning-customer branch and they
+ are never greeted at all.
+ """
+ user = _User(welcome_sent_at=None)
+ plan = SubscriptionPlan(
+ name="Pro",
+ cycle="monthly",
+ cycle_noun="month",
+ label="Pro — monthly",
+ price_display="$50.00 / month",
+ )
+ with patch(
+ "backend.notifications.lifecycle._user_for", AsyncMock(return_value=user)
+ ), patch(PLAN_PATCH, AsyncMock(return_value=plan)), patch(
+ "backend.notifications.lifecycle._claim_welcome", AsyncMock(return_value=True)
+ ), patch(
+ "backend.notifications.lifecycle.queue_notification_async",
+ AsyncMock(
+ return_value=NotificationResult(success=False, message="broker down")
+ ),
+ ), patch(
+ "backend.notifications.lifecycle.queue_audience_change", AsyncMock()
+ ) as audience, patch(
+ "backend.notifications.lifecycle._release_welcome", AsyncMock()
+ ) as released:
+ with pytest.raises(RuntimeError):
+ await lifecycle.on_checkout_completed(
+ {"customer": CUSTOMER, "mode": "subscription"}, _subscription()
+ )
+
+ released.assert_awaited_once_with(user)
+ # The tour enrolment must not run for a welcome that never went out.
+ audience.assert_not_awaited()
diff --git a/autogpt_platform/backend/backend/notifications/mailerlite.py b/autogpt_platform/backend/backend/notifications/mailerlite.py
new file mode 100644
index 0000000000..faf5f3b2ab
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/mailerlite.py
@@ -0,0 +1,145 @@
+"""MailerLite audience management.
+
+Two emails live entirely in MailerLite — the six-email White Glove Tour and the
+monthly changelog — and neither needs a deploy to change. The platform's only
+job is managing who is in each audience, and there is exactly one owner per
+transition:
+
+1. ENTER · tour finishers → changelog: owned by MailerLite. The onboarding
+ automation's final step moves the subscriber across. That handoff is what
+ implements the suppression rule — nobody gets the monthly update mid-tour,
+ because mid-tour users simply are not in the group.
+2. ENTER · resubscribers and pre-tour users → changelog: owned here.
+3. LEAVE · churn: owned here. Churned users get win-back only, never the
+ monthly update.
+
+If both sides managed the same edge we would double-add or fight over
+removals, so nothing in this module touches the tour → changelog handoff.
+"""
+
+import hashlib
+import logging
+
+from backend.util.request import Requests
+from backend.util.settings import Settings
+
+logger = logging.getLogger(__name__)
+
+
+def _pseudonym(email: str) -> str:
+ """A stable, non-reversible handle for logs.
+
+ A subscriber's address is personal data; putting it in a log line or an
+ exception message copies it into log retention and every downstream sink.
+ The digest is enough to correlate one subscriber's records without storing
+ the address itself.
+ """
+ return hashlib.sha256(email.strip().lower().encode()).hexdigest()[:12]
+
+
+settings = Settings()
+
+API_BASE = "https://connect.mailerlite.com/api"
+_OK_STATUSES = (200, 201, 202, 204)
+
+
+class MailerLiteNotConfigured(RuntimeError):
+ """Raised so a queued job retries once credentials are in place, rather
+ than silently reporting success."""
+
+
+class MailerLiteError(RuntimeError):
+ """A MailerLite call failed. Raised so the queued job retries with backoff
+ — a MailerLite outage must never fail payment processing, but it must not
+ silently drop an enrolment either."""
+
+
+async def enroll_in_onboarding(email: str) -> None:
+ """Add a first-time subscriber to the tour group. Joining the group is the
+ automation's trigger; MailerLite sends the six emails from there."""
+ await _add_to_group(
+ email, settings.config.mailerlite_onboarding_group_id, "onboarding tour"
+ )
+
+
+async def add_to_changelog(email: str) -> None:
+ """Returning customers and anyone who predates the tour."""
+ await _add_to_group(
+ email, settings.config.mailerlite_changelog_group_id, "changelog"
+ )
+
+
+async def remove_from_changelog(email: str) -> None:
+ """The day a plan ends."""
+ group_id = settings.config.mailerlite_changelog_group_id
+ _require_config(group_id, "changelog")
+
+ subscriber_id = await _find_subscriber_id(email)
+ if subscriber_id is None:
+ logger.info(
+ "No MailerLite subscriber for %s; nothing to remove", _pseudonym(email)
+ )
+ return
+
+ response = await _client().delete(
+ f"{API_BASE}/subscribers/{subscriber_id}/groups/{group_id}",
+ headers=_headers(),
+ )
+ # 404 means they are already out of the group, which is the desired state.
+ if response.status not in _OK_STATUSES and response.status != 404:
+ raise MailerLiteError(
+ f"Removing subscriber {_pseudonym(email)} from the changelog group "
+ f"failed with {response.status}"
+ )
+ logger.info("Removed %s from the MailerLite changelog group", _pseudonym(email))
+
+
+async def _add_to_group(email: str, group_id: str, description: str) -> None:
+ _require_config(group_id, description)
+ response = await _client().post(
+ f"{API_BASE}/subscribers",
+ headers=_headers(),
+ json={"email": email, "groups": [group_id]},
+ )
+ if response.status not in _OK_STATUSES:
+ raise MailerLiteError(
+ f"Adding subscriber {_pseudonym(email)} to the {description} group "
+ f"failed with {response.status}"
+ )
+ logger.info("Added %s to the MailerLite %s group", _pseudonym(email), description)
+
+
+async def _find_subscriber_id(email: str) -> str | None:
+ response = await _client().get(
+ f"{API_BASE}/subscribers/{email}", headers=_headers()
+ )
+ if response.status == 404:
+ return None
+ if response.status not in _OK_STATUSES:
+ raise MailerLiteError(
+ f"Looking up MailerLite subscriber {_pseudonym(email)} failed with "
+ f"{response.status}"
+ )
+ return ((response.json() or {}).get("data") or {}).get("id")
+
+
+def _client() -> Requests:
+ # Statuses are inspected rather than raised on, because "already gone" is a
+ # success for a removal.
+ return Requests(trusted_origins=[API_BASE], raise_for_status=False)
+
+
+def _headers() -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {settings.secrets.mailerlite_api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _require_config(group_id: str, description: str) -> None:
+ if not settings.secrets.mailerlite_api_token:
+ raise MailerLiteNotConfigured("MAILERLITE_API_TOKEN is not set")
+ if not group_id:
+ raise MailerLiteNotConfigured(
+ f"The MailerLite {description} group ID is not configured"
+ )
diff --git a/autogpt_platform/backend/backend/notifications/notifications.py b/autogpt_platform/backend/backend/notifications/notifications.py
index 87edaba2ae..f40407d191 100644
--- a/autogpt_platform/backend/backend/notifications/notifications.py
+++ b/autogpt_platform/backend/backend/notifications/notifications.py
@@ -1,38 +1,47 @@
+"""The notification service.
+
+Consumes the three notification queues, and owns the two scheduled passes that
+the Alert and Briefing families need: flushing matured alerts out of the
+debounce window, and assembling briefings for the users whose local morning it
+is.
+"""
+
import asyncio
import logging
from concurrent.futures import Future
from concurrent.futures import TimeoutError as FutureTimeoutError
-from datetime import datetime, timedelta, timezone
-from typing import Awaitable, Callable
+from datetime import date, datetime, timezone
+from typing import Awaitable, Callable, Coroutine
import aio_pika
-from prisma.enums import NotificationType
from backend.data import rabbitmq
from backend.data.notifications import (
+ AudienceAction,
+ AudienceEventModel,
BaseEventModel,
- BaseSummaryData,
- BaseSummaryParams,
- DailySummaryData,
- DailySummaryParams,
NotificationEventModel,
NotificationResult,
- NotificationTypeOverride,
- QueueType,
- SummaryParamsEventModel,
- WeeklySummaryData,
- WeeklySummaryParams,
- get_batch_delay,
+ PassWorkEvent,
get_notif_data_type,
- get_summary_params_type,
)
-from backend.data.rabbitmq import Exchange, ExchangeType, Queue, RabbitMQConfig
from backend.data.user import (
- disable_all_user_notifications,
+ FOOTER_CHOICES,
+ generate_preference_link,
generate_unsubscribe_link,
- set_user_email_verification,
)
+from backend.notifications import briefing_runner, mailerlite
+from backend.notifications.dedupe import claim_daily_send
from backend.notifications.email import EmailSender
+from backend.notifications.preferences import SERVICE_MESSAGES, wants_notification
+from backend.notifications.queue import (
+ AUDIENCE_QUEUE,
+ OPS_NOTIFICATIONS_QUEUE,
+ PASS_WORK_QUEUE,
+ USER_NOTIFICATIONS_QUEUE,
+ create_notification_config,
+ queue_notification_async,
+)
from backend.util.clients import get_database_manager_async_client
from backend.util.logging import TruncatedLogger
from backend.util.metrics import DiscordChannel, discord_send_alert
@@ -44,192 +53,33 @@ from backend.util.service import (
endpoint_to_sync,
expose,
)
-from backend.util.settings import AppEnvironment, Settings
+from backend.util.settings import Settings
logger = TruncatedLogger(logging.getLogger(__name__), "[NotificationManager]")
settings = Settings()
-# Retry settings for transient failures in queue consumers. With these defaults
-# the consumer makes 3 attempts with 2s + 4s = 6s of backoff between them
-# before reject-to-DLQ — enough to ride out the most common transient failures
-# (DB connection blip, Postmark 5xx, brief network outage) without trapping
-# truly broken messages on the queue for long.
+
+def _utc_today() -> date:
+ """The cap resets at UTC midnight, matching the Alert engine's own daily
+ cap. Both are documented as a follow-up to move to the user's local day."""
+ return datetime.now(tz=timezone.utc).date()
+
+
MAX_CONSUMER_RETRY_ATTEMPTS = 3
CONSUMER_RETRY_BACKOFF_SECONDS = 2
-
-# Upper bound for each stage of _shutdown_service (consumer-task cancellation
-# and RabbitMQ disconnect). A consumer stuck unwinding on a dead broker
-# connection must not hang cleanup forever — the process has to keep making
-# forward progress so its supervisor sees a clean exit. Mirrors the
-# timeout=10 drain in GraphExecutorManager.cleanup.
SHUTDOWN_TIMEOUT_SECONDS = 10
-
-# Outer deadline for cleanup()'s cross-thread wait on the _shutdown_service
-# barrier. Each barrier stage is individually bounded by
-# SHUTDOWN_TIMEOUT_SECONDS, so this only fires when the event loop stops
-# before ever servicing the barrier — without it, Future.result() would block
-# process exit indefinitely.
CLEANUP_TIMEOUT_SECONDS = SHUTDOWN_TIMEOUT_SECONDS * 2 + 5
-
-NOTIFICATION_EXCHANGE = Exchange(name="notifications", type=ExchangeType.TOPIC)
-DEAD_LETTER_EXCHANGE = Exchange(name="dead_letter", type=ExchangeType.TOPIC)
-EXCHANGES = [NOTIFICATION_EXCHANGE, DEAD_LETTER_EXCHANGE]
-
-# ``_v2`` suffix marks the classic→quorum rollover: old classic queues keep
-# draining via old-image consumers; orphans are cleaned up by a follow-up PR.
-IMMEDIATE_NOTIFICATIONS_QUEUE = "immediate_notifications_v2"
-ADMIN_NOTIFICATIONS_QUEUE = "admin_notifications_v2"
-SUMMARY_NOTIFICATIONS_QUEUE = "summary_notifications_v2"
-BATCH_NOTIFICATIONS_QUEUE = "batch_notifications_v2"
-FAILED_NOTIFICATIONS_QUEUE = "failed_notifications_v2"
-
-
-def create_notification_config() -> RabbitMQConfig:
- """Create RabbitMQ configuration for notifications"""
- queues = [
- # Main notification queues
- Queue(
- name=IMMEDIATE_NOTIFICATIONS_QUEUE,
- exchange=NOTIFICATION_EXCHANGE,
- routing_key="notification.immediate.#",
- arguments={
- "x-queue-type": "quorum",
- "x-dead-letter-exchange": DEAD_LETTER_EXCHANGE.name,
- "x-dead-letter-routing-key": "failed.immediate",
- },
- ),
- Queue(
- name=ADMIN_NOTIFICATIONS_QUEUE,
- exchange=NOTIFICATION_EXCHANGE,
- routing_key="notification.admin.#",
- arguments={
- "x-queue-type": "quorum",
- "x-dead-letter-exchange": DEAD_LETTER_EXCHANGE.name,
- "x-dead-letter-routing-key": "failed.admin",
- },
- ),
- # Summary notification queues
- Queue(
- name=SUMMARY_NOTIFICATIONS_QUEUE,
- exchange=NOTIFICATION_EXCHANGE,
- routing_key="notification.summary.#",
- arguments={
- "x-queue-type": "quorum",
- "x-dead-letter-exchange": DEAD_LETTER_EXCHANGE.name,
- "x-dead-letter-routing-key": "failed.summary",
- },
- ),
- # Batch Queue
- Queue(
- name=BATCH_NOTIFICATIONS_QUEUE,
- exchange=NOTIFICATION_EXCHANGE,
- routing_key="notification.batch.#",
- arguments={
- "x-queue-type": "quorum",
- "x-dead-letter-exchange": DEAD_LETTER_EXCHANGE.name,
- "x-dead-letter-routing-key": "failed.batch",
- },
- ),
- # DLQ destination — quorum so dead letters survive a broker restart.
- Queue(
- name=FAILED_NOTIFICATIONS_QUEUE,
- exchange=DEAD_LETTER_EXCHANGE,
- routing_key="failed.#",
- arguments={"x-queue-type": "quorum"},
- ),
- ]
-
- return RabbitMQConfig(
- exchanges=EXCHANGES,
- queues=queues,
- )
-
-
-def get_routing_key(event_type: NotificationType) -> str:
- strategy = NotificationTypeOverride(event_type).strategy
- """Get the appropriate routing key for an event"""
- if strategy == QueueType.IMMEDIATE:
- return f"notification.immediate.{event_type.value}"
- elif strategy == QueueType.BACKOFF:
- return f"notification.backoff.{event_type.value}"
- elif strategy == QueueType.ADMIN:
- return f"notification.admin.{event_type.value}"
- elif strategy == QueueType.BATCH:
- return f"notification.batch.{event_type.value}"
- elif strategy == QueueType.SUMMARY:
- return f"notification.summary.{event_type.value}"
- return f"notification.{event_type.value}"
-
-
-def queue_notification(event: NotificationEventModel) -> NotificationResult:
- """Queue a notification - exposed method for other services to call"""
- # Disable in production
- if settings.config.app_env == AppEnvironment.PRODUCTION:
- return NotificationResult(
- success=True,
- message="Queueing notifications is disabled in production",
- )
- try:
- logger.debug(f"Received Request to queue {event=}")
-
- exchange = "notifications"
- routing_key = get_routing_key(event.type)
-
- from backend.util.clients import get_notification_queue
-
- queue = get_notification_queue()
- queue.publish_message(
- routing_key=routing_key,
- message=event.model_dump_json(),
- exchange=next(ex for ex in EXCHANGES if ex.name == exchange),
- )
-
- return NotificationResult(
- success=True,
- message=f"Notification queued with routing key: {routing_key}",
- )
-
- except Exception as e:
- logger.exception(f"Error queueing notification: {e}")
- return NotificationResult(success=False, message=str(e))
-
-
-async def queue_notification_async(event: NotificationEventModel) -> NotificationResult:
- """Queue a notification - exposed method for other services to call"""
- # Disable in production
- if settings.config.app_env == AppEnvironment.PRODUCTION:
- return NotificationResult(
- success=True,
- message="Queueing notifications is disabled in production",
- )
- try:
- logger.debug(f"Received Request to queue {event=}")
-
- exchange = "notifications"
- routing_key = get_routing_key(event.type)
-
- from backend.util.clients import get_async_notification_queue
-
- queue = await get_async_notification_queue()
- await queue.publish_message(
- routing_key=routing_key,
- message=event.model_dump_json(),
- exchange=next(ex for ex in EXCHANGES if ex.name == exchange),
- )
-
- return NotificationResult(
- success=True,
- message=f"Notification queued with routing key: {routing_key}",
- )
-
- except Exception as e:
- logger.exception(f"Error queueing notification: {e}")
- return NotificationResult(success=False, message=str(e))
+__all__ = [
+ "NotificationManager",
+ "NotificationManagerClient",
+ "queue_notification_async",
+ "NotificationResult",
+]
class NotificationManager(AppService):
- """Service for handling notifications with batching support"""
+ """Renders and sends every email the platform produces."""
def __init__(self):
super().__init__()
@@ -239,24 +89,18 @@ class NotificationManager(AppService):
self.email_sender = EmailSender()
self._run_service_future: Future[None] | None = None
self._run_service_task: asyncio.Task[None] | None = None
+ # In-flight scheduled passes, keyed by name, so a slow tick cannot
+ # overlap the next one and double-send.
+ self._passes: dict[str, asyncio.Task[None]] = {}
@property
def rabbit(self) -> rabbitmq.AsyncRabbitMQ:
- """Access the RabbitMQ service. Will raise if not configured."""
- if not hasattr(self, "rabbitmq_service") or not self.rabbitmq_service:
+ if not self.rabbitmq_service:
raise UnhealthyServiceError("RabbitMQ not configured for this service")
return self.rabbitmq_service
- @property
- def rabbit_config(self) -> rabbitmq.RabbitMQConfig:
- """Access the RabbitMQ config. Will raise if not configured."""
- if not self.rabbitmq_config:
- raise UnhealthyServiceError("RabbitMQ not configured for this service")
- return self.rabbitmq_config
-
async def health_check(self) -> str:
- # Service is unhealthy if RabbitMQ is not ready
- if not hasattr(self, "rabbitmq_service") or not self.rabbitmq_service:
+ if not self.rabbitmq_service:
raise UnhealthyServiceError("RabbitMQ not configured for this service")
if not self.rabbitmq_service.is_ready:
raise UnhealthyServiceError("RabbitMQ channel is not ready")
@@ -266,189 +110,62 @@ class NotificationManager(AppService):
def get_port(cls) -> int:
return settings.config.notification_service_port
- @expose
- async def queue_weekly_summary(self):
- # disable in prod
- if settings.config.app_env == AppEnvironment.PRODUCTION:
- return
- # Use the existing event loop instead of creating a new one with asyncio.run()
- asyncio.create_task(self._queue_weekly_summary())
+ # ── scheduled passes ────────────────────────────────────────────────
- async def _queue_weekly_summary(self):
- """Process weekly summary for specified notification types"""
- try:
- logger.info("Processing weekly summary queuing operation")
- processed_count = 0
- current_time = datetime.now(tz=timezone.utc)
- start_time = current_time - timedelta(days=7)
- logger.info(
- f"Querying for active users between {start_time} and {current_time}"
- )
- users = await get_database_manager_async_client(
- should_retry=False
- ).get_active_user_ids_in_timerange(
- end_time=current_time.isoformat(),
- start_time=start_time.isoformat(),
- )
- logger.info(f"Found {len(users)} active users in the last 7 days")
- for user in users:
- await self._queue_scheduled_notification(
- SummaryParamsEventModel(
- user_id=user,
- type=NotificationType.WEEKLY_SUMMARY,
- data=WeeklySummaryParams(
- start_date=start_time,
- end_date=current_time,
- ),
- ),
- )
- processed_count += 1
-
- logger.info(f"Processed {processed_count} weekly summaries into queue")
-
- except Exception as e:
- logger.exception(f"Error processing weekly summary: {e}")
+ @expose
+ async def flush_matured_alerts(self) -> None:
+ """Send everything that has sat out the ten-minute debounce window, one
+ coalesced email per user."""
+ self._spawn_pass("flush_matured_alerts", briefing_runner.flush_matured_alerts)
@expose
- async def process_existing_batches(
- self, notification_types: list[NotificationType]
- ):
- # disable in prod
- if settings.config.app_env == AppEnvironment.PRODUCTION:
+ async def send_due_briefings(self) -> None:
+ """Assemble and queue briefings for every user whose local ~07:30 this
+ hour is."""
+ self._spawn_pass("send_due_briefings", briefing_runner.send_due_briefings)
+
+ def _spawn_pass(
+ self, name: str, work: Callable[[], Coroutine[None, None, None]]
+ ) -> None:
+ """Run a scheduled pass in the background, at most one at a time.
+
+ The scheduler fires these on a fixed interval and this RPC returns as
+ soon as the task is spawned, so nothing else stops a slow pass from
+ overlapping the next tick. Both passes queue their email *before*
+ marking the rows that suppress a resend, so two concurrent runs read
+ the same PENDING conditions and send the same alert twice.
+
+ The task is also held in a dict rather than left to float: a bare
+ `create_task` reference can be garbage-collected mid-flight.
+ """
+ existing = self._passes.get(name)
+ if existing and not existing.done():
+ logger.warning(
+ f"{name} is still running from the previous tick; skipping this one"
+ )
return
- # Use the existing event loop instead of creating a new process
- asyncio.create_task(self._process_existing_batches(notification_types))
- async def _process_existing_batches(
- self, notification_types: list[NotificationType]
- ):
- """Process existing batches for specified notification types"""
- try:
- processed_count = 0
- current_time = datetime.now(tz=timezone.utc)
-
- for notification_type in notification_types:
- # Get all batches for this notification type
- batches = await get_database_manager_async_client(
- should_retry=False
- ).get_all_batches_by_type(notification_type)
-
- for batch in batches:
- # Check if batch has aged out
- oldest_message = await get_database_manager_async_client(
- should_retry=False
- ).get_user_notification_oldest_message_in_batch(
- batch.user_id, notification_type
- )
-
- if not oldest_message:
- logger.warning(
- f"Batch for user {batch.user_id} and type {notification_type} "
- f"has no oldest message — batch may have been cleared concurrently"
- )
- continue
-
- max_delay = get_batch_delay(notification_type)
-
- # If batch has aged out, process it
- if oldest_message.created_at + max_delay < current_time:
- recipient_email = await get_database_manager_async_client(
- should_retry=False
- ).get_user_email_by_id(batch.user_id)
-
- if not recipient_email:
- logger.warning(
- f"User email not found for user {batch.user_id}"
- )
- continue
+ task = asyncio.create_task(work(), name=name)
+ self._passes[name] = task
+ task.add_done_callback(self._clear_pass)
- should_send = await self._should_email_user_based_on_preference(
- batch.user_id, notification_type
- )
+ def _clear_pass(self, task: asyncio.Task) -> None:
+ """Drop a finished pass, but only if it is still the registered one.
- if not should_send:
- logger.debug(
- f"User {batch.user_id} does not want to receive {notification_type} notifications"
- )
- # Clear the batch
- await get_database_manager_async_client(
- should_retry=False
- ).empty_user_notification_batch(
- batch.user_id, notification_type
- )
- continue
-
- batch_data = await get_database_manager_async_client(
- should_retry=False
- ).get_user_notification_batch(batch.user_id, notification_type)
-
- if not batch_data or not batch_data.notifications:
- logger.warning(
- f"Batch data not found for user {batch.user_id}"
- )
- # Clear the batch
- await get_database_manager_async_client(
- should_retry=False
- ).empty_user_notification_batch(
- batch.user_id, notification_type
- )
- continue
-
- unsub_link = generate_unsubscribe_link(batch.user_id)
- events = []
- for db_event in batch_data.notifications:
- try:
- events.append(
- NotificationEventModel[
- get_notif_data_type(db_event.type)
- ].model_validate(
- {
- "user_id": batch.user_id,
- "type": db_event.type,
- "data": db_event.data,
- "created_at": db_event.created_at,
- }
- )
- )
- except Exception as e:
- logger.warning(
- f"Error parsing notification event: {e=}, {db_event=}"
- )
- continue
- logger.info(f"{events=}")
-
- await self.email_sender.send_templated(
- notification=notification_type,
- user_email=recipient_email,
- data=events,
- user_unsub_link=unsub_link,
- )
-
- # Clear the batch
- await get_database_manager_async_client(
- should_retry=False
- ).empty_user_notification_batch(
- batch.user_id, notification_type
- )
-
- processed_count += 1
-
- logger.info(f"Processed {processed_count} aged batches")
- return {
- "success": True,
- "processed_count": processed_count,
- "notification_types": [nt.value for nt in notification_types],
- "timestamp": current_time.isoformat(),
- }
-
- except Exception as e:
- logger.exception(f"Error processing batches: {e}")
- return {
- "success": False,
- "error": str(e),
- "notification_types": [nt.value for nt in notification_types],
- "timestamp": datetime.now(tz=timezone.utc).isoformat(),
- }
+ Done callbacks are dispatched via `call_soon`, so a task that finished
+ just before the next tick can have its callback run *after* the
+ successor is registered. Popping by name alone would clear the guard
+ out from under a pass that is still running.
+ """
+ name = task.get_name()
+ if self._passes.get(name) is task:
+ del self._passes[name]
+ if task.cancelled():
+ # Shutdown cancels these; `task.exception()` would re-raise the
+ # CancelledError inside the done-callback.
+ return
+ if (exc := task.exception()) is not None:
+ logger.error(f"Scheduled pass {name} failed: {exc}", exc_info=exc)
@expose
async def discord_system_alert(
@@ -461,585 +178,172 @@ class NotificationManager(AppService):
@expose
async def send_email_or_raise(self, to: str, subject: str, body: str):
- """Send a one-off transactional email (e.g. Better Auth password-reset
- links forwarded by the REST API) through this service's Postmark
- credential. Deliberately not wrapped in try/except: a delivery failure
- must propagate to the RPC caller so it can surface the error instead
- of reporting "email sent" for an undeliverable message."""
- # send_email_or_raise wraps a blocking Postmark HTTP call; run it off
- # the event loop so it can't stall the notification service.
+ """One-off transactional email (e.g. Better Auth password-reset links
+ forwarded by the REST API). Deliberately not wrapped in try/except: a
+ delivery failure must reach the RPC caller."""
await asyncio.to_thread(
self.email_sender.send_email_or_raise, to, subject, body
)
- async def _queue_scheduled_notification(self, event: SummaryParamsEventModel):
- """Queue a scheduled notification - exposed method for other services to call"""
- try:
- logger.info(
- f"Queueing scheduled notification type={event.type} user_id={event.user_id}"
- )
-
- exchange = "notifications"
- routing_key = get_routing_key(event.type)
- logger.info(f"Using routing key: {routing_key}")
-
- # Publish to RabbitMQ
- await self.rabbit.publish_message(
- routing_key=routing_key,
- message=event.model_dump_json(),
- exchange=next(ex for ex in EXCHANGES if ex.name == exchange),
- )
- logger.info(f"Successfully queued notification for user {event.user_id}")
-
- except Exception as e:
- logger.exception(f"Error queueing notification: {e}")
-
- async def _should_email_user_based_on_preference(
- self, user_id: str, event_type: NotificationType
- ) -> bool:
- """Check if a user wants to receive a notification based on their preferences and email verification status"""
- validated_email = await get_database_manager_async_client(
- should_retry=False
- ).get_user_email_verification(user_id)
- preference = (
- await get_database_manager_async_client(
- should_retry=False
- ).get_user_notification_preference(user_id)
- ).preferences.get(event_type, True)
- # only if both are true, should we email this person
- return validated_email and preference
-
- async def _gather_summary_data(
- self, user_id: str, event_type: NotificationType, params: BaseSummaryParams
- ) -> BaseSummaryData:
- """Gathers the data to build a summary notification"""
-
- logger.info(
- f"Gathering summary data for {user_id} and {event_type} with {params=}"
- )
-
- try:
- # Get summary data from the database
- summary_data = await get_database_manager_async_client(
- should_retry=False
- ).get_user_execution_summary_data(
- user_id=user_id,
- start_time=params.start_date,
- end_time=params.end_date,
- )
-
- # Extract data from summary
- total_credits_used = summary_data.total_credits_used
- total_executions = summary_data.total_executions
- most_used_agent = summary_data.most_used_agent
- successful_runs = summary_data.successful_runs
- failed_runs = summary_data.failed_runs
- total_execution_time = summary_data.total_execution_time
- average_execution_time = summary_data.average_execution_time
- cost_breakdown = summary_data.cost_breakdown
-
- if event_type == NotificationType.DAILY_SUMMARY and isinstance(
- params, DailySummaryParams
- ):
- return DailySummaryData(
- total_credits_used=total_credits_used,
- total_executions=total_executions,
- most_used_agent=most_used_agent,
- total_execution_time=total_execution_time,
- successful_runs=successful_runs,
- failed_runs=failed_runs,
- average_execution_time=average_execution_time,
- cost_breakdown=cost_breakdown,
- date=params.date,
- )
- elif event_type == NotificationType.WEEKLY_SUMMARY and isinstance(
- params, WeeklySummaryParams
- ):
- return WeeklySummaryData(
- total_credits_used=total_credits_used,
- total_executions=total_executions,
- most_used_agent=most_used_agent,
- total_execution_time=total_execution_time,
- successful_runs=successful_runs,
- failed_runs=failed_runs,
- average_execution_time=average_execution_time,
- cost_breakdown=cost_breakdown,
- start_date=params.start_date,
- end_date=params.end_date,
- )
- else:
- raise ValueError("Invalid event type or params")
-
- except Exception as e:
- logger.warning(f"Failed to gather summary data: {e}")
- # Return sensible defaults in case of error
- if event_type == NotificationType.DAILY_SUMMARY and isinstance(
- params, DailySummaryParams
- ):
- return DailySummaryData(
- total_credits_used=0.0,
- total_executions=0,
- most_used_agent="No data available",
- total_execution_time=0.0,
- successful_runs=0,
- failed_runs=0,
- average_execution_time=0.0,
- cost_breakdown={},
- date=params.date,
- )
- elif event_type == NotificationType.WEEKLY_SUMMARY and isinstance(
- params, WeeklySummaryParams
- ):
- return WeeklySummaryData(
- total_credits_used=0.0,
- total_executions=0,
- most_used_agent="No data available",
- total_execution_time=0.0,
- successful_runs=0,
- failed_runs=0,
- average_execution_time=0.0,
- cost_breakdown={},
- start_date=params.start_date,
- end_date=params.end_date,
- )
- else:
- raise ValueError("Invalid event type or params") from e
-
- async def _should_batch(
- self, user_id: str, event_type: NotificationType, event: NotificationEventModel
- ) -> bool:
-
- await get_database_manager_async_client(
- should_retry=False
- ).create_or_add_to_user_notification_batch(user_id, event_type, event)
-
- oldest_message = await get_database_manager_async_client(
- should_retry=False
- ).get_user_notification_oldest_message_in_batch(user_id, event_type)
- if not oldest_message:
- logger.warning(
- f"Batch for user {user_id} and type {event_type} "
- f"has no oldest message — batch may have been cleared concurrently"
- )
- return False
- oldest_age = oldest_message.created_at
-
- max_delay = get_batch_delay(event_type)
-
- if oldest_age + max_delay < datetime.now(tz=timezone.utc):
- logger.info(f"Batch for user {user_id} and type {event_type} is old enough")
- return True
- logger.info(
- f"Batch for user {user_id} and type {event_type} is not old enough: {oldest_age + max_delay} < {datetime.now(tz=timezone.utc)} max_delay={max_delay}"
- )
- return False
-
- def _parse_message(self, message: str) -> NotificationEventModel | None:
- try:
- event = BaseEventModel.model_validate_json(message)
- return NotificationEventModel[
- get_notif_data_type(event.type)
- ].model_validate_json(message)
- except Exception as e:
- logger.warning(f"Error parsing message due to non matching schema {e}")
- return None
+ # ── consumers ───────────────────────────────────────────────────────
- async def _process_admin_message(self, message: str) -> bool:
- """Process an admin notification.
-
- Returns False for permanent failures (e.g. unparseable message) — the
- consumer treats False as "do not retry, send to DLQ". Transient
- failures (DB blip, Postmark 5xx, network timeout) propagate as
- exceptions so the consumer's retry-with-backoff loop can recover.
- """
+ async def _process_user_notification(self, message: str) -> bool:
+ """A customer-facing notification. Returns False for permanent failures
+ (the consumer sends those straight to the DLQ); transient failures
+ propagate so the retry-with-backoff loop can recover."""
event = self._parse_message(message)
if not event:
return False
- logger.debug(f"Processing notification for admin: {event}")
- recipient_email = settings.config.refund_notification_email
- await self.email_sender.send_templated(event.type, recipient_email, event)
- return True
-
- async def _process_immediate(self, message: str) -> bool:
- """Process an immediate notification.
- See `_process_admin_message` for the False vs. raise contract.
- """
- event = self._parse_message(message)
- if not event:
- return False
- logger.debug(f"Processing immediate notification: {event}")
-
- recipient_email = await get_database_manager_async_client(
+ preference = await get_database_manager_async_client(
should_retry=False
- ).get_user_email_by_id(event.user_id)
- if not recipient_email:
+ ).get_user_notification_preference(event.user_id)
+ if not preference.email:
logger.warning(f"User email not found for user {event.user_id}")
return False
- should_send = await self._should_email_user_based_on_preference(
- event.user_id, event.type
- )
- if not should_send:
+ verified = await get_database_manager_async_client(
+ should_retry=False
+ ).get_user_email_verification(event.user_id)
+ if not verified or not wants_notification(preference, event.type):
logger.debug(
- f"User {event.user_id} does not want to receive {event.type} notifications"
+ f"Skipping {event.type} for user {event.user_id}: not wanted or "
+ "unverified"
)
return True
- unsub_link = generate_unsubscribe_link(event.user_id)
+ # The volume knob's own ceiling, across every product notification.
+ # Service messages are exempt for the same reason they ignore the rest
+ # of the preferences: they are about the customer's account, and a
+ # payment failure has to reach them whatever their inbox settings say.
+ if event.type not in SERVICE_MESSAGES and not await claim_daily_send(
+ event.user_id, preference.daily_limit, _utc_today()
+ ):
+ logger.info(
+ f"Skipping {event.type} for user {event.user_id}: at their "
+ f"limit of {preference.daily_limit} emails a day"
+ )
+ # Acked, not retried: tomorrow's send is a new decision, and a
+ # redelivery today would only be refused again.
+ return True
- await self.email_sender.send_templated(
- notification=event.type,
- user_email=recipient_email,
- data=event,
- user_unsub_link=unsub_link,
+ await self.email_sender.send_notification(
+ notification_type=event.type,
+ user_email=preference.email,
+ data=event.data,
+ unsubscribe_link=generate_unsubscribe_link(event.user_id),
+ volume_links={
+ c: generate_preference_link(event.user_id, c) for c in FOOTER_CHOICES
+ },
)
return True
- async def _process_batch(self, message: str) -> bool:
- """Process a batched notification.
-
- See `_process_admin_message` for the False vs. raise contract. The
- inner per-chunk try/except below intentionally absorbs Postmark API
- errors (406/422/oversized) so one bad notification doesn't kill the
- rest of the batch — those are permanent failures, not transient.
- Anything outside that inner block (DB calls, template load) is left
- to bubble up so the consumer's retry loop can recover.
- """
+ async def _process_ops_notification(self, message: str) -> bool:
+ """Internal mail to the refunds team. No preference gating: it is not
+ opt-in mail, and it carries no unsubscribe."""
event = self._parse_message(message)
if not event:
return False
- logger.info(f"Processing batch notification: {event}")
-
- recipient_email = await get_database_manager_async_client(
- should_retry=False
- ).get_user_email_by_id(event.user_id)
- if not recipient_email:
- logger.warning(f"User email not found for user {event.user_id}")
- return False
-
- should_send = await self._should_email_user_based_on_preference(
- event.user_id, event.type
+ recipient = settings.config.refund_notification_email
+ await self.email_sender.send_notification(
+ notification_type=event.type,
+ user_email=recipient,
+ data=event.data,
+ unsubscribe_link="",
)
- if not should_send:
- logger.info(
- f"User {event.user_id} does not want to receive {event.type} notifications"
- )
- return True
+ return True
- should_send = await self._should_batch(event.user_id, event.type, event)
+ async def _process_pass_work(self, message: str) -> bool:
+ """One user's share of a scheduled pass.
- if not should_send:
- # The notification has already been persisted into the batch in
- # _should_batch. Ack the queue message — the next message for
- # this user/type, or the periodic flush, will deliver the batch
- # once it matures. Returning False here would DLQ the trigger.
- logger.info("Batch not old enough to send (notification persisted)")
- return True
- batch = await get_database_manager_async_client(
- should_retry=False
- ).get_user_notification_batch(event.user_id, event.type)
- if not batch or not batch.notifications:
- logger.warning(f"Batch not found for user {event.user_id}")
+ Idempotent by construction: `run_pass_work` claims the user plus the
+ period before it does anything, so a redelivery is a no-op rather than
+ a second email. A transient failure propagates so the retry loop can
+ recover; an unparseable message is permanent and goes to the DLQ.
+ """
+ try:
+ event = PassWorkEvent.model_validate_json(message)
+ except ValueError as e:
+ logger.warning(f"Unparseable pass work (sending to DLQ): {e}")
return False
- unsub_link = generate_unsubscribe_link(event.user_id)
-
- batch_messages = [
- NotificationEventModel[get_notif_data_type(db_event.type)].model_validate(
- {
- "id": db_event.id, # Include ID from database
- "user_id": event.user_id,
- "type": db_event.type,
- "data": db_event.data,
- "created_at": db_event.created_at,
- }
- )
- for db_event in batch.notifications
- ]
-
- # Split batch into chunks to avoid exceeding email size limits
- # Start with a reasonable chunk size and adjust dynamically
- MAX_EMAIL_SIZE = 4_500_000 # 4.5MB to leave buffer under 5MB limit
- chunk_size = 100 # Initial chunk size
- successfully_sent_count = 0
- failed_indices = []
-
- i = 0
- while i < len(batch_messages):
- # Try progressively smaller chunks if needed
- chunk_sent = False
- for attempt_size in [chunk_size, 50, 25, 10, 5, 1]:
- chunk = batch_messages[i : i + attempt_size]
- chunk_ids = [
- msg.id for msg in chunk if msg.id
- ] # Extract IDs for removal
-
- try:
- # Try to render the email to check its size
- template = self.email_sender._get_template(event.type)
- (
- _,
- test_message,
- ) = await self.email_sender.formatter.format_email(
- base_template=template.base_template,
- subject_template=template.subject_template,
- content_template=template.body_template,
- data={"notifications": chunk},
- unsubscribe_link=f"{self.email_sender.formatter.env.globals.get('base_url', '')}/profile/settings",
- )
-
- if len(test_message) < MAX_EMAIL_SIZE:
- # Size is acceptable, send the email
- logger.info(
- f"Sending email with {len(chunk)} notifications "
- f"(size: {len(test_message):,} chars)"
- )
-
- await self.email_sender.send_templated(
- notification=event.type,
- user_email=recipient_email,
- data=chunk,
- user_unsub_link=unsub_link,
- )
-
- # Remove successfully sent notifications immediately
- if chunk_ids:
- try:
- await get_database_manager_async_client(
- should_retry=False
- ).remove_notifications_from_batch(
- event.user_id, event.type, chunk_ids
- )
- logger.info(
- f"Removed {len(chunk_ids)} sent notifications from batch"
- )
- except Exception as e:
- logger.warning(
- f"Failed to remove sent notifications: {e}"
- )
- # Continue anyway - better to risk duplicates than lose emails
-
- # Track successful sends
- successfully_sent_count += len(chunk)
-
- # Update chunk_size for next iteration based on success
- if (
- attempt_size == chunk_size
- and len(test_message) < MAX_EMAIL_SIZE * 0.7
- ):
- # If we're well under limit, try larger chunks next time
- chunk_size = min(chunk_size + 10, 100)
- elif len(test_message) > MAX_EMAIL_SIZE * 0.9:
- # If we're close to limit, use smaller chunks
- chunk_size = max(attempt_size - 10, 1)
-
- i += len(chunk)
- chunk_sent = True
- break
- else:
- # Message is too large even after size reduction
- if attempt_size == 1:
- logger.warning(
- f"Failed to send notification at index {i}: "
- f"Single notification exceeds email size limit "
- f"({len(test_message):,} chars > {MAX_EMAIL_SIZE:,} chars). "
- f"Removing permanently from batch - will not retry."
- )
-
- # Remove the oversized notification permanently - it will NEVER fit
- if chunk_ids:
- try:
- await get_database_manager_async_client(
- should_retry=False
- ).remove_notifications_from_batch(
- event.user_id, event.type, chunk_ids
- )
- logger.info(
- f"Removed oversized notification {chunk_ids[0]} from batch permanently"
- )
- except Exception as e:
- logger.warning(
- f"Failed to remove oversized notification: {e}"
- )
-
- failed_indices.append(i)
- i += 1
- chunk_sent = True
- break
- # Try smaller chunk size
- continue
- except Exception as e:
- # Check if it's a Postmark API error
- if attempt_size == 1:
- # Single notification failed - determine the actual cause
- error_message = str(e).lower()
- error_type = type(e).__name__
-
- # Check for HTTP 406 - Inactive recipient (common in Postmark errors)
- if "406" in error_message or "inactive" in error_message:
- logger.warning(
- f"Failed to send notification at index {i}: "
- f"Recipient marked as inactive by Postmark. "
- f"Error: {e}. Disabling ALL notifications for this user."
- )
-
- # 1. Mark email as unverified
- try:
- await set_user_email_verification(event.user_id, False)
- logger.info(
- f"Set email verification to false for user {event.user_id}"
- )
- except Exception as deactivation_error:
- logger.warning(
- f"Failed to deactivate email for user {event.user_id}: "
- f"{deactivation_error}"
- )
-
- # 2. Disable all notification preferences
- try:
- await disable_all_user_notifications(event.user_id)
- logger.info(
- f"Disabled all notification preferences for user {event.user_id}"
- )
- except Exception as disable_error:
- logger.warning(
- f"Failed to disable notification preferences: {disable_error}"
- )
-
- # 3. Clear ALL notification batches for this user
- try:
- await get_database_manager_async_client(
- should_retry=False
- ).clear_all_user_notification_batches(event.user_id)
- logger.info(
- f"Cleared ALL notification batches for user {event.user_id}"
- )
- except Exception as remove_error:
- logger.warning(
- f"Failed to clear batches for inactive recipient: {remove_error}"
- )
-
- # Stop processing - we've nuked everything for this user
- return True
- # Check for HTTP 422 - Malformed data
- elif "422" in error_message or "unprocessable" in error_message:
- logger.warning(
- f"Failed to send notification at index {i}: "
- f"Malformed notification data rejected by Postmark. "
- f"Error: {e}. Removing from batch permanently."
- )
-
- # Remove from batch - 422 means bad data that won't fix itself
- if chunk_ids:
- try:
- await get_database_manager_async_client(
- should_retry=False
- ).remove_notifications_from_batch(
- event.user_id, event.type, chunk_ids
- )
- logger.info(
- "Removed malformed notification from batch permanently"
- )
- except Exception as remove_error:
- logger.warning(
- f"Failed to remove malformed notification: {remove_error}"
- )
- # Check if it's a ValueError for size limit
- elif isinstance(e, ValueError) and "too large" in error_message:
- logger.warning(
- f"Failed to send notification at index {i}: "
- f"Notification size exceeds email limit. "
- f"Error: {e}. Skipping this notification."
- )
- # Other API errors
- else:
- logger.warning(
- f"Failed to send notification at index {i}: "
- f"Email API error ({error_type}): {e}. "
- f"Skipping this notification."
- )
-
- failed_indices.append(i)
- i += 1
- chunk_sent = True
- break
- # Try smaller chunk
- continue
-
- if not chunk_sent:
- # Should not reach here due to single notification handling
- logger.warning(f"Failed to send notifications starting at index {i}")
- failed_indices.append(i)
- i += 1
+ await briefing_runner.run_pass_work(event)
+ return True
- # Check what remains in the batch (notifications are removed as sent)
- remaining_batch = await get_database_manager_async_client(
- should_retry=False
- ).get_user_notification_batch(event.user_id, event.type)
+ async def _process_audience_change(self, message: str) -> bool:
+ try:
+ event = AudienceEventModel.model_validate_json(message)
+ except ValueError as e:
+ logger.warning(f"Unparseable audience change (sending to DLQ): {e}")
+ return False
- if not remaining_batch or not remaining_batch.notifications:
- logger.info(
- f"All {successfully_sent_count} notifications sent and removed from batch"
- )
- else:
- remaining_count = len(remaining_batch.notifications)
- logger.warning(
- f"Sent {successfully_sent_count} notifications. "
- f"{remaining_count} remain in batch for retry due to errors."
- )
+ handler = {
+ AudienceAction.ENROLL_TOUR: mailerlite.enroll_in_onboarding,
+ AudienceAction.ADD_CHANGELOG: mailerlite.add_to_changelog,
+ AudienceAction.REMOVE_CHANGELOG: mailerlite.remove_from_changelog,
+ }[event.action]
+ await handler(event.email)
return True
- async def _process_summary(self, message: str) -> bool:
- """Process a summary notification.
-
- See `_process_admin_message` for the False vs. raise contract.
- """
- logger.info(f"Processing summary notification: {message}")
+ def _parse_message(self, message: str) -> NotificationEventModel | None:
try:
event = BaseEventModel.model_validate_json(message)
- model = SummaryParamsEventModel[
- get_summary_params_type(event.type)
+ return NotificationEventModel[
+ get_notif_data_type(event.type)
].model_validate_json(message)
- except ValueError as e:
- logger.warning(f"Unparseable summary notification (sending to DLQ): {e}")
- return False
+ except Exception as e:
+ logger.warning(f"Error parsing message due to non matching schema {e}")
+ return None
- logger.info(f"Processing summary notification: {model}")
+ # ── service lifecycle ───────────────────────────────────────────────
- recipient_email = await get_database_manager_async_client(
- should_retry=False
- ).get_user_email_by_id(event.user_id)
- if not recipient_email:
- logger.warning(f"User email not found for user {event.user_id}")
- return False
- should_send = await self._should_email_user_based_on_preference(
- event.user_id, event.type
+ def run_service(self):
+ self._run_service_future = asyncio.run_coroutine_threadsafe(
+ self._run_service_with_task_reference(), self.shared_event_loop
)
- if not should_send:
- logger.info(
- f"User {event.user_id} does not want to receive {event.type} notifications"
- )
- return True
+ super().run_service()
- summary_data = await self._gather_summary_data(
- event.user_id, event.type, model.data
- )
+ async def _run_service_with_task_reference(self) -> None:
+ task = asyncio.current_task()
+ if task is None:
+ raise RuntimeError("Notification service did not start in an asyncio task")
+ self._run_service_task = task
+ try:
+ await self._run_service()
+ finally:
+ if self._run_service_task is task:
+ self._run_service_task = None
- unsub_link = generate_unsubscribe_link(event.user_id)
+ @continuous_retry()
+ async def _run_service(self):
+ logger.info(f"[{self.service_name}] ⏳ Configuring RabbitMQ...")
+ self.rabbitmq_service = rabbitmq.AsyncRabbitMQ(self.rabbitmq_config)
+ await self.rabbitmq_service.connect()
+ logger.info(f"[{self.service_name}] Started notification service")
- data = NotificationEventModel(
- user_id=event.user_id,
- type=event.type,
- data=summary_data,
- )
+ channel = await self.rabbit.get_channel()
+ await channel.set_qos(prefetch_count=10)
- await self.email_sender.send_templated(
- notification=event.type,
- user_email=recipient_email,
- data=data,
- user_unsub_link=unsub_link,
- )
- return True
+ consumers = {
+ USER_NOTIFICATIONS_QUEUE: self._process_user_notification,
+ OPS_NOTIFICATIONS_QUEUE: self._process_ops_notification,
+ AUDIENCE_QUEUE: self._process_audience_change,
+ PASS_WORK_QUEUE: self._process_pass_work,
+ }
+ tasks = [
+ asyncio.create_task(
+ self._consume_queue(await channel.get_queue(name), handler, name)
+ )
+ for name, handler in consumers.items()
+ ]
+
+ try:
+ await asyncio.gather(*tasks)
+ except asyncio.CancelledError:
+ logger.info("Service shutdown requested")
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ raise
async def _consume_queue(
self,
@@ -1047,15 +351,7 @@ class NotificationManager(AppService):
process_func: Callable[[str], Awaitable[bool]],
queue_name: str,
):
- """Continuously consume messages from a queue using async iteration.
-
- On transient failures (raised exceptions), retry in-process with
- exponential backoff up to MAX_CONSUMER_RETRY_ATTEMPTS times before
- rejecting to the DLQ. process_func returning False means
- "unrecoverable, do not retry" — reject immediately.
- """
logger.info(f"Starting consumer for queue: {queue_name}")
-
try:
async with queue.iterator() as queue_iter:
async for message in queue_iter:
@@ -1077,30 +373,20 @@ class NotificationManager(AppService):
process_func: Callable[[str], Awaitable[bool]],
queue_name: str,
):
- """Run process_func against one message with retry-with-backoff.
+ """Acks on success, rejects (no requeue → DLQ) on permanent failure or
+ after exhausting retries.
- Acks on success, rejects (no requeue → DLQ) on permanent failure or
- after exhausting retry attempts.
-
- ``process_func`` MUST be idempotent: the same message body is replayed
- on each attempt, so a partial-success on one attempt (e.g. Postmark
- accepted the email but the database commit failed afterwards) will
- re-run on retry. The notification consumers tolerate this because
- their permanent side-effect (Postmark send) is the last step before
- ack, but anyone wiring a new ``process_func`` here must keep the
- contract or risk duplicate sends.
+ ``process_func`` MUST be idempotent: the same body is replayed on each
+ attempt, so a partial success (Postmark accepted the email but a later
+ write failed) re-runs on retry.
"""
last_error: Exception | None = None
for attempt in range(MAX_CONSUMER_RETRY_ATTEMPTS):
try:
- # Decoding inside the try so a UnicodeDecodeError on a
- # malformed body is treated as a permanent failure and goes
- # to the DLQ instead of crashing the consumer task.
body = message.body.decode()
if await process_func(body):
await message.ack()
return
- # process_func returned False = explicit "do not retry"
logger.warning(
f"Message in {queue_name} rejected (process_func returned False)"
)
@@ -1114,8 +400,7 @@ class NotificationManager(AppService):
return
except Exception as e:
last_error = e
- is_last_attempt = attempt == MAX_CONSUMER_RETRY_ATTEMPTS - 1
- if is_last_attempt:
+ if attempt == MAX_CONSUMER_RETRY_ATTEMPTS - 1:
break
delay = CONSUMER_RETRY_BACKOFF_SECONDS * (2**attempt)
logger.warning(
@@ -1124,7 +409,6 @@ class NotificationManager(AppService):
f"Retrying in {delay}s.",
)
await asyncio.sleep(delay)
- # All retries exhausted — log full context and send to DLQ.
logger.exception(
f"Sending message to DLQ from {queue_name} after "
f"{MAX_CONSUMER_RETRY_ATTEMPTS} attempts. Last error: {last_error}",
@@ -1132,99 +416,10 @@ class NotificationManager(AppService):
)
await message.reject(requeue=False)
- def run_service(self):
- # Queue the main _run_service task
- # Keep the concurrent Future alive for as long as the manager. asyncio's
- # event loop only keeps weak references to tasks, so discarding this
- # handle can garbage-collect the pending RabbitMQ connection task.
- self._run_service_future = asyncio.run_coroutine_threadsafe(
- self._run_service_with_task_reference(), self.shared_event_loop
- )
-
- # Start the main event loop
- super().run_service()
-
- async def _run_service_with_task_reference(self) -> None:
- """Retain the asyncio task so cleanup can await its full cancellation."""
- task = asyncio.current_task()
- if task is None:
- raise RuntimeError("Notification service did not start in an asyncio task")
- self._run_service_task = task
- try:
- await self._run_service()
- finally:
- if self._run_service_task is task:
- self._run_service_task = None
-
- @continuous_retry()
- async def _run_service(self):
- logger.info(f"[{self.service_name}] ⏳ Configuring RabbitMQ...")
- self.rabbitmq_service = rabbitmq.AsyncRabbitMQ(self.rabbitmq_config)
- await self.rabbitmq_service.connect()
-
- logger.info(f"[{self.service_name}] Started notification service")
-
- # Set up queue consumers with QoS settings
- channel = await self.rabbit.get_channel()
-
- # Set prefetch to prevent overwhelming the service
- await channel.set_qos(prefetch_count=10)
-
- immediate_queue = await channel.get_queue(IMMEDIATE_NOTIFICATIONS_QUEUE)
- batch_queue = await channel.get_queue(BATCH_NOTIFICATIONS_QUEUE)
- admin_queue = await channel.get_queue(ADMIN_NOTIFICATIONS_QUEUE)
- summary_queue = await channel.get_queue(SUMMARY_NOTIFICATIONS_QUEUE)
-
- # Create consumer tasks for each queue - running in parallel
- consumer_tasks = [
- asyncio.create_task(
- self._consume_queue(
- queue=immediate_queue,
- process_func=self._process_immediate,
- queue_name=IMMEDIATE_NOTIFICATIONS_QUEUE,
- )
- ),
- asyncio.create_task(
- self._consume_queue(
- queue=admin_queue,
- process_func=self._process_admin_message,
- queue_name=ADMIN_NOTIFICATIONS_QUEUE,
- )
- ),
- asyncio.create_task(
- self._consume_queue(
- queue=batch_queue,
- process_func=self._process_batch,
- queue_name=BATCH_NOTIFICATIONS_QUEUE,
- )
- ),
- asyncio.create_task(
- self._consume_queue(
- queue=summary_queue,
- process_func=self._process_summary,
- queue_name=SUMMARY_NOTIFICATIONS_QUEUE,
- )
- ),
- ]
-
- try:
- # Run all consumers concurrently
- await asyncio.gather(*consumer_tasks)
- except asyncio.CancelledError:
- logger.info("Service shutdown requested")
- # Cancel all consumer tasks
- for task in consumer_tasks:
- task.cancel()
- # Wait for all tasks to complete cancellation
- await asyncio.gather(*consumer_tasks, return_exceptions=True)
- raise
-
async def _shutdown_service(self) -> None:
"""Stop consumers completely before closing their RabbitMQ connection."""
service_future = self._run_service_future
service_task = self._run_service_task
- # Cleanup can race the tracked coroutine's first loop turn. Yield until
- # it records the actual asyncio task or its scheduling proxy completes.
while (
service_task is None
and service_future is not None
@@ -1236,8 +431,6 @@ class NotificationManager(AppService):
if service_task is not None and service_task is not asyncio.current_task():
if not service_task.done():
service_task.cancel()
- # Bounded wait: a consumer stuck unwinding (e.g. awaiting a broker
- # reply on a dead connection) must not hang shutdown forever.
_, pending = await asyncio.wait(
[service_task], timeout=SHUTDOWN_TIMEOUT_SECONDS
)
@@ -1249,10 +442,6 @@ class NotificationManager(AppService):
if self.rabbitmq_service is not None:
logger.info("⏳ Disconnecting RabbitMQ...")
- # asyncio.wait (not wait_for): on timeout, wait_for would cancel
- # the disconnect and then await that cancellation, so a
- # cancellation-resistant disconnect could still hang shutdown.
- # wait() returns at the deadline and abandons the task instead.
disconnect_task = asyncio.ensure_future(self.rabbitmq_service.disconnect())
_, pending = await asyncio.wait(
[disconnect_task], timeout=SHUTDOWN_TIMEOUT_SECONDS
@@ -1270,18 +459,10 @@ class NotificationManager(AppService):
logger.warning(f"RabbitMQ disconnect failed during shutdown: {exc}")
def cleanup(self):
- """Cleanup service resources."""
self.running = False
try:
- # Use one coroutine as a shutdown barrier. Cancelling only the
- # concurrent Future marks that proxy done before the underlying
- # asyncio task and its consumer children have finished unwinding.
shutdown = self._shutdown_service()
if self.shared_event_loop.is_closed():
- # The loop thread already stopped and closed the loop (loop
- # crash or repeated cleanup): every task on it is gone, and
- # both scheduling paths below would raise "Event loop is
- # closed" instead of shutting down.
shutdown.close()
logger.warning(
"Event loop is already closed; "
@@ -1289,10 +470,6 @@ class NotificationManager(AppService):
)
elif self.shared_event_loop.is_running():
try:
- # Each stage of _shutdown_service is already bounded by
- # SHUTDOWN_TIMEOUT_SECONDS; this outer deadline only fires
- # when the loop stops before ever servicing the barrier,
- # which would otherwise block .result() forever.
self.run_and_wait(shutdown, timeout=CLEANUP_TIMEOUT_SECONDS)
except FutureTimeoutError:
logger.warning(
@@ -1300,8 +477,6 @@ class NotificationManager(AppService):
f"{CLEANUP_TIMEOUT_SECONDS}s; continuing cleanup"
)
except RuntimeError as e:
- # The loop closed between the is_closed() check above and
- # the scheduling call; nothing is left to shut down.
shutdown.close()
logger.warning(f"Could not run notification service shutdown: {e}")
else:
@@ -1317,9 +492,7 @@ class NotificationManagerClient(AppServiceClient):
def get_service_type(cls):
return NotificationManager
- process_existing_batches = endpoint_to_sync(
- NotificationManager.process_existing_batches
- )
- queue_weekly_summary = endpoint_to_sync(NotificationManager.queue_weekly_summary)
+ flush_matured_alerts = endpoint_to_sync(NotificationManager.flush_matured_alerts)
+ send_due_briefings = endpoint_to_sync(NotificationManager.send_due_briefings)
discord_system_alert = endpoint_to_sync(NotificationManager.discord_system_alert)
send_email_or_raise = endpoint_to_sync(NotificationManager.send_email_or_raise)
diff --git a/autogpt_platform/backend/backend/notifications/notifications_test.py b/autogpt_platform/backend/backend/notifications/notifications_test.py
new file mode 100644
index 0000000000..5e49648281
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/notifications_test.py
@@ -0,0 +1,162 @@
+"""Guards on the two scheduled passes.
+
+The scheduler fires these on a fixed interval and the RPC returns as soon as
+the task is spawned, so a pass that outlives its tick would otherwise overlap
+the next one. Both passes queue their email *before* marking the rows that
+suppress a resend, so an overlap is a duplicate email, not just wasted work.
+"""
+
+import asyncio
+from collections.abc import Iterator
+
+import pytest
+
+from backend.notifications.notifications import NotificationManager
+
+
[email protected](scope="session")
+def server() -> None:
+ return None
+
+
[email protected](scope="session", autouse=True)
+def graph_cleanup() -> Iterator[None]:
+ yield
+
+
+def _manager() -> NotificationManager:
+ """A manager with no service wiring: `_spawn_pass` touches only `_passes`."""
+ manager = NotificationManager.__new__(NotificationManager)
+ manager._passes = {}
+ return manager
+
+
+async def test_a_slow_pass_is_not_started_twice():
+ manager = _manager()
+ started = 0
+ release = asyncio.Event()
+
+ async def slow_pass() -> None:
+ nonlocal started
+ started += 1
+ await release.wait()
+
+ manager._spawn_pass("flush", slow_pass)
+ await asyncio.sleep(0)
+ manager._spawn_pass("flush", slow_pass) # the next tick, while still running
+ await asyncio.sleep(0)
+
+ assert started == 1, "the second tick must not start an overlapping pass"
+
+ release.set()
+ await asyncio.gather(*list(manager._passes.values()))
+
+
+async def test_the_next_tick_runs_once_the_previous_pass_finishes():
+ manager = _manager()
+ started = 0
+
+ async def quick_pass() -> None:
+ nonlocal started
+ started += 1
+
+ manager._spawn_pass("flush", quick_pass)
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+ manager._spawn_pass("flush", quick_pass)
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+
+ assert started == 2
+ assert not manager._passes, "a finished pass must not stay registered"
+
+
+async def test_the_two_passes_do_not_block_each_other():
+ manager = _manager()
+ ran: list[str] = []
+ release = asyncio.Event()
+
+ async def briefings() -> None:
+ ran.append("briefings")
+ await release.wait()
+
+ async def alerts() -> None:
+ ran.append("alerts")
+
+ manager._spawn_pass("send_due_briefings", briefings)
+ await asyncio.sleep(0)
+ manager._spawn_pass("flush_matured_alerts", alerts)
+ await asyncio.sleep(0)
+
+ assert ran == ["briefings", "alerts"]
+
+ release.set()
+ await asyncio.gather(*list(manager._passes.values()))
+
+
+async def test_a_failing_pass_does_not_wedge_the_schedule():
+ """A pass that raises must still clear its slot, or the guard would latch
+ on and silently stop every later tick."""
+ manager = _manager()
+
+ async def boom() -> None:
+ raise RuntimeError("boom")
+
+ manager._spawn_pass("flush", boom)
+ await asyncio.sleep(0)
+ await asyncio.sleep(0)
+
+ assert not manager._passes
+
+ ran = False
+
+ async def after() -> None:
+ nonlocal ran
+ ran = True
+
+ manager._spawn_pass("flush", after)
+ await asyncio.sleep(0)
+ assert ran
+
+
+async def test_a_late_done_callback_does_not_clear_a_running_successor():
+ """Done callbacks fire via `call_soon`, so a task that finished just before
+ the next tick can have its callback run after the successor registers.
+ Clearing by name alone would drop the guard while the successor still runs.
+ """
+ manager = _manager()
+ release = asyncio.Event()
+ started = 0
+
+ async def first() -> None:
+ return None
+
+ async def second() -> None:
+ nonlocal started
+ started += 1
+ await release.wait()
+
+ manager._spawn_pass("flush", first)
+ first_task = manager._passes["flush"]
+ await asyncio.sleep(0)
+ assert first_task.done()
+
+ # Successor registers before the finished task's callback is dispatched.
+ manager._spawn_pass("flush", second)
+ second_task = manager._passes["flush"]
+ assert second_task is not first_task
+
+ await asyncio.sleep(0)
+ assert manager._passes.get("flush") is second_task, "successor was evicted"
+
+ manager._spawn_pass("flush", second)
+ await asyncio.sleep(0)
+ assert started == 1, "guard must still block while the successor runs"
+
+ release.set()
+ await second_task
diff --git a/autogpt_platform/backend/backend/notifications/preferences.py b/autogpt_platform/backend/backend/notifications/preferences.py
new file mode 100644
index 0000000000..89850d6b10
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/preferences.py
@@ -0,0 +1,39 @@
+"""Which notifications a user has asked for.
+
+The volume knob, not a checkbox list: a frequency for the Briefing, a switch
+for Alerts, and a switch for store verdicts. Billing and account messages are
+service mail — they are about the customer's account rather than a promotion,
+so they are sent regardless of these settings.
+"""
+
+from prisma.enums import NotificationType
+
+from backend.data.notifications import NotificationPreference
+
+# Service messages: sent even to someone who has opted out of everything else.
+SERVICE_MESSAGES = frozenset(
+ {
+ NotificationType.SUBSCRIPTION_WELCOME,
+ NotificationType.PAYMENT_FAILED,
+ NotificationType.PAYMENT_FINAL_NOTICE,
+ NotificationType.SUBSCRIPTION_CANCELLED,
+ NotificationType.SUBSCRIPTION_RESUMED,
+ NotificationType.SUBSCRIPTION_ENDED,
+ }
+)
+
+
+def wants_notification(
+ preference: NotificationPreference, notification_type: NotificationType
+) -> bool:
+ if notification_type in SERVICE_MESSAGES:
+ return True
+ if notification_type is NotificationType.BRIEFING:
+ return preference.wants_briefing
+ if notification_type is NotificationType.ALERT:
+ return preference.alerts_enabled
+ if notification_type is NotificationType.VERDICT:
+ return preference.store_verdicts_enabled
+ # Ops mail never reaches this path: it goes to the refunds team, not to a
+ # user with preferences.
+ return True
diff --git a/autogpt_platform/backend/backend/notifications/preferences_test.py b/autogpt_platform/backend/backend/notifications/preferences_test.py
new file mode 100644
index 0000000000..8b22754aa2
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/preferences_test.py
@@ -0,0 +1,44 @@
+"""Service messages are about the customer's account, not a promotion, so the
+volume knob doesn't apply to them."""
+
+import pytest
+from prisma.enums import BriefingFrequency, NotificationType
+
+from backend.data.notifications import NotificationPreference
+from backend.notifications.preferences import SERVICE_MESSAGES, wants_notification
+
+EVERYTHING_OFF = NotificationPreference(
+ user_id="u1",
+ briefing_frequency=BriefingFrequency.OFF,
+ alerts_enabled=False,
+ store_verdicts_enabled=False,
+)
+EVERYTHING_ON = NotificationPreference(
+ user_id="u1",
+ briefing_frequency=BriefingFrequency.WEEKLY,
+ alerts_enabled=True,
+ store_verdicts_enabled=True,
+)
+
+
[email protected]("notification_type", sorted(SERVICE_MESSAGES, key=str))
+def test_billing_messages_are_sent_even_to_someone_who_opted_out(notification_type):
+ assert wants_notification(EVERYTHING_OFF, notification_type)
+
+
+def test_the_briefing_follows_the_frequency():
+ assert wants_notification(EVERYTHING_ON, NotificationType.BRIEFING)
+ assert not wants_notification(EVERYTHING_OFF, NotificationType.BRIEFING)
+
+
+def test_alerts_only_means_alerts_survive_the_digest_being_off():
+ alerts_only = EVERYTHING_OFF.model_copy(update={"alerts_enabled": True})
+ assert not wants_notification(alerts_only, NotificationType.BRIEFING)
+ assert wants_notification(alerts_only, NotificationType.ALERT)
+
+
+def test_store_verdicts_have_their_own_switch():
+ assert wants_notification(EVERYTHING_ON, NotificationType.VERDICT)
+ assert not wants_notification(EVERYTHING_OFF, NotificationType.VERDICT)
diff --git a/autogpt_platform/backend/backend/notifications/queue.py b/autogpt_platform/backend/backend/notifications/queue.py
new file mode 100644
index 0000000000..82caa32761
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/queue.py
@@ -0,0 +1,123 @@
+"""RabbitMQ wiring for notifications.
+
+Three destinations, because there are three genuinely different consumers:
+customer-facing mail, internal ops mail, and MailerLite audience changes. The
+old batch and summary queues are gone with the per-run email and the summary
+digests they carried — the Briefing is assembled on a schedule, not batched
+from queued events.
+"""
+
+import logging
+
+from prisma.enums import NotificationType
+
+from backend.data.notifications import (
+ AudienceEventModel,
+ DeliveryStream,
+ NotificationEventModel,
+ NotificationResult,
+ get_delivery_stream,
+)
+from backend.data.rabbitmq import Exchange, ExchangeType, Queue, RabbitMQConfig
+from backend.util.logging import TruncatedLogger
+
+logger = TruncatedLogger(logging.getLogger(__name__), "[NotificationQueue]")
+
+NOTIFICATION_EXCHANGE = Exchange(name="notifications", type=ExchangeType.TOPIC)
+DEAD_LETTER_EXCHANGE = Exchange(name="dead_letter", type=ExchangeType.TOPIC)
+EXCHANGES = [NOTIFICATION_EXCHANGE, DEAD_LETTER_EXCHANGE]
+
+# ``_v3`` marks the cutover to the redesigned email system: the old queues hold
+# payloads in a shape no current template can render, so they are not reused.
+USER_NOTIFICATIONS_QUEUE = "user_notifications_v3"
+OPS_NOTIFICATIONS_QUEUE = "ops_notifications_v3"
+AUDIENCE_QUEUE = "audience_changes_v3"
+FAILED_NOTIFICATIONS_QUEUE = "failed_notifications_v3"
+# Per-user work fanned out by the scheduled passes: they publish one message
+# per due user and return, so a tick can never run past its own interval.
+PASS_WORK_QUEUE = "notification_work_v3"
+
+_QUORUM = "quorum"
+
+
+def create_notification_config() -> RabbitMQConfig:
+ queues = [
+ _queue(USER_NOTIFICATIONS_QUEUE, "notification.user.#", "failed.user"),
+ _queue(OPS_NOTIFICATIONS_QUEUE, "notification.ops.#", "failed.ops"),
+ _queue(AUDIENCE_QUEUE, "notification.audience.#", "failed.audience"),
+ _queue(PASS_WORK_QUEUE, "notification.work.#", "failed.work"),
+ # DLQ destination — quorum so dead letters survive a broker restart.
+ Queue(
+ name=FAILED_NOTIFICATIONS_QUEUE,
+ exchange=DEAD_LETTER_EXCHANGE,
+ routing_key="failed.#",
+ arguments={"x-queue-type": _QUORUM},
+ ),
+ ]
+ return RabbitMQConfig(exchanges=EXCHANGES, queues=queues)
+
+
+def get_routing_key(event_type: NotificationType) -> str:
+ stream = get_delivery_stream(event_type)
+ destination = "ops" if stream is DeliveryStream.OPS else "user"
+ return f"notification.{destination}.{event_type.value}"
+
+
+async def queue_notification_async(
+ event: NotificationEventModel,
+) -> NotificationResult:
+ """Hand a notification to the sender. Callers never send inline: the
+ consumer owns preference checks, rendering and retries."""
+ return await _publish(get_routing_key(event.type), event.model_dump_json())
+
+
+async def queue_audience_change(event: AudienceEventModel) -> NotificationResult:
+ """Hand a MailerLite audience change to the queue.
+
+ Never call MailerLite inline from a Stripe webhook: an outage there must
+ not fail payment processing.
+ """
+ return await _publish(
+ f"notification.audience.{event.action.value}", event.model_dump_json()
+ )
+
+
+async def queue_pass_work(kind: str, user_id: str, payload: str) -> NotificationResult:
+ """Hand one user's share of a scheduled pass to the work queue.
+
+ The pass itself must stay cheap: it decides *who* is due and publishes,
+ and the consumer decides *what* to send. A pass that did the assembling
+ inline would hold the tick open for as long as the slowest user.
+ """
+ return await _publish(f"notification.work.{kind}", payload)
+
+
+async def _publish(routing_key: str, message: str) -> NotificationResult:
+ try:
+ from backend.util.clients import get_async_notification_queue
+
+ queue = await get_async_notification_queue()
+ await queue.publish_message(
+ routing_key=routing_key,
+ message=message,
+ exchange=NOTIFICATION_EXCHANGE,
+ )
+ return NotificationResult(
+ success=True, message=f"Queued with routing key: {routing_key}"
+ )
+ except Exception as e:
+ logger.exception(f"Error queueing {routing_key}: {e}")
+ return NotificationResult(success=False, message=str(e))
+
+
+def _queue(name: str, routing_key: str, dead_letter_key: str) -> Queue:
+ return Queue(
+ name=name,
+ exchange=NOTIFICATION_EXCHANGE,
+ routing_key=routing_key,
+ arguments={
+ "x-queue-type": _QUORUM,
+ "x-dead-letter-exchange": DEAD_LETTER_EXCHANGE.name,
+ "x-dead-letter-routing-key": dead_letter_key,
+ },
+ )
diff --git a/autogpt_platform/backend/backend/notifications/renderer.py b/autogpt_platform/backend/backend/notifications/renderer.py
new file mode 100644
index 0000000000..bd034f4359
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/renderer.py
@@ -0,0 +1,168 @@
+"""Renders a notification payload into a complete, sendable email.
+
+These templates are complete documents, not content fragments, so they replace
+the old base template *and* the per-type content templates. They are rendered
+directly rather than through the old `bleach.clean()` content path: that
+sanitizer's allow-list has no `<table>`, `<tr>` or `<td>` and would strip the
+entire layout. That is safe here — the sanitizer existed to neutralise HTML
+inside content templates, and every user-supplied value (agent names, reviewer
+comments, refund reasons) is neutralised by Jinja's autoescape, which is the
+correct defence.
+
+The subject template renders first and produces two lines (subject, then
+preheader); both are then passed into the body template.
+"""
+
+import pathlib
+
+from jinja2 import Environment, FileSystemLoader
+from prisma.enums import NotificationType
+from pydantic import BaseModel
+
+from backend.data.notifications import (
+ BaseNotificationData,
+ get_lifecycle_kind,
+ get_template_family,
+)
+from backend.util.settings import Settings
+
+settings = Settings()
+
+TEMPLATE_DIR = pathlib.Path(__file__).parent / "templates"
+
+# Autoescape is the defence for user-supplied values, so it is not optional.
+_html_env = Environment(
+ loader=FileSystemLoader(TEMPLATE_DIR),
+ autoescape=True,
+ trim_blocks=True,
+ lstrip_blocks=True,
+)
+# NB: no trim_blocks here — the subject template's line break between subject
+# and preheader must survive block tags at end-of-line.
+_subject_env = Environment(loader=FileSystemLoader(TEMPLATE_DIR), autoescape=False)
+# The plain-text part is built from the same context, so a text-only client
+# gets the same facts rather than a tag-stripped approximation of the HTML.
+_text_env = Environment(
+ loader=FileSystemLoader(TEMPLATE_DIR),
+ autoescape=False,
+ trim_blocks=True,
+ lstrip_blocks=True,
+)
+
+
+class RenderedEmail(BaseModel):
+ subject: str
+ preheader: str
+ html: str
+ text: str
+
+
+class EmailUrls(BaseModel):
+ """Per-recipient destinations. Kept out of the queued payload so a message
+ that sat in the queue over a deploy still links at today's platform."""
+
+ dashboard: str
+ settings: str
+ unsubscribe: str
+ # The volume knob's five footer links, each signed for this recipient and
+ # that choice. Keyed daily|weekly|monthly|alerts|off.
+ volume: dict[str, str] = {}
+ attention: str
+ billing: str
+ prefs: str
+ marketplace: str
+ docs: str
+ discord: str
+
+
+def build_urls(
+ unsubscribe_link: str, volume: dict[str, str] | None = None
+) -> EmailUrls:
+ base = settings.config.frontend_base_url or settings.config.platform_base_url
+ return EmailUrls(
+ dashboard=f"{base}/library",
+ # The Briefing footer appends ?f=daily|weekly|monthly|alerts|off to
+ # this, and the settings page applies it on load — that is what makes
+ # the volume knob one click rather than a form.
+ settings=f"{base}/settings/account",
+ unsubscribe=unsubscribe_link,
+ volume=volume or {},
+ attention=f"{base}/library?filter=needs-attention",
+ billing=f"{base}/settings/billing",
+ prefs=f"{base}/settings/account",
+ marketplace=f"{base}/marketplace",
+ docs=settings.config.docs_base_url,
+ discord=settings.config.discord_invite_url,
+ )
+
+
+def render(
+ notification_type: NotificationType,
+ data: BaseNotificationData,
+ user_email: str,
+ urls: EmailUrls,
+) -> RenderedEmail:
+ """Render one notification into subject, preheader, HTML and plain text."""
+ family = get_template_family(notification_type)
+ context = _build_context(notification_type, data, user_email, urls)
+
+ subject, preheader = _render_subject(family, context)
+ html = _html_env.get_template(f"{family}.html.j2").render(
+ **context, subject=subject, preheader=preheader
+ )
+ text = _text_env.get_template(f"{family}.txt.j2").render(
+ **context, subject=subject, preheader=preheader
+ )
+ return RenderedEmail(subject=subject, preheader=preheader, html=html, text=text)
+
+
+def _flatten_for_subject(value):
+ """Collapse newlines in every string reachable from the render context."""
+ if isinstance(value, str):
+ return " ".join(value.split())
+ if isinstance(value, dict):
+ return {k: _flatten_for_subject(v) for k, v in value.items()}
+ if isinstance(value, list):
+ return [_flatten_for_subject(v) for v in value]
+ return value
+
+
+def _build_context(
+ notification_type: NotificationType,
+ data: BaseNotificationData,
+ user_email: str,
+ urls: EmailUrls,
+) -> dict:
+ # Dropped rather than passed as None: Jinja's `default` filter fires on
+ # undefined, not on None. Only the top level, so `totals.usd_estimate`
+ # survives for its `is not none` test.
+ context = {k: v for k, v in data.model_dump().items() if v is not None}
+ context["user_email"] = user_email
+ context["urls"] = urls.model_dump()
+ # Hero art is hosted, not inline: Outlook does not render inline SVG, and
+ # Gmail does not display data-URI images.
+ context["assets"] = settings.config.email_asset_base_url.rstrip("/")
+ if kind := get_lifecycle_kind(notification_type):
+ context["kind"] = kind
+ return context
+
+
+def _render_subject(family: str, context: dict) -> tuple[str, str]:
+ """Subject templates render two lines: subject, then preheader.
+
+ The preheader is the lede's second sentence, never "View this email in your
+ browser". A template that emits only one line still returns cleanly.
+
+ The split is positional, so the two lines have to come from the *template*.
+ Interpolated values are flattened first: an agent name containing a newline
+ would otherwise cut the subject short and promote its own remainder into the
+ preheader slot, discarding the intended one. `_subject_env` has autoescape
+ off (a subject is not HTML), so nothing else neutralises it.
+ """
+ rendered = _subject_env.get_template(f"{family}.subject.j2").render(
+ **_flatten_for_subject(context)
+ )
+ lines = [line.strip() for line in rendered.strip().splitlines() if line.strip()]
+ if not lines:
+ raise ValueError(f"{family}.subject.j2 rendered no subject line")
+ return lines[0], (lines[1] if len(lines) > 1 else "")
diff --git a/autogpt_platform/backend/backend/notifications/renderer_test.py b/autogpt_platform/backend/backend/notifications/renderer_test.py
new file mode 100644
index 0000000000..71700a1210
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/renderer_test.py
@@ -0,0 +1,270 @@
+"""Every family renders a complete document, a plain-text twin, and a subject
+that states the news.
+
+These are complete documents rather than content fragments, so the old
+bleach-into-a-base-template path is gone; the guard that user-supplied values
+stay inert is Jinja's autoescape, which is what the injection test below
+checks.
+"""
+
+import pytest
+from prisma.enums import BriefingFrequency, NotificationType
+
+from backend.data.notifications import (
+ AlertData,
+ AlertPrimary,
+ BriefingData,
+ BriefingLedgerRow,
+ BriefingPeriod,
+ BriefingTotals,
+ CardDetails,
+ NotificationPreference,
+ OpsData,
+ PaymentFailedData,
+ PaymentFinalNoticeData,
+ SubscriptionCancelledData,
+ SubscriptionEndedData,
+ SubscriptionPlan,
+ SubscriptionResumedData,
+ SubscriptionWelcomeData,
+ VerdictData,
+ supports_list_unsubscribe,
+)
+from backend.notifications.preferences import SERVICE_MESSAGES, wants_notification
+from backend.notifications.renderer import EmailUrls, render
+
+URLS = EmailUrls(
+ dashboard="https://p.example/library",
+ settings="https://p.example/settings/account",
+ unsubscribe="https://p.example/api/email/unsubscribe?token=x",
+ attention="https://p.example/library?filter=needs-attention",
+ billing="https://p.example/settings/billing",
+ prefs="https://p.example/settings/account",
+ marketplace="https://p.example/marketplace",
+ docs="https://docs.example",
+ discord="https://discord.gg/autogpt",
+)
+PLAN = SubscriptionPlan(
+ name="Pro",
+ cycle="monthly",
+ cycle_noun="month",
+ label="Pro — monthly",
+ price_display="$50.00 / month",
+)
+
+BRIEFING = BriefingData(
+ period=BriefingPeriod(
+ label="Mon 27 Jul – Sun 2 Aug",
+ noun="this week",
+ adjective="week",
+ frequency="weekly",
+ ),
+ totals=BriefingTotals(
+ runs=136,
+ agents_active=1,
+ failed=0,
+ credits_used=21.72,
+ credits_balance=118.28,
+ ),
+ ledger=[BriefingLedgerRow(agent="Lead Scout", runs=136, credits=21.72)],
+)
+ALERT = AlertData(
+ timestamp_label="Thu 6 Aug, 9:26",
+ primary=AlertPrimary(
+ headline="Invoice Chaser is stuck",
+ body="Gmail's connection expired at 9:14.",
+ cta_label="Reconnect Gmail",
+ cta_url="https://p.example/integrations/gmail",
+ subject="Invoice Chaser is stuck — Gmail needs a reconnect",
+ preheader="2 runs skipped; the next try is at 16:00.",
+ ),
+)
+VERDICT = VerdictData(
+ outcome="approved",
+ agent_name="Lead Scout",
+ version=4,
+ reviewer_name="Morgan Reyes",
+ reviewed_at_label="5 August",
+ comments="Clean submission.",
+ store_url="https://p.example/store/lead-scout",
+ share_url="https://p.example/store/lead-scout",
+)
+OPS = OpsData(
+ kind="request",
+ user_name="Priya Natarajan",
+ user_email="[email protected]",
+ user_id="usr_1",
+ transaction_id="txn_1",
+ refund_request_id="rr_1",
+ amount_cents=1200,
+ balance_cents=340,
+ reason="Charged but no output.",
+ recipient="[email protected]",
+ stripe_url="https://dashboard.stripe.com/payments/txn_1",
+ admin_url="https://admin.example/refunds/rr_1",
+ age_label="6 August at 09:14",
+ requested_at_label="6 August at 09:14",
+)
+WELCOME = SubscriptionWelcomeData(user_name="Sam", plan=PLAN, renews_label="8 Sep 2026")
+ENDED = SubscriptionEndedData(
+ user_name="Sam", plan=PLAN, ended_label="8 Aug 2026", due_to_payment=True
+)
+
+ALL = [
+ (NotificationType.BRIEFING, BRIEFING),
+ (NotificationType.ALERT, ALERT),
+ (NotificationType.VERDICT, VERDICT),
+ (NotificationType.OPS, OPS),
+ (NotificationType.SUBSCRIPTION_WELCOME, WELCOME),
+ (NotificationType.SUBSCRIPTION_ENDED, ENDED),
+]
+
+
[email protected]("notification_type,data", ALL)
+def test_every_family_renders_a_complete_document(notification_type, data):
+ email = render(notification_type, data, "[email protected]", URLS)
+ assert email.html.startswith("<!doctype html>")
+ assert "<table" in email.html
+ assert email.html.rstrip().endswith("</html>")
+
+
[email protected]("notification_type,data", ALL)
+def test_every_family_has_a_plain_text_part_from_the_same_data(notification_type, data):
+ email = render(notification_type, data, "[email protected]", URLS)
+ assert len(email.text) > 200
+ assert "<table" not in email.text
+
+
[email protected]("notification_type,data", ALL)
+def test_subjects_state_the_news(notification_type, data):
+ email = render(notification_type, data, "[email protected]", URLS)
+ assert email.subject
+ for banned in ("Summary", "Report", "Update", "Newsletter"):
+ assert banned not in email.subject
+ assert "View this email" not in email.preheader
+
+
+def test_the_briefing_subject_carries_the_actual_numbers():
+ email = render(NotificationType.BRIEFING, BRIEFING, "[email protected]", URLS)
+ assert "136 runs" in email.subject
+
+
+def test_the_footer_offers_a_volume_knob_not_just_a_trapdoor():
+ email = render(NotificationType.BRIEFING, BRIEFING, "[email protected]", URLS)
+ for choice in ("f=daily", "f=monthly", "f=alerts", "f=off"):
+ assert choice in email.html
+
+
+def test_only_the_product_families_carry_one_click_unsubscribe():
+ assert not supports_list_unsubscribe(NotificationType.OPS)
+ for notification_type in (
+ NotificationType.BRIEFING,
+ NotificationType.ALERT,
+ NotificationType.VERDICT,
+ ):
+ assert supports_list_unsubscribe(notification_type)
+
+
[email protected]("notification_type", sorted(SERVICE_MESSAGES, key=str))
+def test_we_never_advertise_an_unsubscribe_we_do_not_honour(notification_type):
+ """A header we cannot act on is a broken unsubscribe.
+
+ Service messages are sent whatever the preferences say, so if one carried
+ List-Unsubscribe the subscriber could click it in Gmail, have every
+ preference switched off, and still keep receiving the mail — on the
+ billing sender's own reputation.
+ """
+ unsubscribed = NotificationPreference(
+ user_id="u1",
+ briefing_frequency=BriefingFrequency.OFF,
+ alerts_enabled=False,
+ store_verdicts_enabled=False,
+ daily_limit=0,
+ )
+ still_sends = wants_notification(unsubscribed, notification_type)
+ assert still_sends, "fixture assumes service mail ignores preferences"
+ assert not supports_list_unsubscribe(notification_type)
+
+
+def test_ops_says_it_is_internal_and_offers_no_unsubscribe():
+ email = render(NotificationType.OPS, OPS, "[email protected]", URLS)
+ assert "Not customer-facing" in email.html
+ assert URLS.unsubscribe not in email.html
+
+
+def test_user_supplied_values_are_escaped_not_executed():
+ hostile = VERDICT.model_copy(update={"agent_name": "<script>alert('x')</script>"})
+ email = render(NotificationType.VERDICT, hostile, "[email protected]", URLS)
+ assert "<script>" not in email.html
+ assert "&lt;script&gt;" in email.html
+
+
+def test_hero_art_is_hosted_rather_than_inlined():
+ email = render(NotificationType.BRIEFING, BRIEFING, "[email protected]", URLS)
+ assert "<img" in email.html
+ assert "data:image" not in email.html
+
+
+def test_a_newline_in_user_data_cannot_hijack_the_preheader():
+ """The subject/preheader split is positional, so the two lines must come
+ from the template. An agent name carrying a newline would otherwise cut the
+ subject short and push its own remainder into the preheader slot."""
+ hostile = VERDICT.model_copy(update={"agent_name": "Lead Scout\nBUY CHEAP PILLS"})
+ email = render(NotificationType.VERDICT, hostile, "[email protected]", URLS)
+
+ assert "\n" not in email.subject
+ assert "BUY CHEAP PILLS" not in email.preheader
+ assert "Lead Scout BUY CHEAP PILLS" in email.subject
+
+
+def test_the_preheader_still_comes_from_the_templates_second_line():
+ """Flattening must not collapse the template's own two lines into one."""
+ email = render(NotificationType.BRIEFING, BRIEFING, "[email protected]", URLS)
+ assert email.subject
+ assert email.preheader
+ assert email.preheader != email.subject
+
+
+SERVICE_PAYLOADS = {
+ NotificationType.SUBSCRIPTION_WELCOME: WELCOME,
+ NotificationType.SUBSCRIPTION_ENDED: ENDED,
+ NotificationType.PAYMENT_FAILED: PaymentFailedData(
+ user_name="Sam",
+ plan=PLAN,
+ amount_display="$50.00",
+ card=CardDetails(brand="Visa", last4="4242"),
+ next_retry_label="11 Aug 2026",
+ ),
+ NotificationType.PAYMENT_FINAL_NOTICE: PaymentFinalNoticeData(
+ user_name="Sam", plan=PLAN, amount_display="$50.00", pauses_label="22 Aug 2026"
+ ),
+ NotificationType.SUBSCRIPTION_CANCELLED: SubscriptionCancelledData(
+ user_name="Sam", plan=PLAN, access_until_label="8 Sep 2026"
+ ),
+ NotificationType.SUBSCRIPTION_RESUMED: SubscriptionResumedData(
+ user_name="Sam", plan=PLAN, renews_label="8 Sep 2026"
+ ),
+}
+
+
[email protected]("notification_type", sorted(SERVICE_MESSAGES, key=str))
+def test_service_mail_offers_preferences_not_an_unsubscribe(notification_type):
+ """The plain-text part has to agree with the header and the HTML.
+
+ Service mail sends whatever the preferences say, so an unsubscribe link in
+ any part of it is a promise we do not keep — it just happened to be the
+ text MIME part that still carried one.
+ """
+ email = render(
+ notification_type, SERVICE_PAYLOADS[notification_type], "[email protected]", URLS
+ )
+
+ assert URLS.unsubscribe not in email.text
+ assert URLS.unsubscribe not in email.html
+ assert URLS.prefs in email.text
+
+
+def test_every_service_message_has_a_payload_here():
+ """Keeps the check above honest if a seventh service type is added."""
+ assert set(SERVICE_PAYLOADS) == set(SERVICE_MESSAGES)
diff --git a/autogpt_platform/backend/backend/notifications/review_alerts.py b/autogpt_platform/backend/backend/notifications/review_alerts.py
new file mode 100644
index 0000000000..62558c9a42
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/review_alerts.py
@@ -0,0 +1,63 @@
+"""Keeping the "waiting on your review" alert in step with reality.
+
+This is one of the conditions the notification surface this replaces could not
+report at all: an agent holding outputs that nothing will send until a human
+approves or dismisses them. Because it is a *state* rather than an event, the
+alert is re-derived from the live count every time the queue changes — so
+approving the last item resolves the condition instead of leaving a stale alert
+behind.
+"""
+
+import logging
+
+from prisma.enums import AlertCause, ReviewStatus
+from prisma.models import PendingHumanReview
+
+from backend.data import alerts as alerts_db
+from backend.data.graph import get_graph_metadata
+from backend.notifications.alert_causes import AwaitingReviewCause
+from backend.util.logging import TruncatedLogger
+
+logger = TruncatedLogger(logging.getLogger(__name__), prefix="[ReviewAlerts]")
+
+
+async def sync_awaiting_review(user_id: str, graph_id: str) -> None:
+ """Raise, update or clear the review-queue alert for one agent.
+
+ Never raises: a notification must not fail the review flow that triggered
+ it.
+ """
+ try:
+ waiting = await PendingHumanReview.prisma().find_many(
+ where={
+ "userId": user_id,
+ "graphId": graph_id,
+ "status": ReviewStatus.WAITING,
+ },
+ order={"createdAt": "asc"},
+ )
+ cause_key = f"awaiting_review:{graph_id}"
+ if not waiting:
+ await alerts_db.resolve_alert_condition(user_id, cause_key)
+ return
+
+ oldest = waiting[0].createdAt
+ metadata = await get_graph_metadata(graph_id=graph_id)
+ cause = AwaitingReviewCause(
+ cta_path=f"/library/agents/{graph_id}/reviews",
+ agent=metadata.name if metadata else f"Agent {graph_id[:8]}",
+ count=len(waiting),
+ since_label=f"{oldest.day} {oldest.strftime('%b')}, {oldest.strftime('%H:%M')}",
+ )
+ await alerts_db.raise_alert_condition(
+ user_id=user_id,
+ cause=AlertCause.AWAITING_REVIEW,
+ cause_key=cause_key,
+ data=cause.model_dump(mode="json"),
+ )
+ except Exception:
+ logger.warning(
+ f"Could not sync the awaiting-review alert for user {user_id} agent "
+ f"{graph_id}",
+ exc_info=True,
+ )
diff --git a/autogpt_platform/backend/backend/notifications/scoring.py b/autogpt_platform/backend/backend/notifications/scoring.py
new file mode 100644
index 0000000000..9cf69156dc
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/scoring.py
@@ -0,0 +1,182 @@
+"""Interestingness scoring for finished runs.
+
+Each completed run is scored once, at completion, from signals the platform
+already has. Scoring at completion is what lets Briefing assembly be a cheap
+ranked read instead of a scan: a user with one agent and a user with two
+hundred agents get emails of roughly the same length, and what changes is the
+compression ratio.
+
+Signals, in the order the design calls them out:
+
+* terminal state — blocked and failed outrank success
+* first-ever success of a newly created agent
+* novel output versus a no-op ("checked, nothing new")
+* cost or duration anomalies against that agent's own baseline
+"""
+
+import logging
+
+from prisma.enums import AgentExecutionStatus
+from prisma.models import AgentGraphExecution
+
+from backend.data.db import query_raw_with_schema
+from backend.util.logging import TruncatedLogger
+
+logger = TruncatedLogger(logging.getLogger(__name__), prefix="[RunScoring]")
+
+# A failed or blocked run always outranks a clean one: the Briefing leads with
+# what needs a decision.
+_STATUS_SCORE: dict[AgentExecutionStatus, float] = {
+ AgentExecutionStatus.FAILED: 0.80,
+ AgentExecutionStatus.TERMINATED: 0.70,
+ AgentExecutionStatus.COMPLETED: 0.30,
+}
+
+FIRST_SUCCESS_BONUS = 0.40
+NOVEL_OUTPUT_BONUS = 0.20
+NO_OP_PENALTY = 0.20
+ANOMALY_BONUS = 0.15
+# How far past its own baseline a run has to go before it counts as an anomaly
+# rather than normal variance.
+ANOMALY_FACTOR = 3.0
+# Enough history for a baseline to mean anything.
+MIN_BASELINE_RUNS = 5
+# How far back the baseline looks. Scoring runs once per finished run, so this
+# has to stay a bounded read.
+BASELINE_WINDOW_RUNS = 200
+
+
+async def score_completed_run(graph_exec_id: str) -> float | None:
+ """Score one finished run and persist it. Never raises: a scoring failure
+ must not fail the run that triggered it."""
+ try:
+ execution = await AgentGraphExecution.prisma().find_unique(
+ where={"id": graph_exec_id}
+ )
+ if execution is None or execution.executionStatus not in _STATUS_SCORE:
+ return None
+
+ stats = dict(execution.stats or {})
+ baseline = await _agent_cost_baseline(execution.agentGraphId, graph_exec_id)
+ first_success = await _is_first_success(
+ execution.agentGraphId, execution.executionStatus, graph_exec_id
+ )
+ score = compute_score(
+ status=execution.executionStatus,
+ cost_cents=_numeric_stat(stats.get("cost")),
+ node_error_count=int(_numeric_stat(stats.get("node_error_count"))),
+ has_activity=bool(stats.get("activity_status")),
+ first_success=first_success,
+ cost_baseline=baseline,
+ )
+ await AgentGraphExecution.prisma().update(
+ where={"id": graph_exec_id}, data={"interestingness": score}
+ )
+ return score
+ except Exception:
+ logger.warning(
+ f"Could not score run {graph_exec_id} for the briefing", exc_info=True
+ )
+ return None
+
+
+def _numeric_stat(value: object) -> float:
+ if isinstance(value, bool):
+ return 0.0
+ if isinstance(value, (int, float)):
+ return float(value)
+ if isinstance(value, str):
+ try:
+ return float(value)
+ except ValueError:
+ return 0.0
+ return 0.0
+
+
+def compute_score(
+ status: AgentExecutionStatus,
+ cost_cents: float,
+ node_error_count: int,
+ has_activity: bool,
+ first_success: bool,
+ cost_baseline: float | None,
+) -> float:
+ """Pure scoring rule, so the ranking can be reasoned about and tested
+ without a database."""
+ score = _STATUS_SCORE.get(status, 0.0)
+
+ if first_success:
+ score += FIRST_SUCCESS_BONUS
+
+ # A run that produced something is worth surfacing; a run that checked and
+ # found nothing new is the definition of a no-op.
+ if has_activity:
+ score += NOVEL_OUTPUT_BONUS
+ else:
+ score -= NO_OP_PENALTY
+
+ # An unusually expensive run against the agent's own history is news even
+ # when it succeeded.
+ if cost_baseline and cost_cents > cost_baseline * ANOMALY_FACTOR:
+ score += ANOMALY_BONUS
+
+ if node_error_count > 0 and status is AgentExecutionStatus.COMPLETED:
+ # Finished, but not cleanly — worth ranking above a silent success.
+ score += ANOMALY_BONUS
+
+ return max(0.0, score)
+
+
+async def _agent_cost_baseline(graph_id: str, exclude_exec_id: str) -> float | None:
+ """Mean cost of this agent's own recent runs, or None when there isn't
+ enough history for "unusual" to mean anything.
+
+ Bounded to the most recent window rather than the agent's whole history:
+ this runs once per finished run, and a busy agent can have hundreds of
+ thousands of them.
+ """
+ rows = await query_raw_with_schema(
+ """
+ SELECT AVG(cost) AS mean_cost, COUNT(*) AS runs
+ FROM (
+ SELECT ("stats"::jsonb->>'cost')::numeric AS cost
+ FROM {schema_prefix}"AgentGraphExecution"
+ WHERE "agentGraphId" = $1
+ AND "id" <> $2
+ AND "isDeleted" = false
+ AND "stats" IS NOT NULL
+ ORDER BY "createdAt" DESC
+ LIMIT $3
+ ) recent
+ """,
+ graph_id,
+ exclude_exec_id,
+ BASELINE_WINDOW_RUNS,
+ )
+ if not rows or int(rows[0]["runs"] or 0) < MIN_BASELINE_RUNS:
+ return None
+ mean = rows[0]["mean_cost"]
+ return float(mean) if mean is not None else None
+
+
+async def _is_first_success(
+ graph_id: str, status: AgentExecutionStatus, exec_id: str
+) -> bool:
+ """A newly built agent working for the first time is the single most
+ interesting thing that can happen in a period.
+
+ A find_first rather than a count: we only care whether *any* earlier clean
+ run exists, and stopping at the first one keeps this cheap for agents with
+ a long history.
+ """
+ if status is not AgentExecutionStatus.COMPLETED:
+ return False
+ earlier = await AgentGraphExecution.prisma().find_first(
+ where={
+ "agentGraphId": graph_id,
+ "id": {"not": exec_id},
+ "isDeleted": False,
+ "executionStatus": AgentExecutionStatus.COMPLETED,
+ }
+ )
+ return earlier is None
diff --git a/autogpt_platform/backend/backend/notifications/scoring_test.py b/autogpt_platform/backend/backend/notifications/scoring_test.py
new file mode 100644
index 0000000000..7f25cc26da
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/scoring_test.py
@@ -0,0 +1,57 @@
+"""Interestingness ranking: blocked and failed outrank success, and a
+first-ever success outranks everything."""
+
+from prisma.enums import AgentExecutionStatus
+
+from backend.notifications.scoring import ANOMALY_FACTOR, compute_score
+
+
+def _score(status, **over):
+ args = {
+ "cost_cents": 10.0,
+ "node_error_count": 0,
+ "has_activity": True,
+ "first_success": False,
+ "cost_baseline": None,
+ }
+ args.update(over)
+ return compute_score(status=status, **args)
+
+
+def test_failed_outranks_success():
+ assert _score(AgentExecutionStatus.FAILED) > _score(AgentExecutionStatus.COMPLETED)
+
+
+def test_first_ever_success_outranks_a_routine_one():
+ assert _score(AgentExecutionStatus.COMPLETED, first_success=True) > _score(
+ AgentExecutionStatus.COMPLETED
+ )
+
+
+def test_a_no_op_ranks_below_a_run_that_produced_something():
+ assert _score(AgentExecutionStatus.COMPLETED, has_activity=False) < _score(
+ AgentExecutionStatus.COMPLETED, has_activity=True
+ )
+
+
+def test_cost_anomaly_is_measured_against_the_agents_own_baseline():
+ baseline = 10.0
+ normal = _score(
+ AgentExecutionStatus.COMPLETED, cost_cents=baseline * 2, cost_baseline=baseline
+ )
+ spike = _score(
+ AgentExecutionStatus.COMPLETED,
+ cost_cents=baseline * ANOMALY_FACTOR + 1,
+ cost_baseline=baseline,
+ )
+ assert spike > normal
+
+
+def test_finished_but_not_cleanly_outranks_a_silent_success():
+ assert _score(AgentExecutionStatus.COMPLETED, node_error_count=2) > _score(
+ AgentExecutionStatus.COMPLETED
+ )
+
+
+def test_score_never_goes_negative():
+ assert _score(AgentExecutionStatus.COMPLETED, has_activity=False, cost_cents=0) >= 0
diff --git a/autogpt_platform/backend/backend/notifications/stripe_payloads.py b/autogpt_platform/backend/backend/notifications/stripe_payloads.py
new file mode 100644
index 0000000000..9ae0e6614f
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/stripe_payloads.py
@@ -0,0 +1,130 @@
+"""Typed views over the Stripe payloads the billing emails read.
+
+Webhook payloads are not the same shape as an API response, and that
+difference has already cost us one silently-undelivered email:
+
+* **Nothing is expanded.** `invoice.payment_intent` and
+ `invoice.default_payment_method` arrive as ID *strings*. Walking into them
+ as if they were objects raises `AttributeError`, and in `on_payment_failed`
+ that happens *after* the idempotency key is claimed — so Stripe's retry is
+ deduped away and the customer never hears that their payment failed.
+* **The shape drifts with the API version.** `PaymentIntent.charges` was
+ replaced by `latest_charge` in 2022-11-15, and the account renders webhooks
+ at whatever version its endpoint is pinned to, not at the library's version.
+
+Both problems have the same answer: read Stripe payloads through models that
+treat every nested field as optional-and-possibly-an-id, in one place, instead
+of chained `.get()` calls spread across the formatting helpers.
+"""
+
+from typing import Any
+
+from pydantic import BaseModel, Field, field_validator
+
+
+def _object_or_none(value: Any) -> dict | None:
+ """A nested Stripe field, or None when absent or an unexpanded ID string."""
+ return value if isinstance(value, dict) else None
+
+
+class StripeCard(BaseModel):
+ brand: str | None = None
+ last4: str | None = None
+
+
+class StripePaymentMethodDetails(BaseModel):
+ card: StripeCard | None = None
+
+ @field_validator("card", mode="before")
+ @classmethod
+ def _unwrap(cls, v: Any) -> Any:
+ return _object_or_none(v)
+
+
+class StripeCharge(BaseModel):
+ payment_method_details: StripePaymentMethodDetails | None = None
+
+ @field_validator("payment_method_details", mode="before")
+ @classmethod
+ def _unwrap(cls, v: Any) -> Any:
+ return _object_or_none(v)
+
+
+class StripePaymentIntent(BaseModel):
+ """Both charge shapes, because which one is populated depends on the API
+ version the webhook endpoint is pinned to."""
+
+ latest_charge: StripeCharge | None = None
+ charges: list[StripeCharge] = Field(default_factory=list)
+
+ @field_validator("latest_charge", mode="before")
+ @classmethod
+ def _unwrap_charge(cls, v: Any) -> Any:
+ return _object_or_none(v)
+
+ @field_validator("charges", mode="before")
+ @classmethod
+ def _unwrap_charges(cls, v: Any) -> Any:
+ data = (v or {}).get("data") if isinstance(v, dict) else v
+ if not isinstance(data, list):
+ return []
+ return [c for c in data if isinstance(c, dict)]
+
+ @property
+ def card(self) -> StripeCard | None:
+ for charge in (
+ [self.latest_charge] if self.latest_charge else []
+ ) + self.charges:
+ details = charge.payment_method_details
+ if details and details.card:
+ return details.card
+ return None
+
+
+class StripePaymentMethod(BaseModel):
+ card: StripeCard | None = None
+
+ @field_validator("card", mode="before")
+ @classmethod
+ def _unwrap(cls, v: Any) -> Any:
+ return _object_or_none(v)
+
+
+class StripeInvoice(BaseModel):
+ """The invoice fields the payment emails read.
+
+ `model_config` is deliberately permissive: Stripe adds fields constantly
+ and an unknown one must never fail a billing email.
+ """
+
+ id: str | None = None
+ amount_due: int | None = None
+ currency: str = "usd"
+ attempt_count: int = 0
+ next_payment_attempt: int | None = None
+ period_end: int | None = None
+ payment_intent: StripePaymentIntent | None = None
+ default_payment_method: StripePaymentMethod | None = None
+
+ @field_validator("payment_intent", "default_payment_method", mode="before")
+ @classmethod
+ def _unwrap(cls, v: Any) -> Any:
+ return _object_or_none(v)
+
+ @field_validator("currency", mode="before")
+ @classmethod
+ def _default_currency(cls, v: Any) -> Any:
+ return v or "usd"
+
+ @property
+ def card(self) -> StripeCard | None:
+ """Card details from wherever this payload happens to carry them."""
+ if self.payment_intent and (card := self.payment_intent.card):
+ return card
+ if self.default_payment_method:
+ return self.default_payment_method.card
+ return None
+
+ @classmethod
+ def parse(cls, payload: dict) -> "StripeInvoice":
+ return cls.model_validate(payload)
diff --git a/autogpt_platform/backend/backend/notifications/templates/_lifecycle_ui.j2 b/autogpt_platform/backend/backend/notifications/templates/_lifecycle_ui.j2
new file mode 100644
index 0000000000..9801e02cd3
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/_lifecycle_ui.j2
@@ -0,0 +1,242 @@
+{# ============================================================
+ _lifecycle_ui.j2 — shared components for AutoGPT lifecycle
+ (billing & account) emails. Same design system as _ui.j2:
+ #eceaf6 paper, 560px sheet, #070629 masthead with the logo,
+ 560x184 hero art with bgcolor fallback, #5635b2 actions,
+ AA-corrected fine-print grays (#575072 / #575072) and
+ step numerals at #5635b2.
+ Pass `assets` in the render context as the base URL for
+ logo-light.png and the hero art. Import **with context**.
+ ============================================================ #}
+
+{%- macro head_block(title_text) -%}
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<meta name="color-scheme" content="light">
+<title>{{ title_text }}</title>
+<style>
+ @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800&display=swap');
+ html, body { margin:0 !important; padding:0 !important; width:100% !important; }
+ table { border-collapse:collapse; }
+ a { text-decoration:none; }
+ @media only screen and (max-width: 600px) {
+ .sheet { width:100% !important; }
+ .gutter { padding-left:22px !important; padding-right:22px !important; }
+ .headline { font-size:23px !important; line-height:31px !important; }
+ .mobile-hide { display:none !important; }
+ .kvl { display:block !important; width:100% !important; padding:10px 0 2px !important; border-top:1px solid #e7e4f4 !important; }
+ .kvv { display:block !important; width:100% !important; text-align:left !important; padding:0 0 10px !important; border-top:0 !important; font-size:11px !important; }
+ .kvfirst { border-top:0 !important; padding-top:0 !important; }
+ }
+</style>
+{%- endmacro -%}
+
+{%- macro preheader(text) -%}
+<div style="display:none; font-size:1px; color:#eceaf6; line-height:1px; max-height:0; overflow:hidden;">
+ {{ text }}&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;
+</div>
+{%- endmacro -%}
+
+{%- macro page_open() -%}
+<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#eceaf6">
+<tr><td align="center" style="padding:32px 12px 44px;">
+ <table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" class="sheet" style="width:560px; max-width:560px;">
+{%- endmacro -%}
+
+{%- macro page_close() -%}
+ </table>
+{%- endmacro -%}
+
+{%- macro masthead() -%}
+ <tr><td bgcolor="#070629" align="center" style="border-radius:16px 16px 0 0; padding:8px 0 6px; line-height:0;">
+ <img src="{{ assets | default('../assets', true) }}/logo-light.png" width="100" height="45" alt="AutoGPT" style="display:block; border:0;">
+ </td></tr>
+{%- endmacro -%}
+
+{%- macro hero_img(name, bgc, alt) -%}
+ <tr><td bgcolor="{{ bgc }}" align="center" style="padding:0; line-height:0; font-size:0;">
+ <img src="{{ assets | default('../assets', true) }}/{{ name }}.jpg" width="560" height="184" alt="{{ alt }}"
+ style="display:block; width:100%; max-width:560px; height:auto; border:0; outline:none; text-decoration:none;">
+ </td></tr>
+{%- endmacro -%}
+
+{# Per-email hero art. Each name maps to kit/assets/<name>.jpg and the
+ bgcolor is that image's own flat background, so blocked-image clients
+ show the same field of colour. #}
+{%- set HEROES = {
+ 'welcome': ('hero-welcome', '#fef8f5', 'Otto beside a switch reading plan on, with three agent cards waking up'),
+ 'payment_hiccup': ('hero-payment-hiccup', '#f7f4fc', 'Otto holding a bank card with a small spark, beside a retry clock'),
+ 'final_notice': ('hero-final-notice', '#f7f4fa', 'Otto offering a bank card beside an almost-empty hourglass and a pausing agent'),
+ 'cancel_safe': ('hero-cancel-safe', '#f6f3f9', 'Otto filing agent cards into a storage box beside a calendar with one day circled'),
+ 'welcome_back': ('hero-welcome-back', '#fef9f6', 'Otto hugging an agent card inside a sweeping U-turn arrow'),
+ 'plan_asleep': ('hero-plan-asleep', '#f3eae6', 'Otto tucking agent cards under a blanket at dusk, a key glowing on the wall'),
+ 'trial_headsup': ('hero-trial-headsup', '#eae1f9', 'Otto tapping the third of three calendar cards beneath a clock'),
+ 'tour_firstwin': ('hero-tour-firstwin', '#e6ddf9', 'Otto fist-bumping a freshly completed agent card'),
+ 'tour_fiveways': ('hero-tour-fiveways', '#e7e1fa', 'Otto juggling five task cards, each with a different glyph'),
+ 'tour_workspace': ('hero-tour-workspace', '#eae2f7', 'Otto with a flag leading a tour past three framed workspace panels'),
+ 'tour_listening': ('hero-tour-listening', '#f6f4f2', 'Otto holding out an empty speech bubble, listening'),
+ 'tour_shipping': ('hero-tour-shipping', '#fef9f6', 'Otto at a conveyor ramp as feature crates ship out'),
+ 'tour_directline': ('hero-tour-directline', '#e6dffc', 'Otto waving, with dotted lines to a chat bubble, a form and a calendar'),
+ 'changelog': ('hero-changelog', '#fef9f6', 'Otto peering over an open box as new feature chips float out'),
+} -%}
+
+{%- macro hero(state) -%}
+{%- set h = HEROES[state] -%}
+{{ hero_img(h[0], h[1], h[2]) }}
+{%- endmacro -%}
+
+{%- macro strip_amber(text) -%}
+ <tr><td bgcolor="#fff6e8" class="gutter" style="padding:12px 48px; border-bottom:1px solid #f2dcb0;">
+ <div style="font-size:12px; font-weight:800; letter-spacing:2.2px; color:#b45309;">&#9650;&nbsp; {{ text }}</div>
+ </td></tr>
+{%- endmacro -%}
+
+{%- macro eyebrow(color='#575072', top=26) -%}
+ <tr><td class="gutter" style="padding:{{ top }}px 48px 0;">
+ <div style="font-size:12px; font-weight:800; letter-spacing:2.2px; color:{{ color }};">{{ caller() }}</div>
+ </td></tr>
+{%- endmacro -%}
+
+{%- macro headline(top=8) -%}
+ <tr><td class="gutter" style="padding:{{ top }}px 48px 0;">
+ <div class="headline" style="font-size:26px; line-height:34px; font-weight:800; color:#070629; overflow-wrap:anywhere;">{{ caller() }}</div>
+ </td></tr>
+{%- endmacro -%}
+
+{%- macro para(top=16, color='#2d2a3e', size=15, lh=24) -%}
+ <tr><td class="gutter" style="padding:{{ top }}px 48px 0;">
+ <div style="font-size:{{ size }}px; line-height:{{ lh }}px; color:{{ color }};">{{ caller() }}</div>
+ </td></tr>
+{%- endmacro -%}
+
+{# rows: list of (label, value, mono) #}
+{%- macro kvpanel(rows, top=18) -%}
+ <tr><td class="gutter" style="padding:{{ top }}px 48px 0;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#f5f3fb" style="border-radius:10px;">
+ <tr><td style="padding:14px 18px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+ {%- for label, value, mono in rows %}
+ <tr>
+ <td width="150" valign="top" class="kvl{{ ' kvfirst' if loop.first }}" style="padding:{{ '0' if loop.first else '9px' }} 12px 9px 0; font-size:13px; color:#575072; border-top:{{ '0' if loop.first else '1px solid #e7e4f4' }};">{{ label }}</td>
+ <td valign="top" align="right" class="kvv" style="padding:{{ '0' if loop.first else '9px' }} 0 9px; {% if mono %}font-family:ui-monospace,Menlo,Consolas,monospace; font-size:12px;{% else %}font-size:13px;{% endif %} color:#070629; border-top:{{ '0' if loop.first else '1px solid #e7e4f4' }}; overflow-wrap:anywhere;">{{ value }}</td>
+ </tr>
+ {%- endfor %}
+ </table>
+ </td></tr>
+ </table>
+ </td></tr>
+{%- endmacro -%}
+
+{# tone: 'amber' | 'neutral' #}
+{%- macro note_card(label, tone='neutral', top=20) -%}
+ <tr><td class="gutter" style="padding:{{ top }}px 48px 0;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="{{ '#fff6e8' if tone == 'amber' else '#f5f3fb' }}" style="border:1px solid {{ '#f2dcb0' if tone == 'amber' else '#e7e4f4' }}; border-left:4px solid {{ '#e8940a' if tone == 'amber' else '#7c5cd6' }}; border-radius:10px;">
+ <tr><td style="padding:16px 18px;">
+ <div style="font-size:11px; font-weight:800; letter-spacing:2px; color:{{ '#8a5800' if tone == 'amber' else '#575072' }}; padding-bottom:7px;">{{ label | upper }}</div>
+ <div style="font-size:15px; line-height:24px; color:#2d2a3e; overflow-wrap:anywhere;">{{ caller() }}</div>
+ </td></tr>
+ </table>
+ </td></tr>
+{%- endmacro -%}
+
+{# items: list of (strong, text, link_label, url) #}
+{%- macro also_panel(label, items, top=28) -%}
+ <tr><td class="gutter" style="padding:{{ top }}px 48px 0;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#f5f3fb" style="border-radius:10px;">
+ <tr><td style="padding:15px 18px;">
+ <div style="font-size:11px; font-weight:800; letter-spacing:2px; color:#575072; padding-bottom:5px;">{{ label | upper }}</div>
+ {%- for strong, text, link_label, url in items %}
+ <div style="font-size:14px; line-height:21px; color:#2d2a3e;{{ ' padding-top:8px;' if not loop.first }}">
+ <strong style="color:#070629;">{{ strong }}</strong> {{ text }}
+ <a href="{{ url }}" style="color:#5635b2; font-weight:700; text-decoration:underline;">{{ link_label }}</a>
+ </div>
+ {%- endfor %}
+ </td></tr>
+ </table>
+ </td></tr>
+{%- endmacro -%}
+
+{# items: list of (lead, rest) — lead is bolded #}
+{%- macro steps(items, top=18) -%}
+ <tr><td class="gutter" style="padding:{{ top }}px 48px 0;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+ {%- for lead, rest in items %}
+ <tr>
+ <td width="26" valign="top" style="font-family:ui-monospace,Menlo,Consolas,monospace; font-size:13px; line-height:22px; font-weight:bold; color:#5635b2; padding-bottom:{{ '0' if loop.last else '12px' }};">{{ loop.index }}</td>
+ <td valign="top" style="font-size:14px; line-height:22px; color:#2d2a3e; padding-bottom:{{ '0' if loop.last else '12px' }};"><strong style="color:#070629;">{{ lead }}</strong> {{ rest }}</td>
+ </tr>
+ {%- endfor %}
+ </table>
+ </td></tr>
+{%- endmacro -%}
+
+{%- macro cta(label, url, micro=none, top=24) -%}
+ <tr><td class="gutter" style="padding:{{ top }}px 48px 0;">
+ <table role="presentation" cellpadding="0" cellspacing="0" border="0">
+ <tr><td bgcolor="#5635b2" style="border-radius:8px;">
+ <a href="{{ url }}" style="display:inline-block; padding:13px 28px; font-size:15px; font-weight:700; color:#ffffff;">{{ label }}</a>
+ </td></tr>
+ </table>
+ {%- if micro %}
+ <div style="padding-top:10px; font-size:12px; color:#575072;">{{ micro }}</div>
+ {%- endif %}
+ </td></tr>
+{%- endmacro -%}
+
+{%- macro close_row(text, link_label, url) -%}
+ <tr><td align="center" class="gutter" style="padding:22px 48px 24px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+ <tr><td height="1" bgcolor="#eeecf5" style="font-size:0; line-height:0;">&nbsp;</td></tr>
+ <tr><td align="center" style="padding-top:12px; font-size:12px; line-height:19px; color:#575072;">
+ {{ text }}<div style="padding-top:4px;"><a href="{{ url }}" style="color:#5635b2; text-decoration:underline;">{{ link_label }}</a></div>
+ </td></tr>
+ </table>
+ </td></tr>
+{%- endmacro -%}
+
+{%- macro legal_footer(first_line, link_label, link_url, discord=false) -%}
+ <table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" class="sheet" style="width:560px; max-width:560px;">
+ <tr><td align="center" style="padding:18px 24px 0; font-size:11px; line-height:18px; color:#575072;">
+ {{ first_line }}<br>
+ Legally, we have to tell you where we live: <a href="https://agpt.co" style="color:#5635b2; text-decoration:underline;">AutoGPT</a>, 3rd Floor, 1 Ashley Road, Altrincham, WA14 2DT, UK &nbsp;&middot;&nbsp;
+ <a href="{{ link_url }}" style="color:#575072; text-decoration:underline;">{{ link_label }}</a>{% if discord %} &nbsp;&middot;&nbsp;
+ <a href="https://discord.gg/autogpt" style="color:#575072; text-decoration:underline;">Discord</a>{% endif %}
+ </td></tr>
+ </table>
+{%- endmacro -%}
+
+{%- macro signature(name, title, email=none, top=26) -%}
+ <tr><td class="gutter" style="padding:{{ top }}px 48px 0;">
+ <div style="font-size:14px; font-weight:700; color:#070629;">{{ name }}</div>
+ <div style="font-size:13px; line-height:20px; color:#575072;">{{ title }}</div>
+ {%- if email %}
+ <div style="font-size:13px; line-height:20px;"><a href="mailto:{{ email }}" style="color:#5635b2; text-decoration:underline;">{{ email }}</a></div>
+ {%- endif %}
+ </td></tr>
+{%- endmacro -%}
+
+{# small card list with emoji lead — one panel per item #}
+{%- macro emoji_cards(items, top=20) -%}
+ <tr><td class="gutter" style="padding:{{ top }}px 48px 0;">
+ {%- for emoji, title, body in items %}
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#f5f3fb" style="border-radius:10px;{{ ' margin-top:10px;' if not loop.first }}">
+ <tr><td style="padding:13px 16px;">
+ <div style="font-size:14px; font-weight:700; color:#070629;">{{ emoji }}&nbsp; {{ title }}</div>
+ <div style="font-size:13.5px; line-height:21px; color:#2d2a3e; padding-top:3px;">{{ body }}</div>
+ </td></tr>
+ </table>
+ {%- endfor %}
+ </td></tr>
+{%- endmacro -%}
+
+{# video / media link row #}
+{%- macro media_link(label, sub, url, top=20) -%}
+ <tr><td class="gutter" style="padding:{{ top }}px 48px 0;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#f5f3fb" style="border-radius:10px;">
+ <tr><td style="padding:13px 16px;">
+ <div style="font-size:14px; font-weight:700;"><a href="{{ url }}" style="color:#5635b2; text-decoration:underline;">&#9654;&nbsp; {{ label }}</a></div>
+ <div style="font-size:13px; line-height:20px; color:#575072; padding-top:2px;">{{ sub }}</div>
+ </td></tr>
+ </table>
+ </td></tr>
+{%- endmacro -%}
diff --git a/autogpt_platform/backend/backend/notifications/templates/_ui.j2 b/autogpt_platform/backend/backend/notifications/templates/_ui.j2
new file mode 100644
index 0000000000..b2a6cdd791
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/_ui.j2
@@ -0,0 +1,228 @@
+{# ============================================================
+ _ui.j2 — shared components for AutoGPT notification emails
+ All macros emit table-based, inline-styled, email-safe HTML.
+ Hero art is hosted images (see hero_img). Pass `assets` in the
+ render context as the base URL those images are served from.
+ ============================================================ #}
+
+{%- macro page_open() -%}
+<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#f1efe9">
+<tr><td align="center" style="padding:32px 12px 44px;">
+ <table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" class="sheet" style="width:560px; max-width:560px;">
+{%- endmacro -%}
+
+{%- macro page_close() -%}
+ </table>
+{%- endmacro -%}
+
+{%- macro head_block(title_text) -%}
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<meta name="color-scheme" content="light">
+<title>{{ title_text }}</title>
+<style>
+ html, body { margin:0 !important; padding:0 !important; width:100% !important; }
+ table { border-collapse:collapse; }
+ a { text-decoration:none; }
+ @media only screen and (max-width: 600px) {
+ .sheet { width:100% !important; }
+ .gutter { padding-left:22px !important; padding-right:22px !important; }
+ .headline { font-size:23px !important; line-height:31px !important; }
+ .sum { font-size:10px !important; letter-spacing:0 !important; }
+ .mobile-hide { display:none !important; }
+ .kvl { display:block !important; width:100% !important; padding:10px 0 2px !important; border-top:1px solid #e7e4f4 !important; }
+ .kvv { display:block !important; width:100% !important; text-align:left !important; padding:0 0 10px !important; border-top:0 !important; font-size:11px !important; }
+ .kvfirst { border-top:0 !important; padding-top:0 !important; }
+ }
+</style>
+{%- endmacro -%}
+
+{%- macro preheader(text) -%}
+<div style="display:none; font-size:1px; color:#f1efe9; line-height:1px; max-height:0; overflow:hidden;">
+ {{ text }}&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;
+</div>
+{%- endmacro -%}
+
+{%- macro header() -%}
+ <tr><td bgcolor="#0b0a14" align="center" style="border-radius:14px 14px 0 0; padding:19px 0 17px;">
+ <table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr>
+ <td style="padding-right:9px; line-height:0;">
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M5 20 L12 3 L19 20" stroke="#ffffff" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round" fill="none"/>
+ <circle cx="12" cy="3.4" r="2.6" fill="#8b5cf6"/>
+ <circle cx="5" cy="20" r="2.6" fill="#ffffff"/>
+ <circle cx="19" cy="20" r="2.6" fill="#ffffff"/>
+ </svg>
+ </td>
+ <td style="font-size:19px; font-weight:800; color:#ffffff; letter-spacing:-0.2px; line-height:24px; font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">AutoGPT</td>
+ </tr></table>
+ </td></tr>
+{%- endmacro -%}
+
+{# ---------------------------------------------------------------
+ Hero art. Hosted images, not inline SVG: Outlook does not render
+ inline SVG at all. `assets` comes from the render context (see
+ README); the td keeps a bgcolor matching the art so a blocked
+ image still leaves the right colour band behind the card.
+ --------------------------------------------------------------- #}
+{%- macro hero_img(name, bgc, alt) -%}
+ <tr><td bgcolor="{{ bgc }}" align="center" style="padding:0; line-height:0; font-size:0;">
+ <img src="{{ assets | default('https://platform.agpt.co/email', true) }}/{{ name }}.jpg"
+ width="560" height="184" alt="{{ alt }}"
+ style="display:block; width:100%; max-width:560px; height:auto; border:0; outline:none; text-decoration:none;">
+ </td></tr>
+{%- endmacro -%}
+
+{# Briefing hero. state: 'clean' | 'attention' | 'rough' | 'quiet' #}
+{%- macro hero_briefing(state) -%}
+{%- if state == 'quiet' -%}
+{{ hero_img('hero-briefing-quiet', '#f0f0ee', 'Otto asleep beside a mug and a crescent moon') }}
+{%- elif state == 'rough' -%}
+{{ hero_img('hero-briefing-rough', '#eae1f5', 'Otto looking unhappy between a flagged and a failed document') }}
+{%- elif state == 'attention' -%}
+{{ hero_img('hero-briefing-attention', '#e6def7', 'Otto beside one flagged document and one completed one') }}
+{%- else -%}
+{{ hero_img('hero-briefing-clean', '#e7e0f8', 'Otto smiling between two completed documents') }}
+{%- endif -%}
+{%- endmacro -%}
+
+{# Verdict hero. state: 'approved' | 'changes' #}
+{%- macro hero_verdict(state) -%}
+{%- if state == 'approved' -%}
+{{ hero_img('hero-verdict-approved', '#fcf9f6', 'Otto celebrating beside an approval rosette') }}
+{%- else -%}
+{{ hero_img('hero-verdict-changes', '#f9f4f5', 'Otto considering a clipboard of review notes') }}
+{%- endif -%}
+{%- endmacro -%}
+
+{%- macro hero_alert() -%}
+{{ hero_img('hero-alert', '#f7f4fb', 'Otto looking startled above an unplugged cable') }}
+{%- endmacro -%}
+
+{%- macro btn(label, url) -%}
+ <table role="presentation" cellpadding="0" cellspacing="0" border="0">
+ <tr><td bgcolor="#5d23bb" style="border-radius:8px;">
+ <a href="{{ url }}" style="display:inline-block; padding:13px 28px; font-size:15px; font-weight:700; color:#ffffff;">{{ label }}</a>
+ </td></tr>
+ </table>
+{%- endmacro -%}
+
+{%- macro btn_small(label, url) -%}
+ <table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr><td bgcolor="#5d23bb" style="border-radius:6px;">
+ <a href="{{ url }}" style="display:inline-block; padding:8px 14px; font-size:13px; font-weight:700; color:#ffffff;">{{ label }}</a>
+ </td></tr></table>
+{%- endmacro -%}
+
+{%- macro trunc(s, n=40) -%}
+{%- if s | length <= n -%}{{ s }}
+{%- else -%}
+{%- set cut = s[:n-1] -%}
+{%- set sp = cut.rfind(' ') -%}
+{%- set base = cut[:sp] if sp > ((n * 6) // 10) else cut -%}
+{%- set base = base | trim(' (&–—-·:,;') -%}
+{#- never leave an unmatched opening bracket dangling before the ellipsis -#}
+{%- if base.count('(') > base.count(')') -%}
+{%- set base = base[:base.rfind('(')] | trim(' (&–—-·:,;') -%}
+{%- endif -%}
+{%- if base.count('“') > base.count('”') -%}
+{%- set base = base[:base.rfind('“')] | trim(' (&“"–—-·:,;') -%}
+{%- endif -%}
+{{- base ~ '…' -}}
+{%- endif -%}
+{%- endmacro -%}
+
+{%- macro attention_card(item, primary=true) -%}
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#fff6e8" style="border:1px solid #f2dcb0; border-left:4px solid {{ '#e8940a' if primary else '#f0cf9a' }}; border-radius:10px;">
+ <tr><td style="padding:16px 18px;">
+ <div style="font-size:15px; font-weight:700; color:#17123b;">
+ <span style="color:#b45309;">&#9650;</span>&nbsp; {{ trunc(item.title, 52) }}{% if item.tag %} &nbsp;<span style="font-size:11px; font-weight:800; letter-spacing:1px; color:#b45309; white-space:nowrap;">{{ item.tag|upper }}</span>{% endif %}
+ </div>
+ <div style="padding-top:5px; font-size:14px; line-height:21px; color:#5d5872;">
+ {{ item.body }}
+ </div>
+ <div style="padding-top:11px;">
+ {{ btn_small(item.cta_label, item.cta_url) }}
+ </div>
+ </td></tr>
+ </table>
+{%- endmacro -%}
+
+{%- macro section_label(text, color='#8a86a3') -%}
+ <div style="font-size:12px; font-weight:800; letter-spacing:2.2px; color:{{ color }};">{{ text }}</div>
+{%- endmacro -%}
+
+{%- macro legal_footer(first_line, unsubscribe_url, discord=true) -%}
+ <table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" class="sheet" style="width:560px; max-width:560px;">
+ <tr><td align="center" style="padding:18px 24px 0; font-size:11px; line-height:18px; color:#9b97ad;">
+ {{ first_line }}<br>
+ Legally, we have to tell you where we live: <a href="https://agpt.co" style="color:#6d28d9; text-decoration:underline;">AutoGPT</a>, 3rd Floor, 1 Ashley Road, Altrincham, WA14 2DT, UK &nbsp;&middot;&nbsp;
+ <a href="{{ unsubscribe_url }}" style="color:#9b97ad; text-decoration:underline;">Unsubscribe</a>{% if discord %} &nbsp;&middot;&nbsp;
+ <a href="https://discord.gg/autogpt" style="color:#9b97ad; text-decoration:underline;">Discord</a>{% endif %}
+ </td></tr>
+ </table>
+{%- endmacro -%}
+
+
+
+{# Quoted note / feedback card. tone: 'amber' | 'neutral' #}
+{%- macro note_card(label, body, tone='neutral') -%}
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="{{ '#fff6e8' if tone == 'amber' else '#f7f6fc' }}" style="border:1px solid {{ '#f2dcb0' if tone == 'amber' else '#e7e4f4' }}; border-left:4px solid {{ '#e8940a' if tone == 'amber' else '#8b5cf6' }}; border-radius:10px;">
+ <tr><td style="padding:16px 18px;">
+ <div style="font-size:11px; font-weight:800; letter-spacing:2px; color:{{ '#8a5800' if tone == 'amber' else '#6f6b8a' }}; padding-bottom:7px;">{{ label|upper }}</div>
+ <div style="font-size:15px; line-height:24px; color:#3b3757; overflow-wrap:anywhere;">{{ body }}</div>
+ </td></tr>
+ </table>
+{%- endmacro -%}
+
+{# Numbered step, used for "how to resubmit" / "how to reject" #}
+{%- macro step(n, text) -%}
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+ <tr>
+ <td width="26" valign="top" style="font-family:ui-monospace,Menlo,Consolas,monospace; font-size:13px; line-height:22px; font-weight:bold; color:#8b5cf6;">{{ n }}</td>
+ <td style="font-size:14px; line-height:22px; color:#494566;">{{ text }}</td>
+ </tr>
+ </table>
+{%- endmacro -%}
+
+{# Compact ops band: big amount + status chip + small mascot. Internal emails
+ don't get a 184px hero — the number is the hero. #}
+{%- macro ops_band(eyebrow, amount_text, sub_text, status_label, status_bg) -%}
+ <tr><td bgcolor="#1c1a2e" style="padding:20px 30px 22px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+ <tr>
+ <td valign="middle">
+ <div style="font-size:11px; font-weight:800; letter-spacing:2px; color:#9a95b8;">{{ eyebrow }}</div>
+ <div style="padding-top:6px; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:32px; font-weight:bold; color:#ffffff; letter-spacing:-0.5px;">{{ amount_text }}</div>
+ <div style="padding-top:5px; font-size:13px; line-height:19px; color:#b8b3d1; overflow-wrap:anywhere;">{{ sub_text }}</div>
+ <div style="padding-top:11px;">
+ <table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr>
+ <td bgcolor="{{ status_bg }}" style="border-radius:4px; padding:5px 10px; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:10px; font-weight:bold; letter-spacing:1.4px; color:#1c1a2e;">{{ status_label|upper }}</td>
+ </tr></table>
+ </div>
+ </td>
+ <td width="118" align="right" valign="middle" class="mobile-hide" style="line-height:0; font-size:0;">
+ <img src="{{ assets | default('https://platform.agpt.co/email', true) }}/mark-otto.png"
+ width="118" height="80" alt=""
+ style="display:block; border:0; outline:none; text-decoration:none;">
+ </td>
+ </tr>
+ </table>
+ </td></tr>
+{%- endmacro -%}
+
+{# Key/value ledger row for ops emails #}
+{%- macro kv(label, value, mono=true, first=false) -%}
+ <tr>
+ <td width="150" valign="top" class="kvl{{ ' kvfirst' if first }}" style="padding:{{ '0' if first else '9px' }} 12px 9px 0; font-size:13px; color:#8a86a3; border-top:{{ '0' if first else '1px solid #e7e4f4' }};">{{ label }}</td>
+ <td valign="top" align="right" class="kvv" style="padding:{{ '0' if first else '9px' }} 0 9px; {% if mono %}font-family:ui-monospace,Menlo,Consolas,monospace; font-size:12px;{% else %}font-size:13px;{% endif %} color:#17123b; border-top:{{ '0' if first else '1px solid #e7e4f4' }}; overflow-wrap:anywhere;">{{ value }}</td>
+ </tr>
+{%- endmacro -%}
+
+{# Internal footer — no marketing chrome, no unsubscribe (ops mail is not opt-in) #}
+{%- macro internal_footer(line) -%}
+ <table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" class="sheet" style="width:560px; max-width:560px;">
+ <tr><td align="center" style="padding:18px 24px 0; font-size:11px; line-height:18px; color:#9b97ad;">
+ {{ line }}
+ </td></tr>
+ </table>
+{%- endmacro -%}
diff --git a/autogpt_platform/backend/backend/notifications/templates/agent_approved.html.jinja2 b/autogpt_platform/backend/backend/notifications/templates/agent_approved.html.jinja2
deleted file mode 100644
index fceb350c7a..0000000000
--- a/autogpt_platform/backend/backend/notifications/templates/agent_approved.html.jinja2
+++ /dev/null
@@ -1,73 +0,0 @@
-{# Agent Approved Notification Email Template #}
-{#
- Template variables:
- data.agent_name: the name of the approved agent
- data.graph_id: the ID of the agent
- data.graph_version: the version of the agent
- data.reviewer_name: the name of the reviewer who approved it
- data.reviewer_email: the email of the reviewer
- data.comments: comments from the reviewer
- data.reviewed_at: when the agent was reviewed
- data.store_url: URL to view the agent in the store
-
- Subject: 🎉 Your agent '{{ data.agent_name }}' has been approved!
-#}
-
-{% block content %}
-<h1 style="color: #28a745; font-size: 32px; font-weight: 700; margin: 0 0 24px 0; text-align: center;">
- 🎉 Congratulations!
-</h1>
-
-<p style="color: #586069; font-size: 18px; text-align: center; margin: 0 0 24px 0;">
- Your agent <strong>'{{ data.agent_name }}'</strong> has been approved and is now live in the store!
-</p>
-
-<div style="height: 32px; background: transparent;"></div>
-
-{% if data.comments %}
-<div style="background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 0;">
- <h3 style="color: #155724; font-size: 16px; font-weight: 600; margin: 0 0 12px 0;">
- 💬 Creator feedback area
- </h3>
- <p style="color: #155724; margin: 0; font-size: 16px; line-height: 1.5;">
- {{ data.comments }}
- </p>
-</div>
-
-<div style="height: 40px; background: transparent;"></div>
-{% endif %}
-
-<div style="background: #d1ecf1; border: 1px solid #bee5eb; border-radius: 8px; padding: 20px; margin: 0;">
- <h3 style="color: #0c5460; font-size: 16px; font-weight: 600; margin: 0 0 12px 0;">
- What's Next?
- </h3>
- <ul style="color: #0c5460; margin: 0; padding-left: 18px; font-size: 16px; line-height: 1.6;">
- <li>Your agent is now live and discoverable in the AutoGPT Store</li>
- <li>Users can find, install, and run your agent</li>
- <li>You can update your agent anytime by submitting a new version</li>
- </ul>
-</div>
-
-<div style="height: 32px; background: transparent;"></div>
-
-<div style="text-align: center; margin: 24px 0;">
- <a href="{{ data.store_url }}" style="display: inline-block; background: linear-gradient(135deg, #7c3aed 0%, #5b21b6 100%); color: black; text-decoration: none; padding: 14px 28px; border-radius: 6px; font-weight: 600; font-size: 16px;">
- View Your Agent in Store
- </a>
-</div>
-
-<div style="height: 32px; background: transparent;"></div>
-
-<div style="background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 6px; padding: 16px; margin: 24px 0; text-align: center;">
- <p style="margin: 0; color: #856404; font-size: 14px;">
- <strong>💡 Pro Tip:</strong> Share your agent with the community! Post about it on social media, forums, or your blog to help more users discover and benefit from your creation.
- </p>
-</div>
-
-<div style="height: 32px; background: transparent;"></div>
-
-<p style="color: #6a737d; font-size: 14px; text-align: center; margin: 24px 0;">
- Thank you for contributing to the AutoGPT ecosystem! 🚀
-</p>
-
-{% endblock %}
diff --git a/autogpt_platform/backend/backend/notifications/templates/agent_rejected.html.jinja2 b/autogpt_platform/backend/backend/notifications/templates/agent_rejected.html.jinja2
deleted file mode 100644
index 7c4ddd41c3..0000000000
--- a/autogpt_platform/backend/backend/notifications/templates/agent_rejected.html.jinja2
+++ /dev/null
@@ -1,77 +0,0 @@
-{# Agent Rejected Notification Email Template #}
-{#
- Template variables:
- data.agent_name: the name of the rejected agent
- data.graph_id: the ID of the agent
- data.graph_version: the version of the agent
- data.reviewer_name: the name of the reviewer who rejected it
- data.reviewer_email: the email of the reviewer
- data.comments: comments from the reviewer explaining the rejection
- data.reviewed_at: when the agent was reviewed
- data.resubmit_url: URL to resubmit the agent
-
- Subject: Your agent '{{ data.agent_name }}' needs some updates
-#}
-
-
-{% block content %}
-<h1 style="color: #d73a49; font-size: 32px; font-weight: 700; margin: 0 0 24px 0; text-align: center;">
- 📝 Review Complete
-</h1>
-
-<p style="color: #586069; font-size: 18px; text-align: center; margin: 0 0 24px 0;">
- Your agent <strong>'{{ data.agent_name }}'</strong> needs some updates before approval.
-</p>
-
-<div style="height: 32px; background: transparent;"></div>
-
-<div style="background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 0 0 24px 0;">
- <h3 style="color: #721c24; font-size: 16px; font-weight: 600; margin: 0 0 12px 0;">
- 💬 Creator feedback area
- </h3>
- <p style="color: #721c24; margin: 0; font-size: 16px; line-height: 1.5;">
- {{ data.comments }}
- </p>
-</div>
-
-<div style="height: 40px; background: transparent;"></div>
-
-<div style="background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 0 0 24px 0;">
- <h3 style="color: #155724; font-size: 16px; font-weight: 600; margin: 0 0 12px 0;">
- ☑ Steps to Resubmit:
- </h3>
- <ul style="color: #155724; margin: 0; padding-left: 18px; font-size: 16px; line-height: 1.6;">
- <li>Review the feedback provided above carefully</li>
- <li>Make the necessary updates to your agent</li>
- <li>Test your agent thoroughly to ensure it works as expected</li>
- <li>Submit your updated agent for review</li>
- </ul>
-</div>
-
-<div style="height: 32px; background: transparent;"></div>
-
-<div style="background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 6px; padding: 12px; margin: 0 0 24px 0; text-align: center;">
- <p style="margin: 0; color: #856404; font-size: 14px;">
- <strong>💡 Tip:</strong> Address all the points mentioned in the feedback to increase your chances of approval in the next review.
- </p>
-</div>
-
-<div style="text-align: center; margin: 32px 0;">
- <a href="{{ data.resubmit_url }}" style="display: inline-block; background: linear-gradient(135deg, #7c3aed 0%, #5b21b6 100%); color: black; text-decoration: none; padding: 14px 28px; border-radius: 6px; font-weight: 600; font-size: 16px;">
- Update & Resubmit Agent
- </a>
-</div>
-
-<div style="background: #d1ecf1; border: 1px solid #bee5eb; border-radius: 6px; padding: 16px; margin: 24px 0;">
- <p style="margin: 0; color: #0c5460; font-size: 14px; text-align: center;">
- <strong>🌟 Don't Give Up!</strong> Many successful agents go through multiple iterations before approval. Our review team is here to help you succeed!
- </p>
-</div>
-
-<div style="height: 32px; background: transparent;"></div>
-
-<p style="color: #6a737d; font-size: 14px; text-align: center; margin: 32px 0 24px 0;">
- We're excited to see your improved agent submission! 🚀
-</p>
-
-{% endblock %}
diff --git a/autogpt_platform/backend/backend/notifications/templates/agent_run.html.jinja2 b/autogpt_platform/backend/backend/notifications/templates/agent_run.html.jinja2
deleted file mode 100644
index 043e33aed1..0000000000
--- a/autogpt_platform/backend/backend/notifications/templates/agent_run.html.jinja2
+++ /dev/null
@@ -1,142 +0,0 @@
-{# Agent Run #}
-{# Template variables:
-notification.data: the stuff below but a list of them
-data.agent_name: the name of the agent
-data.credits_used: the number of credits used by the agent
-data.node_count: the number of nodes the agent ran on
-data.execution_time: the time it took to run the agent
-data.graph_id: the id of the graph the agent ran on
-data.outputs: the list of outputs of the agent
-#}
-{% if notifications is defined %}
- {# BATCH MODE #}
- <div style="font-family: 'Poppins', sans-serif; color: #070629;">
- <h2 style="color: #5D23BB; margin-bottom: 15px;">Agent Run Summary</h2>
- <p style="font-size: 16px; line-height: 165%; margin-top: 0; margin-bottom: 15px;">
- <strong>{{ notifications|length }}</strong> agent runs have completed!
- </p>
-
- {# Calculate summary stats #}
- {% set total_time = 0 %}
- {% set total_nodes = 0 %}
- {% set total_credits = 0 %}
- {% set agent_names = [] %}
-
- {% for notification in notifications %}
- {% set total_time = total_time + notification.data.execution_time %}
- {% set total_nodes = total_nodes + notification.data.node_count %}
- {% set total_credits = total_credits + notification.data.credits_used %}
- {% if notification.data.agent_name not in agent_names %}
- {% set agent_names = agent_names + [notification.data.agent_name] %}
- {% endif %}
- {% endfor %}
-
- <div style="background-color: #f8f7ff; border-radius: 8px; padding: 15px; margin-bottom: 25px;">
- <h3 style="margin-top: 0; margin-bottom: 10px; color: #5D23BB;">Summary</h3>
- <p style="margin: 5px 0;"><strong>Agents:</strong> {{ agent_names|join(", ") }}</p>
- <p style="margin: 5px 0;"><strong>Total Time:</strong> {{ total_time | int }} seconds</p>
- <p style="margin: 5px 0;"><strong>Total Nodes:</strong> {{ total_nodes }}</p>
- <p style="margin: 5px 0;"><strong>Total Cost:</strong> ${{ "{:.2f}".format((total_credits|float)/100) }}</p>
- </div>
-
- <h3 style="margin-top: 25px; margin-bottom: 15px; color: #5D23BB;">Individual Runs</h3>
-
- {% for notification in notifications %}
- <div style="margin-bottom: 30px; border-left: 3px solid #5D23BB; padding-left: 15px;">
- <p style="font-size: 16px; font-weight: 600; margin-top: 0; margin-bottom: 10px;">
- Agent: <strong>{{ notification.data.agent_name }}</strong>
- </p>
-
- <div style="margin-left: 10px;">
- <p style="margin: 5px 0;"><strong>Time:</strong> {{ notification.data.execution_time | int }} seconds</p>
- <p style="margin: 5px 0;"><strong>Nodes:</strong> {{ notification.data.node_count }}</p>
- <p style="margin: 5px 0;"><strong>Cost:</strong> ${{ "{:.2f}".format((notification.data.credits_used|float)/100) }}</p>
- </div>
-
- {% if notification.data.outputs and notification.data.outputs|length > 0 %}
- <div style="margin-left: 10px; margin-top: 15px;">
- <p style="font-weight: 600; margin-bottom: 10px;">Results:</p>
-
- {% for output in notification.data.outputs %}
- <div style="margin-left: 10px; margin-bottom: 12px;">
- <p style="color: #5D23BB; font-weight: 500; margin-top: 0; margin-bottom: 5px;">
- {{ output.name }}
- </p>
-
- {% for key, value in output.items() %}
- {% if key != 'name' %}
- <div style="margin-left: 10px; background-color: #f5f5ff; padding: 8px 12px; border-radius: 4px;
- font-family: 'Roboto Mono', monospace; white-space: pre-wrap; word-break: break-word;
- overflow-wrap: break-word; max-width: 100%; overflow-x: auto; margin-top: 3px;
- margin-bottom: 8px; line-height: 1.4;">
- {% if value is iterable and value is not string %}
- {% if value|length == 1 %}
- {{ value[0] }}
- {% else %}
- [{% for item in value %}{{ item }}{% if not loop.last %}, {% endif %}{% endfor %}]
- {% endif %}
- {% else %}
- {{ value }}
- {% endif %}
- </div>
- {% endif %}
- {% endfor %}
- </div>
- {% endfor %}
- </div>
- {% endif %}
- </div>
- {% endfor %}
- </div>
-
-{% else %}
- {# SINGLE NOTIFICATION MODE - Original template #}
- <p style="font-family: 'Poppins', sans-serif; color: #070629; font-size: 16px; line-height: 165%;
- margin-top: 0; margin-bottom: 10px;">
- Your agent, <strong>{{ data.agent_name }}</strong>, has completed its run!
- </p>
-
- <p style="font-family: 'Poppins', sans-serif; color: #070629; font-size: 16px; line-height: 165%;
- margin-top: 0; margin-bottom: 20px; padding-left: 20px;">
- <p style="margin-bottom: 10px;"><strong>Time Taken:</strong> {{ data.execution_time | int }} seconds</p>
- <p style="margin-bottom: 10px;"><strong>Nodes Used:</strong> {{ data.node_count }}</p>
- <p style="margin-bottom: 10px;"><strong>Cost:</strong> ${{ "{:.2f}".format((data.credits_used|float)/100) }}</p>
- </p>
-
- {% if data.outputs and data.outputs|length > 0 %}
- <div style="margin-left: 15px; margin-bottom: 20px;">
- <p style="font-family: 'Poppins', sans-serif; color: #070629; font-weight: 600;
- font-size: 16px; margin-bottom: 10px;">
- Results:
- </p>
-
- {% for output in data.outputs %}
- <div style="margin-left: 15px; margin-bottom: 15px;">
- <p style="font-family: 'Poppins', sans-serif; color: #5D23BB; font-weight: 500;
- font-size: 16px; margin-top: 0; margin-bottom: 8px;">
- {{ output.name }}
- </p>
-
- {% for key, value in output.items() %}
- {% if key != 'name' %}
- <div style="margin-left: 15px; background-color: #f5f5ff; padding: 8px 12px; border-radius: 4px;
- font-family: 'Roboto Mono', monospace; white-space: pre-wrap; word-break: break-word;
- overflow-wrap: break-word; max-width: 100%; overflow-x: auto; margin-top: 5px;
- margin-bottom: 10px; line-height: 1.4;">
- {% if value is iterable and value is not string %}
- {% if value|length == 1 %}
- {{ value[0] }}
- {% else %}
- [{% for item in value %}{{ item }}{% if not loop.last %}, {% endif %}{% endfor %}]
- {% endif %}
- {% else %}
- {{ value }}
- {% endif %}
- </div>
- {% endif %}
- {% endfor %}
- </div>
- {% endfor %}
- </div>
- {% endif %}
-{% endif %}
diff --git a/autogpt_platform/backend/backend/notifications/templates/alert.html.j2 b/autogpt_platform/backend/backend/notifications/templates/alert.html.j2
new file mode 100644
index 0000000000..16de105da1
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/alert.html.j2
@@ -0,0 +1,102 @@
+{#- ============================================================
+ alert.html.j2 — the "Needs you" interrupt
+ One template covers every alert cause (auth expired, agent
+ paused, awaiting review, low balance, spend guardrail) plus
+ coalesced secondary items. All strings arrive pre-assembled
+ from the cause catalog (see README.md).
+ ============================================================ -#}
+{%- import "_ui.j2" as ui with context -%}
+{%- set also_items = also | default([]) -%}
+<!doctype html>
+<html lang="en">
+<head>
+{{ ui.head_block(subject | default(primary.headline)) }}
+</head>
+<body style="margin:0; padding:0; background-color:#f1efe9; -webkit-text-size-adjust:100%; font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
+{{ ui.preheader(preheader | default(primary.body)) }}
+{{ ui.page_open() }}
+{{ ui.header() }}
+{{ ui.hero_alert() }}
+
+ <!-- Body card -->
+ <tr><td bgcolor="#ffffff" style="border-radius:0 0 14px 14px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+
+ {#- a tinted severity strip, so the alert still reads as an alert with images off -#}
+ <tr><td bgcolor="#fff6e8" class="gutter" style="padding:12px 48px; border-bottom:1px solid #f2dcb0;">
+ <div style="font-size:12px; font-weight:800; letter-spacing:2.2px; color:#b45309;">&#9650;&nbsp; NEEDS YOU{% if timestamp_label %} &middot; {{ timestamp_label | upper }}{% endif %}</div>
+ </td></tr>
+ <tr><td class="gutter" style="padding:26px 48px 0;">
+ <div class="headline" style="font-size:26px; line-height:34px; font-weight:800; color:#17123b; overflow-wrap:anywhere;">
+ {{ primary.headline }}
+ </div>
+ </td></tr>
+
+ <tr><td class="gutter" style="padding:16px 48px 0;">
+ <div style="font-size:15px; line-height:24px; color:#494566;">
+ {{ primary.body }}
+ </div>
+ </td></tr>
+
+ {%- if primary.facts %}
+ <tr><td class="gutter" style="padding:18px 48px 0;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#f7f6fc" style="border-radius:10px;">
+ <tr><td style="padding:14px 18px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+ {%- for f in primary.facts %}
+ {{ ui.kv(f.label, f.value, mono=true, first=loop.first) }}
+ {%- endfor %}
+ </table>
+ </td></tr>
+ </table>
+ </td></tr>
+ {%- endif %}
+
+ <tr><td class="gutter" style="padding:24px 48px 0;">
+ {{ ui.btn(primary.cta_label, primary.cta_url) }}
+ {%- if primary.microcopy %}
+ <div style="padding-top:10px; font-size:12px; color:#8a86a3;">{{ primary.microcopy }}</div>
+ {%- endif %}
+ </td></tr>
+
+ {%- if also_items %}
+ <tr><td class="gutter" style="padding:28px 48px 0;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#f7f6fc" style="border-radius:10px;">
+ <tr><td style="padding:15px 18px;">
+ <div style="font-size:11px; font-weight:800; letter-spacing:2px; color:#6f6b8a; padding-bottom:5px;">{{ (also_label | default('Also waiting')) | upper }}</div>
+ {%- for a in also_items[:3] %}
+ <div style="font-size:14px; line-height:21px; color:#494566;{{ ' padding-top:8px;' if not loop.first }}">
+ <strong style="color:#17123b;">{{ ui.trunc(a.agent, 44) }}</strong> {{ a.text }}
+ <a href="{{ a.url }}" style="color:#6d28d9; font-weight:700; text-decoration:underline;">{{ a.link_label }}</a>
+ </div>
+ {%- endfor %}
+ {%- if also_items | length > 3 %}
+ <div style="font-size:13px; line-height:20px; color:#8a86a3; padding-top:8px;">
+ + {{ also_items | length - 3 }} more waiting &mdash;
+ <a href="{{ urls.dashboard }}" style="color:#6d28d9; font-weight:700; text-decoration:underline;">open your dashboard</a>
+ </div>
+ {%- endif %}
+ </td></tr>
+ </table>
+ </td></tr>
+ {%- endif %}
+
+ <tr><td align="center" class="gutter" style="padding:22px 48px 24px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+ <tr><td height="1" bgcolor="#eeecf5" style="font-size:0; line-height:0;">&nbsp;</td></tr>
+ <tr><td align="center" style="padding-top:12px; font-size:12px; line-height:19px; color:#8a86a3;">
+ Alerts only fire when your action is needed &mdash; never for a successful run.
+ <div style="padding-top:4px;"><a href="{{ urls.settings }}" style="color:#6d28d9; text-decoration:underline;">Alert&nbsp;settings</a></div>
+ </td></tr>
+ </table>
+ </td></tr>
+
+ </table>
+ </td></tr>
+{{ ui.page_close() }}
+{{ ui.legal_footer('This alert is about the AutoGPT account for ' ~ user_email ~ '.', urls.unsubscribe, discord=false) }}
+
+</td></tr>
+</table>
+</body>
+</html>
diff --git a/autogpt_platform/backend/backend/notifications/templates/alert.subject.j2 b/autogpt_platform/backend/backend/notifications/templates/alert.subject.j2
new file mode 100644
index 0000000000..c1f75b3fe4
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/alert.subject.j2
@@ -0,0 +1,5 @@
+{#- Renders two lines: line 1 = subject, line 2 = preheader.
+ primary.subject / primary.preheader may be set by the cause
+ catalog; both fall back to headline/body. -#}
+{{ primary.subject | default(primary.headline) }}
+{{ primary.preheader | default(primary.body) }}
diff --git a/autogpt_platform/backend/backend/notifications/templates/alert.txt.j2 b/autogpt_platform/backend/backend/notifications/templates/alert.txt.j2
new file mode 100644
index 0000000000..8ba9d1a2d0
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/alert.txt.j2
@@ -0,0 +1,37 @@
+{#- Plain-text part of the Alert, built from the same context as the HTML. -#}
+{%- set also_items = also | default([]) -%}
+NEEDS YOU{% if timestamp_label %} - {{ timestamp_label }}{% endif %}
+
+
+{{ primary.headline }}
+
+{{ primary.body }}
+{% if primary.facts %}
+{% for f in primary.facts %}
+{{ f.label }}: {{ f.value }}
+{% endfor %}
+{% endif %}
+
+{{ primary.cta_label }}: {{ primary.cta_url }}
+{% if primary.microcopy %}
+({{ primary.microcopy }})
+{% endif %}
+{% if also_items %}
+
+{{ also_label | default('Also waiting') }}
+{% for a in also_items[:3] %}
+- {{ a.agent }} {{ a.text }}
+ {{ a.link_label }}: {{ a.url }}
+{% endfor %}
+{% if also_items | length > 3 %}
+- + {{ also_items | length - 3 }} more waiting: {{ urls.dashboard }}
+{% endif %}
+{% endif %}
+
+--
+Alerts only fire when your action is needed - never for a successful run.
+Alert settings: {{ urls.settings }}
+
+This alert is about the AutoGPT account for {{ user_email }}.
+AutoGPT, 3rd Floor, 1 Ashley Road, Altrincham, WA14 2DT, UK
+Unsubscribe: {{ urls.unsubscribe }}
diff --git a/autogpt_platform/backend/backend/notifications/templates/base.html.jinja2 b/autogpt_platform/backend/backend/notifications/templates/base.html.jinja2
deleted file mode 100644
index 3e5ddf22ff..0000000000
--- a/autogpt_platform/backend/backend/notifications/templates/base.html.jinja2
+++ /dev/null
@@ -1,343 +0,0 @@
-{# Base Template #}
-{# Template variables:
- data.message: the message to display in the email
- data.title: the title of the email
- data.unsubscribe_link: the link to unsubscribe from the email
-#}
-<!doctype html>
-<html lang="ltr" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
-
-<head>
- <meta charset="utf-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
- <meta name="format-detection" content="telephone=no, date=no, address=no, email=no, url=no">
- <meta name="x-apple-disable-message-reformatting">
- <!--[if !mso]>
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <![endif]-->
- <!--[if mso]>
- <style>
- * { font-family: sans-serif !important; }
- </style>
- <noscript>
- <xml>
- <o:OfficeDocumentSettings>
- <o:PixelsPerInch>96</o:PixelsPerInch>
- </o:OfficeDocumentSettings>
- </xml>
- </noscript>
- <![endif]-->
- <style type="text/css">
- /* RESET STYLES */
- html,
- body {
- margin: 0 !important;
- padding: 0 !important;
- width: 100% !important;
- height: 100% !important;
- }
-
- body {
- -webkit-font-smoothing: antialiased;
- -moz-osx-font-smoothing: grayscale;
- text-rendering: optimizeLegibility;
- }
-
- .document {
- margin: 0 !important;
- padding: 0 !important;
- width: 100% !important;
- }
-
- img {
- border: 0;
- outline: none;
- text-decoration: none;
- -ms-interpolation-mode: bicubic;
- }
-
- table {
- border-collapse: collapse;
- }
-
- table,
- td {
- mso-table-lspace: 0pt;
- mso-table-rspace: 0pt;
- }
-
- body,
- table,
- td,
- a {
- -webkit-text-size-adjust: 100%;
- -ms-text-size-adjust: 100%;
- }
-
- h1,
- h2,
- h3,
- h4,
- h5,
- p {
- margin: 0;
- word-break: break-word;
- }
-
- /* iOS BLUE LINKS */
- a[x-apple-data-detectors] {
- color: inherit !important;
- text-decoration: none !important;
- font-size: inherit !important;
- font-family: inherit !important;
- font-weight: inherit !important;
- line-height: inherit !important;
- }
-
- /* ANDROID CENTER FIX */
- div[style*="margin: 16px 0;"] {
- margin: 0 !important;
- }
-
- /* MEDIA QUERIES */
- @media all and (max-width:639px) {
- .wrapper {
- width: 100% !important;
- }
-
- .container {
- width: 100% !important;
- min-width: 100% !important;
- padding: 0 !important;
- }
-
- .row {
- padding-left: 20px !important;
- padding-right: 20px !important;
- }
-
- .col-mobile {
- width: 20px !important;
- }
-
- .col {
- display: block !important;
- width: 100% !important;
- }
-
- .mobile-center {
- text-align: center !important;
- float: none !important;
- }
-
- .mobile-mx-auto {
- margin: 0 auto !important;
- float: none !important;
- }
-
- .mobile-left {
- text-align: center !important;
- float: left !important;
- }
-
- .mobile-hide {
- display: none !important;
- }
-
- .img {
- width: 100% !important;
- height: auto !important;
- }
-
- .ml-btn {
- width: 100% !important;
- max-width: 100% !important;
- }
-
- .ml-btn-container {
- width: 100% !important;
- max-width: 100% !important;
- }
- }
- </style>
- <style type="text/css">
- @import url("https://assets.mlcdn.com/fonts-v2.css?version=1729862");
- </style>
- <style type="text/css">
- @media screen {
- body {
- font-family: 'Poppins', sans-serif;
- }
- }
- </style>
- <title>{{data.title}}</title>
-</head>
-
-<body style="margin: 0 !important; padding: 0 !important; background-color:#070629;">
- <div class="document" role="article" aria-roledescription="email" aria-label lang dir="ltr"
- style="background-color:#070629; line-height: 100%; font-size:medium; font-size:max(16px, 1rem);">
- <!-- Main Content -->
- <table width="100%" align="center" cellspacing="0" cellpadding="0" border="0">
- <tr>
- <td class="background" bgcolor="#070629" align="center" valign="top" style="padding: 0 8px;">
- <!-- Email Content -->
- <table class="container" align="center" width="640" cellpadding="0" cellspacing="0" border="0"
- style="max-width: 640px;">
- <tr>
- <td align="center">
- <!-- Logo Section -->
- <table class="container ml-4 ml-default-border" width="640" bgcolor="#E2ECFD" align="center" border="0"
- cellspacing="0" cellpadding="0" style="width: 640px; min-width: 640px;">
- <tr>
- <td class="ml-default-border container" height="40" style="line-height: 40px; min-width: 640px;">
- </td>
- </tr>
- <tr>
- <td>
- <table align="center" width="100%" border="0" cellspacing="0" cellpadding="0">
- <tr>
- <td class="row" align="center" style="padding: 0 50px;">
- <img
- src="https://storage.mlcdn.com/account_image/597379/8QJ8kOjXakVvfe1kJLY2wWCObU1mp5EiDLfBlbQa.png"
- border="0" alt="" width="120" class="logo"
- style="max-width: 120px; display: inline-block;">
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
-
- <!-- Main Content Section -->
- <table class="container ml-6 ml-default-border" width="640" bgcolor="#E2ECFD" align="center" border="0"
- cellspacing="0" cellpadding="0" style="color: #070629; width: 640px; min-width: 640px;">
- <tr>
- <td class="row" style="padding: 0 50px;">
- {{data.message|safe}}
- </td>
- </tr>
- </table>
-
- <!-- Signature Section -->
- <table class="container ml-8 ml-default-border" width="640" bgcolor="#E2ECFD" align="center" border="0"
- cellspacing="0" cellpadding="0" style="color: #070629; width: 640px; min-width: 640px;">
- <tr>
- <td class="row mobile-center" align="left" style="padding: 0 50px;">
- <table class="ml-8 wrapper" border="0" cellspacing="0" cellpadding="0"
- style="color: #070629; text-align: left;">
- <tr>
- <td class="col center mobile-center" align>
- <p
- style="font-family: 'Poppins', sans-serif; color: #070629; font-size: 16px; line-height: 165%; margin-top: 0; margin-bottom: 0;">
- Thank you for being a part of the AutoGPT community! Join the conversation on our Discord <a href="https://discord.gg/autogpt" style="color: #4285F4; text-decoration: underline;">here</a> and share your thoughts with us anytime.
- </p>
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
-
- <!-- Footer Section -->
- <table class="container ml-10 ml-default-border" width="640" bgcolor="#ffffff" align="center" border="0"
- cellspacing="0" cellpadding="0" style="width: 640px; min-width: 640px;">
- <tr>
- <td class="row" style="padding: 0 50px;">
- <table align="center" width="100%" border="0" cellspacing="0" cellpadding="0">
- <tr>
- <td>
- <!-- Footer Content -->
- <table align="center" width="100%" border="0" cellspacing="0" cellpadding="0">
- <tr>
- <td class="col" align="left" valign="middle" width="120">
- <img
- src="https://storage.mlcdn.com/account_image/597379/8QJ8kOjXakVvfe1kJLY2wWCObU1mp5EiDLfBlbQa.png"
- border="0" alt="" width="120" class="logo"
- style="max-width: 120px; display: inline-block;">
- </td>
- <td class="col" width="40" height="30" style="line-height: 30px;"></td>
- <td class="col mobile-left" align="right" valign="middle" width="250">
- <table role="presentation" cellpadding="0" cellspacing="0" border="0">
- <tr>
- <td align="center" valign="middle" width="18" style="padding: 0 5px 0 0;">
- <a href="https://x.com/auto_gpt" target="blank" style="text-decoration: none;">
- <img
- src="https://assets.mlcdn.com/ml/images/icons/default/rounded_corners/black/x.png"
- width="18" alt="x">
- </a>
- </td>
- <td align="center" valign="middle" width="18" style="padding: 0 5px;">
- <a href="https://discord.gg/autogpt" target="blank"
- style="text-decoration: none;">
- <img
- src="https://assets.mlcdn.com/ml/images/icons/default/rounded_corners/black/discord.png"
- width="18" alt="discord">
- </a>
- </td>
- <td align="center" valign="middle" width="18" style="padding: 0 0 0 5px;">
- <a href="https://agpt.co/" target="blank" style="text-decoration: none;">
- <img
- src="https://assets.mlcdn.com/ml/images/icons/default/rounded_corners/black/website.png"
- width="18" alt="website">
- </a>
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
- </td>
- </tr>
- <tr>
- <td align="center" style="text-align: left!important;">
- <h5
- style="font-family: 'Poppins', sans-serif; color: #070629; font-size: 15px; line-height: 125%; font-weight: bold; font-style: normal; text-decoration: none; margin-bottom: 6px;">
- AutoGPT
- </h5>
- </td>
- </tr>
- <tr>
- <td align="center" style="text-align: left!important;">
- <p
- style="font-family: 'Poppins', sans-serif; color: #070629; font-size: 14px; line-height: 150%; display: inline-block; margin-bottom: 0;">
- 3rd Floor 1 Ashley Road, Cheshire, United Kingdom, WA14 2DT, Altrincham<br>United Kingdom
- </p>
- </td>
- </tr>
- <tr>
- <td height="8" style="line-height: 8px;"></td>
- </tr>
- <tr>
- <td align="left" style="text-align: left!important;">
- <p
- style="font-family: 'Poppins', sans-serif; color: #070629; font-size: 14px; line-height: 150%; display: inline-block; margin-bottom: 0;">
- You received this email because you signed up on our website.</p>
- </td>
- </tr>
- <tr>
- <td height="1" style="line-height: 12px;"></td>
- </tr>
- <tr>
- <td align="left">
- <p
- style="font-family: 'Poppins', sans-serif; color: #070629; font-size: 14px; line-height: 150%; display: inline-block; margin-bottom: 0;">
- <a href="{{data.unsubscribe_link}}"
- style="color: #4285F4; font-weight: normal; font-style: normal; text-decoration: underline;">Unsubscribe</a>
- </p>
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
- </div>
-</body>
-
-</html>
\ No newline at end of file
diff --git a/autogpt_platform/backend/backend/notifications/templates/briefing.html.j2 b/autogpt_platform/backend/backend/notifications/templates/briefing.html.j2
new file mode 100644
index 0000000000..f1ec3c32b8
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/briefing.html.j2
@@ -0,0 +1,218 @@
+{#- ============================================================
+ briefing.html.j2 — the Agent Briefing digest (weekly or daily)
+ One template covers busy, clean, rough, and quiet periods.
+ See README.md for the full context schema.
+ Render briefing.subject.j2 first and pass `subject` and
+ `preheader` in; both fall back safely if omitted.
+ ============================================================ -#}
+{%- import "_ui.j2" as ui with context -%}
+
+{#- ---------- derived values ---------- -#}
+{%- set runs = totals.runs -%}
+{%- set failed = totals.failed | default(0) -%}
+{%- set attn = attention | default([]) -%}
+{%- set attn_count = attn | length -%}
+{%- set agents_total = totals.agents_active + (totals.agents_idle | default(0)) -%}
+{%- set runs_fmt = '{:,}'.format(runs) -%}
+{%- set run_word = 'run' if runs == 1 else 'runs' -%}
+{%- set times_phrase = 'once' if runs == 1 else runs_fmt ~ ' times' -%}
+{%- set nw = {1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine'} -%}
+{%- set quiet = (mode | default('standard')) == 'quiet' -%}
+{%- set bad_period = (not quiet) and runs > 0 and failed >= 3 and failed * 3 >= runs -%}
+
+{#- ---------- headline ---------- -#}
+{%- if quiet -%}
+ {%- set headline = 'A quiet ' ~ period.adjective ~ ' — in a good way' -%}
+{%- elif bad_period -%}
+ {%- set headline = 'A rough ' ~ period.adjective ~ ': ' ~ failed ~ ' of ' ~ runs_fmt ~ ' runs failed' -%}
+{%- elif attn_count == 1 -%}
+ {%- set headline = runs_fmt ~ ' ' ~ run_word ~ ', and only one thing needs you' -%}
+{%- elif attn_count > 0 and attn_count <= 3 -%}
+ {%- set headline = runs_fmt ~ ' ' ~ run_word ~ ', and only ' ~ nw[attn_count] ~ ' things need you' -%}
+{%- elif attn_count > 3 -%}
+ {%- set headline = runs_fmt ~ ' ' ~ run_word ~ ' — ' ~ attn_count ~ ' things need you' -%}
+{%- elif failed > 0 -%}
+ {%- set headline = runs_fmt ~ ' ' ~ run_word ~ ', ' ~ failed ~ ' failed — nothing blocked on you' -%}
+{%- else -%}
+ {%- set headline = 'All clear: ' ~ runs_fmt ~ ' ' ~ run_word ~ ', nothing needed you' -%}
+{%- endif -%}
+<!doctype html>
+<html lang="en">
+<head>
+{{ ui.head_block(subject | default(headline)) }}
+</head>
+<body style="margin:0; padding:0; background-color:#f1efe9; -webkit-text-size-adjust:100%; font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
+{{ ui.preheader(preheader | default('Your agents’ ' ~ period.adjective ~ ' at a glance.')) }}
+{{ ui.page_open() }}
+{{ ui.header() }}
+{{ ui.hero_briefing('quiet' if quiet else ('rough' if bad_period else ('attention' if attn_count > 0 else 'clean'))) }}
+
+ <!-- Body card -->
+ <tr><td bgcolor="#ffffff" style="border-radius:0 0 14px 14px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+
+ <tr><td class="gutter" style="padding:30px 48px 0;">
+ <div style="font-size:12px; font-weight:800; letter-spacing:2.2px; color:#6d28d9;">YOUR {{ {'daily':'DAY','weekly':'WEEK','monthly':'MONTH'}.get(period.frequency, 'WEEK') }} IN AGENTS &middot; {{ period.label | upper }}</div>
+ <div class="headline" style="padding-top:10px; font-size:26px; line-height:34px; font-weight:800; color:#17123b;">
+ {{ headline }}
+ </div>
+ </td></tr>
+
+ <tr><td class="gutter" style="padding:16px 48px 0;">
+ <div style="font-size:15px; line-height:24px; color:#494566;">
+ {%- if quiet %}
+ {%- if only_agent %}
+ {{ only_agent }} was your only agent at work {{ period.noun }}.
+ {{ quiet_summary | default('It ran ' ~ times_phrase ~ ', and nothing needed your attention.') }}
+ {%- else %}
+ A light {{ period.adjective }}: {{ totals.agents_active }} agents ran <strong>{{ times_phrase }}</strong>, and nothing needed your attention.
+ {%- endif %}
+ {%- else %}
+ {#- the lede counts agents that actually ran; ledger lists exactly those -#}
+ {%- if totals.agents_active == 1 %}
+ Your agent ran <strong>{{ times_phrase }}</strong> {{ period.noun }}
+ {%- else %}
+ Your {{ nw.get(totals.agents_active, '{:,}'.format(totals.agents_active)) }} agents ran <strong>{{ times_phrase }}</strong> {{ period.noun }}
+ {%- endif %}
+ {%- if failed == 0 %}{{ ', and it finished clean.' if runs == 1 else ', and every run finished clean.' }}
+ {%- elif failed == runs %}{{ ', and it failed.' if runs == 1 else ', and none of them finished clean.' }}
+ {%- elif failed == 1 %} &mdash; all but one finished clean.
+ {%- else %} &mdash; all but {{ failed }} finished clean.
+ {%- endif %}
+ {%- if standout %} {{ standout }}{% endif %}
+ {%- if attn_count == 1 %} One agent is waiting on you before it can carry on.
+ {%- elif attn_count in [2, 3] %} {{ nw[attn_count] | capitalize }} agents are waiting on you before they can carry on.
+ {%- elif attn_count > 3 %} You have {{ attn_count }} things waiting on you before they can carry on.
+ {%- endif %}
+ {%- endif %}
+ </div>
+ </td></tr>
+
+ {%- for item in attn[:3] %}
+ <tr><td class="gutter" style="padding:{{ '22px' if loop.first else '12px' }} 48px 0;">
+ {{ ui.attention_card(item, primary=loop.first) }}
+ </td></tr>
+ {%- endfor %}
+ {%- if attn_count > 3 %}
+ <tr><td class="gutter" style="padding:12px 48px 0;">
+ <div style="font-size:13px; line-height:20px; color:#8a5800;">
+ &#9650;&nbsp; + {{ attn_count - 3 }} more {{ 'thing needs' if attn_count - 3 == 1 else 'things need' }} you &mdash;
+ <a href="{{ urls.attention | default(urls.dashboard) }}" style="color:#6d28d9; font-weight:700; text-decoration:underline;">see everything waiting</a>
+ </div>
+ </td></tr>
+ {%- endif %}
+
+ {%- if highlights %}
+ <tr><td class="gutter" style="padding:30px 48px 0;">
+ {{ ui.section_label('WORTH A LOOK') }}
+ </td></tr>
+ {%- for h in highlights[:3] %}
+ <tr><td class="gutter" style="padding:{{ '14px' if loop.first else '12px' }} 48px 0;">
+ <div style="font-size:15px; line-height:23px; color:#494566;">
+ <strong style="color:#17123b;">{{ ui.trunc(h.agent, 44) }}</strong> {{ h.gist }}
+ <a href="{{ h.url }}" style="color:#6d28d9; font-weight:700; text-decoration:underline;">{{ h.link_label | default('See the run') }}</a>
+ </div>
+ </td></tr>
+ {%- endfor %}
+ {%- endif %}
+
+ {%- if not quiet %}
+ <tr><td class="gutter" style="padding:30px 48px 0;">
+ {{ ui.section_label('THE LEDGER') }}
+ </td></tr>
+ <tr><td class="gutter" style="padding:12px 48px 0;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#f7f6fc" style="border-radius:10px;">
+ <tr><td style="padding:6px 18px 12px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+ <tr>
+ <td style="padding:9px 0 6px; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:10px; letter-spacing:1px; color:#8a86a3;">AGENT</td>
+ <td align="right" style="padding:9px 0 6px 12px; white-space:nowrap; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:10px; letter-spacing:1px; color:#8a86a3;">RUNS</td>
+ <td align="right" style="padding:9px 0 6px 12px; white-space:nowrap; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:10px; letter-spacing:1px; color:#8a86a3;">ISSUES</td>
+ <td align="right" style="padding:9px 0 6px 12px; white-space:nowrap; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:10px; letter-spacing:1px; color:#8a86a3;">CREDITS</td>
+ </tr>
+ {%- for row in ledger %}
+ <tr>
+ <td style="padding:8px 8px 8px 0; font-size:14px; color:#17123b; border-top:1px solid #e7e4f4; overflow-wrap:anywhere;">{{ ui.trunc(row.agent, 34) }}</td>
+ <td align="right" style="padding:8px 0 8px 12px; white-space:nowrap; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:13px; color:#17123b; border-top:1px solid #e7e4f4;">{{ '{:,}'.format(row.runs) }}</td>
+ {%- if row.issues_label %}
+ <td align="right" style="padding:8px 0 8px 12px; white-space:nowrap; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:12px; color:{{ '#b91c1c' if row.issues_kind == 'fail' else '#b45309' }}; border-top:1px solid #e7e4f4;">{{ row.issues_label }}</td>
+ {%- else %}
+ <td align="right" style="padding:8px 0 8px 12px; white-space:nowrap; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:13px; color:#b5b1c9; border-top:1px solid #e7e4f4;">&mdash;</td>
+ {%- endif %}
+ <td align="right" style="padding:8px 0 8px 12px; white-space:nowrap; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:13px; color:#17123b; border-top:1px solid #e7e4f4;">{{ '%.2f' | format(row.credits) }}</td>
+ </tr>
+ {%- endfor %}
+ {%- if ledger_overflow %}
+ {%- set rest_runs = ledger_overflow_runs %}
+ {%- set rest_issues = ledger_overflow_issues %}
+ <tr>
+ <td colspan="4" style="padding:8px 0; font-size:13px; color:#8a86a3; border-top:1px solid #e7e4f4;">
+ + {{ ledger_overflow }} quieter {{ 'agent' if ledger_overflow == 1 else 'agents' }} ran {{ '{:,}'.format(rest_runs) }} {{ 'time' if rest_runs == 1 else 'times' }}{{ ', clean' if rest_issues == 0 else ', ' ~ rest_issues ~ ' with issues' }} &mdash;
+ <a href="{{ urls.dashboard }}" style="color:#6d28d9; font-weight:700; text-decoration:underline;">see the full ledger</a>
+ </td>
+ </tr>
+ {%- endif %}
+ <tr>
+ <td colspan="2" class="sum" style="padding:9px 0 2px; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:11px; letter-spacing:0.5px; font-weight:bold; color:#5d5872; border-top:1px solid #d9d5ec;">
+ {{ '{:,.2f}'.format(totals.credits_used) }}&nbsp;CREDITS&nbsp;USED{% if totals.usd_estimate is not none %} (${{ '{:,.2f}'.format(totals.usd_estimate) }}){% endif %}
+ </td>
+ <td colspan="2" align="right" class="sum" style="padding:9px 0 2px 12px; white-space:nowrap; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:11px; letter-spacing:0.5px; font-weight:bold; color:#5d5872; border-top:1px solid #d9d5ec;">
+ BALANCE&nbsp;{{ '{:,.2f}'.format(totals.credits_balance) }}
+ </td>
+ </tr>
+ </table>
+ </td></tr>
+ </table>
+ </td></tr>
+
+ {#- when attention cards already carry the real actions, this button would
+ compete with them; the ledger's own link is enough of a way through -#}
+ {%- if attn_count == 0 %}
+ <tr><td class="gutter" style="padding:24px 48px 0;">
+ {{ ui.btn('Open your dashboard', urls.dashboard) }}
+ </td></tr>
+ {%- endif %}
+ {%- else %}
+ <tr><td class="gutter" style="padding:18px 48px 0;">
+ <table role="presentation" cellpadding="0" cellspacing="0" border="0" bgcolor="#edf4ee" style="border-radius:8px;">
+ <tr><td style="padding:10px 16px; font-family:ui-monospace,Menlo,Consolas,monospace; font-size:12px; letter-spacing:0.5px; font-weight:bold; color:#3f6549;">
+ {{ runs_fmt }}&nbsp;{{ run_word | upper }} &middot; {{ totals.agents_active }}&nbsp;ACTIVE{% if totals.agents_idle %} &middot; {{ totals.agents_idle }}&nbsp;ON&nbsp;STANDBY{% endif %} &middot; {{ failed }}&nbsp;ISSUES &middot; {{ '{:,.2f}'.format(totals.credits_used) }}&nbsp;CREDITS
+ </td></tr>
+ </table>
+ </td></tr>
+ {%- if attn_count == 0 %}
+ <tr><td class="gutter" style="padding:18px 48px 0;">
+ <div style="font-size:14px; font-weight:700;">
+ <a href="{{ urls.dashboard }}" style="color:#6d28d9; text-decoration:underline;">Open your dashboard</a>
+ </div>
+ </td></tr>
+ {%- endif %}
+ {%- endif %}
+
+ <tr><td align="center" class="gutter" style="padding:26px 48px 30px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+ <tr><td height="1" bgcolor="#eeecf5" style="font-size:0; line-height:0;">&nbsp;</td></tr>
+ <tr><td align="center" style="padding-top:14px; font-size:12px; line-height:19px; color:#8a86a3;">
+ You get this briefing <strong style="color:#5d5872;">{{ period.frequency }}</strong>, and only when your agents actually ran.<br>
+ {%- for f in ['daily', 'weekly', 'monthly'] if f != period.frequency %}
+ <a href="{{ urls.volume.get(f) or (urls.settings ~ '?f=' ~ f) }}" style="color:#6d28d9; text-decoration:underline;">Switch to {{ f }}</a> &nbsp;&middot;&nbsp;
+ {%- endfor %}
+ <a href="{{ urls.volume.get('alerts') or (urls.settings ~ '?f=alerts') }}" style="color:#6d28d9; text-decoration:underline;">Alerts only</a> &nbsp;&middot;&nbsp;
+ <a href="{{ urls.volume.get('off') or (urls.settings ~ '?f=off') }}" style="color:#6d28d9; text-decoration:underline;">Pause</a>
+ </td></tr>
+ </table>
+ </td></tr>
+
+ </table>
+ </td></tr>
+{{ ui.page_close() }}
+{%- if quiet %}
+{{ ui.legal_footer('This is your agent briefing for ' ~ user_email ~ ' — if truly nothing runs, we simply don’t send one.', urls.unsubscribe) }}
+{%- else %}
+{{ ui.legal_footer('This is your agent briefing for ' ~ user_email ~ ' — sent because your agents ran ' ~ period.noun ~ '. They insisted.', urls.unsubscribe) }}
+{%- endif %}
+
+</td></tr>
+</table>
+</body>
+</html>
diff --git a/autogpt_platform/backend/backend/notifications/templates/briefing.subject.j2 b/autogpt_platform/backend/backend/notifications/templates/briefing.subject.j2
new file mode 100644
index 0000000000..1ffe02a6dc
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/briefing.subject.j2
@@ -0,0 +1,28 @@
+{#- Renders two lines: line 1 = subject, line 2 = preheader.
+ subject_note is an optional short server-built phrase, e.g.
+ "Lead Scout found 41 leads" (from the top highlight). -#}
+{%- set runs = totals.runs -%}
+{%- set failed = totals.failed | default(0) -%}
+{%- set attn = attention | default([]) -%}
+{%- set attn_count = attn | length -%}
+{%- set runs_fmt = '{:,}'.format(runs) -%}
+{%- set run_word = 'run' if runs == 1 else 'runs' -%}
+{%- set active = totals.agents_active -%}
+{%- set quiet = (mode | default('standard')) == 'quiet' -%}
+{%- set bad_period = (not quiet) and runs > 0 and failed >= 3 and failed * 3 >= runs -%}
+{%- if quiet -%}
+Quiet {{ period.adjective }}: {{ subject_note | default(runs_fmt ~ ' ' ~ run_word ~ ', nothing needed you') }}
+{% if highlights %}{{ highlights[0].agent }} {{ highlights[0].gist }}{% else %}Everything ran on schedule; no issues and nothing waiting on you.{% endif %}
+{%- elif bad_period -%}
+{{ failed }} of {{ runs_fmt }} runs failed {{ period.noun }}{% if attn_count > 0 %} — {{ attn_count }} {{ 'thing needs' if attn_count == 1 else 'things need' }} you{% endif %}
+{% if attn %}{{ attn[0].title }}{% if attn_count == 2 %} and 1 more is waiting on you{% elif attn_count > 2 %} and {{ attn_count - 1 }} more are waiting on you{% endif %}.{% else %}See what went wrong and where.{% endif %}
+{%- elif attn_count > 0 -%}
+{{ runs_fmt }} {{ run_word }}, {{ '1 thing needs' if attn_count == 1 else attn_count ~ ' things need' }} you{% if subject_note %} · {{ subject_note }}{% endif %}
+{{ attn[0].title }}{% if attn_count > 1 %} and {{ attn_count - 1 }} more{% endif %}{% if failed == 0 %} — the rest ran clean.{% else %} — plus {{ failed }} failed {{ 'run' if failed == 1 else 'runs' }}.{% endif %}
+{%- elif failed > 0 -%}
+{{ runs_fmt }} {{ run_word }}, {{ failed }} failed — nothing blocked on you{% if subject_note %} · {{ subject_note }}{% endif %}
+{% if highlights %}{{ highlights[0].agent }} {{ highlights[0].gist }}{% else %}The failures didn’t block anything; details inside.{% endif %}
+{%- else -%}
+All clear: {{ runs_fmt }} {{ run_word }}{% if active > 1 %} across {{ active }} agents{% endif %}{% if subject_note %} · {{ subject_note }}{% endif %}
+{% if highlights %}{{ highlights[0].agent }} {{ highlights[0].gist }}{% else %}Every run finished clean; nothing is waiting on you.{% endif %}
+{%- endif -%}
diff --git a/autogpt_platform/backend/backend/notifications/templates/briefing.txt.j2 b/autogpt_platform/backend/backend/notifications/templates/briefing.txt.j2
new file mode 100644
index 0000000000..70dbe3f702
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/briefing.txt.j2
@@ -0,0 +1,54 @@
+{#- Plain-text part of the Briefing, built from the same context as the HTML
+ so a text-only client gets the same facts in the same order, not a
+ tag-stripped approximation. -#}
+{%- set quiet = (mode | default('standard')) == 'quiet' -%}
+{%- set attn = attention | default([]) -%}
+{{ subject }}
+
+{{ preheader }}
+
+YOUR {{ {'daily':'DAY','weekly':'WEEK','monthly':'MONTH'}.get(period.frequency, 'WEEK') }} IN AGENTS - {{ period.label }}
+{% if attn %}
+NEEDS YOU
+{% for item in attn[:3] %}
+{{ loop.index }}. {{ item.title }}{% if item.tag %} ({{ item.tag }}){% endif %}
+
+ {{ item.body }}
+ {{ item.cta_label }}: {{ item.cta_url }}
+{% endfor %}
+{% if attn | length > 3 %}
+ + {{ attn | length - 3 }} more waiting: {{ urls.attention }}
+{% endif %}
+{% endif %}
+{% if highlights %}
+WORTH A LOOK
+{% for h in highlights[:3] %}
+- {{ h.agent }} {{ h.gist }}
+ {{ h.link_label }}: {{ h.url }}
+{% endfor %}
+{% endif %}
+{% if not quiet %}
+THE LEDGER
+{% for row in ledger %}
+- {{ row.agent }}: {{ '{:,}'.format(row.runs) }} runs, {{ '%.2f' | format(row.credits) }} credits{% if row.issues_label %}, {{ row.issues_label }}{% endif %}
+
+{% endfor %}
+{% if ledger_overflow %}
+- + {{ ledger_overflow }} quieter agents: {{ urls.dashboard }}
+{% endif %}
+
+{{ '{:,.2f}'.format(totals.credits_used) }} credits used{% if totals.usd_estimate is not none %} (${{ '{:,.2f}'.format(totals.usd_estimate) }}){% endif %} - balance {{ '{:,.2f}'.format(totals.credits_balance) }}
+{% else %}
+{{ '{:,}'.format(totals.runs) }} runs - {{ totals.agents_active }} active{% if totals.agents_idle %} - {{ totals.agents_idle }} on standby{% endif %} - {{ totals.failed }} issues - {{ '{:,.2f}'.format(totals.credits_used) }} credits
+{% endif %}
+
+Open your dashboard: {{ urls.dashboard }}
+
+--
+You get this briefing {{ period.frequency }}, and only when your agents
+actually ran. Switch to daily, weekly or monthly, choose alerts only, or
+pause it entirely: {{ urls.settings }}
+
+This is your agent briefing for {{ user_email }}.
+AutoGPT, 3rd Floor, 1 Ashley Road, Altrincham, WA14 2DT, UK
+Unsubscribe: {{ urls.unsubscribe }}
diff --git a/autogpt_platform/backend/backend/notifications/templates/changelog.html.j2 b/autogpt_platform/backend/backend/notifications/templates/changelog.html.j2
new file mode 100644
index 0000000000..eba01f52aa
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/changelog.html.j2
@@ -0,0 +1,51 @@
+{#- ============================================================
+ changelog.html.j2 — the monthly "AutoGPT Update".
+ Content is authored in MailerLite; this template is the shared
+ design reference for that campaign. Context:
+ edition_label "July 2026"
+ period_label "June 18 – July 9"
+ intro one casual sentence
+ entries [ { emoji, title, body, url } ... ]
+ urls shared link map
+ Sent monthly to the changelog MailerLite group · marketing
+ footer · signed by John.
+ ============================================================ -#}
+{%- import "_lifecycle_ui.j2" as ui with context -%}
+<!doctype html>
+<html lang="en">
+<head>
+{{ ui.head_block(subject) }}
+</head>
+<body style="margin:0; padding:0; background-color:#eceaf6; -webkit-text-size-adjust:100%; font-family:'Poppins',Helvetica,Arial,sans-serif;">
+{{ ui.preheader(preheader) }}
+{{ ui.page_open() }}
+{{ ui.masthead() }}
+{{ ui.hero('changelog') }}
+ <tr><td bgcolor="#ffffff" style="border-radius:0 0 16px 16px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+{% call ui.eyebrow(color='#5635b2') %}AUTOGPT UPDATE · {{ edition_label | upper }}{% endcall %}
+{% call ui.headline() %}What's new — {{ period_label }}{% endcall %}
+{% call ui.para() %}Hey {{ user_name }} — {{ intro }}{% endcall %}
+ <tr><td class="gutter" style="padding:20px 48px 0;">
+ {%- for e in entries %}
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#f5f3fb" style="border-radius:10px;{{ ' margin-top:10px;' if not loop.first }}">
+ <tr><td style="padding:14px 16px;">
+ <div style="font-size:14px; font-weight:700; color:#070629;">{{ e.emoji }}&nbsp; {{ e.title }}</div>
+ <div style="font-size:13.5px; line-height:21px; color:#2d2a3e; padding-top:3px;">{{ e.body }}</div>
+ <div style="font-size:13px; padding-top:5px;"><a href="{{ e.url }}" style="color:#5635b2; font-weight:700; text-decoration:underline;">Learn more</a></div>
+ </td></tr>
+ </table>
+ {%- endfor %}
+ </td></tr>
+{{ ui.cta('See the full changelog', urls.changelog, 'Everything we ship lands there weekly — this email is just the monthly roundup.') }}
+{% call ui.para(color='#575072', size=13, lh=20, top=18) %}Something here you asked for? That's not a coincidence — reply and tell me what should be in next month's edition.{% endcall %}
+{{ ui.signature('John Ababseh', 'Product Manager · AutoGPT', '[email protected]') }}
+{{ ui.close_row('The monthly update lands the same week each month.', 'Choose which emails you get', urls.prefs) }}
+ </table>
+ </td></tr>
+{{ ui.page_close() }}
+{{ ui.legal_footer('You are receiving the monthly AutoGPT Update because you subscribe to the platform, at ' ~ user_email ~ '.', 'Unsubscribe', urls.unsubscribe, discord=true) }}
+
+</td></tr>
+</table>
+</body></html>
diff --git a/autogpt_platform/backend/backend/notifications/templates/changelog.subject.j2 b/autogpt_platform/backend/backend/notifications/templates/changelog.subject.j2
new file mode 100644
index 0000000000..2a80ada6ae
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/changelog.subject.j2
@@ -0,0 +1,2 @@
+AutoGPT Update — {{ edition_label }}
+{{ subject_teaser }}
diff --git a/autogpt_platform/backend/backend/notifications/templates/lifecycle.html.j2 b/autogpt_platform/backend/backend/notifications/templates/lifecycle.html.j2
new file mode 100644
index 0000000000..f311d1df9e
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/lifecycle.html.j2
@@ -0,0 +1,145 @@
+{#- ============================================================
+ lifecycle.html.j2 — billing & account emails, one template.
+ kind: welcome | drip1 | payment_failed | final_notice |
+ cancel_confirmed | cancel_reversed | ended | trial_ending
+ Plan-bearing kinds receive `plan`:
+ { name, label ("Pro — monthly"), price_display ("$50.00 / month"),
+ cycle ("monthly"|"yearly"), cycle_noun ("month"|"year") }
+ Every sentence is assembled from context slots — no per-scenario
+ copy edits. See make_lifecycle_scenarios.py for the context schema.
+ ============================================================ -#}
+{%- import "_lifecycle_ui.j2" as ui with context -%}
+<!doctype html>
+<html lang="en">
+<head>
+{{ ui.head_block(subject) }}
+</head>
+<body style="margin:0; padding:0; background-color:#f1efe9; -webkit-text-size-adjust:100%; font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
+{{ ui.preheader(preheader) }}
+{{ ui.page_open() }}
+{{ ui.masthead() }}
+{%- if kind == 'welcome' %}
+{{ ui.hero('welcome') }}
+{%- elif kind == 'payment_failed' %}
+{{ ui.hero('payment_hiccup') }}
+{%- elif kind == 'final_notice' %}
+{{ ui.hero('final_notice') }}
+{%- elif kind == 'cancel_confirmed' %}
+{{ ui.hero('cancel_safe') }}
+{%- elif kind == 'cancel_reversed' %}
+{{ ui.hero('welcome_back') }}
+{%- elif kind == 'ended' %}
+{{ ui.hero('plan_asleep') }}
+{%- else %}
+{{ ui.hero('trial_headsup') }}
+{%- endif %}
+ <tr><td bgcolor="#ffffff" style="border-radius:0 0 14px 14px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+{%- if kind == 'welcome' %}
+{% call ui.eyebrow(color='#1c7a52') %}PLAN ACTIVE · {{ plan.label | upper }}{% endcall %}
+{% call ui.headline() %}You're in. Let's put an agent to work.{% endcall %}
+{% call ui.para() %}Hi {{ user_name }} — your {{ plan.name }} subscription is active and everything on your plan is unlocked. Here's your setup at a glance:{% endcall %}
+{{ ui.kvpanel([('Plan', plan.label, false), ('Price', plan.price_display, true), ('Renews', renews_label, true)]) }}
+{% call ui.para() %}The best first step takes about ten minutes: pick a ready-made agent from the Marketplace, connect it to something you actually use, and watch it run.{% endcall %}
+{{ ui.cta('Build your first agent', urls.marketplace, 'Takes about ten minutes with a Marketplace agent — no building on day one.') }}
+{{ ui.also_panel('Three good places to start', [
+ ('The quick-start guide', '— from zero to a running agent, step by step.', 'Open the guide', urls.docs),
+ ('The Marketplace', '— proven agents you can use as-is or remix.', 'Browse agents', urls.marketplace),
+ ('Discord', "— where builders share what's working.", 'Join in', urls.discord),
+]) }}
+{{ ui.signature('Toran Bruce Richards', 'Founder · AutoGPT') }}
+{{ ui.close_row('You can change or cancel your plan any time.', 'Billing settings', urls.billing) }}
+{%- elif kind == 'drip1' %}
+{% call ui.eyebrow(color='#5635b2') %}GETTING STARTED · {{ series.n }} OF {{ series.of }}{% endcall %}
+{% call ui.headline() %}Ten minutes to your first working agent{% endcall %}
+{% call ui.para() %}Yesterday you joined AutoGPT. Today, let's make it earn its keep. The fastest way to understand agents isn't reading about them — it's watching one do a job you'd rather not do yourself.{% endcall %}
+{{ ui.steps([
+ ('Pick a job, not a demo.', 'Something small and real: summarise your unread newsletters, watch a webpage for changes, draft replies to a form inbox.'),
+ ('Grab a Marketplace agent.', 'Search for that job — most agents work out of the box, no building required on day one.'),
+ ('Connect one thing.', 'A single account (say, Gmail or a webhook) is enough to see the whole loop run.'),
+ ('Press run, then schedule it.', "Run it once manually. Happy with the result? Set a schedule and it's off your plate for good."),
+]) }}
+{{ ui.cta('Open the Marketplace', urls.marketplace, "Tomorrow: how to read what your agent did while you weren't looking.") }}
+{{ ui.close_row('You are getting the getting-started series because you joined AutoGPT this week.', 'Choose which emails you get', urls.prefs) }}
+{%- elif kind == 'payment_failed' %}
+{{ ui.strip_amber('NEEDS YOU · PAYMENT DECLINED') }}
+{% call ui.headline(top=26) %}Your payment didn't go through{% endcall %}
+{% call ui.para() %}Hi {{ user_name }} — we tried to charge your card for this {{ plan.cycle_noun }}'s renewal on your {{ plan.name }} plan, and the payment was declined. This happens: cards expire, banks get cautious, limits get hit. Your plan and your agents keep running normally while we retry.{% endcall %}
+{{ ui.kvpanel([('Amount', amount_display, true), ('Card', card.brand ~ ' ···· ' ~ card.last4, true), ('Next retry', next_retry_label ~ ' · automatic', true)]) }}
+{% call ui.para() %}If the card details are out of date, fixing it takes about a minute:{% endcall %}
+{{ ui.cta('Update payment method', urls.billing, "Already updated your card? You're set — we'll charge the new one on the next retry.") }}
+{{ ui.close_row('You will only hear about this again if the automatic retries fail.', 'Billing settings', urls.billing) }}
+{%- elif kind == 'final_notice' %}
+{{ ui.strip_amber('FINAL NOTICE · PLAN PAUSES ' ~ (pauses_label | upper)) }}
+{% call ui.headline(top=26) %}Last try — let's keep your agents running{% endcall %}
+{% call ui.para() %}Hi {{ user_name }} — we've attempted this {{ plan.cycle_noun }}'s payment for your {{ plan.name }} plan several times over the past two weeks, and each attempt was declined. This is the final notice before your plan pauses.{% endcall %}
+{{ ui.kvpanel([('Amount due', amount_display, true), ('Plan pauses on', pauses_label, true), ('What pauses', 'Scheduled runs & ' ~ plan.name ~ ' features', false)]) }}
+{% call ui.note_card('If the plan pauses', tone='amber') %}Scheduled agents stop running until a payment succeeds — then everything picks up exactly where it left off. Your agents and their data are kept safe; nothing is deleted.{% endcall %}
+{{ ui.cta('Update payment method', urls.billing, 'Card working fine on your side? Banks sometimes block recurring charges — a quick call to yours usually clears it.') }}
+{{ ui.close_row('Stuck? Reply to this email — a human reads it.', 'Billing settings', urls.billing) }}
+{%- elif kind == 'cancel_confirmed' %}
+{% call ui.eyebrow() %}YOUR PLAN · ENDS {{ access_until_label | upper }}{% endcall %}
+{% call ui.headline() %}Cancellation confirmed{% endcall %}
+{% call ui.para() %}Hi {{ user_name }} — we've cancelled the renewal on your {{ plan.name }} plan, as requested. No further charges will be made, and you keep full {{ plan.name }} access for the time you've already paid for.{% endcall %}
+{{ ui.kvpanel([('Plan', plan.label, false), ('Access until', access_until_label, true), ('After that', 'Agents pause — work kept safe', false)]) }}
+{% call ui.para() %}When the plan ends, your agents and everything you've built stay saved in your account — they just stop running on schedule. Come back any time and switch them on again.{% endcall %}
+{{ ui.cta('Resume my plan', urls.billing, 'Only if you change your mind before ' ~ access_until_label ~ " — otherwise there's nothing more to do.") }}
+{% call ui.para(color='#575072', size=13, lh=20, top=20) %}Thanks for building with us. If something didn't work the way you needed, reply and tell us — it comes straight to me, and I read every one.{% endcall %}
+{{ ui.signature('John Ababseh', 'Product Manager · AutoGPT', '[email protected]', top=18) }}
+{{ ui.close_row('This confirmation was sent the moment you cancelled.', 'Billing settings', urls.billing) }}
+{%- elif kind == 'cancel_reversed' %}
+{% call ui.eyebrow(color='#1c7a52') %}YOUR PLAN · RESUMED{% endcall %}
+{% call ui.headline() %}Welcome back — your plan continues{% endcall %}
+{% call ui.para() %}Hi {{ user_name }} — you've resumed your {{ plan.name }} plan, so the cancellation is off. Nothing pauses, nothing changes: your agents keep running exactly as before.{% endcall %}
+{{ ui.kvpanel([('Plan', plan.label, false), ('Next renewal', renews_label, true), ('Price', plan.price_display, true)]) }}
+{% call ui.note_card('About that earlier email') %}The message saying your plan would end no longer applies — you can safely ignore it.{% endcall %}
+{{ ui.cta('Back to my agents', urls.dashboard) }}
+{{ ui.close_row('Glad to have you along.', 'Billing settings', urls.billing) }}
+{%- elif kind == 'ended' %}
+{% call ui.eyebrow() %}YOUR PLAN · ENDED {{ ended_label | upper }}{% endcall %}
+{% call ui.headline() %}Your plan has ended{% endcall %}
+{%- if due_to_payment %}
+{% call ui.para() %}Hi {{ user_name }} — we couldn't collect payment for your {{ plan.name }} plan after several attempts, so it ended today and paid features are now switched off. Here's exactly where things stand:{% endcall %}
+{{ ui.kvpanel([('Ended on', ended_label, true), ('Why', 'Payment could not be collected', false), ('Your agents', 'Paused — saved as you left them', false), ('Your data', 'Kept safe in your account', false)]) }}
+{%- else %}
+{% call ui.para() %}Hi {{ user_name }} — your {{ plan.name }} plan reached the end of its billing period today, as scheduled after your cancellation, so paid features are now switched off. Here's exactly where things stand:{% endcall %}
+{{ ui.kvpanel([('Ended on', ended_label, true), ('Your agents', 'Paused — saved as you left them', false), ('Your data', 'Kept safe in your account', false)]) }}
+{%- endif %}
+{% call ui.para() %}Everything you built is one click from running again. Restart whenever you're ready and your agents pick up where they left off — schedules, connections and all.{% endcall %}
+{%- if due_to_payment %}
+{{ ui.cta('Restart my plan', urls.billing, 'Restarting takes a working card — you can update it in the same place.') }}
+{%- else %}
+{{ ui.cta('Restart my plan', urls.billing, 'Your account stays free to use in the meantime.') }}
+{%- endif %}
+{% call ui.para(color='#575072', size=13, lh=20, top=20) %}Not the right time? I'd genuinely love to hear what would have made {{ plan.name }} worth keeping — just reply, it comes straight to me.{% endcall %}
+{{ ui.signature('John Ababseh', 'Product Manager · AutoGPT', '[email protected]', top=18) }}
+{{ ui.close_row("We don't delete your work when a plan ends.", 'Billing settings', urls.billing) }}
+{%- elif kind == 'trial_ending' %}
+{% call ui.eyebrow(color='#5635b2') %}YOUR TRIAL · {{ days_left }} DAYS LEFT{% endcall %}
+{% call ui.headline() %}{{ days_left_word }} days left on your trial{% endcall %}
+{% call ui.para() %}Hi {{ user_name }} — your AutoGPT {{ plan.name }} trial ends on <strong style="color:#070629;">{{ ends_label }}</strong>. No surprises; here's exactly what happens next:{% endcall %}
+{%- if has_payment_method %}
+{{ ui.kvpanel([('Trial ends', ends_label, true), ('Then', plan.name ~ ' continues at ' ~ plan.price_display, true), ('First charge', first_charge_label ~ ' · ' ~ card.brand ~ ' ···· ' ~ card.last4, true)]) }}
+{% call ui.para() %}If AutoGPT has been pulling its weight, you don't need to do a thing — your plan continues automatically and your agents never miss a run. Want a moment to decide? You can cancel in two clicks, keep everything you've built, and come back later.{% endcall %}
+{{ ui.cta('Review my plan', urls.billing, 'Cancel before ' ~ ends_label ~ " and you won't be charged anything.") }}
+{%- else %}
+{{ ui.kvpanel([('Trial ends', ends_label, true), ('To continue', plan.name ~ ' at ' ~ plan.price_display, true), ('Payment method', 'None on file yet', false)]) }}
+{% call ui.para() %}There's no card on file, so nothing will ever be charged automatically. If you want {{ plan.name }} to continue after the trial, add a payment method before {{ ends_label }} — otherwise your trial simply ends, and everything you've built stays saved on the free tier.{% endcall %}
+{{ ui.cta('Add a payment method', urls.billing, 'Takes about a minute — and nothing is charged until the trial actually ends.') }}
+{%- endif %}
+{{ ui.close_row('One email, ' ~ days_left ~ ' days ahead — that is the whole reminder.', 'Billing settings', urls.billing) }}
+{%- endif %}
+ </table>
+ </td></tr>
+{{ ui.page_close() }}
+{%- if kind == 'drip1' %}
+{{ ui.legal_footer('This is part ' ~ series.n ~ ' of ' ~ series.of ~ ' of the getting-started series, for ' ~ user_email ~ '.', 'Unsubscribe', urls.unsubscribe, discord=true) }}
+{%- elif kind == 'welcome' %}
+{{ ui.legal_footer("This is a service message about the AutoGPT account for " ~ user_email ~ " — it's sent even if you've opted out of product news.", 'Email preferences', urls.prefs, discord=true) }}
+{%- else %}
+{{ ui.legal_footer("This is a service message about the AutoGPT account for " ~ user_email ~ " — it's sent even if you've opted out of product news.", 'Email preferences', urls.prefs, discord=false) }}
+{%- endif %}
+
+</td></tr>
+</table>
+</body></html>
diff --git a/autogpt_platform/backend/backend/notifications/templates/lifecycle.subject.j2 b/autogpt_platform/backend/backend/notifications/templates/lifecycle.subject.j2
new file mode 100644
index 0000000000..b81b36f09c
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/lifecycle.subject.j2
@@ -0,0 +1,9 @@
+{% if kind == 'welcome' %}Welcome to AutoGPT — your {{ plan.name }} plan is live
+Your {{ plan.label }} plan is active. Here's the fastest route to your first working agent.{% elif kind == 'drip1' %}Build your first agent in 10 minutes
+Ten minutes, one working agent. Let's build.{% elif kind == 'payment_failed' %}We couldn't process your payment
+No panic — we'll retry automatically on {{ next_retry_label }}. Updating your card takes a minute.{% elif kind == 'final_notice' %}Action needed: your AutoGPT plan pauses on {{ pauses_label }}
+We've tried several times without luck. One click keeps your agents running.{% elif kind == 'cancel_confirmed' %}Your cancellation is confirmed
+Your plan stays active until {{ access_until_label }}. Nothing is deleted.{% elif kind == 'cancel_reversed' %}Your AutoGPT plan will continue
+Good news — your {{ plan.name }} plan renews on {{ renews_label }} as usual.{% elif kind == 'ended' %}Your AutoGPT plan has ended
+{% if due_to_payment %}We couldn't collect payment. Your agents are paused, not deleted — restarting takes one click.{% else %}Your agents are paused, not deleted. Pick up right where you left off.{% endif %}{% elif kind == 'trial_ending' %}Your free trial ends on {{ ends_label }}
+{% if has_payment_method %}Your trial ends in {{ days_left }} days. Here's exactly what happens next.{% else %}Your trial ends in {{ days_left }} days — nothing is charged unless you add a card.{% endif %}{% endif %}
diff --git a/autogpt_platform/backend/backend/notifications/templates/lifecycle.txt.j2 b/autogpt_platform/backend/backend/notifications/templates/lifecycle.txt.j2
new file mode 100644
index 0000000000..7dbed1beb3
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/lifecycle.txt.j2
@@ -0,0 +1,192 @@
+{#- Plain-text part of the billing and account messages, branching on the same
+ `kind` as the HTML template and assembled from the same slots. The trial
+ branch of lifecycle.html.j2 has no counterpart here on purpose: the
+ platform does not offer trials and never emits that kind. -#}
+{{ subject }}
+
+{{ preheader }}
+
+{% if kind == 'welcome' %}
+PLAN ACTIVE - {{ plan.label | upper }}
+
+You're in. Let's put an agent to work.
+
+Hi {{ user_name }} - your {{ plan.name }} subscription is active and everything on your
+plan is unlocked. Here's your setup at a glance:
+
+Plan: {{ plan.label }}
+Price: {{ plan.price_display }}
+Renews: {{ renews_label }}
+
+The best first step takes about ten minutes: pick a ready-made agent from the
+Marketplace, connect it to something you actually use, and watch it run.
+
+Build your first agent: {{ urls.marketplace }}
+
+Three good places to start
+- The quick-start guide - from zero to a running agent: {{ urls.docs }}
+- The Marketplace - proven agents you can use as-is: {{ urls.marketplace }}
+- Discord - where builders share what's working: {{ urls.discord }}
+
+Toran Bruce Richards
+Founder - AutoGPT
+
+You can change or cancel your plan any time: {{ urls.billing }}
+{% elif kind == 'drip1' %}
+GETTING STARTED - {{ series.n }} OF {{ series.of }}
+
+Ten minutes to your first working agent
+
+Yesterday you joined AutoGPT. Today, let's make it earn its keep. The fastest
+way to understand agents isn't reading about them - it's watching one do a job
+you'd rather not do yourself.
+
+1. Pick a job, not a demo.
+ Something small and real: summarise your unread newsletters, watch a
+ webpage for changes, draft replies to a form inbox.
+
+2. Grab a Marketplace agent.
+ Search for that job - most agents work out of the box, no building
+ required on day one.
+
+3. Connect one thing.
+ A single account (say, Gmail or a webhook) is enough to see the whole
+ loop run.
+
+4. Press run, then schedule it.
+ Run it once manually. Happy with the result? Set a schedule and it's off
+ your plate for good.
+
+Open the Marketplace: {{ urls.marketplace }}
+
+Tomorrow: how to read what your agent did while you weren't looking.
+{% elif kind == 'payment_failed' %}
+NEEDS YOU - PAYMENT DECLINED
+
+Your payment didn't go through.
+
+Hi {{ user_name }} - we tried to charge your card for this {{ plan.cycle_noun }}'s renewal on your
+{{ plan.name }} plan, and the payment was declined. This happens: cards expire, banks
+get cautious, limits get hit. Your plan and your agents keep running normally
+while we retry.
+
+Amount: {{ amount_display }}
+Card: {{ card.brand }} .... {{ card.last4 }}
+Next retry: {{ next_retry_label }} - automatic
+
+If the card details are out of date, fixing it takes about a minute.
+
+Update payment method: {{ urls.billing }}
+
+You will only hear about this again if the automatic retries fail.
+{% elif kind == 'final_notice' %}
+FINAL NOTICE - PLAN PAUSES {{ pauses_label | upper }}
+
+Last try - let's keep your agents running.
+
+Hi {{ user_name }} - we've attempted this {{ plan.cycle_noun }}'s payment for your {{ plan.name }} plan
+several times over the past two weeks, and each attempt was declined. This is
+the final notice before your plan pauses.
+
+Amount due: {{ amount_display }}
+Plan pauses on: {{ pauses_label }}
+What pauses: Scheduled runs & {{ plan.name }} features
+
+If the plan pauses, scheduled agents stop running until a payment succeeds -
+then everything picks up exactly where it left off. Your agents and their data
+are kept safe; nothing is deleted.
+
+Update payment method: {{ urls.billing }}
+
+Stuck? Reply to this email - a human reads it.
+{% elif kind == 'cancel_confirmed' %}
+YOUR PLAN - ENDS {{ access_until_label | upper }}
+
+Cancellation confirmed.
+
+Hi {{ user_name }} - we've cancelled the renewal on your {{ plan.name }} plan, as requested.
+No further charges will be made, and you keep full {{ plan.name }} access for the time
+you've already paid for.
+
+Plan: {{ plan.label }}
+Access until: {{ access_until_label }}
+After that: Agents pause - work kept safe
+
+When the plan ends, your agents and everything you've built stay saved in your
+account - they just stop running on schedule. Come back any time and switch
+them on again.
+
+Resume my plan: {{ urls.billing }}
+
+Thanks for building with us. If something didn't work the way you needed,
+reply and tell us - it comes straight to me, and I read every one.
+
+John Ababseh
+Product Manager - AutoGPT
+{% elif kind == 'cancel_reversed' %}
+YOUR PLAN - RESUMED
+
+Welcome back - your plan continues.
+
+Hi {{ user_name }} - you've resumed your {{ plan.name }} plan, so the cancellation is off.
+Nothing pauses, nothing changes: your agents keep running exactly as before.
+
+Plan: {{ plan.label }}
+Next renewal: {{ renews_label }}
+Price: {{ plan.price_display }}
+
+About that earlier email: the message saying your plan would end no longer
+applies - you can safely ignore it.
+
+Back to my agents: {{ urls.dashboard }}
+{% elif kind == 'ended' %}
+YOUR PLAN - ENDED {{ ended_label | upper }}
+
+Your plan has ended.
+
+{% if due_to_payment %}
+Hi {{ user_name }} - we couldn't collect payment for your {{ plan.name }} plan after several
+attempts, so it ended today and paid features are now switched off. Here's
+exactly where things stand:
+
+Ended on: {{ ended_label }}
+Why: Payment could not be collected
+Your agents: Paused - saved as you left them
+Your data: Kept safe in your account
+{% else %}
+Hi {{ user_name }} - your {{ plan.name }} plan reached the end of its billing period today, as
+scheduled after your cancellation, so paid features are now switched off.
+Here's exactly where things stand:
+
+Ended on: {{ ended_label }}
+Your agents: Paused - saved as you left them
+Your data: Kept safe in your account
+{% endif %}
+
+Everything you built is one click from running again. Restart whenever you're
+ready and your agents pick up where they left off - schedules, connections and
+all.
+
+Restart my plan: {{ urls.billing }}
+
+Not the right time? I'd genuinely love to hear what would have made {{ plan.name }}
+worth keeping - just reply, it comes straight to me.
+
+John Ababseh
+Product Manager - AutoGPT
+{% endif %}
+
+--
+{% if kind == 'drip1' %}
+This is part {{ series.n }} of {{ series.of }} of the getting-started series,
+for {{ user_email }}.
+Unsubscribe: {{ urls.unsubscribe }}
+{% else %}
+This is a service message about the AutoGPT account for {{ user_email }} - it's
+sent even if you've opted out of product news.
+Email preferences: {{ urls.prefs }}
+{% endif %}
+
+AutoGPT, 3rd Floor, 1 Ashley Road, Altrincham, WA14 2DT, UK
diff --git a/autogpt_platform/backend/backend/notifications/templates/low_balance.html.jinja2 b/autogpt_platform/backend/backend/notifications/templates/low_balance.html.jinja2
deleted file mode 100644
index 8be13d0473..0000000000
--- a/autogpt_platform/backend/backend/notifications/templates/low_balance.html.jinja2
+++ /dev/null
@@ -1,103 +0,0 @@
-{# Low Balance Notification Email Template #}
-{# Template variables:
-data.current_balance: the current balance of the user
-data.billing_page_link: the link to the billing page
-#}
-
-<p style="
- font-family: 'Poppins', sans-serif;
- color: #070629;
- font-size: 16px;
- line-height: 165%;
- margin-top: 0;
- margin-bottom: 10px;
- ">
- <strong>Low Balance Warning</strong>
-</p>
-
-<p style="
- font-family: 'Poppins', sans-serif;
- color: #070629;
- font-size: 16px;
- line-height: 165%;
- margin-top: 0;
- margin-bottom: 20px;
- ">
- Your account balance has dropped below the recommended threshold.
-</p>
-
-<div style="
- margin-left: 15px;
- margin-bottom: 20px;
- padding: 15px;
- border-left: 4px solid #5D23BB;
- background-color: #f8f8ff;
- ">
- <p style="
- font-family: 'Poppins', sans-serif;
- color: #070629;
- font-size: 16px;
- margin-top: 0;
- margin-bottom: 10px;
- ">
- <strong>Current Balance:</strong> ${{ "{:.2f}".format((data.current_balance|float)/100) }}
- </p>
-</div>
-
-
-<div style="
- margin-left: 15px;
- margin-bottom: 20px;
- padding: 15px;
- border-left: 4px solid #FF6B6B;
- background-color: #FFF0F0;
- ">
- <p style="
- font-family: 'Poppins', sans-serif;
- color: #070629;
- font-size: 16px;
- margin-top: 0;
- margin-bottom: 10px;
- ">
- <strong>Low Balance:</strong>
- </p>
- <p style="
- font-family: 'Poppins', sans-serif;
- color: #070629;
- font-size: 16px;
- margin-top: 0;
- margin-bottom: 5px;
- ">
- Your account requires additional credits to continue running agents. Please add credits to your account to avoid service interruption.
- </p>
-</div>
-
-<div style="
- text-align: center;
- margin: 30px 0;
- ">
- <a href="{{ data.billing_page_link }}" style="
- font-family: 'Poppins', sans-serif;
- background-color: #5D23BB;
- color: white;
- padding: 12px 24px;
- text-decoration: none;
- border-radius: 4px;
- font-weight: 500;
- display: inline-block;
- ">
- Manage Billing
- </a>
-</div>
-
-<p style="
- font-family: 'Poppins', sans-serif;
- color: #070629;
- font-size: 16px;
- line-height: 150%;
- margin-top: 30px;
- margin-bottom: 10px;
- font-style: italic;
- ">
- This is an automated low balance notification. Consider adding credits soon to avoid service interruption.
-</p>
diff --git a/autogpt_platform/backend/backend/notifications/templates/onboarding.html.j2 b/autogpt_platform/backend/backend/notifications/templates/onboarding.html.j2
new file mode 100644
index 0000000000..88ccda9e89
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/onboarding.html.j2
@@ -0,0 +1,107 @@
+{#- ============================================================
+ onboarding.html.j2 — the 6-email "White Glove Tour"
+ (John Ababseh's MailerLite sequence, re-skinned to the unified
+ design system). One template; `part` (1–6) selects the email.
+ Context: user_name, user_email, part, of, day, urls
+ Sent from MailerLite · marketing footer · signed by John.
+ ============================================================ -#}
+{%- import "_lifecycle_ui.j2" as ui with context -%}
+<!doctype html>
+<html lang="en">
+<head>
+{{ ui.head_block(subject) }}
+</head>
+<body style="margin:0; padding:0; background-color:#eceaf6; -webkit-text-size-adjust:100%; font-family:'Poppins',Helvetica,Arial,sans-serif;">
+{{ ui.preheader(preheader) }}
+{{ ui.page_open() }}
+{{ ui.masthead() }}
+{%- set TOUR_HEROES = {1: 'tour_firstwin', 2: 'tour_fiveways', 3: 'tour_workspace',
+ 4: 'tour_listening', 5: 'tour_shipping', 6: 'tour_directline'} -%}
+{{ ui.hero(TOUR_HEROES[part]) }}
+ <tr><td bgcolor="#ffffff" style="border-radius:0 0 16px 16px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+{%- if part == 1 %}
+{% call ui.eyebrow(color='#5635b2') %}PART 1 OF {{ of }} · GETTING STARTED{% endcall %}
+{% call ui.headline() %}Welcome — let's get you your first win{% endcall %}
+{% call ui.para() %}Hi {{ user_name }} — welcome aboard, and thank you for subscribing. You now have the full platform, and over the next two weeks I'll send you a short tour: one email at a time, each with something real you can do in a couple of minutes.{% endcall %}
+{% call ui.para() %}I'm John, and I work on product here. You can reply to any of these emails and it comes straight to me — that's not a support queue, it's my inbox.{% endcall %}
+{% call ui.para(top=22) %}<strong style="color:#070629;">Your first win, in 2 minutes:</strong>{% endcall %}
+{{ ui.steps([
+ ('Open AutoPilot.', "It's the first thing you see when you log in."),
+ ('Describe a task in plain language.', 'Try: "Research the top 5 competitors in my space and summarize their pricing."'),
+ ('Watch it work.', 'AutoPilot figures out the steps, runs them, and delivers the result — while you do something else.'),
+]) }}
+{{ ui.cta('Open AutoPilot', urls.dashboard) }}
+{{ ui.media_link('A quick welcome from our founder', '90 seconds on why we built this — and what we hope you do with it.', urls.founder_video) }}
+{% call ui.para(color='#575072', size=13, lh=20, top=18) %}Next up: the five workflows our users run most — steal them.{% endcall %}
+{%- elif part == 2 %}
+{% call ui.eyebrow(color='#5635b2') %}PART 2 OF {{ of }} · FIRST WORKFLOWS{% endcall %}
+{% call ui.headline() %}5 tasks you can hand to AutoPilot today{% endcall %}
+{% call ui.para() %}Hi {{ user_name }} — the best way to get value out of AutoGPT isn't to explore menus. It's to hand it something from your actual to-do list. Here are five workflows that ran start-to-finish in our demo, with zero hand-holding:{% endcall %}
+{{ ui.emoji_cards([
+ ('🖥', 'Engineering & bug triage', 'Connected to Sentry, ranked bugs by impact, pushed sprint actions to Linear, and notified the team on Discord.'),
+ ('📦', 'End-to-end marketing', 'Pulled release notes from GitHub, wrote a changelog email in our brand voice, and built it in send-ready HTML.'),
+ ('📈', 'Strategy & competitive intel', 'Analyzed 13 competitors, built a SWOT with threat scores, and delivered an interactive strategy report.'),
+ ('🔍', 'Talent sourcing & outreach', 'Took a job description, sourced and scored candidates, and wrote personalized outreach — ready to send.'),
+ ('🎯', 'Sales funnel & demo prep', 'Found leads matching our ICP, built curated demo agents, and wrote scripts and follow-up questions.'),
+]) }}
+{{ ui.media_link('Watch all five in 6 minutes', 'Everything in the demo ran autonomously — and these five are just what fit in six minutes.', urls.demo_video) }}
+{% call ui.para() %}Pick the one closest to your work, open AutoPilot, and describe it in your own words. That's it — no setup, no flowcharts.{% endcall %}
+{{ ui.cta('Try a workflow', urls.dashboard) }}
+{% call ui.para(color='#575072', size=13, lh=20, top=18) %}Next up: a tour of your workspace — artifacts, briefings, and the builder.{% endcall %}
+{%- elif part == 3 %}
+{% call ui.eyebrow(color='#5635b2') %}PART 3 OF {{ of }} · KNOW YOUR WORKSPACE{% endcall %}
+{% call ui.headline() %}A quick tour of your workspace{% endcall %}
+{% call ui.para() %}Hi {{ user_name }} — now that you've run a task or two, here's what the rest of your workspace does for you. Three things worth knowing about, so you know them when you see them:{% endcall %}
+{{ ui.emoji_cards([
+ ('🎨', 'Artifacts, right in the conversation', 'Reports open as interactive documents, charts render live, and PDFs are readable in a side panel. No downloads, no tab-juggling.'),
+ ('📋', 'Agent briefings at a glance', "Your Home screen shows a live briefing for each agent: what it's doing, what it finished, and what's next. Scheduled agents surface their upcoming runs automatically."),
+ ('💬', 'Chat with your builder', 'Building a custom workflow? The flow builder has its own AI chat panel that knows your graph and helps you debug or extend it — without switching context.'),
+]) }}
+{{ ui.cta('Open AutoGPT', urls.dashboard) }}
+{% call ui.para(color='#575072', size=13, lh=20, top=18) %}Next up: a quick personal check-in from me. No screenshots, no buttons — just a question.{% endcall %}
+{%- elif part == 4 %}
+{% call ui.eyebrow(color='#5635b2') %}PART 4 OF {{ of }} · JUST A QUESTION{% endcall %}
+{% call ui.headline() %}How's it going so far?{% endcall %}
+{% call ui.para() %}Hi {{ user_name }} — quick one from me. No screenshots, no buttons.{% endcall %}
+{% call ui.para() %}You've had AutoGPT for a week now. <strong style="color:#070629;">How's it actually going?</strong> Did something click? Did something get in your way?{% endcall %}
+{% call ui.para() %}I ask because we're a small team, we ship every week, and the roadmap is genuinely shaped by what subscribers tell us. If AutoPilot mis-handled a task, or there's a feature you keep wishing existed, I want to know about it — the unpolished version is the most useful version.{% endcall %}
+{% call ui.para() %}<strong style="color:#070629;">Just hit reply.</strong> It comes straight to me, and I read every single one.{% endcall %}
+{% call ui.para(color='#575072', size=13, lh=20, top=18) %}P.S. If it's easier: here's a <a href="{{ urls.feedback_form }}" style="color:#5635b2; text-decoration:underline;">2-minute feedback form</a>, or <a href="{{ urls.booking }}" style="color:#5635b2; text-decoration:underline;">book 30 minutes with me</a> — no agenda needed.{% endcall %}
+{%- elif part == 5 %}
+{% call ui.eyebrow(color='#5635b2') %}PART 5 OF {{ of }} · ALWAYS SHIPPING{% endcall %}
+{% call ui.headline() %}We shipped while you were reading this{% endcall %}
+{% call ui.para() %}Hi {{ user_name }} — one thing subscribers tell us they didn't expect: the pace. We ship improvements every week, and everything lands in the public changelog — so you always know what's new and what your feedback turned into.{% endcall %}
+{% call ui.para(top=22) %}<strong style="color:#070629;">Shipped in the last few weeks:</strong>{% endcall %}
+{{ ui.emoji_cards([
+ ('🎨', 'Rich artifacts in a side panel', 'Reports, charts, PDFs — even playable games — open right beside the conversation.'),
+ ('📋', 'Live agent briefings', 'On your Home screen, with upcoming run times for every scheduled agent.'),
+ ('💬', 'An AI chat panel inside the flow builder', 'It knows your graph and helps you debug or extend it.'),
+ ('🔔', 'Web push notifications', 'Plus long-term memory blocks and the latest models — Claude Opus 4.7 and Grok.'),
+]) }}
+{{ ui.cta("See what's new", urls.changelog) }}
+{% call ui.para() %}The best part of shipping weekly: your feedback doesn't sit in a backlog for a year. The Give Feedback button inside the app goes to the same board we plan our sprints from.{% endcall %}
+{% call ui.para(color='#575072', size=13, lh=20, top=18) %}Next up: the last email of the tour — and the most important one.{% endcall %}
+{%- else %}
+{% call ui.eyebrow(color='#5635b2') %}PART 6 OF {{ of }} · YOU'RE IN{% endcall %}
+{% call ui.headline() %}Your direct line to the team{% endcall %}
+{% call ui.para() %}Hi {{ user_name }} — that's the end of the tour. You know your way around AutoPilot, your workspace, and everything we ship weekly. From here on we mostly stay out of your inbox: you'll hear from us when there's something genuinely new.{% endcall %}
+{% call ui.para(top=22) %}<strong style="color:#070629;">Before I go, three things worth keeping:</strong>{% endcall %}
+{{ ui.emoji_cards([
+ ('💬', 'The community', "5,000+ builders share what they're automating in our Discord. The team is in there daily — it's the fastest way to get unstuck."),
+ ('📝', 'The feedback form', "Two minutes, and it directly shapes the roadmap — what's working, what's not, what you wish existed."),
+ ('📅', 'A call with me', "If you'd rather talk it through: 30 minutes, no agenda. I'd love to hear what you're building and what you need from us."),
+]) }}
+{% call ui.para() %}We built AutoGPT to be the business partner you always needed. Thanks for giving us the chance to prove it.{% endcall %}
+{{ ui.cta('Join the Discord', urls.discord) }}
+{%- endif %}
+{{ ui.signature('John Ababseh', 'Product Manager · AutoGPT', '[email protected]') }}
+{{ ui.close_row('Email ' ~ part ~ ' of ' ~ of ~ ' in the getting-started tour · day ' ~ day ~ '.', 'Choose which emails you get', urls.prefs) }}
+ </table>
+ </td></tr>
+{{ ui.page_close() }}
+{{ ui.legal_footer('You received this email because you signed up on our website. This is part ' ~ part ~ ' of ' ~ of ~ ' of the getting-started tour, for ' ~ user_email ~ '.', 'Unsubscribe', urls.unsubscribe, discord=true) }}
+
+</td></tr>
+</table>
+</body></html>
diff --git a/autogpt_platform/backend/backend/notifications/templates/onboarding.subject.j2 b/autogpt_platform/backend/backend/notifications/templates/onboarding.subject.j2
new file mode 100644
index 0000000000..3ca41bf651
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/onboarding.subject.j2
@@ -0,0 +1,7 @@
+{% if part == 1 %}Welcome to AutoGPT — let's get you your first win
+You're all set up. Here's the 2-minute path to your first task, done for you.{% elif part == 2 %}5 tasks you can hand to AutoPilot today
+Real workflows from real users. Steal the prompts and make them yours.{% elif part == 3 %}A quick tour of your workspace
+Artifacts, agent briefings, and an AI copilot inside the builder.{% elif part == 4 %}How's it going so far?
+A real question from a real person. Hit reply — it comes straight to me.{% elif part == 5 %}We shipped while you were reading this
+Weekly releases, a public changelog, and your feedback steering it all.{% else %}You made it — here's your direct line to the team
+The tour is done. The conversation isn't. Discord, feedback, or a call with me.{% endif %}
diff --git a/autogpt_platform/backend/backend/notifications/templates/ops.html.j2 b/autogpt_platform/backend/backend/notifications/templates/ops.html.j2
new file mode 100644
index 0000000000..078bdf52ca
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/ops.html.j2
@@ -0,0 +1,135 @@
+{#- ============================================================
+ ops.html.j2 — internal refund mail (REFUND_REQUEST / REFUND_PROCESSED)
+ Goes to the refunds alias, not to a customer. So: no mascot hero,
+ no Discord, no unsubscribe (it is not opt-in mail), no marketing
+ voice. The amount is the hero because that is the number the
+ person on call is deciding about.
+ kind: 'request' | 'processed'
+ ============================================================ -#}
+{%- import "_ui.j2" as ui with context -%}
+{%- set is_request = (kind == 'request') -%}
+{%- set amount_str = '$' ~ '{:,.2f}'.format(amount_cents / 100) -%}
+{%- set balance_str = '$' ~ '{:,.2f}'.format(balance_cents / 100) -%}
+{%- set headline = ('Approve or reject a ' ~ amount_str ~ ' refund') if is_request else (amount_str ~ ' refunded to ' ~ ui.trunc(user_name, 40)) -%}
+<!doctype html>
+<html lang="en">
+<head>
+{{ ui.head_block(subject | default(headline)) }}
+</head>
+<body style="margin:0; padding:0; background-color:#f1efe9; -webkit-text-size-adjust:100%; font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
+{{ ui.preheader(preheader | default(headline)) }}
+{{ ui.page_open() }}
+{{ ui.header() }}
+{{ ui.ops_band(
+ 'REFUND REQUEST' if is_request else 'REFUND PROCESSED',
+ amount_str,
+ ui.trunc(user_name, 30) ~ ' · ' ~ ui.trunc(user_email, 30),
+ ('Needs a decision · raised ' ~ age_label) if (is_request and age_label) else ('Needs a decision' if is_request else 'Completed — no action needed'),
+ '#f5a623' if is_request else '#4ade80') }}
+
+ <!-- Body card -->
+ <tr><td bgcolor="#ffffff" style="border-radius:0 0 14px 14px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+
+ <tr><td class="gutter" style="padding:26px 44px 0;">
+ <div style="font-size:16px; line-height:26px; color:#3b3757;">
+ {%- if is_request %}
+ {{ ui.trunc(user_name, 40) }} asked for {{ amount_str }} back on {{ requested_at_label }}.
+ Their balance right now is {{ balance_str }}.
+ {%- else %}
+ {{ amount_str }} was refunded to {{ ui.trunc(user_name, 40) }} on {{ processed_at_label }}
+ and the credits have been deducted. Their balance is now {{ balance_str }}.
+ This is a record for the log &mdash; nothing is waiting on you.
+ {%- endif %}
+ </div>
+ </td></tr>
+
+ <!-- Why -->
+ {%- if reason and reason | trim | length > 0 %}
+ <tr><td class="gutter" style="padding:22px 44px 0;">
+ {{ ui.note_card('In their words', reason, 'neutral') }}
+ </td></tr>
+ {%- else %}
+ <tr><td class="gutter" style="padding:18px 44px 0;">
+ <div style="font-size:14px; line-height:22px; color:#8a86a3;">
+ No reason was given with this request{{ ', so ask before deciding.' if is_request else '.' }}
+ </div>
+ </td></tr>
+ {%- endif %}
+
+ <!-- Ledger -->
+ <tr><td class="gutter" style="padding:22px 44px 0;">
+ {{ ui.section_label('THE RECORD') }}
+ </td></tr>
+ <tr><td class="gutter" style="padding:12px 44px 0;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#f7f6fc" style="border-radius:10px;">
+ <tr><td style="padding:14px 18px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+ {{ ui.kv('Customer', user_name, mono=false, first=true) }}
+ {{ ui.kv('Email', user_email, mono=true) }}
+ {{ ui.kv('User ID', user_id, mono=true) }}
+ {{ ui.kv('Transaction', transaction_id, mono=true) }}
+ {{ ui.kv('Request ID', refund_request_id, mono=true) }}
+ {{ ui.kv('Balance ' ~ ('now' if is_request else 'after refund'), balance_str, mono=true) }}
+ </table>
+ </td></tr>
+ </table>
+ </td></tr>
+
+ {%- if is_request %}
+ <!-- Decision -->
+ <tr><td class="gutter" style="padding:26px 44px 0;">
+ {{ ui.section_label('TO APPROVE') }}
+ </td></tr>
+ <tr><td class="gutter" style="padding:14px 44px 0;">
+ <div style="font-size:14px; line-height:22px; color:#494566; padding-bottom:13px;">
+ Issue the refund in Stripe. The balance adjustment on our side happens automatically once Stripe confirms.
+ </div>
+ {{ ui.btn('Refund ' ~ amount_str ~ ' in Stripe', stripe_url) }}
+ </td></tr>
+
+ <tr><td class="gutter" style="padding:26px 44px 0;">
+ {{ ui.section_label('TO REJECT') }}
+ </td></tr>
+ <tr><td class="gutter" style="padding:14px 44px 0;">
+ <div style="font-size:14px; line-height:22px; color:#494566; padding-bottom:11px;">
+ Open the request in the admin panel, mark it rejected, and write the reason &mdash; the customer sees what you write.
+ </div>
+ <table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr>
+ <td style="border:1px solid #d9d5ec; border-radius:8px;">
+ <a href="{{ admin_url }}" style="display:inline-block; padding:11px 20px; font-size:14px; font-weight:700; color:#5d23bb;">Open in the admin panel</a>
+ </td>
+ </tr></table>
+ </td></tr>
+ {%- else %}
+ <tr><td class="gutter" style="padding:22px 44px 0;">
+ <table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr>
+ <td style="border:1px solid #d9d5ec; border-radius:8px;">
+ <a href="{{ stripe_url }}" style="display:inline-block; padding:11px 20px; font-size:14px; font-weight:700; color:#5d23bb;">View the transaction in Stripe</a>
+ </td>
+ </tr></table>
+ </td></tr>
+ {%- endif %}
+
+ <tr><td align="center" class="gutter" style="padding:26px 44px 30px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+ <tr><td height="1" bgcolor="#eeecf5" style="font-size:0; line-height:0;">&nbsp;</td></tr>
+ <tr><td align="center" style="padding-top:14px; font-size:12px; line-height:19px; color:#8a86a3;">
+ {%- if is_request %}
+ This request stays open until someone acts on it. If two of you are looking, the admin panel shows who claimed it.
+ {%- else %}
+ Filed automatically when Stripe confirmed the refund.
+ {%- endif %}
+ </td></tr>
+ </table>
+ </td></tr>
+
+ </table>
+ </td></tr>
+{{ ui.page_close() }}
+{{ ui.internal_footer('Internal notification for the AutoGPT refunds team — sent to ' ~ recipient ~ '. Not customer-facing.') }}
+
+</td></tr>
+</table>
+</body>
+</html>
diff --git a/autogpt_platform/backend/backend/notifications/templates/ops.subject.j2 b/autogpt_platform/backend/backend/notifications/templates/ops.subject.j2
new file mode 100644
index 0000000000..2bd527f5b1
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/ops.subject.j2
@@ -0,0 +1,17 @@
+{#- Two lines: subject, then preheader. Amount leads, because that is what the
+ person on call triages by. -#}
+{%- set is_request = (kind == 'request') -%}
+{%- set amount_str = '$' ~ '{:,.2f}'.format(amount_cents / 100) -%}
+{%- set balance_str = '$' ~ '{:,.2f}'.format(balance_cents / 100) -%}
+{%- import "_ui.j2" as ui -%}
+{%- set name = ui.trunc(user_name, 38) -%}
+{%- set has_reason = reason and reason | trim | length > 0 -%}
+{%- set r = (reason | trim | replace('\n', ' ')) if has_reason else '' -%}
+{%- set r_short = ui.trunc(r, 105) -%}
+{%- if is_request -%}
+Refund needs a decision: {{ amount_str }} for {{ name }}
+{% if has_reason %}{{ r_short }}{% else %}No reason given. Balance now {{ balance_str }}.{% endif %}
+{%- else -%}
+Refunded {{ amount_str }} to {{ name }}
+{% if has_reason %}{{ r_short }}{% else %}Balance after refund {{ balance_str }}. Logged, nothing to do.{% endif %}
+{%- endif -%}
diff --git a/autogpt_platform/backend/backend/notifications/templates/ops.txt.j2 b/autogpt_platform/backend/backend/notifications/templates/ops.txt.j2
new file mode 100644
index 0000000000..82f3fb4d1d
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/ops.txt.j2
@@ -0,0 +1,49 @@
+{#- Plain-text part of the internal ops mail. No unsubscribe line: this is not
+ opt-in mail, and it must not carry List-Unsubscribe headers either. -#}
+{%- set is_request = (kind == 'request') -%}
+{%- set amount_str = '$' ~ '{:,.2f}'.format(amount_cents / 100) -%}
+{%- set balance_str = '$' ~ '{:,.2f}'.format(balance_cents / 100) -%}
+{{ 'REFUND REQUEST' if is_request else 'REFUND PROCESSED' }}{% if age_label %} - RAISED {{ age_label }}{% endif %}
+
+
+{{ amount_str }}
+{{ subject }}
+
+{% if is_request %}
+{{ user_name }} asked for {{ amount_str }} back on {{ requested_at_label }}.
+Their balance right now is {{ balance_str }}.
+{% else %}
+{{ amount_str }} was refunded to {{ user_name }} on {{ processed_at_label }} and the
+credits have been deducted. Their balance is now {{ balance_str }}.
+{% endif %}
+{% if reason and reason | trim | length > 0 %}
+
+IN THEIR WORDS
+{{ reason }}
+{% else %}
+
+No reason was given with this request{{ ', so ask before deciding.' if is_request else '.' }}
+{% endif %}
+
+THE RECORD
+Customer: {{ user_name }}
+Email: {{ user_email }}
+User ID: {{ user_id }}
+Transaction:{{ ' ' }}{{ transaction_id }}
+Request ID: {{ refund_request_id }}
+Balance {{ 'now' if is_request else 'after refund' }}: {{ balance_str }}
+{% if is_request %}
+
+TO APPROVE
+Refund {{ amount_str }} in Stripe: {{ stripe_url }}
+
+TO REJECT
+Open in the admin panel: {{ admin_url }}
+{% else %}
+
+View the transaction in Stripe: {{ stripe_url }}
+{% endif %}
+
+--
+Internal notification for the AutoGPT refunds team - sent to {{ recipient }}.
+Not customer-facing.
diff --git a/autogpt_platform/backend/backend/notifications/templates/refund_processed.html.jinja2 b/autogpt_platform/backend/backend/notifications/templates/refund_processed.html.jinja2
deleted file mode 100644
index 244c062a70..0000000000
--- a/autogpt_platform/backend/backend/notifications/templates/refund_processed.html.jinja2
+++ /dev/null
@@ -1,51 +0,0 @@
-{# Refund Processed Notification Email Template #}
-{#
- Template variables:
- data.user_id: the ID of the user
- data.user_name: the user's name
- data.user_email: the user's email address
- data.transaction_id: the transaction ID for the refund request
- data.refund_request_id: the refund request ID
- data.reason: the reason for the refund request
- data.amount: the refund amount in cents (divide by 100 for dollars)
- data.balance: the user's latest balance in cents (after the refund deduction)
-
- Subject: Refund for ${{ data.amount / 100 }} to {{ data.user_name }} has been processed
-#}
-
-<!DOCTYPE html>
-<html>
- <head>
- <meta charset="UTF-8">
- <title>Refund Processed Notification</title>
- </head>
- <body style="font-family: 'Poppins', sans-serif; color: #070629; font-size: 16px; line-height: 1.65; margin: 0; padding: 20px;">
- <p style="margin-bottom: 10px;">Hello Administrator,</p>
-
- <p style="margin-bottom: 10px;">
- This is to notify you that the refund for <strong>${{ data.amount / 100 }}</strong> to <strong>{{ data.user_name }}</strong> has been processed successfully.
- </p>
-
- <h2 style="margin-bottom: 10px;">Refund Details</h2>
- <ul style="margin-bottom: 10px;">
- <li><strong>User ID:</strong> {{ data.user_id }}</li>
- <li><strong>User Name:</strong> {{ data.user_name }}</li>
- <li><strong>User Email:</strong> {{ data.user_email }}</li>
- <li><strong>Transaction ID:</strong> {{ data.transaction_id }}</li>
- <li><strong>Refund Request ID:</strong> {{ data.refund_request_id }}</li>
- <li><strong>Refund Amount:</strong> ${{ data.amount / 100 }}</li>
- <li><strong>Reason for Refund:</strong> {{ data.reason }}</li>
- <li><strong>Latest User Balance:</strong> ${{ data.balance / 100 }}</li>
- </ul>
-
- <p style="margin-bottom: 10px;">
- The user's balance has been updated accordingly after the deduction.
- </p>
-
- <p style="margin-bottom: 10px;">
- Please contact the support team if you have any questions or need further assistance regarding this refund.
- </p>
-
- <p style="margin-bottom: 0;">Best regards,<br>Your Notification System</p>
- </body>
-</html>
diff --git a/autogpt_platform/backend/backend/notifications/templates/refund_request.html.jinja2 b/autogpt_platform/backend/backend/notifications/templates/refund_request.html.jinja2
deleted file mode 100644
index b9e2ac954a..0000000000
--- a/autogpt_platform/backend/backend/notifications/templates/refund_request.html.jinja2
+++ /dev/null
@@ -1,72 +0,0 @@
-{# Refund Request Email Template #}
-{#
- Template variables:
- data.user_id: the ID of the user
- data.user_name: the user's name
- data.user_email: the user's email address
- data.transaction_id: the transaction ID for the refund request
- data.refund_request_id: the refund request ID
- data.reason: the reason for the refund request
- data.amount: the refund amount in cents (divide by 100 for dollars)
- data.balance: the user's balance in cents (divide by 100 for dollars)
-
- Subject: [ACTION REQUIRED] You got a ${{ data.amount / 100 }} refund request from {{ data.user_name }}
-#}
-
-<!DOCTYPE html>
-<html>
- <head>
- <meta charset="UTF-8">
- <title>Refund Request Approval Needed</title>
- </head>
- <body style="font-family: 'Poppins', sans-serif; color: #070629; font-size: 16px; line-height: 1.65; margin: 0; padding: 20px;">
- <p style="margin-bottom: 10px;">Hello Administrator,</p>
- <p style="margin-bottom: 10px;">
- A refund request has been submitted by a user and requires your approval.
- </p>
-
- <h2 style="margin-bottom: 10px;">Refund Request Details</h2>
- <ul style="margin-bottom: 10px;">
- <li><strong>User ID:</strong> {{ data.user_id }}</li>
- <li><strong>User Name:</strong> {{ data.user_name }}</li>
- <li><strong>User Email:</strong> {{ data.user_email }}</li>
- <li><strong>Transaction ID:</strong> {{ data.transaction_id }}</li>
- <li><strong>Refund Request ID:</strong> {{ data.refund_request_id }}</li>
- <li><strong>Refund Amount:</strong> ${{ data.amount / 100 }}</li>
- <li><strong>User Balance:</strong> ${{ data.balance / 100 }}</li>
- <li><strong>Reason for Refund:</strong> {{ data.reason }}</li>
- </ul>
-
- <p style="margin-bottom: 10px;">
- To approve this refund, please click on the following Stripe link:
- https://dashboard.stripe.com/test/payments/{{data.transaction_id}}
- <br/>
- And then click on the "Refund" button.
- </p>
-
- <p style="margin-bottom: 10px;">
- To reject this refund, please follow these steps:
- </p>
- <ol style="margin-bottom: 10px;">
- <li>
- Visit the Supabase Dashboard:
- https://supabase.com/dashboard/project/bgwpwdsxblryihinutbx/editor
- </li>
- <li>
- Navigate to the <strong>RefundRequest</strong> table.
- </li>
- <li>
- Filter the <code>transactionKey</code> column with the Transaction ID: <strong>{{ data.transaction_id }}</strong>.
- </li>
- <li>
- Update the <code>status</code> field to <strong>REJECTED</strong> and enter the rejection reason in the <code>result</code> column.
- </li>
- </ol>
-
- <p style="margin-bottom: 10px;">
- Please take the necessary action at your earliest convenience.
- </p>
- <p style="margin-bottom: 10px;">Thank you for your prompt attention.</p>
- <p style="margin-bottom: 0;">Best regards,<br>Your Notification System</p>
- </body>
-</html>
diff --git a/autogpt_platform/backend/backend/notifications/templates/verdict.html.j2 b/autogpt_platform/backend/backend/notifications/templates/verdict.html.j2
new file mode 100644
index 0000000000..b6e759d83c
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/verdict.html.j2
@@ -0,0 +1,153 @@
+{#- ============================================================
+ verdict.html.j2 — Store submission review outcome
+ Covers AGENT_APPROVED and AGENT_REJECTED via `outcome`.
+ The reviewer's comment is the payload of this email, so on a
+ changes-needed verdict it is the most prominent block, above
+ the fold, never truncated.
+ ============================================================ -#}
+{%- import "_ui.j2" as ui with context -%}
+{%- set approved = (outcome == 'approved') -%}
+{%- set has_note = comments and comments | trim | length > 0 -%}
+{%- set resubmission = (version | default(1)) > 1 -%}
+{%- if approved -%}
+ {%- set headline = ui.trunc(agent_name, 44) ~ ' is live in the Store' -%}
+{%- else -%}
+ {%- set headline = ui.trunc(agent_name, 40) ~ ' needs one more pass' -%}
+{%- endif -%}
+<!doctype html>
+<html lang="en">
+<head>
+{{ ui.head_block(subject | default(headline)) }}
+</head>
+<body style="margin:0; padding:0; background-color:#f1efe9; -webkit-text-size-adjust:100%; font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
+{{ ui.preheader(preheader | default(headline)) }}
+{{ ui.page_open() }}
+{{ ui.header() }}
+{{ ui.hero_verdict('approved' if approved else 'changes') }}
+
+ <!-- Body card -->
+ <tr><td bgcolor="#ffffff" style="border-radius:0 0 14px 14px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+
+ <tr><td class="gutter" style="padding:30px 48px 0;">
+ <div style="font-size:12px; font-weight:800; letter-spacing:2.2px; color:{{ '#1c7a52' if approved else '#b45309' }};">
+ STORE REVIEW &middot; VERSION {{ version | default(1) }}{% if not approved %} &middot; CHANGES NEEDED{% endif %}
+ </div>
+ <div class="headline" style="padding-top:10px; font-size:26px; line-height:34px; font-weight:800; color:#17123b; overflow-wrap:anywhere;">
+ {{ headline }}
+ </div>
+ </td></tr>
+
+ <tr><td class="gutter" style="padding:16px 48px 0;">
+ <div style="font-size:15px; line-height:24px; color:#494566;">
+ {%- if approved %}
+ {{ reviewer_name }} approved version {{ version | default(1) }} on {{ reviewed_at_label }}.
+ Anyone browsing the Store can now find it, install it, and run it.
+ {%- else %}
+ {{ reviewer_name }} reviewed version {{ version | default(1) }} on {{ reviewed_at_label }} and found something to fix
+ before it can go live.
+ {{ 'Your submission is saved — you are picking up where you left off, not starting over.' if resubmission else 'Nothing is lost: your submission is saved and you can resubmit as soon as it is fixed.' }}
+ {%- endif %}
+ </div>
+ </td></tr>
+
+ {#- On a changes verdict the feedback is the reason the email exists, so it
+ comes before the CTA. On an approval it is a nice-to-have and only
+ renders when the reviewer actually wrote something. -#}
+ {%- if not approved %}
+ {%- if changes %}
+ <tr><td class="gutter" style="padding:22px 48px 0;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#fff6e8" style="border:1px solid #f2dcb0; border-left:4px solid #e8940a; border-radius:10px;">
+ <tr><td style="padding:16px 18px;">
+ <div style="font-size:11px; font-weight:800; letter-spacing:2px; color:#8a5800; padding-bottom:10px;">
+ {{ changes | length }} {{ 'THING' if changes | length == 1 else 'THINGS' }} TO CHANGE
+ </div>
+ {%- for c in changes %}
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="{{ '' if loop.first else 'margin-top:10px;' }}">
+ <tr>
+ <td width="26" valign="top" style="font-family:ui-monospace,Menlo,Consolas,monospace; font-size:13px; line-height:23px; font-weight:bold; color:#b45309;">{{ loop.index }}</td>
+ <td style="font-size:15px; line-height:23px; color:#3b3757; overflow-wrap:anywhere;">{{ c }}</td>
+ </tr>
+ </table>
+ {%- endfor %}
+ {%- if closing_note %}
+ <div style="padding-top:12px; margin-top:12px; border-top:1px solid #f2dcb0; font-size:14px; line-height:22px; color:#6b5426;">{{ closing_note }}</div>
+ {%- endif %}
+ </td></tr>
+ </table>
+ </td></tr>
+ {%- else %}
+ <tr><td class="gutter" style="padding:22px 48px 0;">
+ {{ ui.note_card('What needs to change', comments if has_note else 'The reviewer did not leave a written note. Reply to this email and it goes straight to them.', 'amber') }}
+ </td></tr>
+ {%- endif %}
+ {%- elif has_note %}
+ <tr><td class="gutter" style="padding:22px 48px 0;">
+ {{ ui.note_card('Note from ' ~ reviewer_name, comments, 'neutral') }}
+ </td></tr>
+ {%- endif %}
+
+ <tr><td class="gutter" style="padding:24px 48px 0;">
+ {%- if approved %}
+ {{ ui.btn('View it in the Store', store_url) }}
+ {%- else %}
+ {{ ui.btn('Update and resubmit', resubmit_url) }}
+ <div style="padding-top:10px; font-size:12px; color:#8a86a3;">Re-reviews usually take under two working days</div>
+ {%- endif %}
+ </td></tr>
+
+ {%- if approved %}
+ {%- if share_url %}
+ <tr><td class="gutter" style="padding:26px 48px 0;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#f7f6fc" style="border-radius:10px;">
+ <tr><td style="padding:15px 18px;">
+ <div style="font-size:11px; font-weight:800; letter-spacing:2px; color:#6f6b8a; padding-bottom:6px;">WHAT HAPPENS NOW</div>
+ <div style="font-size:14px; line-height:22px; color:#494566;">
+ Ship updates whenever you like &mdash; each new version goes through the same quick review.
+ Want people to find it in the meantime?
+ <a href="{{ share_url }}" style="color:#6d28d9; font-weight:700; text-decoration:underline; white-space:nowrap;">Copy&nbsp;the&nbsp;link</a>
+ </div>
+ </td></tr>
+ </table>
+ </td></tr>
+ {%- endif %}
+ {%- else %}
+ <tr><td class="gutter" style="padding:24px 48px 0;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#f7f6fc" style="border-radius:10px;">
+ <tr><td style="padding:15px 18px;">
+ <div style="font-size:11px; font-weight:800; letter-spacing:2px; color:#6f6b8a; padding-bottom:6px;">WHAT HAPPENS NEXT</div>
+ <div style="font-size:14px; line-height:22px; color:#494566;">
+ {%- if changes or has_note %}
+ Resubmitting sends it back to {{ reviewer_name }}, who already has your context.
+ {%- endif %}
+ {%- if resubmission %}
+ This is round {{ version | default(1) }} &mdash; most agents that make it do so after a couple of passes, so this is the normal shape of it.
+ {%- else %}
+ Most agents need at least one round of changes.
+ {%- endif %}
+ {% if changes or has_note %} Reply to this email if anything is unclear and it goes straight to the reviewer.{% endif %}
+ </div>
+ </td></tr>
+ </table>
+ </td></tr>
+ {%- endif %}
+
+ <tr><td align="center" class="gutter" style="padding:26px 48px 30px;">
+ <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
+ <tr><td height="1" bgcolor="#eeecf5" style="font-size:0; line-height:0;">&nbsp;</td></tr>
+ <tr><td align="center" style="padding-top:14px; font-size:12px; line-height:19px; color:#8a86a3;">
+ You get this because you submitted an agent to the AutoGPT Store.
+ <div style="padding-top:4px;"><a href="{{ urls.settings }}" style="color:#6d28d9; text-decoration:underline;">Notification&nbsp;settings</a></div>
+ </td></tr>
+ </table>
+ </td></tr>
+
+ </table>
+ </td></tr>
+{{ ui.page_close() }}
+{{ ui.legal_footer('This review update is for the AutoGPT account ' ~ user_email ~ '.', urls.unsubscribe) }}
+
+</td></tr>
+</table>
+</body>
+</html>
diff --git a/autogpt_platform/backend/backend/notifications/templates/verdict.subject.j2 b/autogpt_platform/backend/backend/notifications/templates/verdict.subject.j2
new file mode 100644
index 0000000000..6f7cfb8756
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/verdict.subject.j2
@@ -0,0 +1,16 @@
+{%- import "_ui.j2" as ui -%}
+{#- Two lines: subject, then preheader.
+ The preheader carries the first slice of the reviewer's note, because on a
+ changes verdict that is the single thing the creator wants to see. -#}
+{%- set approved = (outcome == 'approved') -%}
+{%- set has_note = comments and comments | trim | length > 0 -%}
+{%- set note = (comments | trim | replace('\n', ' ')) if has_note else '' -%}
+{%- set note_short = ui.trunc(note, 110) -%}
+{%- set name = ui.trunc(agent_name, 44) -%}
+{%- if approved -%}
+{{ name }} is live in the AutoGPT Store
+{% if has_note %}{{ reviewer_name }} says: {{ note_short }}{% else %}Version {{ version | default(1) }} passed review — it is discoverable and installable now.{% endif %}
+{%- else -%}
+{{ name }} needs one more pass before it goes live
+{% if changes %}{{ ui.trunc(changes[0], 110) }}{% elif has_note %}{{ note_short }}{% else %}No written feedback was left — reply to this email and it goes straight to the reviewer.{% endif %}
+{%- endif -%}
diff --git a/autogpt_platform/backend/backend/notifications/templates/verdict.txt.j2 b/autogpt_platform/backend/backend/notifications/templates/verdict.txt.j2
new file mode 100644
index 0000000000..c872291961
--- /dev/null
+++ b/autogpt_platform/backend/backend/notifications/templates/verdict.txt.j2
@@ -0,0 +1,52 @@
+{#- Plain-text part of the Verdict, built from the same context as the HTML. -#}
+{%- set approved = (outcome == 'approved') -%}
+{%- set has_note = comments and comments | trim | length > 0 -%}
+STORE REVIEW - VERSION {{ version | default(1) }}{% if not approved %} - CHANGES NEEDED{% endif %}
+
+
+{{ subject }}
+
+{% if approved %}
+{{ reviewer_name }} approved version {{ version | default(1) }} on {{ reviewed_at_label }}.
+{{ agent_name }} is live in the AutoGPT Store: anyone can find it, install it
+and run it.
+{% else %}
+{{ reviewer_name }} reviewed version {{ version | default(1) }} on {{ reviewed_at_label }} and found
+something to fix before {{ agent_name }} can go live. Nothing is lost: your
+submission is saved and you can resubmit as soon as it is fixed.
+{% endif %}
+{% if not approved and changes %}
+
+{{ changes | length }} {{ 'THING' if changes | length == 1 else 'THINGS' }} TO CHANGE
+{% for c in changes %}
+{{ loop.index }}. {{ c }}
+{% endfor %}
+{% if closing_note %}
+
+{{ closing_note }}
+{% endif %}
+{% elif not approved %}
+
+WHAT NEEDS TO CHANGE
+{{ comments if has_note else 'The reviewer did not leave a written note. Reply to this email and it goes straight to them.' }}
+{% elif has_note %}
+
+NOTE FROM {{ reviewer_name | upper }}
+{{ comments }}
+{% endif %}
+
+{% if approved %}
+View it in the Store: {{ store_url }}
+{% if share_url %}
+Share it: {{ share_url }}
+{% endif %}
+{% else %}
+Update and resubmit: {{ resubmit_url }}
+{% endif %}
+
+--
+Notification settings: {{ urls.settings }}
+
+This review update is for the AutoGPT account {{ user_email }}.
+AutoGPT, 3rd Floor, 1 Ashley Road, Altrincham, WA14 2DT, UK
+Unsubscribe: {{ urls.unsubscribe }}
diff --git a/autogpt_platform/backend/backend/notifications/templates/weekly_summary.html.jinja2 b/autogpt_platform/backend/backend/notifications/templates/weekly_summary.html.jinja2
deleted file mode 100644
index 6de381a946..0000000000
--- a/autogpt_platform/backend/backend/notifications/templates/weekly_summary.html.jinja2
+++ /dev/null
@@ -1,68 +0,0 @@
-{# Weekly Summary #}
-{# Template variables:
-data: the stuff below
-data.start_date: the start date of the summary
-data.end_date: the end date of the summary
-data.total_credits_used: the total credits used during the summary
-data.total_executions: the total number of executions during the summary
-data.most_used_agent: the most used agent's name during the summary
-data.total_execution_time: the total execution time during the summary
-data.successful_runs: the total number of successful runs during the summary
-data.failed_runs: the total number of failed runs during the summary
-data.average_execution_time: the average execution time during the summary
-data.cost_breakdown: the cost breakdown during the summary (dict mapping agent names to credit amounts)
-#}
-
-<h1 style="color: #5D23BB; font-size: 32px; font-weight: 600; margin-bottom: 25px; margin-top: 0;">
- Weekly Summary
-</h1>
-
-<h2 style="color: #070629; font-size: 24px; font-weight: 500; margin-bottom: 20px;">
- Your Agent Activity: {{ data.start_date.strftime('%B %-d') }} – {{ data.end_date.strftime('%B %-d') }}
-</h2>
-
-<div style="background-color: #ffffff; border-radius: 8px; padding: 20px; margin-bottom: 25px;">
- <ul style="list-style-type: disc; padding-left: 20px; margin: 0;">
- <li style="font-size: 16px; line-height: 1.8; margin-bottom: 8px;">
- <strong>Total Executions:</strong> {{ data.total_executions }}
- </li>
- <li style="font-size: 16px; line-height: 1.8; margin-bottom: 8px;">
- <strong>Total Credits Used:</strong> {{ data.total_credits_used|format("%.2f") }}
- </li>
- <li style="font-size: 16px; line-height: 1.8; margin-bottom: 8px;">
- <strong>Total Execution Time:</strong> {{ data.total_execution_time|format("%.1f") }} seconds
- </li>
- <li style="font-size: 16px; line-height: 1.8; margin-bottom: 8px;">
- <strong>Successful Runs:</strong> {{ data.successful_runs }}
- </li>
- <li style="font-size: 16px; line-height: 1.8; margin-bottom: 8px;">
- <strong>Failed Runs:</strong> {{ data.failed_runs }}
- </li>
- <li style="font-size: 16px; line-height: 1.8; margin-bottom: 8px;">
- <strong>Average Execution Time:</strong> {{ data.average_execution_time|format("%.1f") }} seconds
- </li>
- <li style="font-size: 16px; line-height: 1.8; margin-bottom: 8px;">
- <strong>Most Used Agent:</strong> {{ data.most_used_agent }}
- </li>
- {% if data.cost_breakdown %}
- <li style="font-size: 16px; line-height: 1.8; margin-bottom: 8px;">
- <strong>Cost Breakdown:</strong>
- <ul style="list-style-type: disc; padding-left: 40px; margin-top: 8px;">
- {% for agent_name, credits in data.cost_breakdown.items() %}
- <li style="font-size: 16px; line-height: 1.8; margin-bottom: 4px;">
- {{ agent_name }}: {{ credits|format("%.2f") }} credits
- </li>
- {% endfor %}
- </ul>
- </li>
- {% endif %}
- </ul>
-</div>
-
-<p style="font-size: 16px; line-height: 165%; margin-top: 20px; margin-bottom: 10px;">
- Thank you for being a part of the AutoGPT community! 🎉
-</p>
-
-<p style="font-size: 16px; line-height: 165%; margin-bottom: 0;">
- Join the conversation on <a href="https://discord.gg/autogpt" style="color: #4285F4; text-decoration: underline;">Discord here</a>.
-</p>
\ No newline at end of file
diff --git a/autogpt_platform/backend/backend/notifications/templates/zero_balance.html.jinja2 b/autogpt_platform/backend/backend/notifications/templates/zero_balance.html.jinja2
deleted file mode 100644
index eb6879b898..0000000000
--- a/autogpt_platform/backend/backend/notifications/templates/zero_balance.html.jinja2
+++ /dev/null
@@ -1,114 +0,0 @@
-{# Low Balance Notification Email Template #}
-{# Template variables:
-data.agent_name: the name of the agent
-data.current_balance: the current balance of the user
-data.billing_page_link: the link to the billing page
-data.shortfall: the shortfall amount
-#}
-
-<p style="
- font-family: 'Poppins', sans-serif;
- color: #070629;
- font-size: 16px;
- line-height: 165%;
- margin-top: 0;
- margin-bottom: 10px;
- ">
- <strong>Zero Balance Warning</strong>
-</p>
-
-<p style="
- font-family: 'Poppins', sans-serif;
- color: #070629;
- font-size: 16px;
- line-height: 165%;
- margin-top: 0;
- margin-bottom: 20px;
- ">
- Your agent "<strong>{{ data.agent_name }}</strong>" has been stopped due to low balance.
-</p>
-
-<div style="
- margin-left: 15px;
- margin-bottom: 20px;
- padding: 15px;
- border-left: 4px solid #5D23BB;
- background-color: #f8f8ff;
- ">
- <p style="
- font-family: 'Poppins', sans-serif;
- color: #070629;
- font-size: 16px;
- margin-top: 0;
- margin-bottom: 10px;
- ">
- <strong>Current Balance:</strong> ${{ "{:.2f}".format((data.current_balance|float)/100) }}
- </p>
- <p style="
- font-family: 'Poppins', sans-serif;
- color: #070629;
- font-size: 16px;
- margin-top: 0;
- margin-bottom: 10px;
- ">
- <strong>Shortfall:</strong> ${{ "{:.2f}".format((data.shortfall|float)/100) }}
- </p>
-</div>
-
-
-<div style="
- margin-left: 15px;
- margin-bottom: 20px;
- padding: 15px;
- border-left: 4px solid #FF6B6B;
- background-color: #FFF0F0;
- ">
- <p style="
- font-family: 'Poppins', sans-serif;
- color: #070629;
- font-size: 16px;
- margin-top: 0;
- margin-bottom: 10px;
- ">
- <strong>Low Balance:</strong>
- </p>
- <p style="
- font-family: 'Poppins', sans-serif;
- color: #070629;
- font-size: 16px;
- margin-top: 0;
- margin-bottom: 5px;
- ">
- Your agent "<strong>{{ data.agent_name }}</strong>" requires additional credits to continue running. The current operation has been canceled until your balance is replenished.
- </p>
-</div>
-
-<div style="
- text-align: center;
- margin: 30px 0;
- ">
- <a href="{{ data.billing_page_link }}" style="
- font-family: 'Poppins', sans-serif;
- background-color: #5D23BB;
- color: white;
- padding: 12px 24px;
- text-decoration: none;
- border-radius: 4px;
- font-weight: 500;
- display: inline-block;
- ">
- Manage Billing
- </a>
-</div>
-
-<p style="
- font-family: 'Poppins', sans-serif;
- color: #070629;
- font-size: 16px;
- line-height: 150%;
- margin-top: 30px;
- margin-bottom: 10px;
- font-style: italic;
- ">
- This is an automated notification. Your agent is stopped and will need manually restarted unless set to trigger automatically.
-</p>
diff --git a/autogpt_platform/backend/backend/notifications/test_notifications.py b/autogpt_platform/backend/backend/notifications/test_notifications.py
deleted file mode 100644
index f312a382a9..0000000000
--- a/autogpt_platform/backend/backend/notifications/test_notifications.py
+++ /dev/null
@@ -1,1157 +0,0 @@
-"""Tests for notification error handling in NotificationManager."""
-
-import asyncio
-import threading
-from datetime import datetime, timezone
-from unittest.mock import AsyncMock, MagicMock, Mock, patch
-
-import pytest
-from prisma.enums import NotificationType
-
-from backend.data.notifications import AgentRunData, NotificationEventModel
-from backend.notifications.notifications import NotificationManager
-
-
-class TestNotificationErrorHandling:
- """Test cases for notification error handling in NotificationManager."""
-
- @pytest.fixture
- def notification_manager(self):
- """Create a NotificationManager instance for testing."""
- with patch("backend.notifications.notifications.AppService.__init__"):
- manager = NotificationManager()
- manager.email_sender = MagicMock()
- manager.email_sender.send_templated = AsyncMock()
- # Mock the _get_template method used by _process_batch
- template_mock = Mock()
- template_mock.base_template = "base"
- template_mock.subject_template = "subject"
- template_mock.body_template = "body"
- manager.email_sender._get_template = Mock(return_value=template_mock)
- # Mock the formatter
- manager.email_sender.formatter = Mock()
- manager.email_sender.formatter.format_email = AsyncMock(
- return_value=("subject", "body content")
- )
- manager.email_sender.send_templated = AsyncMock()
- manager.email_sender.formatter.env = Mock()
- manager.email_sender.formatter.env.globals = {
- "base_url": "http://example.com"
- }
- return manager
-
- @pytest.fixture
- def sample_batch_event(self):
- """Create a sample batch event for testing."""
- return NotificationEventModel(
- type=NotificationType.AGENT_RUN,
- user_id="user_1",
- created_at=datetime.now(timezone.utc),
- data=AgentRunData(
- agent_name="Test Agent",
- credits_used=10.0,
- execution_time=5.0,
- node_count=3,
- graph_id="graph_1",
- outputs=[],
- ),
- )
-
- @pytest.fixture
- def sample_batch_notifications(self):
- """Create sample batch notifications for testing."""
- notifications = []
- for i in range(3):
- notification = Mock()
- notification.type = NotificationType.AGENT_RUN
- notification.data = {
- "agent_name": f"Test Agent {i}",
- "credits_used": 10.0 * (i + 1),
- "execution_time": 5.0 * (i + 1),
- "node_count": 3 + i,
- "graph_id": f"graph_{i}",
- "outputs": [],
- }
- notification.created_at = datetime.now(timezone.utc)
- notifications.append(notification)
- return notifications
-
- @pytest.mark.asyncio
- async def test_406_stops_all_processing_for_user(
- self, notification_manager, sample_batch_event
- ):
- """Test that 406 inactive recipient error stops ALL processing for that user."""
- with patch("backend.notifications.notifications.logger"), patch(
- "backend.notifications.notifications.set_user_email_verification",
- new_callable=AsyncMock,
- ) as mock_set_verification, patch(
- "backend.notifications.notifications.disable_all_user_notifications",
- new_callable=AsyncMock,
- ) as mock_disable_all, patch(
- "backend.notifications.notifications.get_database_manager_async_client"
- ) as mock_db_client, patch(
- "backend.notifications.notifications.generate_unsubscribe_link"
- ) as mock_unsub_link:
-
- # Create batch of 5 notifications
- notifications = []
- for i in range(5):
- notification = Mock()
- notification.id = f"notif_{i}"
- notification.type = NotificationType.AGENT_RUN
- notification.data = {
- "agent_name": f"Test Agent {i}",
- "credits_used": 10.0 * (i + 1),
- "execution_time": 5.0 * (i + 1),
- "node_count": 3 + i,
- "graph_id": f"graph_{i}",
- "outputs": [],
- }
- notification.created_at = datetime.now(timezone.utc)
- notifications.append(notification)
-
- # Setup mocks
- mock_db = mock_db_client.return_value
- mock_db.get_user_email_by_id = AsyncMock(return_value="[email protected]")
- mock_db.get_user_notification_batch = AsyncMock(
- return_value=Mock(notifications=notifications)
- )
- mock_db.clear_all_user_notification_batches = AsyncMock()
- mock_db.remove_notifications_from_batch = AsyncMock()
- mock_unsub_link.return_value = "http://example.com/unsub"
-
- # Mock internal methods
- notification_manager._should_email_user_based_on_preference = AsyncMock(
- return_value=True
- )
- notification_manager._should_batch = AsyncMock(return_value=True)
- notification_manager._parse_message = Mock(return_value=sample_batch_event)
-
- # Track calls
- call_count = [0]
-
- def send_side_effect(*args, **kwargs):
- data = kwargs.get("data", [])
- if isinstance(data, list) and len(data) == 1:
- current_call = call_count[0]
- call_count[0] += 1
-
- # First two succeed, third hits 406
- if current_call < 2:
- return None
- else:
- raise Exception("Recipient marked as inactive (406)")
- # Force single processing
- raise Exception("Force single processing")
-
- notification_manager.email_sender.send_templated.side_effect = (
- send_side_effect
- )
-
- # Act
- result = await notification_manager._process_batch(
- sample_batch_event.model_dump_json()
- )
-
- # Assert
- assert result is True
-
- # Only 3 calls should have been made (2 successful, 1 failed with 406)
- assert call_count[0] == 3
-
- # User should be deactivated
- mock_set_verification.assert_called_once_with("user_1", False)
- mock_disable_all.assert_called_once_with("user_1")
- mock_db.clear_all_user_notification_batches.assert_called_once_with(
- "user_1"
- )
-
- # No further processing should occur after 406
-
- @pytest.mark.asyncio
- async def test_422_permanently_removes_malformed_notification(
- self, notification_manager, sample_batch_event
- ):
- """Test that 422 error permanently removes the malformed notification from batch and continues with others."""
- with patch("backend.notifications.notifications.logger") as mock_logger, patch(
- "backend.notifications.notifications.get_database_manager_async_client"
- ) as mock_db_client, patch(
- "backend.notifications.notifications.generate_unsubscribe_link"
- ) as mock_unsub_link:
-
- # Create batch of 5 notifications
- notifications = []
- for i in range(5):
- notification = Mock()
- notification.id = f"notif_{i}"
- notification.type = NotificationType.AGENT_RUN
- notification.data = {
- "agent_name": f"Test Agent {i}",
- "credits_used": 10.0 * (i + 1),
- "execution_time": 5.0 * (i + 1),
- "node_count": 3 + i,
- "graph_id": f"graph_{i}",
- "outputs": [],
- }
- notification.created_at = datetime.now(timezone.utc)
- notifications.append(notification)
-
- # Setup mocks
- mock_db = mock_db_client.return_value
- mock_db.get_user_email_by_id = AsyncMock(return_value="[email protected]")
- mock_db.get_user_notification_batch = AsyncMock(
- side_effect=[
- Mock(notifications=notifications),
- Mock(notifications=[]), # Empty after processing
- ]
- )
- mock_db.remove_notifications_from_batch = AsyncMock()
- mock_unsub_link.return_value = "http://example.com/unsub"
-
- # Mock internal methods
- notification_manager._should_email_user_based_on_preference = AsyncMock(
- return_value=True
- )
- notification_manager._should_batch = AsyncMock(return_value=True)
- notification_manager._parse_message = Mock(return_value=sample_batch_event)
-
- # Track calls
- call_count = [0]
- successful_indices = []
- removed_notification_ids = []
-
- # Capture what gets removed
- def remove_side_effect(user_id, notif_type, notif_ids):
- removed_notification_ids.extend(notif_ids)
- return None
-
- mock_db.remove_notifications_from_batch.side_effect = remove_side_effect
-
- def send_side_effect(*args, **kwargs):
- data = kwargs.get("data", [])
- if isinstance(data, list) and len(data) == 1:
- current_call = call_count[0]
- call_count[0] += 1
-
- # Index 2 has malformed data (422)
- if current_call == 2:
- raise Exception(
- "Unprocessable entity (422): Malformed email data"
- )
- else:
- successful_indices.append(current_call)
- return None
- # Force single processing
- raise Exception("Force single processing")
-
- notification_manager.email_sender.send_templated.side_effect = (
- send_side_effect
- )
-
- # Act
- result = await notification_manager._process_batch(
- sample_batch_event.model_dump_json()
- )
-
- # Assert
- assert result is True
- assert call_count[0] == 5 # All 5 attempted
- assert len(successful_indices) == 4 # 4 succeeded (all except index 2)
- assert 2 not in successful_indices # Index 2 failed
-
- # Verify 422 error was logged
- warning_calls = [call[0][0] for call in mock_logger.warning.call_args_list]
- assert any(
- "422" in call or "malformed" in call.lower() for call in warning_calls
- )
-
- # Verify all notifications were removed (4 successful + 1 malformed)
- assert mock_db.remove_notifications_from_batch.call_count == 5
- assert (
- "notif_2" in removed_notification_ids
- ) # Malformed one was removed permanently
-
- @pytest.mark.asyncio
- async def test_oversized_notification_permanently_removed(
- self, notification_manager, sample_batch_event
- ):
- """Test that oversized notifications are permanently removed from batch but others continue."""
- with patch("backend.notifications.notifications.logger") as mock_logger, patch(
- "backend.notifications.notifications.get_database_manager_async_client"
- ) as mock_db_client, patch(
- "backend.notifications.notifications.generate_unsubscribe_link"
- ) as mock_unsub_link:
-
- # Create batch of 5 notifications
- notifications = []
- for i in range(5):
- notification = Mock()
- notification.id = f"notif_{i}"
- notification.type = NotificationType.AGENT_RUN
- notification.data = {
- "agent_name": f"Test Agent {i}",
- "credits_used": 10.0 * (i + 1),
- "execution_time": 5.0 * (i + 1),
- "node_count": 3 + i,
- "graph_id": f"graph_{i}",
- "outputs": [],
- }
- notification.created_at = datetime.now(timezone.utc)
- notifications.append(notification)
-
- # Setup mocks
- mock_db = mock_db_client.return_value
- mock_db.get_user_email_by_id = AsyncMock(return_value="[email protected]")
- mock_db.get_user_notification_batch = AsyncMock(
- side_effect=[
- Mock(notifications=notifications),
- Mock(notifications=[]), # Empty after processing
- ]
- )
- mock_db.remove_notifications_from_batch = AsyncMock()
- mock_unsub_link.return_value = "http://example.com/unsub"
-
- # Mock internal methods
- notification_manager._should_email_user_based_on_preference = AsyncMock(
- return_value=True
- )
- notification_manager._should_batch = AsyncMock(return_value=True)
- notification_manager._parse_message = Mock(return_value=sample_batch_event)
-
- # Override formatter to simulate oversized on index 3
- # original_format = notification_manager.email_sender.formatter.format_email
-
- def format_side_effect(*args, **kwargs):
- # Check if we're formatting index 3
- data = kwargs.get("data", {}).get("notifications", [])
- if data and len(data) == 1:
- # Check notification content to identify index 3
- if any("Test Agent 3" in str(n.data) for n in data):
- # Return oversized message for index 3
- return ("subject", "x" * 5_000_000) # Over 4.5MB limit
- return ("subject", "normal sized content")
-
- notification_manager.email_sender.formatter.format_email = AsyncMock(
- side_effect=format_side_effect
- )
-
- # Track calls
- successful_indices = []
-
- def send_side_effect(*args, **kwargs):
- data = kwargs.get("data", [])
- if isinstance(data, list) and len(data) == 1:
- # Track which notification was sent based on content
- for i, notif in enumerate(notifications):
- if any(f"Test Agent {i}" in str(n.data) for n in data):
- successful_indices.append(i)
- return None
- return None
- # Force single processing
- raise Exception("Force single processing")
-
- notification_manager.email_sender.send_templated.side_effect = (
- send_side_effect
- )
-
- # Act
- result = await notification_manager._process_batch(
- sample_batch_event.model_dump_json()
- )
-
- # Assert
- assert result is True
- assert (
- len(successful_indices) == 4
- ) # Only 4 sent (index 3 skipped due to size)
- assert 3 not in successful_indices # Index 3 was not sent
-
- # Verify oversized error was logged
- warning_calls = [call[0][0] for call in mock_logger.warning.call_args_list]
- assert any(
- "exceeds email size limit" in call or "oversized" in call.lower()
- for call in warning_calls
- )
-
- @pytest.mark.asyncio
- async def test_generic_api_error_keeps_notification_for_retry(
- self, notification_manager, sample_batch_event
- ):
- """Test that generic API errors keep notifications in batch for retry while others continue."""
- with patch("backend.notifications.notifications.logger") as mock_logger, patch(
- "backend.notifications.notifications.get_database_manager_async_client"
- ) as mock_db_client, patch(
- "backend.notifications.notifications.generate_unsubscribe_link"
- ) as mock_unsub_link:
-
- # Create batch of 5 notifications
- notifications = []
- for i in range(5):
- notification = Mock()
- notification.id = f"notif_{i}"
- notification.type = NotificationType.AGENT_RUN
- notification.data = {
- "agent_name": f"Test Agent {i}",
- "credits_used": 10.0 * (i + 1),
- "execution_time": 5.0 * (i + 1),
- "node_count": 3 + i,
- "graph_id": f"graph_{i}",
- "outputs": [],
- }
- notification.created_at = datetime.now(timezone.utc)
- notifications.append(notification)
-
- # Notification that failed with generic error
- failed_notifications = [notifications[1]] # Only index 1 remains for retry
-
- # Setup mocks
- mock_db = mock_db_client.return_value
- mock_db.get_user_email_by_id = AsyncMock(return_value="[email protected]")
- mock_db.get_user_notification_batch = AsyncMock(
- side_effect=[
- Mock(notifications=notifications),
- Mock(
- notifications=failed_notifications
- ), # Failed ones remain for retry
- ]
- )
- mock_db.remove_notifications_from_batch = AsyncMock()
- mock_unsub_link.return_value = "http://example.com/unsub"
-
- # Mock internal methods
- notification_manager._should_email_user_based_on_preference = AsyncMock(
- return_value=True
- )
- notification_manager._should_batch = AsyncMock(return_value=True)
- notification_manager._parse_message = Mock(return_value=sample_batch_event)
-
- # Track calls
- successful_indices = []
- failed_indices = []
- removed_notification_ids = []
-
- # Capture what gets removed
- def remove_side_effect(user_id, notif_type, notif_ids):
- removed_notification_ids.extend(notif_ids)
- return None
-
- mock_db.remove_notifications_from_batch.side_effect = remove_side_effect
-
- def send_side_effect(*args, **kwargs):
- data = kwargs.get("data", [])
- if isinstance(data, list) and len(data) == 1:
- # Track which notification based on content
- for i, notif in enumerate(notifications):
- if any(f"Test Agent {i}" in str(n.data) for n in data):
- # Index 1 has generic API error
- if i == 1:
- failed_indices.append(i)
- raise Exception("Network timeout - temporary failure")
- else:
- successful_indices.append(i)
- return None
- return None
- # Force single processing
- raise Exception("Force single processing")
-
- notification_manager.email_sender.send_templated.side_effect = (
- send_side_effect
- )
-
- # Act
- result = await notification_manager._process_batch(
- sample_batch_event.model_dump_json()
- )
-
- # Assert
- assert result is True
- assert len(successful_indices) == 4 # 4 succeeded (0, 2, 3, 4)
- assert len(failed_indices) == 1 # 1 failed
- assert 1 in failed_indices # Index 1 failed
-
- # Verify generic error was logged
- warning_calls = [call[0][0] for call in mock_logger.warning.call_args_list]
- assert any(
- "api error" in call.lower() or "skipping" in call.lower()
- for call in warning_calls
- )
-
- # Only successful ones should be removed from batch (failed one stays for retry)
- assert mock_db.remove_notifications_from_batch.call_count == 4
- assert (
- "notif_1" not in removed_notification_ids
- ) # Failed one NOT removed (stays for retry)
- assert "notif_0" in removed_notification_ids # Successful one removed
- assert "notif_2" in removed_notification_ids # Successful one removed
- assert "notif_3" in removed_notification_ids # Successful one removed
- assert "notif_4" in removed_notification_ids # Successful one removed
-
- @pytest.mark.asyncio
- async def test_batch_all_notifications_sent_successfully(
- self, notification_manager, sample_batch_event
- ):
- """Test successful batch processing where all notifications are sent without errors."""
- with patch("backend.notifications.notifications.logger") as mock_logger, patch(
- "backend.notifications.notifications.get_database_manager_async_client"
- ) as mock_db_client, patch(
- "backend.notifications.notifications.generate_unsubscribe_link"
- ) as mock_unsub_link:
-
- # Create batch of 5 notifications
- notifications = []
- for i in range(5):
- notification = Mock()
- notification.id = f"notif_{i}"
- notification.type = NotificationType.AGENT_RUN
- notification.data = {
- "agent_name": f"Test Agent {i}",
- "credits_used": 10.0 * (i + 1),
- "execution_time": 5.0 * (i + 1),
- "node_count": 3 + i,
- "graph_id": f"graph_{i}",
- "outputs": [],
- }
- notification.created_at = datetime.now(timezone.utc)
- notifications.append(notification)
-
- # Setup mocks
- mock_db = mock_db_client.return_value
- mock_db.get_user_email_by_id = AsyncMock(return_value="[email protected]")
- mock_db.get_user_notification_batch = AsyncMock(
- side_effect=[
- Mock(notifications=notifications),
- Mock(notifications=[]), # Empty after all sent successfully
- ]
- )
- mock_db.remove_notifications_from_batch = AsyncMock()
- mock_unsub_link.return_value = "http://example.com/unsub"
-
- # Mock internal methods
- notification_manager._should_email_user_based_on_preference = AsyncMock(
- return_value=True
- )
- notification_manager._should_batch = AsyncMock(return_value=True)
- notification_manager._parse_message = Mock(return_value=sample_batch_event)
-
- # Track successful sends
- successful_indices = []
- removed_notification_ids = []
-
- # Capture what gets removed
- def remove_side_effect(user_id, notif_type, notif_ids):
- removed_notification_ids.extend(notif_ids)
- return None
-
- mock_db.remove_notifications_from_batch.side_effect = remove_side_effect
-
- def send_side_effect(*args, **kwargs):
- data = kwargs.get("data", [])
- if isinstance(data, list) and len(data) == 1:
- # Track which notification was sent
- for i, notif in enumerate(notifications):
- if any(f"Test Agent {i}" in str(n.data) for n in data):
- successful_indices.append(i)
- return None
- return None # Success
- # Force single processing
- raise Exception("Force single processing")
-
- notification_manager.email_sender.send_templated.side_effect = (
- send_side_effect
- )
-
- # Act
- result = await notification_manager._process_batch(
- sample_batch_event.model_dump_json()
- )
-
- # Assert
- assert result is True
-
- # All 5 notifications should be sent successfully
- assert len(successful_indices) == 5
- assert successful_indices == [0, 1, 2, 3, 4]
-
- # All notifications should be removed from batch
- assert mock_db.remove_notifications_from_batch.call_count == 5
- assert len(removed_notification_ids) == 5
- for i in range(5):
- assert f"notif_{i}" in removed_notification_ids
-
- # No errors should be logged
- assert mock_logger.error.call_count == 0
-
- # Info message about successful sends should be logged
- info_calls = [call[0][0] for call in mock_logger.info.call_args_list]
- assert any("sent and removed" in call.lower() for call in info_calls)
-
-
-def test_run_service_retains_background_future():
- """The RabbitMQ task must remain strongly referenced while it is pending."""
- manager = NotificationManager.__new__(NotificationManager)
- manager.shared_event_loop = MagicMock()
- scheduled_future = MagicMock()
-
- with patch(
- "backend.notifications.notifications.asyncio.run_coroutine_threadsafe",
- return_value=scheduled_future,
- ) as run_coroutine_threadsafe, patch(
- "backend.notifications.notifications.AppService.run_service"
- ) as parent_run_service:
- manager.run_service()
-
- wrapper_coroutine = run_coroutine_threadsafe.call_args.args[0]
- wrapper_coroutine.close()
- assert manager._run_service_future is scheduled_future
- parent_run_service.assert_called_once_with()
-
-
-def test_cleanup_awaits_background_task_before_disconnect():
- manager = NotificationManager.__new__(NotificationManager)
- manager.running = True
- events = []
- manager._run_service_future = MagicMock()
- # Explicitly mark the scheduling proxy done so the wait loop in
- # _shutdown_service is skipped intentionally, not via a truthy MagicMock.
- manager._run_service_future.done.return_value = True
- manager._run_service_task = None
- manager.shared_event_loop = MagicMock()
- manager.shared_event_loop.is_closed.return_value = False
- manager.shared_event_loop.is_running.return_value = True
- manager.rabbitmq_service = MagicMock()
- manager.rabbitmq_service.disconnect = AsyncMock(
- side_effect=lambda: events.append("disconnect")
- )
- manager.run_and_wait = MagicMock(
- side_effect=lambda coro, timeout=None: asyncio.run(coro)
- )
-
- with patch(
- "backend.notifications.notifications.AppService.cleanup",
- side_effect=lambda: events.append("parent"),
- ):
- manager.cleanup()
-
- assert manager.running is False
- assert events == ["disconnect", "parent"]
- manager.rabbitmq_service.disconnect.assert_awaited_once_with()
- manager.run_and_wait.assert_called_once()
- assert manager._run_service_future is None
-
-
-def test_shutdown_tolerates_cancelled_disconnect_task():
- """A disconnect that ends up cancelled must not crash _shutdown_service.
-
- Task.exception() raises CancelledError (rather than returning it) on a
- cancelled task, so the error-logging branch must skip cancelled tasks.
- """
- manager = NotificationManager.__new__(NotificationManager)
- manager._run_service_future = None
- manager._run_service_task = None
- manager.rabbitmq_service = MagicMock()
-
- async def cancelled_disconnect():
- raise asyncio.CancelledError()
-
- manager.rabbitmq_service.disconnect = cancelled_disconnect
-
- # Must complete without propagating CancelledError.
- asyncio.run(manager._shutdown_service())
-
-
-def test_cleanup_handles_shutdown_before_rabbitmq_startup():
- manager = NotificationManager.__new__(NotificationManager)
- manager.running = True
- manager.rabbitmq_service = None
- manager._run_service_future = None
- manager._run_service_task = None
- manager.shared_event_loop = MagicMock()
- manager.shared_event_loop.is_closed.return_value = False
- manager.shared_event_loop.is_running.return_value = True
- manager.run_and_wait = MagicMock(
- side_effect=lambda coro, timeout=None: asyncio.run(coro)
- )
-
- with patch(
- "backend.notifications.notifications.AppService.cleanup"
- ) as parent_cleanup:
- manager.cleanup()
-
- assert manager.running is False
- manager.run_and_wait.assert_called_once()
- parent_cleanup.assert_called_once_with()
-
-
-def test_cleanup_waits_for_consumer_task_cancellation_to_finish():
- """The event loop must not close while notification tasks are still pending."""
- manager = NotificationManager.__new__(NotificationManager)
- manager.running = True
- manager._run_service_future = None
- manager._run_service_task = None
- manager.shared_event_loop = asyncio.new_event_loop()
- service_started = threading.Event()
- service_finished = threading.Event()
- events = []
-
- async def slow_to_cancel_service():
- service_started.set()
- try:
- await asyncio.Event().wait()
- finally:
- # Model async context-manager cleanup that needs several loop turns.
- for _ in range(5):
- await asyncio.sleep(0)
- service_finished.set()
- events.append("service-finished")
-
- manager._run_service = slow_to_cancel_service
- manager.rabbitmq_service = MagicMock()
- manager.rabbitmq_service.disconnect = AsyncMock(
- side_effect=lambda: events.append("disconnect")
- )
- loop_thread = threading.Thread(
- target=manager.shared_event_loop.run_forever,
- daemon=True,
- )
- loop_thread.start()
- scheduled_future = asyncio.run_coroutine_threadsafe(
- manager._run_service_with_task_reference(), manager.shared_event_loop
- )
- manager._run_service_future = scheduled_future
- assert service_started.wait(timeout=2)
-
- def stop_parent_loop():
- manager.shared_event_loop.call_soon_threadsafe(manager.shared_event_loop.stop)
-
- try:
- with patch(
- "backend.notifications.notifications.AppService.cleanup",
- side_effect=stop_parent_loop,
- ):
- manager.cleanup()
- loop_thread.join(timeout=2)
-
- assert service_finished.is_set()
- assert events == ["service-finished", "disconnect"]
- assert not loop_thread.is_alive()
- assert scheduled_future.done()
- assert not asyncio.all_tasks(manager.shared_event_loop)
- finally:
- if loop_thread.is_alive():
- manager.shared_event_loop.call_soon_threadsafe(
- manager.shared_event_loop.stop
- )
- loop_thread.join(timeout=2)
- manager.shared_event_loop.close()
-
-
-def test_cleanup_gives_up_on_service_task_that_ignores_cancellation():
- """A consumer stuck unwinding must not hang cleanup past the timeout."""
- manager = NotificationManager.__new__(NotificationManager)
- manager.running = True
- manager.rabbitmq_service = None
- manager._run_service_future = None
- manager._run_service_task = None
- manager.shared_event_loop = asyncio.new_event_loop()
- service_started = threading.Event()
-
- async def uncancellable_service():
- service_started.set()
- while True:
- try:
- await asyncio.sleep(60)
- except asyncio.CancelledError:
- # Model a task wedged in unwinding (e.g. awaiting a broker
- # reply on a dead connection) that never finishes cancelling.
- continue
-
- manager._run_service = uncancellable_service
- loop_thread = threading.Thread(
- target=manager.shared_event_loop.run_forever,
- daemon=True,
- )
- loop_thread.start()
- scheduled_future = asyncio.run_coroutine_threadsafe(
- manager._run_service_with_task_reference(), manager.shared_event_loop
- )
- manager._run_service_future = scheduled_future
- assert service_started.wait(timeout=2)
-
- def stop_parent_loop():
- manager.shared_event_loop.call_soon_threadsafe(manager.shared_event_loop.stop)
-
- try:
- with patch(
- "backend.notifications.notifications.SHUTDOWN_TIMEOUT_SECONDS", 0.1
- ), patch(
- "backend.notifications.notifications.AppService.cleanup",
- side_effect=stop_parent_loop,
- ):
- manager.cleanup()
- loop_thread.join(timeout=2)
-
- assert not loop_thread.is_alive()
- assert manager._run_service_future is None
- assert manager._run_service_task is None
- finally:
- if loop_thread.is_alive():
- manager.shared_event_loop.call_soon_threadsafe(
- manager.shared_event_loop.stop
- )
- loop_thread.join(timeout=2)
- manager.shared_event_loop.close()
-
-
-def test_cleanup_handles_shutdown_before_service_task_first_loop_turn():
- manager = NotificationManager.__new__(NotificationManager)
- manager.running = True
- manager.rabbitmq_service = None
- manager._run_service_task = None
- manager.shared_event_loop = asyncio.new_event_loop()
- service_finished = threading.Event()
-
- async def slow_to_cancel_service():
- try:
- await asyncio.Event().wait()
- finally:
- for _ in range(3):
- await asyncio.sleep(0)
- service_finished.set()
-
- manager._run_service = slow_to_cancel_service
- scheduled_future = asyncio.run_coroutine_threadsafe(
- manager._run_service_with_task_reference(), manager.shared_event_loop
- )
- manager._run_service_future = scheduled_future
-
- try:
- with patch("backend.notifications.notifications.AppService.cleanup"):
- manager.cleanup()
- manager.shared_event_loop.run_until_complete(asyncio.sleep(0))
-
- assert service_finished.is_set()
- assert scheduled_future.done()
- assert not asyncio.all_tasks(manager.shared_event_loop)
- finally:
- manager.shared_event_loop.close()
-
-
-def test_cleanup_skips_shutdown_when_loop_already_closed():
- """A crashed-and-closed loop must not turn cleanup into a RuntimeError."""
- manager = NotificationManager.__new__(NotificationManager)
- manager.running = True
- manager.rabbitmq_service = MagicMock()
- manager.rabbitmq_service.disconnect = AsyncMock()
- manager._run_service_future = MagicMock()
- manager._run_service_future.done.return_value = True
- manager._run_service_task = None
- manager.shared_event_loop = asyncio.new_event_loop()
- manager.shared_event_loop.close()
-
- # Unpatched parent cleanup: BaseAppService.cleanup must also survive the
- # closed loop instead of raising from call_soon_threadsafe(loop.stop).
- manager.cleanup()
-
- assert manager.running is False
- manager.rabbitmq_service.disconnect.assert_not_awaited()
- assert manager._run_service_future is None
- assert manager._run_service_task is None
-
-
-def test_cleanup_survives_loop_closing_between_check_and_schedule():
- """A loop that closes right after the checks must not crash cleanup."""
- manager = NotificationManager.__new__(NotificationManager)
- manager.running = True
- manager.rabbitmq_service = None
- manager._run_service_future = None
- manager._run_service_task = None
- manager.shared_event_loop = MagicMock()
- manager.shared_event_loop.is_closed.return_value = False
- manager.shared_event_loop.is_running.return_value = True
- manager.run_and_wait = MagicMock(side_effect=RuntimeError("Event loop is closed"))
-
- with patch(
- "backend.notifications.notifications.AppService.cleanup"
- ) as parent_cleanup:
- manager.cleanup()
-
- parent_cleanup.assert_called_once_with()
- assert manager._run_service_future is None
- assert manager._run_service_task is None
-
-
-def test_cleanup_gives_up_when_loop_never_services_the_barrier():
- """cleanup() must not block forever if the loop never runs the barrier."""
- manager = NotificationManager.__new__(NotificationManager)
- manager.running = True
- manager.rabbitmq_service = None
- manager._run_service_future = None
- manager._run_service_task = None
- manager.shared_event_loop = asyncio.new_event_loop()
- loop_hogged = threading.Event()
- release_loop = threading.Event()
-
- def hog_the_loop():
- # Keep the loop stuck in one callback so the shutdown barrier
- # scheduled by cleanup() never gets serviced before the deadline.
- loop_hogged.set()
- release_loop.wait(timeout=5)
-
- loop_thread = threading.Thread(
- target=manager.shared_event_loop.run_forever,
- daemon=True,
- )
- loop_thread.start()
- manager.shared_event_loop.call_soon_threadsafe(hog_the_loop)
- assert loop_hogged.wait(timeout=2)
-
- def stop_parent_loop():
- manager.shared_event_loop.call_soon_threadsafe(manager.shared_event_loop.stop)
-
- try:
- with patch(
- "backend.notifications.notifications.CLEANUP_TIMEOUT_SECONDS", 0.1
- ), patch(
- "backend.notifications.notifications.AppService.cleanup",
- side_effect=stop_parent_loop,
- ):
- manager.cleanup()
-
- # cleanup() returned while the loop was still wedged, so the outer
- # deadline fired instead of blocking on Future.result() forever.
- assert not release_loop.is_set()
- assert manager._run_service_future is None
- assert manager._run_service_task is None
- finally:
- release_loop.set()
- loop_thread.join(timeout=2)
- # Drain the abandoned barrier task so closing the loop does not leak
- # a pending task or a never-awaited coroutine.
- manager.shared_event_loop.run_until_complete(asyncio.sleep(0))
- manager.shared_event_loop.close()
-
-
-class TestConsumerRetryWithBackoff:
- """Verify _process_message_with_retry retries transient failures and only DLQs after exhausting attempts."""
-
- @pytest.fixture
- def manager(self):
- # Build a NotificationManager without invoking __init__ side effects
- # (RabbitMQ connections, threads). We only exercise the
- # _process_message_with_retry method.
- m = NotificationManager.__new__(NotificationManager)
- return m
-
- def _make_message(self, body: bytes = b"{}"):
- msg = MagicMock()
- msg.body = body
- msg.ack = AsyncMock()
- msg.reject = AsyncMock()
- return msg
-
- @pytest.mark.asyncio
- async def test_acks_on_success(self, manager):
- msg = self._make_message()
- process = AsyncMock(return_value=True)
- await manager._process_message_with_retry(msg, process, "test_q")
- assert process.call_count == 1
- msg.ack.assert_awaited_once()
- msg.reject.assert_not_called()
-
- @pytest.mark.asyncio
- async def test_rejects_when_process_returns_false_no_retry(self, manager):
- msg = self._make_message()
- process = AsyncMock(return_value=False)
- await manager._process_message_with_retry(msg, process, "test_q")
- # Explicit False = unrecoverable, do not retry
- assert process.call_count == 1
- msg.reject.assert_awaited_once_with(requeue=False)
- msg.ack.assert_not_called()
-
- @pytest.mark.asyncio
- async def test_retries_transient_then_succeeds(self, manager):
- msg = self._make_message()
- # Fail twice, succeed on 3rd attempt
- process = AsyncMock(
- side_effect=[RuntimeError("blip"), RuntimeError("blip"), True]
- )
- with patch(
- "backend.notifications.notifications.asyncio.sleep", new=AsyncMock()
- ) as sleep:
- await manager._process_message_with_retry(msg, process, "test_q")
- assert process.call_count == 3
- assert sleep.await_count == 2 # backoff sleeps before attempts 2 and 3
- msg.ack.assert_awaited_once()
- msg.reject.assert_not_called()
-
- @pytest.mark.asyncio
- async def test_dlqs_after_exhausting_retries(self, manager):
- msg = self._make_message()
- process = AsyncMock(side_effect=RuntimeError("permanent boom"))
- with patch(
- "backend.notifications.notifications.asyncio.sleep", new=AsyncMock()
- ):
- await manager._process_message_with_retry(msg, process, "test_q")
- # Defaults: 3 attempts total
- assert process.call_count == 3
- msg.reject.assert_awaited_once_with(requeue=False)
- msg.ack.assert_not_called()
-
- @pytest.mark.asyncio
- async def test_backoff_doubles_per_attempt(self, manager):
- msg = self._make_message()
- process = AsyncMock(side_effect=RuntimeError("boom"))
- sleeps = []
-
- async def fake_sleep(s):
- sleeps.append(s)
-
- with patch(
- "backend.notifications.notifications.asyncio.sleep", side_effect=fake_sleep
- ):
- await manager._process_message_with_retry(msg, process, "test_q")
- # CONSUMER_RETRY_BACKOFF_SECONDS = 2, so delays are 2*(2**0)=2, 2*(2**1)=4
- assert sleeps == [2, 4]
-
- @pytest.mark.asyncio
- async def test_inner_process_raises_so_retry_triggers(self, manager):
- """Regression: the four `_process_*` methods must let transient
- exceptions propagate so `_process_message_with_retry` can retry them.
- If they swallow exceptions and return False instead, the retry loop
- treats it as a permanent failure and DLQs on the first attempt.
- """
- # Stand up just enough state for _process_immediate to reach the
- # email_sender call (mocked) and raise.
- manager.email_sender = MagicMock()
- manager.email_sender.send_templated = AsyncMock(
- side_effect=RuntimeError("postmark 502")
- )
- manager._should_email_user_based_on_preference = AsyncMock(return_value=True)
-
- with patch(
- "backend.notifications.notifications.get_database_manager_async_client"
- ) as mock_db_client, patch(
- "backend.notifications.notifications.generate_unsubscribe_link",
- return_value="unsub",
- ):
- mock_db = MagicMock()
- mock_db.get_user_email_by_id = AsyncMock(return_value="[email protected]")
- mock_db_client.return_value = mock_db
- event = MagicMock()
- event.user_id = "u1"
- event.type = MagicMock()
- # _process_immediate uses self._parse_message
- manager._parse_message = MagicMock(return_value=event)
-
- with pytest.raises(RuntimeError, match="postmark 502"):
- await manager._process_immediate("{}")
-
- @pytest.mark.asyncio
- async def test_admin_message_returns_true_on_send(self, manager):
- manager.email_sender = MagicMock()
- manager.email_sender.send_templated = AsyncMock()
- event = MagicMock()
- event.type = MagicMock()
- manager._parse_message = MagicMock(return_value=event)
- result = await manager._process_admin_message("{}")
- assert result is True
- manager.email_sender.send_templated.assert_awaited_once()
-
- @pytest.mark.asyncio
- async def test_admin_message_returns_false_on_unparseable(self, manager):
- manager._parse_message = MagicMock(return_value=None)
- result = await manager._process_admin_message("garbage")
- assert result is False
-
- @pytest.mark.asyncio
- async def test_admin_message_propagates_send_failure(self, manager):
- manager.email_sender = MagicMock()
- manager.email_sender.send_templated = AsyncMock(
- side_effect=RuntimeError("postmark 502")
- )
- event = MagicMock()
- event.type = MagicMock()
- manager._parse_message = MagicMock(return_value=event)
- with pytest.raises(RuntimeError, match="postmark 502"):
- await manager._process_admin_message("{}")
-
- @pytest.mark.asyncio
- async def test_immediate_returns_false_on_unparseable(self, manager):
- manager._parse_message = MagicMock(return_value=None)
- result = await manager._process_immediate("garbage")
- assert result is False
-
- @pytest.mark.asyncio
- async def test_immediate_returns_false_when_no_email(self, manager):
- event = MagicMock()
- event.user_id = "u1"
- event.type = MagicMock()
- manager._parse_message = MagicMock(return_value=event)
- with patch(
- "backend.notifications.notifications.get_database_manager_async_client"
- ) as mock_db_client:
- mock_db = MagicMock()
- mock_db.get_user_email_by_id = AsyncMock(return_value=None)
- mock_db_client.return_value = mock_db
- result = await manager._process_immediate("{}")
- assert result is False
-
- @pytest.mark.asyncio
- async def test_immediate_returns_true_when_user_opted_out(self, manager):
- event = MagicMock()
- event.user_id = "u1"
- event.type = MagicMock()
- manager._parse_message = MagicMock(return_value=event)
- manager._should_email_user_based_on_preference = AsyncMock(return_value=False)
- with patch(
- "backend.notifications.notifications.get_database_manager_async_client"
- ) as mock_db_client:
- mock_db = MagicMock()
- mock_db.get_user_email_by_id = AsyncMock(return_value="[email protected]")
- mock_db_client.return_value = mock_db
- result = await manager._process_immediate("{}")
- # Opted-out = "delivered" from queue's POV, no retry needed
- assert result is True
-
- @pytest.mark.asyncio
- async def test_undecodable_body_dlqs_without_retry(self, manager):
- """Decode failure must reject-to-DLQ, not crash the consumer task."""
- msg = MagicMock()
- # Lone continuation byte — not valid UTF-8.
- msg.body = b"\xff\xfe\x00"
- msg.ack = AsyncMock()
- msg.reject = AsyncMock()
- process = AsyncMock()
- await manager._process_message_with_retry(msg, process, "test_q")
- process.assert_not_called()
- msg.ack.assert_not_called()
- msg.reject.assert_awaited_once_with(requeue=False)
-
- @pytest.mark.asyncio
- async def test_summary_unparseable_returns_false_not_raise(self, manager):
- """_process_summary must return False (DLQ) on parse failure,
- not raise a ValidationError that triggers retry-with-backoff.
- """
- result = await manager._process_summary("{not json")
- assert result is False
-
- @pytest.mark.asyncio
- async def test_batch_not_old_enough_acks(self, manager):
- """When the batch isn't ready to flush, the trigger message must be
- acked — the notification is already persisted. Returning False would
- DLQ the trigger and silently drop a future delivery.
- """
- event = MagicMock()
- event.user_id = "u1"
- event.type = MagicMock()
- manager._parse_message = MagicMock(return_value=event)
- manager._should_email_user_based_on_preference = AsyncMock(return_value=True)
- manager._should_batch = AsyncMock(return_value=False)
- with patch(
- "backend.notifications.notifications.get_database_manager_async_client"
- ) as mock_db_client:
- mock_db = MagicMock()
- mock_db.get_user_email_by_id = AsyncMock(return_value="[email protected]")
- mock_db_client.return_value = mock_db
- result = await manager._process_batch("{}")
- assert result is True
diff --git a/autogpt_platform/backend/backend/util/clients.py b/autogpt_platform/backend/backend/util/clients.py
index 4d35b3fa1d..65e3f05dfd 100644
--- a/autogpt_platform/backend/backend/util/clients.py
+++ b/autogpt_platform/backend/backend/util/clients.py
@@ -293,7 +293,7 @@ def openrouter_helper_cost_provider() -> str:
def get_notification_queue() -> "SyncRabbitMQ":
"""Get a thread-cached SyncRabbitMQ notification queue client."""
from backend.data.rabbitmq import SyncRabbitMQ
- from backend.notifications.notifications import create_notification_config
+ from backend.notifications.queue import create_notification_config
client = SyncRabbitMQ(create_notification_config())
client.connect()
@@ -304,7 +304,7 @@ def get_notification_queue() -> "SyncRabbitMQ":
async def get_async_notification_queue() -> "AsyncRabbitMQ":
"""Get a thread-cached AsyncRabbitMQ notification queue client."""
from backend.data.rabbitmq import AsyncRabbitMQ
- from backend.notifications.notifications import create_notification_config
+ from backend.notifications.queue import create_notification_config
client = AsyncRabbitMQ(create_notification_config())
await client.connect()
diff --git a/autogpt_platform/backend/backend/util/settings.py b/autogpt_platform/backend/backend/util/settings.py
index e17a858dcb..ea2d9fd163 100644
--- a/autogpt_platform/backend/backend/util/settings.py
+++ b/autogpt_platform/backend/backend/util/settings.py
@@ -482,6 +482,62 @@ class Config(UpdateTrackingModel["Config"], BaseSettings):
description="The email address to use for sending emails",
)
+ # Separated so each kind carries its own reputation. Marketing mail goes
+ # from MailerLite as [email protected] and has no sender here.
+ billing_sender_email: str = Field(
+ default="AutoGPT <[email protected]>",
+ description="Sender for subscription and account service messages",
+ )
+ product_sender_email: str = Field(
+ default="AutoGPT <[email protected]>",
+ description="Sender for the Briefing, Alert and Verdict families",
+ )
+ ops_sender_email: str = Field(
+ default="AutoGPT Platform <[email protected]>",
+ description="Sender for internal ops mail to the refunds team",
+ )
+ postmark_transactional_stream: str = Field(
+ default="outbound",
+ description=(
+ "Postmark message stream for Alerts, Briefings and account mail. "
+ "Must be a transactional stream, separate from marketing mail."
+ ),
+ )
+ email_asset_base_url: str = Field(
+ default="https://platform.agpt.co/email",
+ description=(
+ "Base URL the email hero art and logo are served from. Outlook "
+ "does not render inline SVG and Gmail does not display data-URI "
+ "images, so these must be hosted files."
+ ),
+ )
+ docs_base_url: str = Field(
+ default="https://docs.agpt.co",
+ description="Documentation site linked from emails",
+ )
+ discord_invite_url: str = Field(
+ default="https://discord.gg/autogpt",
+ description="Discord invite linked from email footers",
+ )
+ admin_panel_base_url: str = Field(
+ default="https://admin.agpt.co",
+ description="Admin panel base URL, deep-linked from internal ops mail",
+ )
+
+ # MailerLite owns the onboarding tour and the monthly changelog. The
+ # backend's only job is managing who is in each audience.
+ mailerlite_onboarding_group_id: str = Field(
+ default="",
+ description=(
+ "MailerLite group whose membership triggers the six-email "
+ "'Subscription Onboarding — White Glove Tour' automation"
+ ),
+ )
+ mailerlite_changelog_group_id: str = Field(
+ default="",
+ description="MailerLite group that receives the monthly changelog campaign",
+ )
+
use_agent_image_generation_v2: bool = Field(
default=True,
description="Whether to use the new agent image generation service",
@@ -782,6 +838,11 @@ class Secrets(UpdateTrackingModel["Secrets"], BaseSettings):
description="The token to use for the Postmark webhook",
)
+ mailerlite_api_token: str = Field(
+ default="",
+ description="MailerLite API token used to manage tour and changelog audiences",
+ )
+
unsubscribe_secret_key: str = Field(
default="",
description="The secret key to use for the unsubscribe user by token",
diff --git a/autogpt_platform/backend/backend/util/text.py b/autogpt_platform/backend/backend/util/text.py
index b1e7eb2f85..f387c38242 100644
--- a/autogpt_platform/backend/backend/util/text.py
+++ b/autogpt_platform/backend/backend/util/text.py
@@ -2,12 +2,9 @@ import asyncio
import logging
import re
-import bleach
-from bleach.css_sanitizer import CSSSanitizer
from jinja2 import BaseLoader
from jinja2.exceptions import TemplateError
from jinja2.sandbox import SandboxedEnvironment
-from markupsafe import Markup
logger = logging.getLogger(__name__)
@@ -42,77 +39,6 @@ class TextFormatter:
self.env.filters["format"] = format_filter_for_jinja2
- # Define allowed CSS properties (sorted alphabetically, if you add more)
- allowed_css_properties = [
- "background-color",
- "border",
- "border-bottom",
- "border-color",
- "border-left",
- "border-radius",
- "border-right",
- "border-style",
- "border-top",
- "border-width",
- "bottom",
- "box-shadow",
- "clear",
- "color",
- "display",
- "float",
- "font-family",
- "font-size",
- "font-weight",
- "height",
- "left",
- "letter-spacing",
- "line-height",
- "margin-bottom",
- "margin-left",
- "margin-right",
- "margin-top",
- "padding",
- "position",
- "right",
- "text-align",
- "text-decoration",
- "text-shadow",
- "text-transform",
- "top",
- "width",
- ]
-
- self.css_sanitizer = CSSSanitizer(allowed_css_properties=allowed_css_properties)
-
- # Define allowed tags (sorted alphabetically, if you add more)
- self.allowed_tags = [
- "a",
- "b",
- "br",
- "div",
- "em",
- "h1",
- "h2",
- "h3",
- "h4",
- "h5",
- "i",
- "img",
- "li",
- "p",
- "span",
- "strong",
- "u",
- "ul",
- ]
-
- # Define allowed attributes to be used on specific tags
- self.allowed_attributes = {
- "*": ["class", "style"],
- "a": ["href"],
- "img": ["src"],
- }
-
async def format_string(
self,
template_str: str,
@@ -140,57 +66,6 @@ class TextFormatter:
except TemplateError as e:
raise ValueError(e) from e
- async def format_email(
- self,
- subject_template: str,
- base_template: str,
- content_template: str,
- data=None,
- **kwargs,
- ) -> tuple[str, str]:
- """
- Special handling for email templates where content needs to be rendered as HTML
- """
- # First render the content template
- content = await self.format_string(content_template, data, **kwargs)
-
- # Clean the HTML + CSS but don't escape it
- clean_content = bleach.clean(
- content,
- tags=self.allowed_tags,
- attributes=self.allowed_attributes,
- css_sanitizer=self.css_sanitizer,
- strip=True,
- )
-
- # Mark the cleaned HTML as safe using Markup
- safe_content = Markup(clean_content)
-
- # Render subject
- rendered_subject_template = await self.format_string(
- subject_template, data, **kwargs
- )
-
- # Create restricted env for HTML template (defense-in-depth)
- html_env = _RestrictedEnvironment(
- loader=BaseLoader(), autoescape=True, enable_async=True
- )
- html_env.filters["safe"] = lambda x: (
- x if isinstance(x, Markup) else Markup(str(x))
- )
-
- # Render base template with the safe content
- template = html_env.from_string(base_template)
- rendered_base_template = await template.render_async(
- data={
- "message": safe_content,
- "title": rendered_subject_template,
- "unsubscribe_link": kwargs.get("unsubscribe_link", ""),
- }
- )
-
- return rendered_subject_template, rendered_base_template
-
def _safe_range(*args: int) -> range:
"""range() replacement that caps the number of items to prevent DoS."""
diff --git a/autogpt_platform/backend/migrations/20260811120000_replace_email_notification_system/migration.sql b/autogpt_platform/backend/migrations/20260811120000_replace_email_notification_system/migration.sql
new file mode 100644
index 0000000000..3089b9f9dd
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260811120000_replace_email_notification_system/migration.sql
@@ -0,0 +1,127 @@
+-- Replace the 12-type notification surface with the four product-notification
+-- families plus the account/billing service messages, and add the tables the
+-- Alert and Briefing engines need.
+
+-- 1. NotificationType: recreate rather than ALTER, because every old value is
+-- gone. Pending rows in the old shape cannot be re-rendered by the new
+-- templates, so the queue/batch tables are truncated as part of the swap.
+TRUNCATE TABLE "NotificationEvent";
+TRUNCATE TABLE "UserNotificationBatch" CASCADE;
+
+ALTER TABLE "NotificationEvent" ALTER COLUMN "type" TYPE TEXT;
+ALTER TABLE "UserNotificationBatch" ALTER COLUMN "type" TYPE TEXT;
+
+DROP TYPE "NotificationType";
+
+CREATE TYPE "NotificationType" AS ENUM (
+ 'BRIEFING',
+ 'ALERT',
+ 'VERDICT',
+ 'OPS',
+ 'SUBSCRIPTION_WELCOME',
+ 'PAYMENT_FAILED',
+ 'PAYMENT_FINAL_NOTICE',
+ 'SUBSCRIPTION_CANCELLED',
+ 'SUBSCRIPTION_RESUMED',
+ 'SUBSCRIPTION_ENDED'
+);
+
+ALTER TABLE "NotificationEvent"
+ ALTER COLUMN "type" TYPE "NotificationType" USING "type"::"NotificationType";
+ALTER TABLE "UserNotificationBatch"
+ ALTER COLUMN "type" TYPE "NotificationType" USING "type"::"NotificationType";
+
+-- 2. Preferences: the volume knob replaces the per-type checkbox list.
+CREATE TYPE "BriefingFrequency" AS ENUM ('DAILY', 'WEEKLY', 'MONTHLY', 'OFF');
+
+ALTER TABLE "User"
+ ADD COLUMN "briefingFrequency" "BriefingFrequency" NOT NULL DEFAULT 'WEEKLY',
+ ADD COLUMN "alertsEnabled" BOOLEAN NOT NULL DEFAULT true,
+ ADD COLUMN "notifyOnStoreVerdict" BOOLEAN NOT NULL DEFAULT true,
+ ADD COLUMN "lastBriefingAt" TIMESTAMP(3),
+ ADD COLUMN "welcomeEmailSentAt" TIMESTAMP(3);
+
+-- Carry over what the old columns can say about intent before dropping them:
+-- someone who had turned the weekly summary off keeps their digest off, and
+-- someone who had turned every alert-shaped notification off keeps alerts off.
+UPDATE "User"
+SET "briefingFrequency" = 'OFF'
+WHERE "notifyOnWeeklySummary" = false;
+
+-- Alerts stay on unless the user had switched off *every* alert-shaped
+-- notification. The new AlertCause enum covers block failures and continuous
+-- errors as well as the two balance causes, so consulting only the balance
+-- pair would disable alerts for someone who had explicitly asked for the
+-- other two.
+UPDATE "User"
+SET "alertsEnabled" = false
+WHERE "notifyOnLowBalance" = false
+ AND "notifyOnZeroBalance" = false
+ AND "notifyOnBlockExecutionFailed" = false
+ AND "notifyOnContinuousAgentError" = false;
+
+UPDATE "User"
+SET "notifyOnStoreVerdict" = false
+WHERE "notifyOnAgentApproved" = false
+ AND "notifyOnAgentRejected" = false;
+
+ALTER TABLE "User"
+ DROP COLUMN "notifyOnAgentRun",
+ DROP COLUMN "notifyOnZeroBalance",
+ DROP COLUMN "notifyOnLowBalance",
+ DROP COLUMN "notifyOnBlockExecutionFailed",
+ DROP COLUMN "notifyOnContinuousAgentError",
+ DROP COLUMN "notifyOnDailySummary",
+ DROP COLUMN "notifyOnWeeklySummary",
+ DROP COLUMN "notifyOnMonthlySummary",
+ DROP COLUMN "notifyOnAgentApproved",
+ DROP COLUMN "notifyOnAgentRejected";
+
+-- 3. Alert conditions.
+CREATE TYPE "AlertCause" AS ENUM (
+ 'AUTH_EXPIRED',
+ 'PAUSED_FAILURES',
+ 'BLOCK_FAILED',
+ 'CONTINUOUS_ERROR',
+ 'AWAITING_REVIEW',
+ 'AWAITING_INPUT',
+ 'LOW_BALANCE',
+ 'ZERO_BALANCE',
+ 'GUARDRAIL'
+);
+
+CREATE TYPE "AlertConditionStatus" AS ENUM ('PENDING', 'SENT', 'DEFERRED', 'RESOLVED');
+
+CREATE TABLE "AlertCondition" (
+ "id" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "userId" TEXT NOT NULL,
+ "cause" "AlertCause" NOT NULL,
+ "causeKey" TEXT NOT NULL,
+ "data" JSONB NOT NULL,
+ "status" "AlertConditionStatus" NOT NULL DEFAULT 'PENDING',
+ "sentAt" TIMESTAMP(3),
+ "resolvedAt" TIMESTAMP(3),
+ "briefedAt" TIMESTAMP(3),
+
+ CONSTRAINT "AlertCondition_pkey" PRIMARY KEY ("id")
+);
+
+CREATE UNIQUE INDEX "AlertCondition_userId_causeKey_key"
+ ON "AlertCondition"("userId", "causeKey");
+CREATE INDEX "AlertCondition_status_createdAt_idx"
+ ON "AlertCondition"("status", "createdAt");
+CREATE INDEX "AlertCondition_userId_status_idx"
+ ON "AlertCondition"("userId", "status");
+
+ALTER TABLE "AlertCondition"
+ ADD CONSTRAINT "AlertCondition_userId_fkey"
+ FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- 4. Run interestingness, scored at completion so Briefing assembly is a
+-- ranked read instead of a scan.
+ALTER TABLE "AgentGraphExecution" ADD COLUMN "interestingness" DOUBLE PRECISION;
+
+CREATE INDEX "AgentGraphExecution_userId_endedAt_interestingness_idx"
+ ON "AgentGraphExecution"("userId", "endedAt", "interestingness");
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 8eb5f4775a..6ec7571457 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -111,17 +111,21 @@ model User {
stripeCustomerId String?
topUpConfig Json?
- maxEmailsPerDay Int @default(3)
- notifyOnAgentRun Boolean @default(true)
- notifyOnZeroBalance Boolean @default(true)
- notifyOnLowBalance Boolean @default(true)
- notifyOnBlockExecutionFailed Boolean @default(true)
- notifyOnContinuousAgentError Boolean @default(true)
- notifyOnDailySummary Boolean @default(true)
- notifyOnWeeklySummary Boolean @default(true)
- notifyOnMonthlySummary Boolean @default(true)
- notifyOnAgentApproved Boolean @default(true)
- notifyOnAgentRejected Boolean @default(true)
+ maxEmailsPerDay Int @default(3)
+
+ // The volume knob from the Briefing footer: a frequency plus two switches,
+ // instead of one unsubscribe trapdoor.
+ briefingFrequency BriefingFrequency @default(WEEKLY)
+ alertsEnabled Boolean @default(true)
+ notifyOnStoreVerdict Boolean @default(true)
+
+ // Last Briefing actually sent, so a re-run of the scheduler can't send the
+ // same period twice and the next period knows where to start.
+ lastBriefingAt DateTime?
+
+ // Set the first time this user pays for a plan. Doubles as the "first
+ // subscription" test for the welcome email and its idempotency key.
+ welcomeEmailSentAt DateTime?
timezone String @default("not-set")
@@ -154,6 +158,7 @@ model User {
APIKeys APIKey[]
IntegrationWebhooks IntegrationWebhook[]
NotificationBatches UserNotificationBatch[]
+ AlertConditions AlertCondition[]
PushSubscriptions PushSubscription[]
PendingHumanReviews PendingHumanReview[]
Workspace UserWorkspace?
@@ -700,19 +705,87 @@ model AgentPreset {
@@index([organizationId])
}
+// The four product-notification families plus the account/billing service
+// messages. Every email the platform sends is one of these; there is
+// deliberately no per-run notification type — a finished run is evidence for
+// the Briefing's highlights, not a message of its own.
enum NotificationType {
- AGENT_RUN
- ZERO_BALANCE
+ BRIEFING
+ ALERT
+ VERDICT
+ OPS
+ SUBSCRIPTION_WELCOME
+ PAYMENT_FAILED
+ PAYMENT_FINAL_NOTICE
+ SUBSCRIPTION_CANCELLED
+ SUBSCRIPTION_RESUMED
+ SUBSCRIPTION_ENDED
+}
+
+// How often the Briefing is delivered. OFF is the "alerts only" / "pause"
+// half of the footer volume knob; `alertsEnabled` carries the other half.
+enum BriefingFrequency {
+ DAILY
+ WEEKLY
+ MONTHLY
+ OFF
+}
+
+// Every condition the Alert family can fire for. The last four have no
+// equivalent in the notification surface this replaces.
+enum AlertCause {
+ AUTH_EXPIRED
+ PAUSED_FAILURES
+ BLOCK_FAILED
+ CONTINUOUS_ERROR
+ AWAITING_REVIEW
+ AWAITING_INPUT
LOW_BALANCE
- BLOCK_EXECUTION_FAILED
- CONTINUOUS_AGENT_ERROR
- DAILY_SUMMARY
- WEEKLY_SUMMARY
- MONTHLY_SUMMARY
- REFUND_REQUEST
- REFUND_PROCESSED
- AGENT_APPROVED
- AGENT_REJECTED
+ ZERO_BALANCE
+ GUARDRAIL
+}
+
+enum AlertConditionStatus {
+ // Raised, inside the debounce window, not yet emailed.
+ PENDING
+ // Emailed. Blocks the same cause from re-alerting for 24h.
+ SENT
+ // Deduped or capped — folds into the next Briefing's attention block
+ // instead of re-pinging the inbox.
+ DEFERRED
+ // Cleared before it was ever sent, or fixed afterwards.
+ RESOLVED
+}
+
+// One row per live "the platform is blocked on the human" condition. The
+// alert engine debounces (10 min), coalesces, dedupes per cause per 24h and
+// caps sends at two a day off this table; anything it can't send lands in the
+// Briefing rather than being dropped.
+model AlertCondition {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+ updatedAt DateTime @default(now()) @updatedAt
+
+ userId String
+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)
+
+ cause AlertCause
+ // Stable identity of the underlying problem (e.g. "auth_expired:gmail:<graph
+ // id>"), so re-raising the same condition updates one row instead of piling
+ // up duplicates, and resolving it can find the row without the payload.
+ causeKey String
+ data Json
+
+ status AlertConditionStatus @default(PENDING)
+ sentAt DateTime?
+ resolvedAt DateTime?
+ // Set once the condition has been carried into a Briefing's attention
+ // block, so the next Briefing doesn't repeat it.
+ briefedAt DateTime?
+
+ @@unique([userId, causeKey])
+ @@index([status, createdAt])
+ @@index([userId, status])
}
model NotificationEvent {
@@ -1111,6 +1184,13 @@ model AgentGraphExecution {
stats Json?
+ // Scored once, when the run reaches a terminal state, from signals we
+ // already have (outcome, first-ever success, novel output, cost/duration
+ // anomaly). Assembling a Briefing is then a ranked read rather than a scan
+ // of every run in the period. Null for runs that finished before scoring
+ // existed, and for runs still in flight.
+ interestingness Float?
+
// Parent-child execution tracking for nested agent graphs
parentGraphExecutionId String?
ParentExecution AgentGraphExecution? @relation("ParentChildExecution", fields: [parentGraphExecutionId], references: [id], onDelete: SetNull)
@@ -1136,6 +1216,8 @@ model AgentGraphExecution {
@@index([agentGraphId, agentGraphVersion])
@@index([userId, isDeleted, createdAt])
@@index([createdAt])
+ // Briefing assembly: top-scored runs for one user over one period.
+ @@index([userId, endedAt, interestingness])
@@index([agentPresetId])
@@index([expertId, createdAt])
@@index([shareToken])
diff --git a/autogpt_platform/frontend/public/email/hero-alert.jpg b/autogpt_platform/frontend/public/email/hero-alert.jpg
new file mode 100644
index 0000000000..bb646ce4a2
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-alert.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-briefing-attention.jpg b/autogpt_platform/frontend/public/email/hero-briefing-attention.jpg
new file mode 100644
index 0000000000..614909d82c
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-briefing-attention.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-briefing-clean.jpg b/autogpt_platform/frontend/public/email/hero-briefing-clean.jpg
new file mode 100644
index 0000000000..5c701b5ddd
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-briefing-clean.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-briefing-quiet.jpg b/autogpt_platform/frontend/public/email/hero-briefing-quiet.jpg
new file mode 100644
index 0000000000..95337b1b4a
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-briefing-quiet.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-briefing-rough.jpg b/autogpt_platform/frontend/public/email/hero-briefing-rough.jpg
new file mode 100644
index 0000000000..bf08c5a815
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-briefing-rough.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-cancel-safe.jpg b/autogpt_platform/frontend/public/email/hero-cancel-safe.jpg
new file mode 100644
index 0000000000..eb5a8dcc8a
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-cancel-safe.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-changelog.jpg b/autogpt_platform/frontend/public/email/hero-changelog.jpg
new file mode 100644
index 0000000000..e635f69408
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-changelog.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-final-notice.jpg b/autogpt_platform/frontend/public/email/hero-final-notice.jpg
new file mode 100644
index 0000000000..9222aa1c27
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-final-notice.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-payment-hiccup.jpg b/autogpt_platform/frontend/public/email/hero-payment-hiccup.jpg
new file mode 100644
index 0000000000..868b9d0c08
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-payment-hiccup.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-plan-asleep.jpg b/autogpt_platform/frontend/public/email/hero-plan-asleep.jpg
new file mode 100644
index 0000000000..00f1ba1485
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-plan-asleep.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-tour-directline.jpg b/autogpt_platform/frontend/public/email/hero-tour-directline.jpg
new file mode 100644
index 0000000000..f96819e067
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-tour-directline.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-tour-firstwin.jpg b/autogpt_platform/frontend/public/email/hero-tour-firstwin.jpg
new file mode 100644
index 0000000000..b8b3d4b5e5
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-tour-firstwin.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-tour-fiveways.jpg b/autogpt_platform/frontend/public/email/hero-tour-fiveways.jpg
new file mode 100644
index 0000000000..2bd6a6d929
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-tour-fiveways.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-tour-listening.jpg b/autogpt_platform/frontend/public/email/hero-tour-listening.jpg
new file mode 100644
index 0000000000..46fe48ecc9
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-tour-listening.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-tour-shipping.jpg b/autogpt_platform/frontend/public/email/hero-tour-shipping.jpg
new file mode 100644
index 0000000000..e1ca3137f4
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-tour-shipping.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-tour-workspace.jpg b/autogpt_platform/frontend/public/email/hero-tour-workspace.jpg
new file mode 100644
index 0000000000..894ccfe446
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-tour-workspace.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-trial-headsup.jpg b/autogpt_platform/frontend/public/email/hero-trial-headsup.jpg
new file mode 100644
index 0000000000..83ec76a663
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-trial-headsup.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-verdict-approved.jpg b/autogpt_platform/frontend/public/email/hero-verdict-approved.jpg
new file mode 100644
index 0000000000..6d995b6a65
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-verdict-approved.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-verdict-changes.jpg b/autogpt_platform/frontend/public/email/hero-verdict-changes.jpg
new file mode 100644
index 0000000000..a6fa537448
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-verdict-changes.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-welcome-back.jpg b/autogpt_platform/frontend/public/email/hero-welcome-back.jpg
new file mode 100644
index 0000000000..a1194f3bac
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-welcome-back.jpg differ
diff --git a/autogpt_platform/frontend/public/email/hero-welcome.jpg b/autogpt_platform/frontend/public/email/hero-welcome.jpg
new file mode 100644
index 0000000000..f38c4b1b75
Binary files /dev/null and b/autogpt_platform/frontend/public/email/hero-welcome.jpg differ
diff --git a/autogpt_platform/frontend/public/email/logo-light.png b/autogpt_platform/frontend/public/email/logo-light.png
new file mode 100644
index 0000000000..c5dda2d41b
Binary files /dev/null and b/autogpt_platform/frontend/public/email/logo-light.png differ
diff --git a/autogpt_platform/frontend/public/email/mark-otto.png b/autogpt_platform/frontend/public/email/mark-otto.png
new file mode 100644
index 0000000000..f1e9f714ad
Binary files /dev/null and b/autogpt_platform/frontend/public/email/mark-otto.png differ
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/__tests__/page.test.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/__tests__/page.test.tsx
index 1eb1576630..7424d58a42 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/__tests__/page.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/__tests__/page.test.tsx
@@ -11,6 +11,8 @@ import {
getPostV1UpdateNotificationPreferencesMockHandler,
getPostV1UpdateUserEmailMockHandler,
} from "@/app/api/__generated__/endpoints/auth/auth.msw";
+import type { NotificationPreference } from "@/app/api/__generated__/models/notificationPreference";
+import type { NotificationPreferenceDTO } from "@/app/api/__generated__/models/notificationPreferenceDTO";
import { server } from "@/mocks/mock-server";
import SettingsPage from "../page";
import { beforeEach, describe, expect, test, vi } from "vitest";
@@ -34,6 +36,15 @@ const testUser = {
created_at: "2026-01-01T00:00:00.000Z",
};
+const defaultPreferences = {
+ user_id: "user-1",
+ email: "[email protected]",
+ briefing_frequency: "WEEKLY" as const,
+ alerts_enabled: true,
+ store_verdicts_enabled: true,
+ daily_limit: 0,
+} satisfies NotificationPreference;
+
describe("SettingsPage", () => {
beforeEach(() => {
mockUseAuth.mockReturnValue({
@@ -45,35 +56,10 @@ describe("SettingsPage", () => {
test("renders the account actions", async () => {
server.use(
- getGetV1GetNotificationPreferencesMockHandler({
- user_id: "user-1",
- email: "[email protected]",
- preferences: {
- AGENT_RUN: true,
- ZERO_BALANCE: false,
- LOW_BALANCE: false,
- BLOCK_EXECUTION_FAILED: true,
- CONTINUOUS_AGENT_ERROR: false,
- DAILY_SUMMARY: false,
- WEEKLY_SUMMARY: true,
- MONTHLY_SUMMARY: false,
- AGENT_APPROVED: true,
- AGENT_REJECTED: true,
- },
- daily_limit: 0,
- emails_sent_today: 0,
- last_reset_date: new Date("2026-01-01T00:00:00.000Z"),
- }),
+ getGetV1GetNotificationPreferencesMockHandler(defaultPreferences),
getGetV1GetUserTimezoneMockHandler({ timezone: "Asia/Kolkata" }),
getPostV1UpdateUserEmailMockHandler({}),
- getPostV1UpdateNotificationPreferencesMockHandler({
- user_id: "user-1",
- email: "[email protected]",
- preferences: {},
- daily_limit: 0,
- emails_sent_today: 0,
- last_reset_date: new Date("2026-01-01T00:00:00.000Z"),
- }),
+ getPostV1UpdateNotificationPreferencesMockHandler(defaultPreferences),
);
render(<SettingsPage />);
@@ -86,61 +72,36 @@ describe("SettingsPage", () => {
});
test("saves notification preference changes", async () => {
- let submittedPreferences:
- | {
- email: string;
- preferences: Record<string, boolean>;
- }
- | undefined;
+ let submitted: NotificationPreferenceDTO | undefined;
server.use(
- getGetV1GetNotificationPreferencesMockHandler({
- user_id: "user-1",
- email: "[email protected]",
- preferences: {
- AGENT_RUN: false,
- ZERO_BALANCE: false,
- LOW_BALANCE: false,
- BLOCK_EXECUTION_FAILED: false,
- CONTINUOUS_AGENT_ERROR: false,
- DAILY_SUMMARY: false,
- WEEKLY_SUMMARY: false,
- MONTHLY_SUMMARY: false,
- AGENT_APPROVED: false,
- AGENT_REJECTED: false,
- },
- daily_limit: 0,
- emails_sent_today: 0,
- last_reset_date: new Date("2026-01-01T00:00:00.000Z"),
- }),
+ getGetV1GetNotificationPreferencesMockHandler(defaultPreferences),
getGetV1GetUserTimezoneMockHandler({ timezone: "Asia/Kolkata" }),
getPostV1UpdateUserEmailMockHandler({}),
getPostV1UpdateNotificationPreferencesMockHandler(async ({ request }) => {
- submittedPreferences = (await request.json()) as {
- email: string;
- preferences: Record<string, boolean>;
- };
-
- return {
- user_id: "user-1",
- email: submittedPreferences.email,
- preferences: submittedPreferences.preferences,
- daily_limit: 0,
- emails_sent_today: 0,
- last_reset_date: new Date("2026-01-01T00:00:00.000Z"),
- };
+ submitted = (await request.json()) as NotificationPreferenceDTO;
+ return { ...defaultPreferences, ...submitted };
}),
);
render(<SettingsPage />);
fireEvent.click(
- await screen.findByRole("switch", { name: "Agent Run Notifications" }),
+ await screen.findByRole("combobox", { name: "Briefing frequency" }),
+ );
+ fireEvent.click(await screen.findByRole("option", { name: "Monthly" }));
+ fireEvent.click(await screen.findByRole("switch", { name: "Alerts" }));
+ fireEvent.click(
+ screen.getByRole("switch", { name: "Marketplace reviews" }),
);
fireEvent.click(screen.getByRole("button", { name: "Save preferences" }));
await waitFor(() => {
- expect(submittedPreferences?.preferences.AGENT_RUN).toBe(true);
+ expect(submitted).toMatchObject({
+ briefing_frequency: "MONTHLY",
+ alerts_enabled: false,
+ store_verdicts_enabled: false,
+ });
});
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/components/SettingsForm/components/NotificationForm/NotificationForm.tsx b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/components/SettingsForm/components/NotificationForm/NotificationForm.tsx
index 3f0ff7ca24..111ecc478c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/components/SettingsForm/components/NotificationForm/NotificationForm.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/components/SettingsForm/components/NotificationForm/NotificationForm.tsx
@@ -8,9 +8,13 @@ import {
} from "@/components/__legacy__/ui/form";
import { Text } from "@/components/atoms/Text/Text";
import { Button } from "@/components/atoms/Button/Button";
+import { Select } from "@/components/atoms/Select/Select";
import { NotificationPreference } from "@/app/api/__generated__/models/notificationPreference";
import type { User } from "@/lib/auth/types";
-import { useNotificationForm } from "./useNotificationForm";
+import {
+ useNotificationForm,
+ type NotificationFormValues,
+} from "./useNotificationForm";
import { Switch } from "@/components/atoms/Switch/Switch";
type NotificationFormProps = {
@@ -18,6 +22,13 @@ type NotificationFormProps = {
user: User;
};
+const BRIEFING_OPTIONS = [
+ { value: "DAILY", label: "Daily" },
+ { value: "WEEKLY", label: "Weekly" },
+ { value: "MONTHLY", label: "Monthly" },
+ { value: "OFF", label: "Off" },
+];
+
export function NotificationForm({ preferences, user }: NotificationFormProps) {
const { form, onSubmit, onCancel, isLoading } = useNotificationForm({
preferences,
@@ -29,217 +40,42 @@ export function NotificationForm({ preferences, user }: NotificationFormProps) {
<Text variant="h3" size="large-semibold">
Notifications
</Text>
+ <Text variant="body" className="mt-2 text-slate-400">
+ Billing and account messages are always sent — they are about your
+ account, not a promotion.
+ </Text>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="mt-6 flex flex-col gap-10"
>
- {/* Agent Notifications */}
<div className="flex flex-col gap-6">
- <Text variant="h4" size="body-medium" className="text-slate-400">
- Agent Notifications
- </Text>
- <FormField
- control={form.control}
- name="notifyOnAgentRun"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between">
- <div className="space-y-0.5">
- <Text variant="h4" size="body-medium">
- Agent Run Notifications
- </Text>
- <Text variant="body">
- Receive notifications when an agent starts or completes a
- run
- </Text>
- </div>
- <FormControl>
- <Switch
- aria-label="Agent Run Notifications"
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="notifyOnBlockExecutionFailed"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between">
- <div className="space-y-0.5">
- <Text variant="h4" size="body-medium">
- Block Execution Failures
- </Text>
- <Text variant="body">
- Get notified when a block execution fails during agent
- runs
- </Text>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="notifyOnContinuousAgentError"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between">
- <div className="space-y-0.5">
- <Text variant="h4" size="body-medium">
- Continuous Agent Errors
- </Text>
- <Text variant="body">
- Receive alerts when an agent encounters repeated errors
- </Text>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
- </div>
-
- {/* Store Notifications */}
- <div className="flex flex-col gap-6">
- <Text variant="h4" size="body-medium" className="text-slate-400">
- Store Notifications
- </Text>
- <FormField
- control={form.control}
- name="notifyOnAgentApproved"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between">
- <div className="space-y-0.5">
- <Text variant="h4" size="body-medium">
- Agent Approved
- </Text>
- <Text variant="body">
- Get notified when your submitted agent is approved for the
- store
- </Text>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="notifyOnAgentRejected"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between">
- <div className="space-y-0.5">
- <Text variant="h4" size="body-medium">
- Agent Rejected
- </Text>
- <Text variant="body">
- Receive notifications when your agent submission needs
- updates
- </Text>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
- </div>
-
- {/* Balance Notifications */}
- <div className="flex flex-col gap-4">
- <Text variant="h4" size="body-medium" className="text-slate-400">
- Balance Notifications
- </Text>
<FormField
control={form.control}
- name="notifyOnZeroBalance"
+ name="briefingFrequency"
render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between">
+ <FormItem className="flex flex-col gap-2">
<div className="space-y-0.5">
<Text variant="h4" size="body-medium">
- Zero Balance Alert
+ Briefing
</Text>
<Text variant="body">
- Get notified when your account balance reaches zero
+ What your agents got done, at around 07:30 your time.
+ Never sent when nothing ran.
</Text>
</div>
<FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
-
- <FormField
- control={form.control}
- name="notifyOnLowBalance"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between">
- <div className="space-y-0.5">
- <Text variant="h4" size="body-medium">
- Low Balance Warning
- </Text>
- <Text variant="body">
- Receive warnings when your balance is running low
- </Text>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- </FormItem>
- )}
- />
- </div>
-
- {/* Summary Reports */}
- <div className="flex flex-col gap-4">
- <Text variant="h4" size="body-medium" className="text-slate-400">
- Summary reports
- </Text>
- <FormField
- control={form.control}
- name="notifyOnDailySummary"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between">
- <div className="space-y-1">
- <Text variant="h4" size="body-medium">
- Daily Summary
- </Text>
- <Text variant="body">
- Receive a daily summary of your account activity
- </Text>
- </div>
- <FormControl>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
+ <Select
+ id="briefing-frequency"
+ label="Briefing frequency"
+ hideLabel
+ value={field.value}
+ options={BRIEFING_OPTIONS}
+ onValueChange={(value) =>
+ field.onChange(
+ value as NotificationFormValues["briefingFrequency"],
+ )
+ }
/>
</FormControl>
</FormItem>
@@ -248,19 +84,21 @@ export function NotificationForm({ preferences, user }: NotificationFormProps) {
<FormField
control={form.control}
- name="notifyOnWeeklySummary"
+ name="alertsEnabled"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between">
<div className="space-y-0.5">
<Text variant="h4" size="body-medium">
- Weekly Summary
+ Alerts
</Text>
<Text variant="body">
- Get a weekly overview of your account performance
+ Only when something is waiting on you — never for a
+ successful run. At most two a day.
</Text>
</div>
<FormControl>
<Switch
+ aria-label="Alerts"
checked={field.value}
onCheckedChange={field.onChange}
/>
@@ -271,19 +109,20 @@ export function NotificationForm({ preferences, user }: NotificationFormProps) {
<FormField
control={form.control}
- name="notifyOnMonthlySummary"
+ name="storeVerdictsEnabled"
render={({ field }) => (
<FormItem className="flex flex-row items-center justify-between">
<div className="space-y-0.5">
<Text variant="h4" size="body-medium">
- Monthly Summary
+ Marketplace reviews
</Text>
<Text variant="body">
- Receive a comprehensive monthly report of your account
+ When an agent you submitted is approved or needs changes.
</Text>
</div>
<FormControl>
<Switch
+ aria-label="Marketplace reviews"
checked={field.value}
onCheckedChange={field.onChange}
/>
diff --git a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/components/SettingsForm/components/NotificationForm/useNotificationForm.ts b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/components/SettingsForm/components/NotificationForm/useNotificationForm.ts
index cb16b346d4..0ab75c7d51 100644
--- a/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/components/SettingsForm/components/NotificationForm/useNotificationForm.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/profile/(user)/settings/components/SettingsForm/components/NotificationForm/useNotificationForm.ts
@@ -7,37 +7,26 @@ import { useToast } from "@/components/molecules/Toast/use-toast";
import { NotificationPreference } from "@/app/api/__generated__/models/notificationPreference";
import type { User } from "@/lib/auth/types";
import { usePostV1UpdateNotificationPreferences } from "@/app/api/__generated__/endpoints/auth/auth";
-import { NotificationPreferenceDTO } from "@/lib/autogpt-server-api/types";
+// The volume knob from the Briefing footer, not a checkbox list. Billing and
+// account messages are service mail and are deliberately absent — they are
+// sent regardless of what is set here.
const notificationFormSchema = z.object({
- notifyOnAgentRun: z.boolean(),
- notifyOnZeroBalance: z.boolean(),
- notifyOnLowBalance: z.boolean(),
- notifyOnBlockExecutionFailed: z.boolean(),
- notifyOnContinuousAgentError: z.boolean(),
- notifyOnDailySummary: z.boolean(),
- notifyOnWeeklySummary: z.boolean(),
- notifyOnMonthlySummary: z.boolean(),
- notifyOnAgentApproved: z.boolean(),
- notifyOnAgentRejected: z.boolean(),
+ briefingFrequency: z.enum(["DAILY", "WEEKLY", "MONTHLY", "OFF"]),
+ alertsEnabled: z.boolean(),
+ storeVerdictsEnabled: z.boolean(),
});
-function createNotificationDefaultValues(preferences: {
- preferences?: Record<string, boolean>;
-}) {
+export type NotificationFormValues = z.infer<typeof notificationFormSchema>;
+
+function createNotificationDefaultValues(
+ preferences: NotificationPreference,
+): NotificationFormValues {
return {
- notifyOnAgentRun: preferences.preferences?.AGENT_RUN,
- notifyOnZeroBalance: preferences.preferences?.ZERO_BALANCE,
- notifyOnLowBalance: preferences.preferences?.LOW_BALANCE,
- notifyOnBlockExecutionFailed:
- preferences.preferences?.BLOCK_EXECUTION_FAILED,
- notifyOnContinuousAgentError:
- preferences.preferences?.CONTINUOUS_AGENT_ERROR,
- notifyOnDailySummary: preferences.preferences?.DAILY_SUMMARY,
- notifyOnWeeklySummary: preferences.preferences?.WEEKLY_SUMMARY,
- notifyOnMonthlySummary: preferences.preferences?.MONTHLY_SUMMARY,
- notifyOnAgentApproved: preferences.preferences?.AGENT_APPROVED,
- notifyOnAgentRejected: preferences.preferences?.AGENT_REJECTED,
+ briefingFrequency: (preferences.briefing_frequency ??
+ "WEEKLY") as NotificationFormValues["briefingFrequency"],
+ alertsEnabled: preferences.alerts_enabled ?? true,
+ storeVerdictsEnabled: preferences.store_verdicts_enabled ?? true,
};
}
@@ -51,7 +40,7 @@ export function useNotificationForm({
const { toast } = useToast();
const defaultValues = createNotificationDefaultValues(preferences);
- const form = useForm<z.infer<typeof notificationFormSchema>>({
+ const form = useForm<NotificationFormValues>({
resolver: zodResolver(notificationFormSchema),
defaultValues,
});
@@ -71,27 +60,15 @@ export function useNotificationForm({
},
});
- async function onSubmit(values: z.infer<typeof notificationFormSchema>) {
+ async function onSubmit(values: NotificationFormValues) {
try {
- const notificationPreferences: NotificationPreferenceDTO = {
- email: user.email || "",
- preferences: {
- AGENT_RUN: values.notifyOnAgentRun,
- ZERO_BALANCE: values.notifyOnZeroBalance,
- LOW_BALANCE: values.notifyOnLowBalance,
- BLOCK_EXECUTION_FAILED: values.notifyOnBlockExecutionFailed,
- CONTINUOUS_AGENT_ERROR: values.notifyOnContinuousAgentError,
- DAILY_SUMMARY: values.notifyOnDailySummary,
- WEEKLY_SUMMARY: values.notifyOnWeeklySummary,
- MONTHLY_SUMMARY: values.notifyOnMonthlySummary,
- AGENT_APPROVED: values.notifyOnAgentApproved,
- AGENT_REJECTED: values.notifyOnAgentRejected,
- },
- daily_limit: 0,
- };
-
await updateNotificationsMutation.mutateAsync({
- data: notificationPreferences,
+ data: {
+ email: user.email || "",
+ briefing_frequency: values.briefingFrequency,
+ alerts_enabled: values.alertsEnabled,
+ store_verdicts_enabled: values.storeVerdictsEnabled,
+ },
});
toast({
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/helpers.test.ts
new file mode 100644
index 0000000000..47f048c9ed
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/helpers.test.ts
@@ -0,0 +1,191 @@
+import { describe, expect, it, test } from "vitest";
+
+import type { NotificationPreference } from "@/app/api/__generated__/models/notificationPreference";
+
+import {
+ BRIEFING_OPTIONS,
+ describeFooterChoice,
+ dirtyKinds,
+ findTimezoneLabel,
+ isFormDirty,
+ preferencesToSettings,
+ settingsFromFooterLink,
+ type NotificationSettings,
+ type PreferencesFormState,
+} from "../helpers";
+
+const currentSettings: NotificationSettings = {
+ briefingFrequency: "WEEKLY",
+ alertsEnabled: false,
+ storeVerdictsEnabled: true,
+};
+
+function makeState(
+ notifications: NotificationSettings = currentSettings,
+ timezone = "Europe/London",
+): PreferencesFormState {
+ return { timezone, notifications };
+}
+
+describe("account preference helpers", () => {
+ test("offers every supported briefing frequency", () => {
+ expect(BRIEFING_OPTIONS.map(({ value }) => value)).toEqual([
+ "DAILY",
+ "WEEKLY",
+ "MONTHLY",
+ "OFF",
+ ]);
+ });
+
+ test("maps every email footer choice to notification settings", () => {
+ expect(settingsFromFooterLink("daily", currentSettings)).toEqual({
+ ...currentSettings,
+ briefingFrequency: "DAILY",
+ });
+ expect(settingsFromFooterLink("weekly", currentSettings)).toEqual({
+ ...currentSettings,
+ briefingFrequency: "WEEKLY",
+ });
+ expect(settingsFromFooterLink("monthly", currentSettings)).toEqual({
+ ...currentSettings,
+ briefingFrequency: "MONTHLY",
+ });
+ expect(settingsFromFooterLink("alerts", currentSettings)).toEqual({
+ ...currentSettings,
+ briefingFrequency: "OFF",
+ alertsEnabled: true,
+ });
+ expect(settingsFromFooterLink("off", currentSettings)).toEqual({
+ ...currentSettings,
+ briefingFrequency: "OFF",
+ alertsEnabled: false,
+ });
+ expect(settingsFromFooterLink(null, currentSettings)).toBeNull();
+ expect(settingsFromFooterLink("unsupported", currentSettings)).toBeNull();
+ });
+
+ test("uses safe defaults for omitted notification preferences", () => {
+ const preferences = {
+ user_id: "user-1",
+ email: "[email protected]",
+ } satisfies NotificationPreference;
+
+ expect(preferencesToSettings(preferences)).toEqual({
+ briefingFrequency: "WEEKLY",
+ alertsEnabled: true,
+ storeVerdictsEnabled: true,
+ });
+ });
+
+ test("preserves notification preferences returned by the API", () => {
+ const preferences = {
+ user_id: "user-1",
+ email: "[email protected]",
+ briefing_frequency: "MONTHLY",
+ alerts_enabled: false,
+ store_verdicts_enabled: false,
+ } satisfies NotificationPreference;
+
+ expect(preferencesToSettings(preferences)).toEqual({
+ briefingFrequency: "MONTHLY",
+ alertsEnabled: false,
+ storeVerdictsEnabled: false,
+ });
+ });
+
+ test("reports which preference groups have unsaved changes", () => {
+ const initial = makeState();
+ const briefingChanged = makeState({
+ ...currentSettings,
+ briefingFrequency: "DAILY",
+ });
+ const alertsChanged = makeState({
+ ...currentSettings,
+ alertsEnabled: true,
+ });
+ const verdictsChanged = makeState({
+ ...currentSettings,
+ storeVerdictsEnabled: false,
+ });
+
+ expect(dirtyKinds(initial, initial)).toEqual({
+ timezone: false,
+ notifications: false,
+ });
+ expect(
+ dirtyKinds(initial, makeState(currentSettings, "Asia/Tokyo")),
+ ).toEqual({
+ timezone: true,
+ notifications: false,
+ });
+ expect(dirtyKinds(initial, briefingChanged).notifications).toBe(true);
+ expect(dirtyKinds(initial, alertsChanged).notifications).toBe(true);
+ expect(dirtyKinds(initial, verdictsChanged).notifications).toBe(true);
+ expect(isFormDirty(initial, initial)).toBe(false);
+ expect(isFormDirty(initial, verdictsChanged)).toBe(true);
+ });
+
+ test("shows known timezone labels and preserves unknown values", () => {
+ expect(findTimezoneLabel("Europe/London")).toBe("London (UK)");
+ expect(findTimezoneLabel("Mars/Olympus_Mons")).toBe("Mars/Olympus_Mons");
+ });
+});
+
+describe("the volume knob's footer links", () => {
+ it("maps every option the Briefing footer offers", () => {
+ const current = {
+ briefingFrequency: "WEEKLY" as const,
+ alertsEnabled: true,
+ storeVerdictsEnabled: true,
+ };
+ // The five links in briefing.html.j2's footer, in order.
+ expect(settingsFromFooterLink("daily", current)?.briefingFrequency).toBe(
+ "DAILY",
+ );
+ expect(settingsFromFooterLink("weekly", current)?.briefingFrequency).toBe(
+ "WEEKLY",
+ );
+ expect(settingsFromFooterLink("monthly", current)?.briefingFrequency).toBe(
+ "MONTHLY",
+ );
+
+ // "Alerts only" and "Pause" both stop the digest; they differ on alerts.
+ const alertsOnly = settingsFromFooterLink("alerts", current);
+ expect(alertsOnly?.briefingFrequency).toBe("OFF");
+ expect(alertsOnly?.alertsEnabled).toBe(true);
+
+ const paused = settingsFromFooterLink("off", current);
+ expect(paused?.briefingFrequency).toBe("OFF");
+ expect(paused?.alertsEnabled).toBe(false);
+ });
+
+ it("leaves unrelated preferences alone", () => {
+ const current = {
+ briefingFrequency: "WEEKLY" as const,
+ alertsEnabled: true,
+ storeVerdictsEnabled: false,
+ };
+ // A frequency link must not quietly re-enable store verdicts.
+ expect(settingsFromFooterLink("daily", current)?.storeVerdictsEnabled).toBe(
+ false,
+ );
+ });
+
+ it("ignores an unknown or absent choice", () => {
+ const current = {
+ briefingFrequency: "WEEKLY" as const,
+ alertsEnabled: true,
+ storeVerdictsEnabled: true,
+ };
+ expect(settingsFromFooterLink(null, current)).toBeNull();
+ expect(settingsFromFooterLink("bogus", current)).toBeNull();
+ });
+
+ it("confirms the choice rather than prompting for it", () => {
+ // The click already saved; the toast is a receipt, not a question.
+ expect(describeFooterChoice("daily")).toMatch(/every day/i);
+ expect(describeFooterChoice("alerts")).toMatch(/still get alerts/i);
+ expect(describeFooterChoice("off")).toMatch(/paused/i);
+ expect(describeFooterChoice(null)).toBe("Preferences updated");
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/main.test.tsx
index ec91f12471..c54b42cff9 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/main.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/account/__tests__/main.test.tsx
@@ -8,6 +8,10 @@ import {
getPostV1UpdateUserEmailMockHandler,
getPostV1UpdateUserTimezoneMockHandler,
} from "@/app/api/__generated__/endpoints/auth/auth.msw";
+import type { NotificationPreference } from "@/app/api/__generated__/models/notificationPreference";
+import type { NotificationPreferenceDTO } from "@/app/api/__generated__/models/notificationPreferenceDTO";
+import { http, HttpResponse } from "msw";
+
import { server } from "@/mocks/mock-server";
import {
fireEvent,
@@ -20,6 +24,9 @@ import SettingsPreferencesPage from "../page";
const mockUseAuth = vi.hoisted(() => vi.fn());
const mockUseGetFlag = vi.hoisted(() => vi.fn());
+const mockUseSearchParams = vi.hoisted(() =>
+ vi.fn(() => new URLSearchParams()),
+);
vi.mock("@/providers/onboarding/onboarding-provider", () => ({
default: ({ children }: { children: ReactNode }) => <>{children}</>,
@@ -29,6 +36,27 @@ vi.mock("@/lib/auth/hooks/useAuth", () => ({
useAuth: mockUseAuth,
}));
+const mockRouterReplace = vi.fn();
+
+vi.mock("next/navigation", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("next/navigation")>();
+ return {
+ ...actual,
+ useSearchParams: mockUseSearchParams,
+ usePathname: () => "/settings/account",
+ // The footer link strips its own ?f= once applied, so the page needs a
+ // router even when the test never navigates.
+ useRouter: () => ({
+ replace: mockRouterReplace,
+ push: vi.fn(),
+ back: vi.fn(),
+ forward: vi.fn(),
+ refresh: vi.fn(),
+ prefetch: vi.fn(),
+ }),
+ };
+});
+
vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => {
const actual =
await importOriginal<
@@ -49,45 +77,31 @@ const testUser = {
created_at: "2026-01-01T00:00:00.000Z",
};
-const baseDate = new Date("2026-01-01T00:00:00.000Z");
-
-const allFalsePreferences = {
- AGENT_RUN: false,
- ZERO_BALANCE: false,
- LOW_BALANCE: false,
- BLOCK_EXECUTION_FAILED: false,
- CONTINUOUS_AGENT_ERROR: false,
- DAILY_SUMMARY: false,
- WEEKLY_SUMMARY: false,
- MONTHLY_SUMMARY: false,
- AGENT_APPROVED: false,
- AGENT_REJECTED: false,
-};
+const defaultPreferences = {
+ user_id: "user-1",
+ email: "[email protected]",
+ briefing_frequency: "WEEKLY" as const,
+ alerts_enabled: true,
+ store_verdicts_enabled: true,
+ daily_limit: 0,
+} satisfies NotificationPreference;
function setupBaseHandlers(
- options: { timezone?: string; preferences?: Record<string, boolean> } = {},
+ options: {
+ timezone?: string;
+ preferences?: Partial<typeof defaultPreferences>;
+ } = {},
) {
server.use(
getGetV1GetNotificationPreferencesMockHandler({
- user_id: "user-1",
- email: "[email protected]",
- preferences: options.preferences ?? allFalsePreferences,
- daily_limit: 0,
- emails_sent_today: 0,
- last_reset_date: baseDate,
+ ...defaultPreferences,
+ ...options.preferences,
}),
getGetV1GetUserTimezoneMockHandler({
timezone: options.timezone ?? "Asia/Kolkata",
}),
getPostV1UpdateUserEmailMockHandler({}),
- getPostV1UpdateNotificationPreferencesMockHandler({
- user_id: "user-1",
- email: "[email protected]",
- preferences: {},
- daily_limit: 0,
- emails_sent_today: 0,
- last_reset_date: baseDate,
- }),
+ getPostV1UpdateNotificationPreferencesMockHandler(defaultPreferences),
getPostV1UpdateUserTimezoneMockHandler({
timezone: "Europe/London",
}),
@@ -105,9 +119,11 @@ describe("SettingsPreferencesPage", () => {
// "on" so the notification cases exercise the card, and flip it off in
// the case that asserts it stays hidden.
mockUseGetFlag.mockReturnValue(true);
+ mockUseSearchParams.mockReturnValue(new URLSearchParams());
});
test("renders Account card with current email and reset password link", async () => {
+ mockUseGetFlag.mockReturnValue(false);
setupBaseHandlers();
render(<SettingsPreferencesPage />);
@@ -169,36 +185,17 @@ describe("SettingsPreferencesPage", () => {
expect((discardButton as HTMLButtonElement).disabled).toBe(true);
});
- test("toggling a notification enables Save and persists on click", async () => {
- let submittedPreferences:
- | { email: string; preferences: Record<string, boolean> }
- | undefined;
+ test("switching Alerts off enables Save and persists the volume knob", async () => {
+ let submitted: NotificationPreferenceDTO | undefined;
server.use(
- getGetV1GetNotificationPreferencesMockHandler({
- user_id: "user-1",
- email: "[email protected]",
- preferences: allFalsePreferences,
- daily_limit: 0,
- emails_sent_today: 0,
- last_reset_date: baseDate,
- }),
+ getGetV1GetNotificationPreferencesMockHandler(defaultPreferences),
getGetV1GetUserTimezoneMockHandler({ timezone: "Asia/Kolkata" }),
getPostV1UpdateUserEmailMockHandler({}),
getPostV1UpdateUserTimezoneMockHandler({ timezone: "Asia/Kolkata" }),
getPostV1UpdateNotificationPreferencesMockHandler(async ({ request }) => {
- submittedPreferences = (await request.json()) as {
- email: string;
- preferences: Record<string, boolean>;
- };
- return {
- user_id: "user-1",
- email: submittedPreferences.email,
- preferences: submittedPreferences.preferences,
- daily_limit: 0,
- emails_sent_today: 0,
- last_reset_date: baseDate,
- };
+ submitted = (await request.json()) as NotificationPreferenceDTO;
+ return { ...defaultPreferences, ...submitted };
}),
);
@@ -209,8 +206,7 @@ describe("SettingsPreferencesPage", () => {
});
expect((saveButton as HTMLButtonElement).disabled).toBe(true);
- const switches = await screen.findAllByRole("switch");
- fireEvent.click(switches[0]);
+ fireEvent.click(await screen.findByRole("switch", { name: "Alerts" }));
await waitFor(() => {
expect((saveButton as HTMLButtonElement).disabled).toBe(false);
@@ -219,36 +215,134 @@ describe("SettingsPreferencesPage", () => {
fireEvent.click(saveButton);
await waitFor(() => {
- expect(submittedPreferences).toBeDefined();
+ expect(submitted).toBeDefined();
});
- const flippedKey = Object.entries(submittedPreferences!.preferences).find(
- ([, v]) => v === true,
- )?.[0];
- expect(flippedKey).toBeDefined();
+ expect(submitted!.alerts_enabled).toBe(false);
+ // Billing and account messages are service mail and aren't represented
+ // here at all, so there is nothing to switch off for them.
+ expect(submitted!.briefing_frequency).toBe("WEEKLY");
});
- test("saving a timezone change posts the new value", async () => {
- let submittedTimezone: string | undefined;
+ test("applies an Alerts-only footer link when it carries a valid token", async () => {
+ let applied: URL | undefined;
+ mockUseSearchParams.mockReturnValue(
+ new URLSearchParams({ f: "alerts", t: "signed-token" }),
+ );
server.use(
getGetV1GetNotificationPreferencesMockHandler({
- user_id: "user-1",
- email: "[email protected]",
- preferences: allFalsePreferences,
- daily_limit: 0,
- emails_sent_today: 0,
- last_reset_date: baseDate,
+ ...defaultPreferences,
+ alerts_enabled: false,
}),
getGetV1GetUserTimezoneMockHandler({ timezone: "Asia/Kolkata" }),
+ http.post("*/api/auth/user/preferences/from-email", ({ request }) => {
+ applied = new URL(request.url);
+ return HttpResponse.json({
+ ...defaultPreferences,
+ alerts_enabled: true,
+ });
+ }),
+ );
+
+ render(<SettingsPreferencesPage />);
+
+ // One click, not two: the design calls these "live one-click links".
+ await waitFor(() => expect(applied).toBeDefined());
+ expect(applied?.searchParams.get("choice")).toBe("alerts");
+ // Token-authenticated, so a bare ?f= from a third-party link is inert.
+ expect(applied?.searchParams.get("token")).toBe("signed-token");
+ expect(mockRouterReplace).toHaveBeenCalledWith("/settings/account");
+ });
+
+ test("ignores a footer link with no token", async () => {
+ let applied = false;
+ mockUseSearchParams.mockReturnValue(new URLSearchParams({ f: "off" }));
+
+ server.use(
+ getGetV1GetNotificationPreferencesMockHandler(defaultPreferences),
+ getGetV1GetUserTimezoneMockHandler({ timezone: "Asia/Kolkata" }),
+ http.post("*/api/auth/user/preferences/from-email", () => {
+ applied = true;
+ return HttpResponse.json(defaultPreferences);
+ }),
+ );
+
+ render(<SettingsPreferencesPage />);
+ await screen.findByRole("switch", { name: "Alerts" });
+
+ // A third party can put anyone on this URL; without the signed token it
+ // must not change a thing.
+ expect(applied).toBe(false);
+ });
+
+ test("saves briefing frequency and marketplace review changes", async () => {
+ let submitted: NotificationPreferenceDTO | undefined;
+
+ server.use(
+ getGetV1GetNotificationPreferencesMockHandler(defaultPreferences),
+ getGetV1GetUserTimezoneMockHandler({ timezone: "Asia/Kolkata" }),
getPostV1UpdateUserEmailMockHandler({}),
- getPostV1UpdateNotificationPreferencesMockHandler({
- user_id: "user-1",
- email: "[email protected]",
- preferences: {},
- daily_limit: 0,
- emails_sent_today: 0,
- last_reset_date: baseDate,
+ getPostV1UpdateUserTimezoneMockHandler({ timezone: "Asia/Kolkata" }),
+ getPostV1UpdateNotificationPreferencesMockHandler(async ({ request }) => {
+ submitted = (await request.json()) as NotificationPreferenceDTO;
+ return { ...defaultPreferences, ...submitted };
}),
+ );
+
+ render(<SettingsPreferencesPage />);
+
+ fireEvent.click(await screen.findByRole("combobox", { name: "Briefing" }));
+ fireEvent.click(await screen.findByRole("option", { name: "Monthly" }));
+ fireEvent.click(
+ screen.getByRole("switch", { name: "Marketplace reviews" }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
+
+ await waitFor(() => {
+ expect(submitted).toMatchObject({
+ briefing_frequency: "MONTHLY",
+ alerts_enabled: true,
+ store_verdicts_enabled: false,
+ });
+ });
+ });
+
+ test("Discard reverts an unsaved notification change", async () => {
+ setupBaseHandlers();
+
+ render(<SettingsPreferencesPage />);
+
+ const saveButton = await screen.findByRole("button", {
+ name: "Save changes",
+ });
+ const discardButton = screen.getByRole("button", { name: "Discard" });
+
+ const alertsSwitch = await screen.findByRole("switch", { name: "Alerts" });
+ const initialChecked = alertsSwitch.getAttribute("aria-checked");
+
+ fireEvent.click(alertsSwitch);
+
+ await waitFor(() => {
+ expect((saveButton as HTMLButtonElement).disabled).toBe(false);
+ expect((discardButton as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ fireEvent.click(discardButton);
+
+ await waitFor(() => {
+ expect((saveButton as HTMLButtonElement).disabled).toBe(true);
+ expect(alertsSwitch.getAttribute("aria-checked")).toBe(initialChecked);
+ });
+ });
+
+ test("saving a timezone change posts the new value", async () => {
+ let submittedTimezone: string | undefined;
+
+ server.use(
+ getGetV1GetNotificationPreferencesMockHandler(defaultPreferences),
+ getGetV1GetUserTimezoneMockHandler({ timezone: "Asia/Kolkata" }),
+ getPostV1UpdateUserEmailMockHandler({}),
+ getPostV1UpdateNotificationPreferencesMockHandler(defaultPreferences),
getPostV1UpdateUserTimezoneMockHandler(async ({ request }) => {
const body = (await request.json()) as { timezone: string };
submittedTimezone = body.timezone;
@@ -290,24 +384,10 @@ describe("SettingsPreferencesPage", () => {
let submittedTimezone: string | undefined;
server.use(
- getGetV1GetNotificationPreferencesMockHandler({
- user_id: "user-1",
- email: "[email protected]",
- preferences: allFalsePreferences,
- daily_limit: 0,
- emails_sent_today: 0,
- last_reset_date: baseDate,
- }),
+ getGetV1GetNotificationPreferencesMockHandler(defaultPreferences),
getGetV1GetUserTimezoneMockHandler({ timezone: "not-set" }),
getPostV1UpdateUserEmailMockHandler({}),
- getPostV1UpdateNotificationPreferencesMockHandler({
- user_id: "user-1",
- email: "[email protected]",
- preferences: {},
- daily_limit: 0,
- emails_sent_today: 0,
- last_reset_date: baseDate,
- }),
+ getPostV1UpdateNotificationPreferencesMockHandler(defaultPreferences),
getPostV1UpdateUserTimezoneMockHandler(async ({ request }) => {
const body = (await request.json()) as { timezone: string };
submittedTimezone = body.timezone;
@@ -382,36 +462,6 @@ describe("SettingsPreferencesPage", () => {
vi.unstubAllGlobals();
});
-
- test("Discard reverts unsaved notification toggles", async () => {
- setupBaseHandlers();
-
- render(<SettingsPreferencesPage />);
-
- const saveButton = await screen.findByRole("button", {
- name: "Save changes",
- });
- const discardButton = screen.getByRole("button", { name: "Discard" });
-
- const switches = await screen.findAllByRole("switch");
- const targetSwitch = switches[0] as HTMLInputElement;
- const initialChecked = targetSwitch.getAttribute("aria-checked");
-
- fireEvent.click(targetSwitch);
-
- await waitFor(() => {
- expect((saveButton as HTMLButtonElement).disabled).toBe(false);
- expect((discardButton as HTMLButtonElement).disabled).toBe(false);
- });
-
- fireEvent.click(discardButton);
-
- await waitFor(() => {
- expect((saveButton as HTMLButtonElement).disabled).toBe(true);
- expect(targetSwitch.getAttribute("aria-checked")).toBe(initialChecked);
- });
- });
-
test("hides the notifications card when settings-notifications is off", async () => {
mockUseGetFlag.mockReturnValue(false);
setupBaseHandlers();
@@ -419,7 +469,7 @@ describe("SettingsPreferencesPage", () => {
render(<SettingsPreferencesPage />);
expect(await screen.findByText("Time zone")).toBeDefined();
- expect(screen.queryByText("Notifications")).toBeNull();
+ expect(screen.queryByRole("combobox", { name: "Briefing" })).toBeNull();
expect(screen.queryAllByRole("switch")).toHaveLength(0);
});
});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/account/components/NotificationsCard/NotificationsCard.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/account/components/NotificationsCard/NotificationsCard.tsx
index 6eac940adc..a94652ae95 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/account/components/NotificationsCard/NotificationsCard.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/account/components/NotificationsCard/NotificationsCard.tsx
@@ -1,48 +1,34 @@
"use client";
-import { useState } from "react";
-import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
+import { motion, useReducedMotion } from "framer-motion";
+import { Select } from "@/components/atoms/Select/Select";
import { Switch } from "@/components/atoms/Switch/Switch";
import { Text } from "@/components/atoms/Text/Text";
-import {
- TabsLine,
- TabsLineList,
- TabsLineTrigger,
-} from "@/components/molecules/TabsLine/TabsLine";
-import { cn } from "@/lib/utils";
import {
+ BRIEFING_OPTIONS,
EASE_OUT,
- NOTIFICATION_GROUPS,
- type NotificationFlags,
- type NotificationGroup,
- type NotificationItem,
- type NotificationKey,
+ type BriefingFrequency,
+ type NotificationSettings,
} from "../../helpers";
interface Props {
- values: NotificationFlags;
- onToggle: (key: NotificationKey, value: boolean) => void;
+ values: NotificationSettings;
+ onBriefingFrequencyChange: (value: BriefingFrequency) => void;
+ onAlertsChange: (value: boolean) => void;
+ onStoreVerdictsChange: (value: boolean) => void;
index?: number;
}
-type TabId = NotificationGroup["id"];
-
-export function NotificationsCard({ values, onToggle, index = 0 }: Props) {
+export function NotificationsCard({
+ values,
+ onBriefingFrequencyChange,
+ onAlertsChange,
+ onStoreVerdictsChange,
+ index = 0,
+}: Props) {
const reduceMotion = useReducedMotion();
- const [activeTab, setActiveTab] = useState<TabId>(NOTIFICATION_GROUPS[0].id);
-
- const tabs: { id: TabId; label: string; count: number }[] =
- NOTIFICATION_GROUPS.map((group) => ({
- id: group.id,
- label: group.title,
- count: group.items.filter((item) => values[item.key]).length,
- }));
-
- const visibleGroups: NotificationGroup[] = NOTIFICATION_GROUPS.filter(
- (g) => g.id === activeTab,
- );
return (
<motion.section
@@ -51,124 +37,73 @@ export function NotificationsCard({ values, onToggle, index = 0 }: Props) {
transition={
reduceMotion
? undefined
- : {
- duration: 0.32,
- ease: EASE_OUT,
- delay: 0.04 + index * 0.05,
- }
+ : { duration: 0.32, ease: EASE_OUT, delay: 0.04 + index * 0.05 }
}
- className="flex w-full flex-col gap-2 pt-0"
+ className="flex w-full flex-col"
>
- <div className="flex flex-col gap-1 px-4">
- <Text variant="body-medium" as="span" className="text-textBlack">
- Notifications
- </Text>
- <Text variant="small" className="text-zinc-500">
- Filter by category, or scan everything in one place.
- </Text>
- </div>
+ <div className="flex h-fit flex-col gap-4 rounded-[18px] border border-zinc-200 bg-white px-4 py-3 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">
+ <div className="flex flex-col gap-1">
+ <Text variant="body-medium" as="span" className="text-textBlack">
+ Email
+ </Text>
+ <Text variant="small" as="span" className="text-zinc-500">
+ Billing and account messages are always sent — they are about your
+ account, not a promotion.
+ </Text>
+ </div>
- <div className="flex flex-col gap-3 rounded-[18px] border border-zinc-200 bg-white px-4 pb-4 pt-0 shadow-[0_1px_2px_rgba(15,15,20,0.04)]">
- <TabsLine
- value={activeTab}
- onValueChange={(v) => setActiveTab(v as TabId)}
- >
- <TabsLineList>
- {tabs.map((tab) => (
- <TabsLineTrigger key={tab.id} value={tab.id}>
- {tab.label}
- <span className="ml-2 inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-zinc-100 px-1 text-[11px] font-medium tabular-nums text-zinc-500">
- {tab.count}
- </span>
- </TabsLineTrigger>
- ))}
- </TabsLineList>
- </TabsLine>
-
- <AnimatePresence initial={false} mode="wait">
- <motion.div
- key={activeTab}
- initial={reduceMotion ? false : { opacity: 0, y: 6 }}
- animate={reduceMotion ? undefined : { opacity: 1, y: 0 }}
- exit={reduceMotion ? undefined : { opacity: 0, y: -6 }}
- transition={
- reduceMotion ? undefined : { duration: 0.2, ease: EASE_OUT }
+ <div className="flex flex-col gap-2">
+ <Select
+ id="briefing-frequency"
+ label="Briefing"
+ value={values.briefingFrequency}
+ options={BRIEFING_OPTIONS.map((option) => ({
+ value: option.value,
+ label: option.label,
+ }))}
+ onValueChange={(value) =>
+ onBriefingFrequencyChange(value as BriefingFrequency)
}
- className="flex flex-col gap-1"
- >
- {visibleGroups.map((group) => (
- <NotificationGroupSection
- key={group.id}
- group={group}
- values={values}
- onToggle={onToggle}
- />
- ))}
- </motion.div>
- </AnimatePresence>
- </div>
- </motion.section>
- );
-}
+ />
+ <Text variant="small" as="span" className="text-zinc-500">
+ What your agents got done, at around 07:30 your time. Never sent
+ when nothing ran.
+ </Text>
+ </div>
-function NotificationGroupSection({
- group,
- values,
- onToggle,
-}: {
- group: NotificationGroup;
- values: NotificationFlags;
- onToggle: (key: NotificationKey, value: boolean) => void;
-}) {
- return (
- <div className="flex flex-col">
- {group.items.map((item, i) => (
- <NotificationRow
- key={item.key}
- item={item}
- value={values[item.key]}
- onChange={(checked) => onToggle(item.key, checked)}
- isLast={i === group.items.length - 1}
- />
- ))}
- </div>
- );
-}
+ <div className="flex items-center justify-between gap-4">
+ <div className="flex flex-col">
+ <Text variant="body-medium" as="span" className="text-textBlack">
+ Alerts
+ </Text>
+ <Text variant="small" as="span" className="text-zinc-500">
+ Only when something is waiting on you — never for a successful
+ run. At most two a day.
+ </Text>
+ </div>
+ <Switch
+ checked={values.alertsEnabled}
+ onCheckedChange={onAlertsChange}
+ aria-label="Alerts"
+ />
+ </div>
-function NotificationRow({
- item,
- value,
- onChange,
- isLast,
-}: {
- item: NotificationItem;
- value: boolean;
- onChange: (value: boolean) => void;
- isLast: boolean;
-}) {
- const id = `notif-${item.key}`;
- return (
- <label
- htmlFor={id}
- className={cn(
- "group flex cursor-pointer items-center justify-between gap-4 rounded-[12px] px-4 py-3 transition-colors duration-150 ease-out hover:bg-zinc-50",
- !isLast && "mb-0.5",
- )}
- >
- <div className="flex min-w-0 flex-col">
- <Text variant="body-medium" as="span" className="text-textBlack">
- {item.title}
- </Text>
- <Text variant="small" as="span" className="text-zinc-500">
- {item.description}
- </Text>
+ <div className="flex items-center justify-between gap-4">
+ <div className="flex flex-col">
+ <Text variant="body-medium" as="span" className="text-textBlack">
+ Marketplace reviews
+ </Text>
+ <Text variant="small" as="span" className="text-zinc-500">
+ When an agent you submitted is approved or needs changes.
+ </Text>
+ </div>
+ <Switch
+ checked={values.storeVerdictsEnabled}
+ onCheckedChange={onStoreVerdictsChange}
+ aria-label="Marketplace reviews"
+ />
+ </div>
</div>
- <Switch
- id={id}
- aria-label={item.title}
- checked={value}
- onCheckedChange={onChange}
- />
- </label>
+ </motion.section>
);
}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/account/components/NotificationsCard/__tests__/NotificationsCard.test.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/account/components/NotificationsCard/__tests__/NotificationsCard.test.tsx
new file mode 100644
index 0000000000..ed1ba0ea2f
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/account/components/NotificationsCard/__tests__/NotificationsCard.test.tsx
@@ -0,0 +1,37 @@
+import { describe, expect, test, vi } from "vitest";
+
+import { fireEvent, render, screen } from "@/tests/integrations/test-utils";
+
+import { NotificationsCard } from "../NotificationsCard";
+
+describe("NotificationsCard", () => {
+ test("renders the email volume controls and reports every change", async () => {
+ const onBriefingFrequencyChange = vi.fn();
+ const onAlertsChange = vi.fn();
+ const onStoreVerdictsChange = vi.fn();
+
+ render(
+ <NotificationsCard
+ values={{
+ briefingFrequency: "WEEKLY",
+ alertsEnabled: true,
+ storeVerdictsEnabled: false,
+ }}
+ onBriefingFrequencyChange={onBriefingFrequencyChange}
+ onAlertsChange={onAlertsChange}
+ onStoreVerdictsChange={onStoreVerdictsChange}
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("combobox", { name: "Briefing" }));
+ fireEvent.click(await screen.findByRole("option", { name: "Monthly" }));
+ fireEvent.click(screen.getByRole("switch", { name: "Alerts" }));
+ fireEvent.click(
+ screen.getByRole("switch", { name: "Marketplace reviews" }),
+ );
+
+ expect(onBriefingFrequencyChange).toHaveBeenCalledWith("MONTHLY");
+ expect(onAlertsChange).toHaveBeenCalledWith(false);
+ expect(onStoreVerdictsChange).toHaveBeenCalledWith(true);
+ });
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/account/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/settings/account/helpers.ts
index 376558c7be..3010db5e88 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/account/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/account/helpers.ts
@@ -1,177 +1,67 @@
import type { NotificationPreference } from "@/app/api/__generated__/models/notificationPreference";
-import {
- ChartIncreaseIcon,
- Coins01Icon,
- Notification03Icon,
- Robot01Icon,
- Store01Icon,
-} from "@hugeicons/core-free-icons";
-import type { IconSvgElement } from "@hugeicons/react";
export const EASE_OUT = [0.16, 1, 0.3, 1] as const;
export const EASE_IOS = [0.32, 0.72, 0, 1] as const;
export const EASE_IN_OUT = [0.4, 0, 0.2, 1] as const;
-export type NotificationKey =
- | "notifyOnAgentRun"
- | "notifyOnBlockExecutionFailed"
- | "notifyOnContinuousAgentError"
- | "notifyOnAgentApproved"
- | "notifyOnAgentRejected"
- | "notifyOnZeroBalance"
- | "notifyOnLowBalance"
- | "notifyOnDailySummary"
- | "notifyOnWeeklySummary"
- | "notifyOnMonthlySummary";
-
-export type NotificationFlags = Record<NotificationKey, boolean>;
+export type BriefingFrequency = "DAILY" | "WEEKLY" | "MONTHLY" | "OFF";
+
+/**
+ * The volume knob from the Briefing footer: a frequency plus two switches.
+ * Billing and account messages are service mail and are deliberately absent —
+ * they are sent regardless of what is set here.
+ */
+export interface NotificationSettings {
+ briefingFrequency: BriefingFrequency;
+ alertsEnabled: boolean;
+ storeVerdictsEnabled: boolean;
+}
export interface PreferencesFormState {
timezone: string;
- notifications: NotificationFlags;
-}
-
-export interface NotificationItem {
- key: NotificationKey;
- title: string;
- description: string;
+ notifications: NotificationSettings;
}
-export interface NotificationGroup {
- id: "agents" | "store" | "balance" | "summary";
- title: string;
- caption: string;
- icon: IconSvgElement;
- accent: string;
- items: NotificationItem[];
-}
-
-export const NOTIFICATION_GROUPS: NotificationGroup[] = [
- {
- id: "agents",
- title: "Agent activity",
- caption: "Heads-up when your agents do something — or stop doing it.",
- icon: Robot01Icon,
- accent: "from-violet-500/15 to-violet-500/0 text-violet-700",
- items: [
- {
- key: "notifyOnAgentRun",
- title: "Run started or completed",
- description: "Hear from us when an agent kicks off or finishes a run.",
- },
- {
- key: "notifyOnBlockExecutionFailed",
- title: "Block execution failed",
- description: "Get notified the moment a block fails mid-run.",
- },
- {
- key: "notifyOnContinuousAgentError",
- title: "Continuous errors",
- description:
- "Alert me when an agent runs into the same error repeatedly.",
- },
- ],
- },
- {
- id: "store",
- title: "Marketplace",
- caption: "Updates on agents you've published to the store.",
- icon: Store01Icon,
- accent: "from-amber-400/15 to-amber-500/0 text-amber-700",
- items: [
- {
- key: "notifyOnAgentApproved",
- title: "Agent approved",
- description: "Your submission is live in the store.",
- },
- {
- key: "notifyOnAgentRejected",
- title: "Agent needs changes",
- description: "Reviewers have feedback before your agent can go live.",
- },
- ],
- },
- {
- id: "balance",
- title: "Credits & balance",
- caption: "Stay ahead of an empty tank.",
- icon: Coins01Icon,
- accent: "from-emerald-400/15 to-emerald-500/0 text-emerald-700",
- items: [
- {
- key: "notifyOnLowBalance",
- title: "Running low",
- description: "Warn me before I run out of credits.",
- },
- {
- key: "notifyOnZeroBalance",
- title: "Empty balance",
- description: "Let me know when my balance hits zero.",
- },
- ],
- },
- {
- id: "summary",
- title: "Summaries",
- caption: "Recap emails to keep tabs on your account at a glance.",
- icon: ChartIncreaseIcon,
- accent: "from-sky-400/15 to-sky-500/0 text-sky-700",
- items: [
- {
- key: "notifyOnDailySummary",
- title: "Daily summary",
- description: "A short daily digest of activity.",
- },
- {
- key: "notifyOnWeeklySummary",
- title: "Weekly summary",
- description: "A weekly overview of performance.",
- },
- {
- key: "notifyOnMonthlySummary",
- title: "Monthly summary",
- description: "A comprehensive monthly report.",
- },
- ],
- },
+export const BRIEFING_OPTIONS: { value: BriefingFrequency; label: string }[] = [
+ { value: "DAILY", label: "Daily" },
+ { value: "WEEKLY", label: "Weekly" },
+ { value: "MONTHLY", label: "Monthly" },
+ { value: "OFF", label: "Off" },
];
-export const NOTIFICATIONS_FALLBACK_ICON = Notification03Icon;
-
-const PREFERENCE_API_KEYS: Record<NotificationKey, string> = {
- notifyOnAgentRun: "AGENT_RUN",
- notifyOnBlockExecutionFailed: "BLOCK_EXECUTION_FAILED",
- notifyOnContinuousAgentError: "CONTINUOUS_AGENT_ERROR",
- notifyOnAgentApproved: "AGENT_APPROVED",
- notifyOnAgentRejected: "AGENT_REJECTED",
- notifyOnZeroBalance: "ZERO_BALANCE",
- notifyOnLowBalance: "LOW_BALANCE",
- notifyOnDailySummary: "DAILY_SUMMARY",
- notifyOnWeeklySummary: "WEEKLY_SUMMARY",
- notifyOnMonthlySummary: "MONTHLY_SUMMARY",
-};
-
-export function preferencesToFlags(
- preferences: NotificationPreference,
-): NotificationFlags {
- const raw = preferences.preferences ?? {};
- return Object.fromEntries(
- (Object.keys(PREFERENCE_API_KEYS) as NotificationKey[]).map((key) => [
- key,
- Boolean(raw[PREFERENCE_API_KEYS[key]]),
- ]),
- ) as NotificationFlags;
+/**
+ * The `?f=` values the Briefing footer links use. "alerts" and "off" both turn
+ * the digest off; they differ in whether alerts survive.
+ */
+export function settingsFromFooterLink(
+ value: string | null,
+ current: NotificationSettings,
+): NotificationSettings | null {
+ switch (value) {
+ case "daily":
+ return { ...current, briefingFrequency: "DAILY" };
+ case "weekly":
+ return { ...current, briefingFrequency: "WEEKLY" };
+ case "monthly":
+ return { ...current, briefingFrequency: "MONTHLY" };
+ case "alerts":
+ return { ...current, briefingFrequency: "OFF", alertsEnabled: true };
+ case "off":
+ return { ...current, briefingFrequency: "OFF", alertsEnabled: false };
+ default:
+ return null;
+ }
}
-export function flagsToPreferenceMap(
- flags: NotificationFlags,
-): Record<string, boolean> {
- return Object.fromEntries(
- (Object.keys(PREFERENCE_API_KEYS) as NotificationKey[]).map((key) => [
- PREFERENCE_API_KEYS[key],
- flags[key],
- ]),
- );
+export function preferencesToSettings(
+ preferences: NotificationPreference,
+): NotificationSettings {
+ return {
+ briefingFrequency: (preferences.briefing_frequency ??
+ "WEEKLY") as BriefingFrequency,
+ alertsEnabled: preferences.alerts_enabled ?? true,
+ storeVerdictsEnabled: preferences.store_verdicts_enabled ?? true,
+ };
}
export function detectBrowserTimezone(): string {
@@ -186,26 +76,24 @@ export function isFormDirty(
initial: PreferencesFormState,
current: PreferencesFormState,
): boolean {
- if (initial.timezone !== current.timezone) return true;
- for (const key of Object.keys(initial.notifications) as NotificationKey[]) {
- if (initial.notifications[key] !== current.notifications[key]) return true;
- }
- return false;
+ const parts = dirtyKinds(initial, current);
+ return parts.timezone || parts.notifications;
}
export function dirtyKinds(
initial: PreferencesFormState,
current: PreferencesFormState,
): { timezone: boolean; notifications: boolean } {
- const timezone = initial.timezone !== current.timezone;
- let notifications = false;
- for (const key of Object.keys(initial.notifications) as NotificationKey[]) {
- if (initial.notifications[key] !== current.notifications[key]) {
- notifications = true;
- break;
- }
- }
- return { timezone, notifications };
+ return {
+ timezone: initial.timezone !== current.timezone,
+ notifications:
+ initial.notifications.briefingFrequency !==
+ current.notifications.briefingFrequency ||
+ initial.notifications.alertsEnabled !==
+ current.notifications.alertsEnabled ||
+ initial.notifications.storeVerdictsEnabled !==
+ current.notifications.storeVerdictsEnabled,
+ };
}
const TIMEZONE_LIST: { value: string; label: string }[] = [
@@ -272,3 +160,27 @@ export const TIMEZONES = TIMEZONE_LIST;
export function findTimezoneLabel(value: string): string {
return TIMEZONES.find((t) => t.value === value)?.label ?? value;
}
+
+/**
+ * What to tell someone who just arrived from a footer link.
+ *
+ * The choice is already saved by the time this shows, so it confirms rather
+ * than prompts — the whole point of the volume knob is that one click is the
+ * entire interaction.
+ */
+export function describeFooterChoice(value: string | null): string {
+ switch (value) {
+ case "daily":
+ return "You'll get a briefing every day";
+ case "weekly":
+ return "You'll get a briefing every week";
+ case "monthly":
+ return "You'll get a briefing every month";
+ case "alerts":
+ return "Briefings paused — you'll still get alerts";
+ case "off":
+ return "Briefings and alerts paused";
+ default:
+ return "Preferences updated";
+ }
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/account/page.tsx b/autogpt_platform/frontend/src/app/(platform)/settings/account/page.tsx
index bb1872ca81..6530017f5e 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/account/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/account/page.tsx
@@ -28,7 +28,9 @@ export default function SettingsPreferencesPage() {
dirty,
isSaving,
setTimezone,
- toggleNotification,
+ setBriefingFrequency,
+ setAlertsEnabled,
+ setStoreVerdictsEnabled,
discardChanges,
savePreferences,
} = usePreferencesPage();
@@ -68,7 +70,9 @@ export default function SettingsPreferencesPage() {
{showNotifications ? (
<NotificationsCard
values={formState.notifications}
- onToggle={toggleNotification}
+ onBriefingFrequencyChange={setBriefingFrequency}
+ onAlertsChange={setAlertsEnabled}
+ onStoreVerdictsChange={setStoreVerdictsEnabled}
index={2}
/>
) : null}
diff --git a/autogpt_platform/frontend/src/app/(platform)/settings/account/usePreferencesPage.ts b/autogpt_platform/frontend/src/app/(platform)/settings/account/usePreferencesPage.ts
index 956d6d3cd7..eaf29646e7 100644
--- a/autogpt_platform/frontend/src/app/(platform)/settings/account/usePreferencesPage.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/settings/account/usePreferencesPage.ts
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
+import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { useQueryClient } from "@tanstack/react-query";
import {
@@ -19,30 +20,39 @@ import { useAuth } from "@/lib/auth/hooks/useAuth";
import {
detectBrowserTimezone,
dirtyKinds,
- flagsToPreferenceMap,
isFormDirty,
- preferencesToFlags,
- type NotificationFlags,
- type NotificationKey,
+ preferencesToSettings,
+ describeFooterChoice,
+ settingsFromFooterLink,
+ type BriefingFrequency,
+ type NotificationSettings,
type PreferencesFormState,
} from "./helpers";
-const EMPTY_FLAGS: NotificationFlags = {
- notifyOnAgentRun: false,
- notifyOnBlockExecutionFailed: false,
- notifyOnContinuousAgentError: false,
- notifyOnAgentApproved: false,
- notifyOnAgentRejected: false,
- notifyOnZeroBalance: false,
- notifyOnLowBalance: false,
- notifyOnDailySummary: false,
- notifyOnWeeklySummary: false,
- notifyOnMonthlySummary: false,
+const DEFAULT_SETTINGS: NotificationSettings = {
+ briefingFrequency: "WEEKLY",
+ alertsEnabled: true,
+ storeVerdictsEnabled: true,
};
export function usePreferencesPage() {
const { user } = useAuth();
const queryClient = useQueryClient();
+ // The Briefing footer's volume knob links here with
+ // ?f=daily|weekly|monthly|alerts|off. The design calls these "live one-click
+ // links — a volume knob instead of a trapdoor", so the choice is saved on
+ // arrival rather than pre-filling a form the reader still has to submit.
+ //
+ // The choice is only honoured with the signed token the email carried. The
+ // session is the wrong authority here: applying on arrival off a bare ?f=
+ // would let a third party change a signed-in reader's preferences just by
+ // getting them to follow a link. The backend verifies an HMAC that binds the
+ // choice to the recipient, so an unsigned or tampered link does nothing.
+ const searchParams = useSearchParams();
+ const footerChoice = searchParams.get("f");
+ const footerToken = searchParams.get("t");
+ const router = useRouter();
+ const pathname = usePathname();
const preferencesQuery = useGetV1GetNotificationPreferences({
query: {
@@ -67,28 +77,68 @@ export function usePreferencesPage() {
const serverTimezone = timezoneQuery.data ?? "not-set";
const formTimezone =
serverTimezone !== "not-set" ? serverTimezone : detectBrowserTimezone();
- const initialFlags = preferencesQuery.data
- ? preferencesToFlags(preferencesQuery.data)
- : EMPTY_FLAGS;
+ const initialSettings = preferencesQuery.data
+ ? preferencesToSettings(preferencesQuery.data)
+ : DEFAULT_SETTINGS;
const initialFormState: PreferencesFormState = {
timezone: formTimezone,
- notifications: initialFlags,
+ notifications:
+ settingsFromFooterLink(footerChoice, initialSettings) ?? initialSettings,
};
const initialSavedState: PreferencesFormState = {
timezone: serverTimezone,
- notifications: initialFlags,
+ notifications: initialSettings,
};
const [formState, setFormState] = useState<PreferencesFormState>({
timezone: detectBrowserTimezone(),
- notifications: EMPTY_FLAGS,
+ notifications: DEFAULT_SETTINGS,
});
const [savedState, setSavedState] = useState<PreferencesFormState>({
timezone: detectBrowserTimezone(),
- notifications: EMPTY_FLAGS,
+ notifications: DEFAULT_SETTINGS,
});
const [isSaving, setIsSaving] = useState(false);
const hasInitializedFormState = useRef(false);
+ const hasAppliedFooterChoice = useRef(false);
+
+ const updateTimezone = usePostV1UpdateUserTimezone();
+ const updateNotifications = usePostV1UpdateNotificationPreferences();
+
+ async function applyFooterChoice(
+ choice: string,
+ token: string,
+ next: NotificationSettings,
+ ) {
+ // Token-authenticated, not session-authenticated — see the note on
+ // footerChoice above.
+ const res = await fetch(
+ `/api/auth/user/preferences/from-email?choice=${encodeURIComponent(choice)}&token=${encodeURIComponent(token)}`,
+ { method: "POST" },
+ );
+ if (!res.ok) throw new Error(`Preference link rejected (${res.status})`);
+ await queryClient.invalidateQueries({
+ queryKey: getGetV1GetNotificationPreferencesQueryKey(),
+ });
+ setFormState((prev) => ({ ...prev, notifications: next }));
+ setSavedState((prev) => ({ ...prev, notifications: next }));
+ }
+
+ async function applyNotificationSettings(next: NotificationSettings) {
+ await updateNotifications.mutateAsync({
+ data: {
+ email: user?.email ?? "",
+ briefing_frequency: next.briefingFrequency,
+ alerts_enabled: next.alertsEnabled,
+ store_verdicts_enabled: next.storeVerdictsEnabled,
+ },
+ });
+ await queryClient.invalidateQueries({
+ queryKey: getGetV1GetNotificationPreferencesQueryKey(),
+ });
+ setFormState((prev) => ({ ...prev, notifications: next }));
+ setSavedState((prev) => ({ ...prev, notifications: next }));
+ }
useEffect(
function syncFormStateOnce() {
@@ -107,6 +157,37 @@ export function usePreferencesPage() {
],
);
+ useEffect(
+ function applyFooterChoiceOnArrival() {
+ if (hasAppliedFooterChoice.current) return;
+ if (!hasInitializedFormState.current) return;
+ if (!footerChoice || !footerToken) return;
+
+ const chosen = settingsFromFooterLink(footerChoice, initialSettings);
+ hasAppliedFooterChoice.current = true;
+ router.replace(pathname);
+
+ if (!chosen) return;
+
+ applyFooterChoice(footerChoice, footerToken, chosen)
+ .then(() => {
+ toast({
+ title: describeFooterChoice(footerChoice),
+ variant: "success",
+ });
+ })
+ .catch(() => {
+ // Leave the choice in the form so the reader can still hit Save.
+ toast({
+ title: "Couldn't update your email frequency",
+ description: "Your choice is selected below — press Save to retry.",
+ variant: "destructive",
+ });
+ });
+ },
+ [footerChoice, footerToken, initialSettings, pathname, router],
+ );
+
const dirty = isFormDirty(savedState, formState);
const dirtyParts = dirtyKinds(savedState, formState);
@@ -114,28 +195,31 @@ export function usePreferencesPage() {
setFormState((prev) => ({ ...prev, timezone: value }));
}
- function toggleNotification(key: NotificationKey, value: boolean) {
+ function setBriefingFrequency(value: BriefingFrequency) {
setFormState((prev) => ({
...prev,
- notifications: { ...prev.notifications, [key]: value },
+ notifications: { ...prev.notifications, briefingFrequency: value },
}));
}
- function setAllInGroup(keys: NotificationKey[], value: boolean) {
- setFormState((prev) => {
- const next = { ...prev.notifications };
- for (const key of keys) next[key] = value;
- return { ...prev, notifications: next };
- });
+ function setAlertsEnabled(value: boolean) {
+ setFormState((prev) => ({
+ ...prev,
+ notifications: { ...prev.notifications, alertsEnabled: value },
+ }));
+ }
+
+ function setStoreVerdictsEnabled(value: boolean) {
+ setFormState((prev) => ({
+ ...prev,
+ notifications: { ...prev.notifications, storeVerdictsEnabled: value },
+ }));
}
function discardChanges() {
setFormState(savedState);
}
- const updateTimezone = usePostV1UpdateUserTimezone();
- const updateNotifications = usePostV1UpdateNotificationPreferences();
-
async function savePreferences() {
if (!dirty || isSaving || !user) return;
@@ -171,20 +255,7 @@ export function usePreferencesPage() {
if (partsAtSubmit.notifications) {
try {
- await updateNotifications.mutateAsync({
- data: {
- email: user.email ?? "",
- preferences: flagsToPreferenceMap(snapshot.notifications),
- daily_limit: 0,
- },
- });
- await queryClient.invalidateQueries({
- queryKey: getGetV1GetNotificationPreferencesQueryKey(),
- });
- setSavedState((prev) => ({
- ...prev,
- notifications: snapshot.notifications,
- }));
+ await applyNotificationSettings(snapshot.notifications);
notificationsSaved = true;
} catch (err) {
failures.push(
@@ -227,8 +298,9 @@ export function usePreferencesPage() {
dirty,
isSaving,
setTimezone,
- toggleNotification,
- setAllInGroup,
+ setBriefingFrequency,
+ setAlertsEnabled,
+ setStoreVerdictsEnabled,
discardChanges,
savePreferences,
};
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index 049e529259..c96571e592 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -3120,6 +3120,48 @@
"security": [{ "HTTPBearerJWT": [] }]
}
},
+ "/api/auth/user/preferences/from-email": {
+ "post": {
+ "tags": ["v1", "auth"],
+ "summary": "Apply a volume-knob choice from a Briefing footer link",
+ "description": "Apply one footer choice, authorised by the token in the link.\n\nDeliberately not `Security(requires_user)`. The session is the wrong\nauthority here: the settings page applies this on arrival, so a\nsession-authenticated write would let any third party change a logged-in\nreader's preferences just by getting them to follow a link. The HMAC binds\nthe choice to the recipient we sent it to, exactly as the unsubscribe link\ndoes, and works whether or not they happen to be signed in.",
+ "operationId": "postV1Apply a volume-knob choice from a briefing footer link",
+ "parameters": [
+ {
+ "name": "choice",
+ "in": "query",
+ "required": true,
+ "schema": { "type": "string", "title": "Choice" }
+ },
+ {
+ "name": "token",
+ "in": "query",
+ "required": true,
+ "schema": { "type": "string", "title": "Token" }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/NotificationPreference"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": { "$ref": "#/components/schemas/HTTPValidationError" }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/auth/user/timezone": {
"get": {
"tags": ["v1", "auth"],
@@ -16521,6 +16563,11 @@
],
"title": "BriefingDecisionItem"
},
+ "BriefingFrequency": {
+ "type": "string",
+ "enum": ["DAILY", "WEEKLY", "MONTHLY", "OFF"],
+ "title": "BriefingFrequency"
+ },
"BriefingResponse": {
"properties": {
"id": { "type": "string", "title": "Id" },
@@ -22479,80 +22526,58 @@
"properties": {
"user_id": { "type": "string", "title": "User Id" },
"email": { "type": "string", "format": "email", "title": "Email" },
- "preferences": {
- "additionalProperties": { "type": "boolean" },
- "propertyNames": {
- "$ref": "#/components/schemas/NotificationType"
- },
- "type": "object",
- "title": "Preferences",
- "description": "Which notifications the user wants"
+ "briefing_frequency": {
+ "$ref": "#/components/schemas/BriefingFrequency",
+ "default": "WEEKLY"
+ },
+ "alerts_enabled": {
+ "type": "boolean",
+ "title": "Alerts Enabled",
+ "default": true
+ },
+ "store_verdicts_enabled": {
+ "type": "boolean",
+ "title": "Store Verdicts Enabled",
+ "default": true
},
"daily_limit": {
"type": "integer",
"title": "Daily Limit",
- "default": 10
- },
- "emails_sent_today": {
- "type": "integer",
- "title": "Emails Sent Today",
- "default": 0
- },
- "last_reset_date": {
- "type": "string",
- "format": "date-time",
- "title": "Last Reset Date"
+ "default": 3
}
},
"type": "object",
"required": ["user_id", "email"],
- "title": "NotificationPreference"
+ "title": "NotificationPreference",
+ "description": "The volume knob from the Briefing footer, not a checkbox list. Billing\nand account messages are service mail and are not represented here — they\nare sent regardless of these settings."
},
"NotificationPreferenceDTO": {
"properties": {
- "email": {
- "type": "string",
- "format": "email",
- "title": "Email",
- "description": "User's email address"
+ "email": { "type": "string", "format": "email", "title": "Email" },
+ "briefing_frequency": {
+ "$ref": "#/components/schemas/BriefingFrequency"
},
- "preferences": {
- "additionalProperties": { "type": "boolean" },
- "propertyNames": {
- "$ref": "#/components/schemas/NotificationType"
- },
- "type": "object",
- "title": "Preferences",
- "description": "Which notifications the user wants"
+ "alerts_enabled": { "type": "boolean", "title": "Alerts Enabled" },
+ "store_verdicts_enabled": {
+ "type": "boolean",
+ "title": "Store Verdicts Enabled"
},
"daily_limit": {
"type": "integer",
"title": "Daily Limit",
- "description": "Max emails per day"
+ "description": "Max product emails per day; 0 sends none. Account and billing messages are service mail and ignore it.",
+ "default": 3
}
},
"type": "object",
- "required": ["email", "preferences", "daily_limit"],
+ "required": [
+ "email",
+ "briefing_frequency",
+ "alerts_enabled",
+ "store_verdicts_enabled"
+ ],
"title": "NotificationPreferenceDTO"
},
- "NotificationType": {
- "type": "string",
- "enum": [
- "AGENT_RUN",
- "ZERO_BALANCE",
- "LOW_BALANCE",
- "BLOCK_EXECUTION_FAILED",
- "CONTINUOUS_AGENT_ERROR",
- "DAILY_SUMMARY",
- "WEEKLY_SUMMARY",
- "MONTHLY_SUMMARY",
- "REFUND_REQUEST",
- "REFUND_PROCESSED",
- "AGENT_APPROVED",
- "AGENT_REJECTED"
- ],
- "title": "NotificationType"
- },
"OAuth2Credentials": {
"properties": {
"id": { "type": "string", "title": "Id" },
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
index 7bea5f2777..d2b0389319 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
@@ -692,28 +692,32 @@ export type HostScopedCredentials = BaseCredentials & {
// Mirror of backend/backend/data/notifications.py:NotificationType
export type NotificationType =
- | "AGENT_RUN"
- | "ZERO_BALANCE"
- | "LOW_BALANCE"
- | "BLOCK_EXECUTION_FAILED"
- | "CONTINUOUS_AGENT_ERROR"
- | "DAILY_SUMMARY"
- | "WEEKLY_SUMMARY"
- | "MONTHLY_SUMMARY"
- | "AGENT_APPROVED"
- | "AGENT_REJECTED";
-
-// Mirror of backend/backend/data/notifications.py:NotificationPreference
+ | "BRIEFING"
+ | "ALERT"
+ | "VERDICT"
+ | "OPS"
+ | "SUBSCRIPTION_WELCOME"
+ | "PAYMENT_FAILED"
+ | "PAYMENT_FINAL_NOTICE"
+ | "SUBSCRIPTION_CANCELLED"
+ | "SUBSCRIPTION_RESUMED"
+ | "SUBSCRIPTION_ENDED";
+
+export type BriefingFrequency = "DAILY" | "WEEKLY" | "MONTHLY" | "OFF";
+
+// Mirror of backend/backend/data/notifications.py:NotificationPreferenceDTO.
+// A volume knob rather than a checkbox list: billing and account messages are
+// service mail and are not represented here.
export type NotificationPreferenceDTO = {
email: string;
- preferences: { [key in NotificationType]: boolean };
+ briefing_frequency: BriefingFrequency;
+ alerts_enabled: boolean;
+ store_verdicts_enabled: boolean;
daily_limit: number;
};
export type NotificationPreference = NotificationPreferenceDTO & {
user_id: UserID;
- emails_sent_today: number;
- last_reset_date: Date;
};
/* Mirror of backend/data/integrations.py:Webhook */
diff --git a/autogpt_platform/frontend/src/playwright/pages/settings.page.ts b/autogpt_platform/frontend/src/playwright/pages/settings.page.ts
index 7d32ccc23a..3a39bb792c 100644
--- a/autogpt_platform/frontend/src/playwright/pages/settings.page.ts
+++ b/autogpt_platform/frontend/src/playwright/pages/settings.page.ts
@@ -14,10 +14,8 @@ export class SettingsPage extends BasePage {
).toBeVisible();
}
- getAgentRunNotificationsSwitch(): Locator {
- return this.page.getByRole("switch", {
- name: "Agent Run Notifications",
- });
+ getAlertsSwitch(): Locator {
+ return this.page.getByRole("switch", { name: "Alerts" });
}
async savePreferences(): Promise<void> {
diff --git a/autogpt_platform/frontend/src/playwright/settings-happy-path.spec.ts b/autogpt_platform/frontend/src/playwright/settings-happy-path.spec.ts
index 9bfdc9bceb..9989200db4 100644
--- a/autogpt_platform/frontend/src/playwright/settings-happy-path.spec.ts
+++ b/autogpt_platform/frontend/src/playwright/settings-happy-path.spec.ts
@@ -14,23 +14,20 @@ test("settings happy path: user can save notification preferences and keep them
await loginPage.loginAsSeededUser("smokeSettings");
await settingsPage.open();
- const agentRunSwitch = settingsPage.getAgentRunNotificationsSwitch();
+ const alertsSwitch = settingsPage.getAlertsSwitch();
// Assert the attribute exists before reading it — defaulting to "false"
// would silently pass a regression that removes `aria-checked` entirely.
- await expect(agentRunSwitch).toHaveAttribute(
- "aria-checked",
- /^(true|false)$/,
- );
- const initialState = await agentRunSwitch.getAttribute("aria-checked");
+ await expect(alertsSwitch).toHaveAttribute("aria-checked", /^(true|false)$/);
+ const initialState = await alertsSwitch.getAttribute("aria-checked");
const expectedState = initialState === "true" ? "false" : "true";
- await agentRunSwitch.click();
+ await alertsSwitch.click();
await settingsPage.savePreferences();
- await expect(agentRunSwitch).toHaveAttribute("aria-checked", expectedState);
+ await expect(alertsSwitch).toHaveAttribute("aria-checked", expectedState);
await page.reload();
await settingsPage.open();
- await expect(settingsPage.getAgentRunNotificationsSwitch()).toHaveAttribute(
+ await expect(settingsPage.getAlertsSwitch()).toHaveAttribute(
"aria-checked",
expectedState,
);
@@ -41,7 +38,7 @@ test("settings happy path: user can save notification preferences and keep them
await loginPage.loginAsSeededUser("smokeSettings");
await settingsPage.open();
- await expect(settingsPage.getAgentRunNotificationsSwitch()).toHaveAttribute(
+ await expect(settingsPage.getAlertsSwitch()).toHaveAttribute(
"aria-checked",
expectedState,
);