:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(customer-analytics): backfill Slack summaries when an account opts in (#79157)
Arthur Moreira de Deus6c84788e88ff
diff --git a/products/conversations/backend/channel_summary_ids.py b/products/conversations/backend/channel_summary_ids.pynew file mode 100644index 000000000000..44c17f7efc6d--- /dev/null+++ b/products/conversations/backend/channel_summary_ids.py@@ -0,0 +1,15 @@+"""Lives outside ``temporal/`` so the facade can import it at module level. Importing+anything under ``temporal/`` runs that package's ``__init__``, which loads the summarize+workflow, which imports the customer_analytics facade, which imports the conversations+facade.+"""++from __future__ import annotations++from datetime import date+++def build_channel_summary_workflow_id(*, account_id: str, cadence: str, period_start: date) -> str:+ """Both the scheduled coordinator and the opt-in backfill start this workflow. They must+ derive the same id, or the two paths summarize a period twice."""+ return f"account-channel-summary-{account_id}-{cadence}-{period_start.isoformat()}"diff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.pyindex f049848d30d6..804700e6898f 100644--- a/products/conversations/backend/facade/api.py+++ b/products/conversations/backend/facade/api.py@@ -6,28 +6,39 @@ Slack integration behind contract types so callers never touch slack_sdk or theteam's Slack credentials directly."""+import asyncio+from datetime import datetimefrom typing import Anyfrom django.conf import settingsfrom django.db.models import F+import structlogfrom slack_sdk.errors import SlackApiError+from temporalio.common import WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedError+from temporalio.service import RPCErrorfrom posthog.models.comment import Commentfrom posthog.models.team import Team+from posthog.temporal.common.client import sync_connect+from products.conversations.backend.channel_summary_ids import build_channel_summary_workflow_idfrom products.conversations.backend.facade.types import (SupportChannel as SupportChannel,TicketSummary as TicketSummary,)from products.conversations.backend.models import Ticketfrom products.conversations.backend.slack import get_slack_client+from products.conversations.backend.support_slack import get_support_slack_bot_tokenfrom products.conversations.backend.support_slack_channels import (SupportSlackChannelsUnavailable as SupportSlackChannelsUnavailable,SupportSlackNotConfigured as SupportSlackNotConfigured,list_support_bot_channels as _list_support_bot_channels,)+logger = structlog.get_logger(__name__)+class SupportMessageSendError(Exception):"""Slack rejected a SupportHog bot message.@@ -137,6 +148,71 @@ def post_ticket_internal_note(team_id: int, ticket_id: str, content: str, *, dedreturn str(comment.id)+def trigger_immediate_channel_summary(+ *,+ team_id: int,+ account_id: str,+ account_name: str,+ slack_channel_id: str,+ cadence: str,+ period_start: datetime,+ period_end: datetime,+) -> bool:+ """Summarize one closed period of an account's Slack channel now, outside the hourly+ coordinator's schedule.++ Applies the same team-level gates the coordinator applies before it fans out: the team+ must have the SupportHog bot (it reads the channel) and the org must have approved AI+ data processing (messages go to an LLM). Returns False when a gate blocks it.++ Fire-and-forget: the caller's own write already succeeded, so a Temporal failure is+ logged and swallowed rather than raised.+ """+ # Deferred: temporal/__init__ loads the summarize workflow, which imports the+ # customer_analytics facade, which imports this module.+ from products.conversations.backend.temporal.channel_summary.schemas import ChannelSummaryInput # noqa: PLC0415+ from products.conversations.backend.temporal.channel_summary.summarize import ( # noqa: PLC0415+ AccountChannelSummaryWorkflow,+ )++ team = Team.objects.select_related("organization").filter(id=team_id).first()+ if team is None or not team.organization.is_ai_data_processing_approved:+ return False+ if not get_support_slack_bot_token(team):+ return False++ workflow_input = ChannelSummaryInput(+ team_id=team_id,+ account_id=account_id,+ account_name=account_name,+ slack_channel_id=slack_channel_id,+ cadence=cadence,+ period_start=period_start.isoformat(),+ period_end=period_end.isoformat(),+ )+ workflow_id = build_channel_summary_workflow_id(+ account_id=account_id, cadence=cadence, period_start=period_start.date()+ )+ try:+ client = sync_connect()+ asyncio.run(+ client.start_workflow(+ AccountChannelSummaryWorkflow.run,+ workflow_input,+ id=workflow_id,+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE_FAILED_ONLY,+ )+ )+ except WorkflowAlreadyStartedError:+ logger.info("immediate_channel_summary_already_started", workflow_id=workflow_id)+ return False+ except RPCError as e:+ logger.warning("immediate_channel_summary_dispatch_failed", workflow_id=workflow_id, error=str(e))+ return False+ return True++def list_account_tickets(team_id: int, organization_id: str, *, limit: int = 50) -> list[TicketSummary]:"""Support tickets whose resolved customer org matches ``organization_id``, newest activity first.diff --git a/products/conversations/backend/temporal/channel_summary/coordinator.py b/products/conversations/backend/temporal/channel_summary/coordinator.pyindex 0b2338b60c46..6041244c6dd0 100644--- a/products/conversations/backend/temporal/channel_summary/coordinator.py+++ b/products/conversations/backend/temporal/channel_summary/coordinator.py@@ -7,7 +7,7 @@ from temporalio.common import RetryPolicy, WorkflowIDReusePolicyfrom temporalio.exceptions import WorkflowAlreadyStartedErrorwith workflow.unsafe.imports_passed_through():- from datetime import timedelta+ from datetime import date, timedeltaimport structlog@@ -15,6 +15,7 @@ with workflow.unsafe.imports_passed_through():from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.heartbeat import Heartbeater+ from products.conversations.backend.channel_summary_ids import build_channel_summary_workflow_idfrom products.conversations.backend.support_slack import get_support_slack_bot_tokenfrom products.conversations.backend.temporal.channel_summary.constants import (MAX_SUMMARIES_PER_RUN,@@ -106,7 +107,11 @@ class ChannelSummaryCoordinatorWorkflow:started = 0skipped = 0for item in result.due:- child_id = f"account-channel-summary-{item.account_id}-{item.cadence}-{item.period_start[:10]}"+ child_id = build_channel_summary_workflow_id(+ account_id=item.account_id,+ cadence=item.cadence,+ period_start=date.fromisoformat(item.period_start[:10]),+ )try:await workflow.start_child_workflow(AccountChannelSummaryWorkflow.run,diff --git a/products/conversations/backend/tests/test_facade.py b/products/conversations/backend/tests/test_facade.pyindex 9c8b896be8eb..bbc254757023 100644--- a/products/conversations/backend/tests/test_facade.py+++ b/products/conversations/backend/tests/test_facade.py@@ -1,4 +1,4 @@-from datetime import timedelta+from datetime import UTC, datetime, timedeltafrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch@@ -10,14 +10,17 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.models import Team+from products.conversations.backend.channel_summary_ids import build_channel_summary_workflow_idfrom products.conversations.backend.facade.api import (SupportMessageSendError,list_account_tickets,post_support_message,+ trigger_immediate_channel_summary,)from products.conversations.backend.models.ticket import TicketCLIENT = "products.conversations.backend.facade.api.get_slack_client"+FACADE = "products.conversations.backend.facade.api"class FakeSlackResponse(dict):@@ -124,3 +127,59 @@ class TestListAccountTickets(BaseTest):self._create_ticket(team=self.team, organization_id="acct-1", number=1)assert list_account_tickets(self.team.pk, "") == []+++ACCOUNT_ID = "e1f4a5b6-0000-4000-8000-000000000001"+PERIOD_START = datetime(2026, 7, 27, tzinfo=UTC)+++class TestTriggerImmediateChannelSummary(BaseTest):+ def _trigger(self) -> bool:+ return trigger_immediate_channel_summary(+ team_id=self.team.pk,+ account_id=ACCOUNT_ID,+ account_name="Acme Corp",+ slack_channel_id="C123",+ cadence="daily",+ period_start=PERIOD_START,+ period_end=PERIOD_START + timedelta(days=1),+ )++ @parameterized.expand(+ [+ ("eligible", True, "xoxb-token", True),+ ("ai_processing_not_approved", False, "xoxb-token", False),+ ("support_bot_not_configured", True, "", False),+ ]+ )+ def test_gates_on_org_approval_and_bot_config(self, _name, ai_approved, bot_token, expected_dispatch):+ self.organization.is_ai_data_processing_approved = ai_approved+ self.organization.save()++ with (+ patch(f"{FACADE}.get_support_slack_bot_token", return_value=bot_token),+ patch(f"{FACADE}.sync_connect") as connect,+ patch(f"{FACADE}.asyncio.run") as run,+ ):+ dispatched = self._trigger()++ assert dispatched is expected_dispatch+ assert connect.called is expected_dispatch+ assert run.called is expected_dispatch++ def test_dispatches_under_the_shared_workflow_id(self):+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ client = MagicMock()++ with (+ patch(f"{FACADE}.get_support_slack_bot_token", return_value="xoxb-token"),+ patch(f"{FACADE}.sync_connect", return_value=client),+ patch(f"{FACADE}.asyncio.run"),+ ):+ self._trigger()++ assert client.start_workflow.call_args.kwargs["id"] == build_channel_summary_workflow_id(+ account_id=ACCOUNT_ID, cadence="daily", period_start=PERIOD_START.date()+ )+ assert client.start_workflow.call_args.args[1].slack_channel_id == "C123"diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 4f8cc2d519f7..964d6614770d 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -26,6 +26,7 @@ from django.apps import appsfrom django.conf import settingsfrom django.contrib.postgres.aggregates import ArrayAggfrom django.contrib.postgres.fields import ArrayField+from django.core.cache import cachefrom django.core.exceptions import ValidationErrorfrom django.db import IntegrityError, transactionfrom django.db.models import (@@ -71,6 +72,7 @@ from products.conversations.backend.facade.api import (SupportSlackNotConfigured,TicketSummary as TicketSummary,list_account_tickets,+ trigger_immediate_channel_summary,)from products.customer_analytics.backend.account_urls import build_account_deeplink as build_account_deeplinkfrom products.customer_analytics.backend.events import emit_account_tags_added@@ -2798,9 +2800,76 @@ def update_account_for_view(was_impersonated=was_impersonated,previous=previous,)+ # Off-to-on only: the coordinator picks a mid-flight cadence change up within the hour,+ # and one backfill per switch is LLM spend nobody asked for.+ if not previous.slack_summary_cadence and account.slack_summary_cadence:+ _dispatch_initial_channel_summary(account)return _to_account_view(account)+# Roughly 70 accounts opting into a daily cadence in one day, far above real use.+CHANNEL_SUMMARY_BACKFILL_DAILY_CAP = 500+++def _reserve_backfill_budget(team_id: int, requested: int) -> int:+ """How many of ``requested`` backfill dispatches this team may still start today.++ The coordinator throttles itself with per-run caps, but these dispatches are driven by+ an API call, so one caller opting in many channel-bound accounts could otherwise start+ unbounded LLM work in a burst. ``cache.incr`` is atomic, so parallel requests cannot all+ slip under the ceiling. Whatever this refuses, the coordinator still summarizes on+ schedule.+ """+ window = int(datetime.now(UTC).timestamp()) // 86400+ key = f"ca_channel_summary_backfills:{team_id}:{window}"+ cache.add(key, 0, timeout=86400)+ try:+ used = cache.incr(key, requested)+ except ValueError:+ # The key expired between add and incr; this request is the window's first.+ used = requested+ allowed = requested - max(0, used - CHANNEL_SUMMARY_BACKFILL_DAILY_CAP)+ return max(0, allowed)+++def _dispatch_initial_channel_summary(account: Account) -> None:+ cadence = account.slack_summary_cadence+ slack_channel_id = (account._properties or {}).get("slack_channel_id")+ if not cadence or not slack_channel_id:+ return+ periods = _channel_summaries_logic.get_initial_summary_periods(cadence, timezone.now(), account.team.timezone_info)+ allowed = _reserve_backfill_budget(account.team_id, len(periods))+ if allowed < len(periods):+ logger.warning(+ "channel_summary_backfill_throttled",+ team_id=account.team_id,+ requested=len(periods),+ allowed=allowed,+ )+ # Newest first, so a partly-throttled backfill keeps the periods a user looks at first.+ for period in sorted(periods, key=lambda p: p.start, reverse=True)[:allowed]:+ try:+ trigger_immediate_channel_summary(+ team_id=account.team_id,+ account_id=str(account.id),+ account_name=account.name,+ slack_channel_id=slack_channel_id,+ cadence=cadence,+ period_start=period.start,+ period_end=period.end,+ )+ except Exception as e:+ # Per period, so one bad dispatch doesn't drop the rest.+ capture_exception(+ e,+ {+ "team_id": account.team_id,+ "account_id": str(account.id),+ "period_start": period.start.isoformat(),+ },+ )++def delete_account_for_view(*,team_id: int,@@ -2971,9 +3040,7 @@ def list_accounts_due_for_slack_summary(now: datetime | None = None) -> list[concadence = account.slack_summary_cadenceif not slack_channel_id or not cadence:continue- period_start, period_end = _channel_summaries_logic.get_last_closed_period(- cadence, now, account.team.timezone_info- )+ period = _channel_summaries_logic.get_last_closed_period(cadence, now, account.team.timezone_info)candidates.append(contracts.AccountDueForSlackSummary(team_id=account.team_id,@@ -2981,8 +3048,8 @@ def list_accounts_due_for_slack_summary(now: datetime | None = None) -> list[conaccount_name=account.name,slack_channel_id=slack_channel_id,cadence=cadence,- period_start=period_start,- period_end=period_end,+ period_start=period.start,+ period_end=period.end,))if not candidates:diff --git a/products/customer_analytics/backend/logic/channel_summaries.py b/products/customer_analytics/backend/logic/channel_summaries.pyindex ea9f31e97d10..8bcf9b66f920 100644--- a/products/customer_analytics/backend/logic/channel_summaries.py+++ b/products/customer_analytics/backend/logic/channel_summaries.py@@ -1,16 +1,41 @@from __future__ import annotations+from dataclasses import dataclassfrom datetime import date, datetime, time, timedeltafrom zoneinfo import ZoneInfo+from dateutil.relativedelta import relativedelta+from products.customer_analytics.backend.models import SlackSummaryCadence-def get_last_closed_period(cadence: str, now: datetime, tz: ZoneInfo) -> tuple[datetime, datetime]:+@dataclass(frozen=True, kw_only=True)+class SummaryPeriod:+ """A half-open ``[start, end)`` window at local midnight in the account team's timezone."""++ start: datetime+ end: datetime+++# Daily reaches back a week because one closed day of a quiet channel is rarely worth opening.+_INITIAL_BACKFILL_PERIODS: dict[str, int] = {+ SlackSummaryCadence.DAILY: 7,+ SlackSummaryCadence.WEEKLY: 1,+ SlackSummaryCadence.MONTHLY: 1,+}++_CADENCE_STEP: dict[str, relativedelta] = {+ SlackSummaryCadence.DAILY: relativedelta(days=1),+ SlackSummaryCadence.WEEKLY: relativedelta(weeks=1),+ SlackSummaryCadence.MONTHLY: relativedelta(months=1),+}+++def get_last_closed_period(cadence: str, now: datetime, tz: ZoneInfo) -> SummaryPeriod:"""The most recent fully-elapsed calendar window for ``cadence`` in ``tz``.Daily → yesterday, weekly → last ISO week (Monday to Monday), monthly → last- calendar month. Returns aware ``[start, end)`` datetimes at local midnight.+ calendar month."""today = now.astimezone(tz).date()if cadence == SlackSummaryCadence.DAILY:@@ -23,7 +48,21 @@ def get_last_closed_period(cadence: str, now: datetime, tz: ZoneInfo) -> tuple[dstart, end = (first_of_this_month - timedelta(days=1)).replace(day=1), first_of_this_monthelse:raise ValueError(f"Unknown slack summary cadence: {cadence}")- return _local_midnight(start, tz), _local_midnight(end, tz)+ return SummaryPeriod(start=_local_midnight(start, tz), end=_local_midnight(end, tz))+++def get_initial_summary_periods(cadence: str, now: datetime, tz: ZoneInfo) -> list[SummaryPeriod]:+ """Oldest first. Excludes the current partial period, whose summary would claim the+ period key the coordinator later wants for the complete one."""+ count = _INITIAL_BACKFILL_PERIODS.get(cadence)+ if count is None:+ raise ValueError(f"Unknown slack summary cadence: {cadence}")+ step = _CADENCE_STEP[cadence]+ periods = [get_last_closed_period(cadence, now, tz)]+ while len(periods) < count:+ previous_end = periods[-1].start+ periods.append(SummaryPeriod(start=_local_midnight(previous_end.date() - step, tz), end=previous_end))+ return list(reversed(periods))def _local_midnight(day: date, tz: ZoneInfo) -> datetime:diff --git a/products/customer_analytics/backend/test/test_channel_summaries.py b/products/customer_analytics/backend/test/test_channel_summaries.pyindex 5c692df375c7..52ac1557b38a 100644--- a/products/customer_analytics/backend/test/test_channel_summaries.py+++ b/products/customer_analytics/backend/test/test_channel_summaries.py@@ -2,6 +2,9 @@ from datetime import UTC, datetimefrom zoneinfo import ZoneInfofrom posthog.test.base import APIBaseTest, BaseTest+from unittest.mock import patch++from django.core.cache import cachefrom parameterized import parameterizedfrom rest_framework import status@@ -9,7 +12,10 @@ from rest_framework import statusfrom posthog.models import Teamfrom products.customer_analytics.backend.facade import api as facade-from products.customer_analytics.backend.logic.channel_summaries import get_last_closed_period+from products.customer_analytics.backend.logic.channel_summaries import (+ get_initial_summary_periods,+ get_last_closed_period,+)from products.customer_analytics.backend.models import Account, AccountChannelSummaryfrom products.customer_analytics.backend.test.factories import create_account@@ -59,10 +65,39 @@ class TestGetLastClosedPeriod:])def test_closed_periods(self, _name, cadence, now, expected_start, expected_end):- start, end = get_last_closed_period(cadence, now, SP)+ period = get_last_closed_period(cadence, now, SP)++ assert period.start == expected_start+ assert period.end == expected_end+++class TestGetInitialSummaryPeriods:+ NOW = datetime(2026, 7, 28, 15, 30, tzinfo=UTC)++ def test_daily_covers_the_seven_closed_days_before_today(self):+ periods = get_initial_summary_periods("daily", self.NOW, SP)++ assert [p.start for p in periods] == [datetime(2026, 7, d, 0, 0, tzinfo=SP) for d in range(21, 28)]+ assert [p.end for p in periods] == [datetime(2026, 7, d, 0, 0, tzinfo=SP) for d in range(22, 29)]++ @parameterized.expand(+ [+ ("weekly", "weekly", datetime(2026, 7, 20, 0, 0, tzinfo=SP), datetime(2026, 7, 27, 0, 0, tzinfo=SP)),+ ("monthly", "monthly", datetime(2026, 6, 1, 0, 0, tzinfo=SP), datetime(2026, 7, 1, 0, 0, tzinfo=SP)),+ ]+ )+ def test_wider_cadences_cover_one_closed_period(self, _name, cadence, expected_start, expected_end):+ periods = get_initial_summary_periods(cadence, self.NOW, SP)++ assert [(p.start, p.end) for p in periods] == [(expected_start, expected_end)]++ def test_every_backfilled_period_is_one_the_coordinator_would_produce(self):+ for cadence in ("daily", "weekly", "monthly"):+ periods = get_initial_summary_periods(cadence, self.NOW, SP)- assert start == expected_start- assert end == expected_end+ assert periods[-1] == get_last_closed_period(cadence, self.NOW, SP)+ for period in periods:+ assert get_last_closed_period(cadence, period.end, SP) == periodclass TestListAccountsDueForSlackSummary(BaseTest):@@ -102,14 +137,14 @@ class TestListAccountsDueForSlackSummary(BaseTest):def test_period_with_existing_summary_is_not_due_again(self):account = self._opted_in_account()- period_start, period_end = get_last_closed_period("daily", self.NOW, ZoneInfo("UTC"))+ period = get_last_closed_period("daily", self.NOW, ZoneInfo("UTC"))facade.record_channel_summary(team_id=self.team.id,account_id=str(account.id),slack_channel_id="C123",cadence="daily",- period_start=period_start,- period_end=period_end,+ period_start=period.start,+ period_end=period.end,content="summary",message_count=3,)@@ -118,14 +153,14 @@ class TestListAccountsDueForSlackSummary(BaseTest):def test_summary_for_another_cadence_does_not_satisfy_the_period(self):account = self._opted_in_account(slack_summary_cadence="monthly")- period_start, period_end = get_last_closed_period("monthly", self.NOW, ZoneInfo("UTC"))+ period = get_last_closed_period("monthly", self.NOW, ZoneInfo("UTC"))AccountChannelSummary.objects.unscoped().create(team_id=self.team.id,account_id=account.id,slack_channel_id="C123",cadence="weekly",- period_start=period_start,- period_end=period_end,+ period_start=period.start,+ period_end=period.end,content="other cadence",)@@ -241,6 +276,67 @@ class TestAccountSummariesEndpoint(APIBaseTest):self.account.refresh_from_db()assert self.account.slack_summary_cadence is None+ @parameterized.expand(+ [+ ("turning_on", None, {"slack_channel_id": "C123"}, {"slack_summary_cadence": "daily"}, True),+ ("turning_off", "daily", {"slack_channel_id": "C123"}, {"slack_summary_cadence": None}, False),+ ("switching_cadence", "daily", {"slack_channel_id": "C123"}, {"slack_summary_cadence": "weekly"}, False),+ ("no_channel_bound", None, {}, {"slack_summary_cadence": "daily"}, False),+ ("unrelated_field", None, {"slack_channel_id": "C123"}, {"name": "Renamed"}, False),+ ]+ )+ def test_turning_summaries_on_backfills_immediately(self, _name, cadence, properties, payload, expected_dispatch):+ account = create_account(team_id=self.team.id, slack_summary_cadence=cadence, _properties=properties)++ with patch("products.customer_analytics.backend.facade.api.trigger_immediate_channel_summary") as dispatch:+ response = self.client.patch(+ f"/api/environments/{self.team.id}/accounts/{account.id}/", payload, format="json"+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert dispatch.called is expected_dispatch+ if expected_dispatch:+ assert dispatch.call_count == 7+ starts = [call.kwargs["period_start"] for call in dispatch.call_args_list]+ assert starts == sorted(starts, reverse=True)+ assert {call.kwargs["cadence"] for call in dispatch.call_args_list} == {"daily"}+ assert {call.kwargs["slack_channel_id"] for call in dispatch.call_args_list} == {"C123"}++ def test_backfill_is_capped_per_team_per_day(self):+ cache.clear()+ account = create_account(team_id=self.team.id, _properties={"slack_channel_id": "C123"})+ detail = f"/api/environments/{self.team.id}/accounts/{account.id}/"++ with (+ patch("products.customer_analytics.backend.facade.api.CHANNEL_SUMMARY_BACKFILL_DAILY_CAP", 4),+ patch("products.customer_analytics.backend.facade.api.trigger_immediate_channel_summary") as dispatch,+ ):+ response = self.client.patch(detail, {"slack_summary_cadence": "daily"}, format="json")++ assert response.status_code == status.HTTP_200_OK, response.json()+ # An API-driven dispatch has no per-run cap of its own, so one caller opting in many+ # channel-bound accounts could otherwise start unbounded LLM work in a burst.+ assert dispatch.call_count == 4+ starts = [call.kwargs["period_start"] for call in dispatch.call_args_list]+ assert starts == sorted(starts, reverse=True)++ def test_a_failed_backfill_does_not_fail_the_update(self):+ account = create_account(team_id=self.team.id, _properties={"slack_channel_id": "C123"})++ with patch(+ "products.customer_analytics.backend.facade.api.trigger_immediate_channel_summary",+ side_effect=RuntimeError("temporal is down"),+ ):+ response = self.client.patch(+ f"/api/environments/{self.team.id}/accounts/{account.id}/",+ {"slack_summary_cadence": "daily"},+ format="json",+ )++ assert response.status_code == status.HTTP_200_OK, response.json()+ account.refresh_from_db()+ assert account.slack_summary_cadence == "daily"+def test_invalid_cadence_is_rejected(self):response = self.client.patch(f"/api/environments/{self.team.id}/accounts/{self.account.id}/",diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 802fadabf804..03f28cb7af02 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -40,22 +40,22 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc### Logics and what each owns-| Logic | Owns |-| ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `accountsLogic` | The hub. Search (debounced), tag / assigned-to/unassigned / custom-property filters, sort, inline role assignment, HogQL and Postgres list-query selection, shareable URL-hash view state, and `openAccount` (the Max entry point). `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references; `tableRowsTransformer` adapts keyed Postgres rows for the existing table. `connect`s column-config, overview-tiles, and expansion logics. |-| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select). Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |-| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), the column-picker groups built from the DB schema + data-warehouse joins, and the per-team saved column config (`columnConfigurations` API), and the custom-property definitions: it loads them, seeds `propertyDefinitionsModel` (so the filter UI resolves per-type operator sets), and exposes `customPropertyTaxonomicOptions` / `customPropertyDefinitionsById`. When `CUSTOMER_ANALYTICS_ACCOUNTS_HOGQL_CLEANUP` is enabled, the picker only offers Postgres-backed account fields, tags, notes, relationships, and custom properties. |-| `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. |-| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`); its `metrics` feed `accountsLogic.metricsQuery`, the separate metrics-only data node (key `ACCOUNTS_METRICS_DATA_NODE_KEY`) it reads `response`/`responseLoading` back from — independent of the list rows. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |-| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). |-| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). US-region orgs come from the org-members endpoint; when it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only, refreshed daily), fetched once per expansion and paginated client-side. A missing view (local dev) degrades to the normal empty state. |-| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint) and `endRelationship` (per active row, POSTs the end endpoint) — both guarded by a shared `relationshipSaving` flag, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |-| `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables, and owns the per-view hidden-series state (`ephemeralHiddenSeriesKeysByShortId`) behind the chart chips. |-| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. |-| `accountSummariesLogic` | The Summaries tab (keyed by `accountId`): fetches the account (for its linked `slack_channel_id` and `slack_summary_cadence`) plus the first page of the `accountsSummariesList` endpoint, navigates server pages via `loadSummariesPage` (5 per page, `page` reducer; each page replaces the last), holds per-summary collapse state (`expandedSummaryIds` / `toggleSummaryExpanded`), and owns the cadence opt-in (`setCadence` PATCHes the account through `accountsPartialUpdate`, guarded by a `cadenceSaving` flag). Distinguishes not-loaded / no-channel-linked / loaded-empty / load-failed; captures unexpected failures. |-| `accountSupportTicketsLogic` | Conversations support tickets behind the Support tickets tab (keyed by `accountId`): fetches the account's tickets from the generated `accountsSupportTicketsList` endpoint (backed by the customer-analytics facade → conversations facade → `Ticket`s matched on `organization_id = external_id`). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. |-| `accountMeetingsLogic` | The Meetings tab (keyed by `accountId`): fetches synced calendar meetings from the generated `accountsMeetingsList` endpoint (customer-analytics facade `get_account_meetings` over the `Meeting` model, populated by the Google Calendar Temporal sync). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. Also owns the "Edit matching" editor: `email_domains` / `known_emails` drafts, normalization (trim, lowercase, strip a leading `@`, dedupe), and `saveMatching` — merges them into the account's `properties` via `accountsPartialUpdate` (guarded by `savingMatching`) and propagates the updated account through `accountLinksLogic.loadAccountSuccess` (it connects to that logic for the account instead of fetching its own copy). |-| `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |+| Logic | Owns |+| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `accountsLogic` | The hub. Search (debounced), tag / assigned-to/unassigned / custom-property filters, sort, inline role assignment, HogQL and Postgres list-query selection, shareable URL-hash view state, and `openAccount` (the Max entry point). `accountsTableQueryPlan` translates live, saved-view, and URL-restored state into typed references; `tableRowsTransformer` adapts keyed Postgres rows for the existing table. `connect`s column-config, overview-tiles, and expansion logics. |+| `accountsViewsLogic` | Saved-views lifecycle (list/create/update/delete/select). Connects to `accountsLogic`, `accountsColumnConfigLogic`, and `accountsOverviewTilesLogic`; is the single owner of reading and writing the `ColumnConfiguration` rows for this area. |+| `accountsColumnConfigLogic` | Selected columns (`selectColumns` / `visibleColumnNames`), the column-picker groups built from the DB schema + data-warehouse joins, and the per-team saved column config (`columnConfigurations` API), and the custom-property definitions: it loads them, seeds `propertyDefinitionsModel` (so the filter UI resolves per-type operator sets), and exposes `customPropertyTaxonomicOptions` / `customPropertyDefinitionsById`. When `CUSTOMER_ANALYTICS_ACCOUNTS_HOGQL_CLEANUP` is enabled, the picker only offers Postgres-backed account fields, tags, notes, relationships, and custom properties. |+| `accountsExpansionLogic` | Which rows are expanded (`expandedAccountIds`) and the active tab per account (`activeTabByAccount`). Pure state — no DOM, no data fetching. |+| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`); its `metrics` feed `accountsLogic.metricsQuery`, the separate metrics-only data node (key `ACCOUNTS_METRICS_DATA_NODE_KEY`) it reads `response`/`responseLoading` back from — independent of the list rows. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. |+| `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). |+| `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). US-region orgs come from the org-members endpoint; when it returns no members, the logic falls back to the `eu_org_members` data warehouse view (a materialized pre-join of the EU postgres sync, prod-only, refreshed daily), fetched once per expansion and paginated client-side. A missing view (local dev) degrades to the normal empty state. |+| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the `displayedRelationships` selector (current assignments first, newest first, optionally narrowed by `definitionFilter`) feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Also owns the tab's mutations: `assignRelationship` (definition picker + `MemberSelect`, POSTs the assign endpoint) and `endRelationship` (per active row, POSTs the end endpoint) — both guarded by a shared `relationshipSaving` flag, reload the timeline, and force-refresh the list's data nodes so relationship columns stay in sync. |+| `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables, and owns the per-view hidden-series state (`ephemeralHiddenSeriesKeysByShortId`) behind the chart chips. |+| `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. |+| `accountSummariesLogic` | The Summaries tab (keyed by `accountId`): fetches the account (for its linked `slack_channel_id` and `slack_summary_cadence`) plus the first page of the `accountsSummariesList` endpoint, navigates server pages via `loadSummariesPage` (5 per page, `page` reducer; each page replaces the last), holds per-summary collapse state (`expandedSummaryIds` / `toggleSummaryExpanded`), and owns the cadence opt-in (`setCadence` PATCHes the account through `accountsPartialUpdate`, guarded by a `cadenceSaving` flag). Turning the cadence on with no summaries yet starts `generatingFirstSummary` polling (`startFirstSummaryPolling` / `stopFirstSummaryPolling`, two `cache.disposables` keys) so the backfill the backend kicks off appears without a refresh; the poll deadline lives in a module-level map keyed by account id, because this logic unmounts whenever its row collapses while the backfill keeps running. Distinguishes not-loaded / no-channel-linked / generating / loaded-empty / load-failed; captures unexpected failures. |+| `accountSupportTicketsLogic` | Conversations support tickets behind the Support tickets tab (keyed by `accountId`): fetches the account's tickets from the generated `accountsSupportTicketsList` endpoint (backed by the customer-analytics facade → conversations facade → `Ticket`s matched on `organization_id = external_id`). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. |+| `accountMeetingsLogic` | The Meetings tab (keyed by `accountId`): fetches synced calendar meetings from the generated `accountsMeetingsList` endpoint (customer-analytics facade `get_account_meetings` over the `Meeting` model, populated by the Google Calendar Temporal sync). Distinguishes not-loaded / loaded-empty / load-failed; captures unexpected failures. Also owns the "Edit matching" editor: `email_domains` / `known_emails` drafts, normalization (trim, lowercase, strip a leading `@`, dedupe), and `saveMatching` — merges them into the account's `properties` via `accountsPartialUpdate` (guarded by `savingMatching`) and propagates the updated account through `accountLinksLogic.loadAccountSuccess` (it connects to that logic for the account instead of fetching its own copy). |+| `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |## Data & query model@@ -123,8 +123,17 @@ The Usage and Spend tabs render existing saved billing insights — **point userThe Opportunities tab lists the account's Salesforce opportunities from the data-warehouse `salesforce.opportunity` table (joined by the account's `sfdc_id`). The query runs in `accountOpportunitiesLogic` rather than via a bare `<Query>` so the tab owns every state: a missing `sfdc_id` shows a "not linked to Salesforce" empty state, and because `salesforce.opportunity` is **access-gated and production-only**, a failed query degrades to a pretty hog empty state instead of a red error box. The expected denied/absent-table `QueryError` (`You don't have access to table …` / `Unknown table …`) is **not** captured to PostHog — it's the normal empty state, not a bug — while genuine, unexpected query failures are still reported (`isExpectedMissingTableError` in `accountOpportunitiesLogic`). Each opportunity name links to its Salesforce record (`SALESFORCE_ORIGIN/<id>` in `constants.ts`, the same origin the Useful links sidebar uses).The Summaries tab lists periodic AI summaries of the account's linked Slack channel (generated by a scheduled pipeline in the conversations product, stored per closed period).-`accountSummariesLogic` fetches the account and the generated `accountsSummariesList` endpoint together; it owns four states: a skeleton while loading, a "couldn't load" state on unexpected failure (captured to PostHog), a "no channel linked" state when `properties.slack_channel_id` is unset (pointing at linking one), and the opt-in empty state carrying the cadence picker.+`accountSummariesLogic` fetches the account and the generated `accountsSummariesList` endpoint together; it owns five states: a skeleton while loading, a "couldn't load" state on unexpected failure (captured to PostHog), a "no channel linked" state when `properties.slack_channel_id` is unset (pointing at linking one), a "generating your first summary" state while the opt-in backfill runs, and the opt-in empty state carrying the cadence picker.The cadence picker (off/daily/weekly/monthly) writes `slack_summary_cadence` through the normal account PATCH and is disabled while saving.+Only an **off-to-on** switch backfills, on both sides: the backend triggers on that transition alone, and the tab starts its wait on the same condition, so switching between two enabled cadences shows no generating state.+Switching it from off to on makes the backend backfill the account's recent **closed** periods immediately instead of waiting for the coordinator's next tick: 7 summaries for daily (one per day), 1 for weekly, 1 for monthly.+The logic polls `loadSummaries` every 15s, stopping once `totalCount` has held steady for `FIRST_SUMMARY_QUIET_MS` or the 5-minute deadline passes.+Both conditions are **wall-clock** and are evaluated inside `loadSummariesSuccess`, never by a `setTimeout`: the disposables plugin suspends the interval while the tab is hidden, so a poll counter would stretch a 90-second wait across however long the user spends in another tab, and a timeout would restart from its full duration on every resume.+It cannot wait for a fixed count: a backfilled period with no messages writes no summary at all, so a 7-day daily backfill over a channel that was quiet on the weekend yields fewer than 7 rows.+A per-team daily cap (`CHANNEL_SUMMARY_BACKFILL_DAILY_CAP`, reserved atomically via `cache.incr`) bounds these dispatches, which are API-driven and so have no per-run cap of their own.+Periods dispatch newest first, so a throttled backfill keeps the ones a user opens first and the coordinator covers the rest on schedule.+Backfilled periods sit exactly on the grid the coordinator derives, and the dispatch reuses the coordinator's workflow id, so a backfill and a scheduled tick can never summarize one period twice.+The current partial period is deliberately not backfilled: it would claim the period key the coordinator later wants for the complete period.Each summary renders **collapsed** (cadence tag + period + message count + generated-at); clicking the header toggles the content open (`expandedSummaryIds` in the logic, so the state survives tab switches while the row stays expanded).Summary content is LLM-generated markdown citing Slack permalinks, rendered with `LemonMarkdown` (`disableImages` because the content is model-produced; links open Slack).The list is server-paginated at 5 per page via `PaginationControl` (`loadSummariesPage` replaces the page; clicks are ignored while a page load is in flight).diff --git a/products/customer_analytics/frontend/components/Accounts/AccountSummariesExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountSummariesExpansion.tsxindex 02ba993580bc..52f59c32d81f 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountSummariesExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountSummariesExpansion.tsx@@ -2,10 +2,11 @@ import clsx from 'clsx'import { useActions, useValues } from 'kea'import { ReactNode } from 'react'-import { LemonDropdown, LemonSelect, LemonSkeleton, LemonTag, Link } from '@posthog/lemon-ui'+import { LemonDropdown, LemonSelect, LemonSkeleton, LemonTag, Link, Spinner } from '@posthog/lemon-ui'import { BigLeaguesHog } from 'lib/components/hedgehogs'import { TZLabel } from 'lib/components/TZLabel'+import { dayjs } from 'lib/dayjs'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { PaginationControl } from 'lib/lemon-ui/PaginationControl'@@ -57,10 +58,21 @@ function CadencePicker({ accountId }: { accountId: string }): JSX.Element {)}-function periodLabel(summary: AccountChannelSummaryApi): string {+function backfillDescription(cadence: SlackSummaryCadenceEnumApi | null): string {+ if (cadence === SlackSummaryCadenceEnumApi.Daily) {+ return 'Summarizing the last 7 days, one summary per day.'+ }+ return cadence === SlackSummaryCadenceEnumApi.Monthly ? 'Summarizing last month.' : 'Summarizing last week.'+}++export function periodLabel(summary: AccountChannelSummaryApi): string {const start = summary.period_start.slice(0, 10)- // period_end is exclusive; a daily summary covers a single day.- return summary.cadence === 'daily' ? start : `${start} to ${summary.period_end.slice(0, 10)}`+ // Span, not cadence: an opt-in backfill writes a trailing window under whichever cadence was picked.+ if (dayjs(summary.period_end).diff(summary.period_start, 'day') <= 1) {+ // period_end is exclusive, so a single day's end already reads as the next date.+ return start+ }+ return `${start} to ${summary.period_end.slice(0, 10)}`}function MessageCountBadge({ summary }: { summary: AccountChannelSummaryApi }): JSX.Element {@@ -136,7 +148,7 @@ function SummaryCard({}export function AccountSummariesExpansion({ accountId }: { accountId: string }): JSX.Element {- const { summariesResult, summariesResultLoading, page, expandedSummaryIds } = useValues(+ const { summariesResult, summariesResultLoading, page, expandedSummaryIds, generatingFirstSummary } = useValues(accountSummariesLogic({ accountId }))const { loadSummariesPage, toggleSummaryExpanded } = useActions(accountSummariesLogic({ accountId }))@@ -166,6 +178,21 @@ export function AccountSummariesExpansion({ accountId }: { accountId: string }):}if (!summaries || summaries.length === 0) {+ if (generatingFirstSummary) {+ return (+ <SummariesEmptyState+ title={+ cadence === SlackSummaryCadenceEnumApi.Daily+ ? 'Generating your first summaries'+ : 'Generating your first summary'+ }+ detail={`${backfillDescription(cadence)} This usually takes a minute.`}+ >+ <Spinner className="text-xl" />+ <CadencePicker accountId={accountId} />+ </SummariesEmptyState>+ )+ }return (<SummariesEmptyStatetitle={cadence ? 'No summaries yet' : 'Summaries are off'}@@ -183,7 +210,14 @@ export function AccountSummariesExpansion({ accountId }: { accountId: string }):return (<div className="flex flex-col gap-3"><div className="flex items-center justify-between">- <h4 className="mb-0">Channel summaries</h4>+ <div className="flex items-center gap-2">+ <h4 className="mb-0">Channel summaries</h4>+ {generatingFirstSummary && (+ <span className="text-muted text-sm flex items-center gap-1">+ <Spinner /> Generating more+ </span>+ )}+ </div><div className="flex items-center gap-2"><span className="text-muted text-sm">Cadence</span><CadencePicker accountId={accountId} />diff --git a/products/customer_analytics/frontend/components/Accounts/accountSummariesLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountSummariesLogic.test.tsindex 6c4fc7466617..07e1870c66b5 100644--- a/products/customer_analytics/frontend/components/Accounts/accountSummariesLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountSummariesLogic.test.ts@@ -10,7 +10,8 @@ import {} from 'products/customer_analytics/frontend/generated/api'import type { AccountApi, AccountChannelSummaryApi } from 'products/customer_analytics/frontend/generated/api.schemas'-import { accountSummariesLogic } from './accountSummariesLogic'+import { periodLabel } from './AccountSummariesExpansion'+import { accountSummariesLogic, FIRST_SUMMARY_POLL_TIMEOUT_MS, FIRST_SUMMARY_QUIET_MS } from './accountSummariesLogic'jest.mock('products/customer_analytics/frontend/generated/api', () => ({// Keep the real module for everything else — connected logics call other generated@@ -30,6 +31,8 @@ const ACCOUNT = {slack_summary_cadence: 'weekly',} as unknown as AccountApi+const CADENCE_OFF = { ...ACCOUNT, slack_summary_cadence: null } as unknown as AccountApi+const SUMMARY = { id: 's-1', cadence: 'weekly', content: '## What happened' } as AccountChannelSummaryApidescribe('accountSummariesLogic', () => {@@ -43,11 +46,13 @@ describe('accountSummariesLogic', () => {})afterEach(() => {+ // Clears this account's module-level backfill deadline, which would leak into the next test.+ logic?.actions.stopFirstSummaryPolling()logic?.unmount()})- const mount = async (): Promise<void> => {- logic = accountSummariesLogic({ accountId: 'acc-1' })+ const mount = async (accountId = 'acc-1'): Promise<void> => {+ logic = accountSummariesLogic({ accountId })logic.mount()await expectLogic(logic).toFinishAllListeners()}@@ -105,6 +110,109 @@ describe('accountSummariesLogic', () => {expect(logic.values.cadenceSaving).toBe(false)})+ it('watches for the backfilled summaries after turning summaries on', async () => {+ mockRetrieve.mockResolvedValue(CADENCE_OFF)+ mockList.mockResolvedValue({ count: 0, next: null, previous: null, results: [] })+ mockPatch.mockResolvedValue(CADENCE_OFF)+ await mount()++ logic.actions.setCadence('daily')+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.generatingFirstSummary).toBe(true)++ mockList.mockResolvedValue({ count: 1, next: null, previous: null, results: [SUMMARY] })+ logic.actions.loadSummaries()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.summariesResult.summaries).toEqual([SUMMARY])+ })++ it('resumes the wait after the account row is collapsed and re-expanded', async () => {+ mockRetrieve.mockResolvedValue(CADENCE_OFF)+ mockList.mockResolvedValue({ count: 0, next: null, previous: null, results: [] })+ mockPatch.mockResolvedValue(CADENCE_OFF)+ await mount('acc-collapse')++ logic.actions.setCadence('daily')+ await expectLogic(logic).toFinishAllListeners()+ logic.unmount()++ await mount('acc-collapse')++ expect(logic.values.generatingFirstSummary).toBe(true)+ })++ it('keeps waiting while summaries are still arriving, then stops when the backfill goes quiet', async () => {+ mockRetrieve.mockResolvedValue(CADENCE_OFF)+ mockList.mockResolvedValue({ count: 0, next: null, previous: null, results: [] })+ mockPatch.mockResolvedValue(CADENCE_OFF)+ await mount('acc-daily')+ const startedAt = Date.now()+ const nowSpy = jest.spyOn(Date, 'now')++ logic.actions.setCadence('daily')+ await expectLogic(logic).toFinishAllListeners()++ for (const count of [3, 6]) {+ nowSpy.mockReturnValue(startedAt + FIRST_SUMMARY_QUIET_MS * 2)+ mockList.mockResolvedValue({ count, next: null, previous: null, results: [SUMMARY] })+ logic.actions.loadSummaries()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.generatingFirstSummary).toBe(true)+ }++ nowSpy.mockReturnValue(startedAt + FIRST_SUMMARY_QUIET_MS * 3 + 1)+ logic.actions.loadSummaries()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.generatingFirstSummary).toBe(false)+ nowSpy.mockRestore()+ })++ it('stops waiting at the deadline even when no summary ever lands', async () => {+ mockRetrieve.mockResolvedValue(CADENCE_OFF)+ mockList.mockResolvedValue({ count: 0, next: null, previous: null, results: [] })+ mockPatch.mockResolvedValue(CADENCE_OFF)+ await mount('acc-deadline')+ const startedAt = Date.now()+ const nowSpy = jest.spyOn(Date, 'now')++ logic.actions.setCadence('daily')+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.generatingFirstSummary).toBe(true)++ nowSpy.mockReturnValue(startedAt + FIRST_SUMMARY_POLL_TIMEOUT_MS + 1)+ logic.actions.loadSummaries()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.generatingFirstSummary).toBe(false)+ nowSpy.mockRestore()+ })++ it.each([+ ['the account already has summaries', [SUMMARY], 'daily' as const],+ ['summaries are being turned off', [], null],+ // ACCOUNT starts on 'weekly', and only an off-to-on switch backfills.+ ['switching between two enabled cadences', [], 'daily' as const],+ ])('does not poll when %s', async (_name, results, cadence) => {+ mockRetrieve.mockResolvedValue(ACCOUNT)+ mockList.mockResolvedValue({ count: results.length, next: null, previous: null, results })+ mockPatch.mockResolvedValue(ACCOUNT)+ await mount()++ logic.actions.setCadence(cadence)+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.generatingFirstSummary).toBe(false)+ })++ it.each([+ ['2026-07-27T00:00:00Z', '2026-07-28T00:00:00Z', '2026-07-27'],+ ['2026-07-21T00:00:00Z', '2026-07-28T15:30:00Z', '2026-07-21 to 2026-07-28'],+ ])('labels a daily summary spanning %s to %s as "%s"', (period_start, period_end, expected) => {+ expect(periodLabel({ ...SUMMARY, cadence: 'daily', period_start, period_end })).toBe(expected)+ })+it('a failed cadence save keeps the previous cadence and resets the saving flag', async () => {mockRetrieve.mockResolvedValue(ACCOUNT)mockList.mockResolvedValue({ count: 0, next: null, previous: null, results: [] })diff --git a/products/customer_analytics/frontend/components/Accounts/accountSummariesLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountSummariesLogic.tsindex 59c2bc5e09d9..9342d8238fb6 100644--- a/products/customer_analytics/frontend/components/Accounts/accountSummariesLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountSummariesLogic.ts@@ -44,11 +44,21 @@ export const NOT_LOADED: AccountSummariesResult = {export const SUMMARIES_PAGE_SIZE = 5+export const FIRST_SUMMARY_POLL_INTERVAL_MS = 15_000+export const FIRST_SUMMARY_POLL_TIMEOUT_MS = 5 * 60_000+// A backfilled period with no messages writes no summary, so there is no count to wait for.+export const FIRST_SUMMARY_QUIET_MS = 90_000++// Module state, not logic state: this tab unmounts when its account row collapses, and the+// backfill it waits on keeps running server-side.+const backfillDeadlines = new Map<string, number>()+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface accountSummariesLogicValues {currentTeamId: number | null // teamLogiccadenceSaving: booleanexpandedSummaryIds: Record<string, boolean>+ generatingFirstSummary: booleanpage: numbersummariesResult: AccountSummariesResultsummariesResultLoading: boolean@@ -95,6 +105,12 @@ export interface accountSummariesLogicActions {setCadenceSuccess: (cadence: SlackSummaryCadenceEnumApi | null) => {cadence: SlackSummaryCadenceEnumApi | null}+ startFirstSummaryPolling: () => {+ value: true+ }+ stopFirstSummaryPolling: () => {+ value: true+ }toggleSummaryExpanded: (summaryId: string) => {summaryId: string}@@ -123,6 +139,8 @@ export const accountSummariesLogic = kea<accountSummariesLogicType>([setCadence: (cadence: SlackSummaryCadenceEnumApi | null) => ({ cadence }),setCadenceSuccess: (cadence: SlackSummaryCadenceEnumApi | null) => ({ cadence }),setCadenceFailure: true,+ startFirstSummaryPolling: true,+ stopFirstSummaryPolling: true,toggleSummaryExpanded: (summaryId: string) => ({ summaryId }),}),loaders(({ props, values }) => ({@@ -186,6 +204,13 @@ export const accountSummariesLogic = kea<accountSummariesLogicType>([setCadenceFailure: () => false,},],+ generatingFirstSummary: [+ false,+ {+ startFirstSummaryPolling: () => true,+ stopFirstSummaryPolling: () => false,+ },+ ],page: [1,{@@ -203,7 +228,42 @@ export const accountSummariesLogic = kea<accountSummariesLogicType>([},],}),- listeners(({ actions, props, values }) => ({+ listeners(({ actions, cache, props, values }) => ({+ startFirstSummaryPolling: () => {+ if ((backfillDeadlines.get(props.accountId) ?? 0) <= Date.now()) {+ actions.stopFirstSummaryPolling()+ return+ }+ cache.lastSeenCount = values.summariesResult.totalCount+ cache.lastChangeAt = Date.now()+ cache.disposables.add(() => {+ const intervalId = setInterval(() => actions.loadSummaries(), FIRST_SUMMARY_POLL_INTERVAL_MS)+ return () => clearInterval(intervalId)+ }, 'firstSummaryPoll')+ },+ stopFirstSummaryPolling: () => {+ backfillDeadlines.delete(props.accountId)+ cache.disposables.dispose('firstSummaryPoll')+ },+ loadSummariesSuccess: ({ summariesResult }) => {+ if (!values.generatingFirstSummary) {+ return+ }+ // totalCount, not the page length: a daily backfill writes up to 7 summaries and a page holds 5.+ const landed = summariesResult.totalCount+ if (landed !== cache.lastSeenCount) {+ cache.lastSeenCount = landed+ cache.lastChangeAt = Date.now()+ return+ }+ // Wall-clock, because the disposables plugin suspends this interval on a hidden+ // tab: counting polls would stretch the wait by however long the user is away.+ const quietFor = Date.now() - (cache.lastChangeAt ?? 0)+ const expired = Date.now() >= (backfillDeadlines.get(props.accountId) ?? 0)+ if (expired || (landed > 0 && quietFor >= FIRST_SUMMARY_QUIET_MS)) {+ actions.stopFirstSummaryPolling()+ }+ },toggleSummaryExpanded: ({ summaryId }) => {if (values.expandedSummaryIds[summaryId]) {posthog.capture(AccountsEvents.SummaryExpanded)@@ -213,12 +273,20 @@ export const accountSummariesLogic = kea<accountSummariesLogicType>([posthog.capture(AccountsEvents.SummariesPageChanged, { page })},setCadence: async ({ cadence }) => {+ // Only an off-to-on switch backfills, so only that one starts a wait.+ const wasOff = !values.summariesResult.cadencetry {await accountsPartialUpdate(String(values.currentTeamId), props.accountId, {slack_summary_cadence: cadence,})actions.setCadenceSuccess(cadence)posthog.capture(AccountsEvents.SummaryCadenceChanged, { cadence: cadence ?? 'off' })+ if (cadence && wasOff && !values.summariesResult.summaries?.length) {+ backfillDeadlines.set(props.accountId, Date.now() + FIRST_SUMMARY_POLL_TIMEOUT_MS)+ actions.startFirstSummaryPolling()+ } else if (!cadence) {+ actions.stopFirstSummaryPolling()+ }} catch (error) {posthog.captureException(error as Error, {scope: 'accountSummariesLogic.setCadence',@@ -228,7 +296,10 @@ export const accountSummariesLogic = kea<accountSummariesLogicType>([}},})),- afterMount(({ actions }) => {+ afterMount(({ actions, props }) => {actions.loadSummaries()+ if ((backfillDeadlines.get(props.accountId) ?? 0) > Date.now()) {+ actions.startFirstSummaryPolling()+ }}),])