: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): configure Google sync cadence (#107079)
Arthur Moreira de Deus943bdb88ed36
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 74c1fa2b8991..dee9095585d0 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -4237,6 +4237,7 @@ def list_calendar_sync_statuses(team_id: int) -> list[contracts.CalendarSyncStatSYNC_RETRY_AT_CONFIG_KEY,SYNC_STALE_AFTER,SYNC_STARTED_AT_CONFIG_KEY,+ get_calendar_sync_interval,)statuses = []@@ -4259,11 +4260,25 @@ def list_calendar_sync_statuses(team_id: int) -> list[contracts.CalendarSyncStatintegration_id=integration.id,last_synced_at=last_synced_at,is_syncing=is_syncing,+ sync_interval_minutes=get_calendar_sync_interval(config),))return statuses+def update_calendar_sync_interval(team_id: int, integration_id: int, interval_minutes: int) -> bool:+ from products.customer_analytics.backend.logic.calendar_sync import ( # noqa: PLC0415+ SYNC_INTERVAL_CONFIG_KEY,+ update_calendar_sync_config,+ )++ try:+ update_calendar_sync_config(integration_id, team_id, {SYNC_INTERVAL_CONFIG_KEY: interval_minutes})+ except Integration.DoesNotExist:+ return False+ return True++def _parse_datetime(value: str | None) -> datetime | None:if not value:return Nonediff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 6bb99d0adf94..17bd41090569 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -193,6 +193,7 @@ class CalendarSyncStatus:integration_id: intlast_synced_at: datetime | Noneis_syncing: bool+ sync_interval_minutes: int@dataclass(frozen=True)diff --git a/products/customer_analytics/backend/logic/calendar_sync.py b/products/customer_analytics/backend/logic/calendar_sync.pyindex 2807eb1207b8..62ddfe0df3bf 100644--- a/products/customer_analytics/backend/logic/calendar_sync.py+++ b/products/customer_analytics/backend/logic/calendar_sync.py@@ -3,6 +3,7 @@ from datetime import datetime, timedeltafrom email.utils import parseaddrfrom typing import Any+from django.db import transactionfrom django.db.models import Prefetch, Qfrom django.utils import timezone@@ -26,6 +27,9 @@ SYNC_TOKEN_CONFIG_KEY = "calendar_sync_token"SYNC_STARTED_AT_CONFIG_KEY = "calendar_sync_started_at"SYNC_RETRY_AT_CONFIG_KEY = "calendar_sync_retry_at"LAST_SYNCED_AT_CONFIG_KEY = "calendar_last_synced_at"+SYNC_INTERVAL_CONFIG_KEY = "calendar_sync_interval_minutes"+SYNC_ATTEMPTED_AT_CONFIG_KEY = "calendar_sync_attempted_at"+ALLOWED_SYNC_INTERVALS = (5, 15, 30, 60)# Matches the sync activity's start_to_close timeout: past this, an unfinished run is dead.SYNC_STALE_AFTER = timedelta(minutes=30)@@ -61,24 +65,54 @@ class CalendarBackfillPage:counts: CalendarSyncCounts+def get_calendar_sync_interval(config: dict) -> int:+ value = config.get(SYNC_INTERVAL_CONFIG_KEY)+ return value if type(value) is int and value in ALLOWED_SYNC_INTERVALS else 60+++def update_calendar_sync_config(+ integration_id: int, team_id: int, updates: dict[str, object], removals: tuple[str, ...] = ()+) -> None:+ with transaction.atomic():+ integration = Integration.objects.select_for_update().get(+ id=integration_id, team_id=team_id, kind="google-calendar"+ )+ config = dict(integration.config or {})+ config.update(updates)+ for key in removals:+ config.pop(key, None)+ integration.config = config+ integration.save(update_fields=["config"])++def mark_calendar_sync_started(integration_id: int, team_id: int) -> None:- integration = Integration.objects.get(id=integration_id, team_id=team_id, kind="google-calendar")- integration.config[SYNC_STARTED_AT_CONFIG_KEY] = timezone.now().isoformat()- integration.config.pop(SYNC_RETRY_AT_CONFIG_KEY, None)- integration.save(update_fields=["config"])+ update_calendar_sync_config(+ integration_id, team_id, {SYNC_STARTED_AT_CONFIG_KEY: timezone.now().isoformat()}, (SYNC_RETRY_AT_CONFIG_KEY,)+ )def mark_calendar_sync_retrying(integration_id: int, team_id: int, retry_after: timedelta) -> None:- integration = Integration.objects.get(id=integration_id, team_id=team_id, kind="google-calendar")- integration.config[SYNC_RETRY_AT_CONFIG_KEY] = (timezone.now() + retry_after).isoformat()- integration.save(update_fields=["config"])+ update_calendar_sync_config(+ integration_id, team_id, {SYNC_RETRY_AT_CONFIG_KEY: (timezone.now() + retry_after).isoformat()}+ )+++def mark_calendar_sync_failed(integration_id: int, team_id: int) -> None:+ update_calendar_sync_config(+ integration_id,+ team_id,+ {SYNC_ATTEMPTED_AT_CONFIG_KEY: timezone.now().isoformat()},+ (SYNC_STARTED_AT_CONFIG_KEY,),+ )def mark_calendar_sync_completed(integration_id: int, team_id: int) -> None:- integration = Integration.objects.get(id=integration_id, team_id=team_id, kind="google-calendar")- integration.config[LAST_SYNCED_AT_CONFIG_KEY] = timezone.now().isoformat()- integration.config.pop(SYNC_RETRY_AT_CONFIG_KEY, None)- integration.save(update_fields=["config"])+ update_calendar_sync_config(+ integration_id,+ team_id,+ {LAST_SYNCED_AT_CONFIG_KEY: timezone.now().isoformat()},+ (SYNC_RETRY_AT_CONFIG_KEY, SYNC_STARTED_AT_CONFIG_KEY, SYNC_ATTEMPTED_AT_CONFIG_KEY),+ )def sync_calendar_integration(integration_id: int, team_id: int) -> CalendarSyncCounts:@@ -90,27 +124,30 @@ def sync_calendar_integration(integration_id: int, team_id: int) -> CalendarSync"""integration = Integration.objects.get(id=integration_id, team_id=team_id, kind="google-calendar")team = integration.team- access_token = _get_fresh_access_token(integration)- connected_email = (integration.config or {}).get("email", "")- internal_domain = _domain_of(connected_email)-- mark_calendar_sync_started(integration_id, team_id)- integration.refresh_from_db(fields=["config"])-counts = CalendarSyncCounts()- sync_token = (integration.config or {}).get(SYNC_TOKEN_CONFIG_KEY)try:- next_sync_token = _sync_events(- team, access_token, str(integration.integration_id), sync_token, internal_domain, counts- )- except SyncTokenExpired:- next_sync_token = _sync_events(- team, access_token, str(integration.integration_id), None, internal_domain, counts- )+ access_token = _get_fresh_access_token(integration)+ connected_email = (integration.config or {}).get("email", "")+ internal_domain = _domain_of(connected_email)++ mark_calendar_sync_started(integration_id, team_id)+ integration.refresh_from_db(fields=["config"])++ sync_token = (integration.config or {}).get(SYNC_TOKEN_CONFIG_KEY)+ try:+ next_sync_token = _sync_events(+ team, access_token, str(integration.integration_id), sync_token, internal_domain, counts+ )+ except SyncTokenExpired:+ next_sync_token = _sync_events(+ team, access_token, str(integration.integration_id), None, internal_domain, counts+ )- integration.config[SYNC_TOKEN_CONFIG_KEY] = next_sync_token- integration.save(update_fields=["config"])- mark_calendar_sync_completed(integration_id, team_id)+ update_calendar_sync_config(integration_id, team_id, {SYNC_TOKEN_CONFIG_KEY: next_sync_token})+ mark_calendar_sync_completed(integration_id, team_id)+ except Exception:+ mark_calendar_sync_failed(integration_id, team_id)+ raisereturn countsdiff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 218d514d8f16..fd3bc49e8bff 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -1477,11 +1477,22 @@ class CalendarSyncStatusSerializer(DataclassSerializer):read_only=True, allow_null=True, help_text="When the last sync run completed; null before the first sync.")is_syncing = serializers.BooleanField(read_only=True, help_text="Whether a sync run is currently in flight.")+ sync_interval_minutes = serializers.IntegerField(read_only=True, help_text="Minutes between scheduled syncs.")class Meta:dataclass = CalendarSyncStatusref_name = "CalendarSyncStatus"- fields = ["integration_id", "last_synced_at", "is_syncing"]+ fields = ["integration_id", "last_synced_at", "is_syncing", "sync_interval_minutes"]+++class CalendarSyncIntervalSerializer(serializers.Serializer):+ integration_id = serializers.IntegerField(help_text="Id of the connected Google account.")+ sync_interval_minutes = serializers.IntegerField(help_text="Minutes between scheduled syncs: 5, 15, 30, or 60.")++ def validate_sync_interval_minutes(self, value: int) -> int:+ if value not in (5, 15, 30, 60):+ raise serializers.ValidationError("Choose 5, 15, 30, or 60 minutes.")+ return valueclass CalendarSyncTriggerSerializer(serializers.Serializer):diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex 87b602d7cbfe..ab52598659f6 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -83,6 +83,7 @@ from products.customer_analytics.backend.presentation.views.serializers import (AccountTrackRuleRunSerializer,AccountTrackRulesConfigSerializer,CalendarSyncBackfillSerializer,+ CalendarSyncIntervalSerializer,CalendarSyncStatusSerializer,CalendarSyncTriggerResponseSerializer,CalendarSyncTriggerSerializer,@@ -2799,6 +2800,22 @@ class CalendarSyncViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viestatuses = api.list_calendar_sync_statuses(self.team_id)return Response(CalendarSyncStatusSerializer(instance=statuses, many=True).data)+ @validated_request(+ request_serializer=CalendarSyncIntervalSerializer,+ responses={200: CalendarSyncIntervalSerializer},+ summary="Set Google account sync interval",+ )+ @action(methods=["POST"], detail=False, url_path="interval")+ def interval(self, request: ValidatedRequest, *args, **kwargs) -> Response:+ requesting_level = self.user_permissions.current_team.effective_membership_level+ if requesting_level is None or requesting_level < OrganizationMembership.Level.ADMIN:+ raise PermissionDenied("Only project admins can change Google account sync intervals.")+ integration_id = request.validated_data["integration_id"]+ interval_minutes = request.validated_data["sync_interval_minutes"]+ if not api.update_calendar_sync_interval(self.team_id, integration_id, interval_minutes):+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ return Response(CalendarSyncIntervalSerializer(instance=request.validated_data).data)+@validated_request(request_serializer=CalendarSyncBackfillSerializer,responses={200: OpenApiResponse(response=CalendarSyncTriggerResponseSerializer)},diff --git a/products/customer_analytics/backend/temporal/calendar_sync.py b/products/customer_analytics/backend/temporal/calendar_sync.pyindex e5aeade17f46..35ef124cc470 100644--- a/products/customer_analytics/backend/temporal/calendar_sync.py+++ b/products/customer_analytics/backend/temporal/calendar_sync.py@@ -31,7 +31,7 @@ logger = structlog.get_logger(__name__)CALENDAR_SYNC_COORDINATOR_SCHEDULE_ID = "customer-analytics-calendar-sync-coordinator-schedule"CALENDAR_SYNC_COORDINATOR_WORKFLOW_NAME = "customer-analytics-calendar-sync-coordinator"-COORDINATOR_INTERVAL_MINUTES = 60+COORDINATOR_INTERVAL_MINUTES = 5MAX_SYNCS_PER_RUN = 200BACKFILL_PAGES_PER_RUN = 100GOOGLE_WORKSPACE_RETRY_DELAY = timedelta(hours=1)@@ -106,10 +106,51 @@ class GoogleAccountBackfillOutput:def _collect_calendar_integrations() -> list[CalendarSyncInput]:# Deferred: keeps Django models out of the workflow sandbox import path.+ from django.utils import timezone # noqa: PLC0415+from posthog.models.integration import Integration # noqa: PLC0415- rows = Integration.objects.filter(kind="google-calendar").values_list("id", "team_id")[:MAX_SYNCS_PER_RUN]- return [CalendarSyncInput(integration_id=row[0], team_id=row[1]) for row in rows]+ from products.customer_analytics.backend.logic.calendar_sync import ( # noqa: PLC0415+ LAST_SYNCED_AT_CONFIG_KEY,+ SYNC_ATTEMPTED_AT_CONFIG_KEY,+ SYNC_RETRY_AT_CONFIG_KEY,+ SYNC_STALE_AFTER,+ SYNC_STARTED_AT_CONFIG_KEY,+ get_calendar_sync_interval,+ )++ now = timezone.now()+ due: list[tuple[datetime, int, int]] = []+ for integration in Integration.objects.filter(kind="google-calendar").only("id", "team_id", "config").iterator():+ config = integration.config or {}+ last_sync = _calendar_config_datetime(config.get(LAST_SYNCED_AT_CONFIG_KEY))+ attempted = _calendar_config_datetime(config.get(SYNC_ATTEMPTED_AT_CONFIG_KEY))+ started = _calendar_config_datetime(config.get(SYNC_STARTED_AT_CONFIG_KEY))+ retry = _calendar_config_datetime(config.get(SYNC_RETRY_AT_CONFIG_KEY))+ if retry and retry > now:+ continue+ if started and started > now - SYNC_STALE_AFTER and (last_sync is None or started > last_sync):+ continue+ last_run = max((date for date in (last_sync, attempted) if date), default=None)+ if last_run and last_run + timedelta(minutes=get_calendar_sync_interval(config)) > now:+ continue+ due.append((last_run or datetime.min.replace(tzinfo=now.tzinfo), integration.id, integration.team_id))++ due.sort()+ return [+ CalendarSyncInput(integration_id=integration_id, team_id=team_id)+ for _, integration_id, team_id in due[:MAX_SYNCS_PER_RUN]+ ]+++def _calendar_config_datetime(value: object) -> datetime | None:+ if not isinstance(value, str):+ return None+ try:+ parsed = datetime.fromisoformat(value)+ return parsed if parsed.tzinfo else None+ except ValueError:+ return None@activity.defn@@ -313,7 +354,7 @@ class GoogleAccountBackfillWorkflow:@workflow.defn(name=CALENDAR_SYNC_COORDINATOR_WORKFLOW_NAME)class CalendarSyncCoordinatorWorkflow:- """Hourly coordinator: one child per connected calendar.+ """Scheduled coordinator: one child per connected calendar.Child ids are deterministic per integration, so overlapping ticks can't sync thesame calendar concurrently (start fails with WorkflowAlreadyStartedError while adiff --git a/products/customer_analytics/backend/test/test_calendar_sync.py b/products/customer_analytics/backend/test/test_calendar_sync.pyindex cf5a0d483c87..3a07b27bf609 100644--- a/products/customer_analytics/backend/test/test_calendar_sync.py+++ b/products/customer_analytics/backend/test/test_calendar_sync.py@@ -1,12 +1,18 @@-from datetime import UTC, datetime+from datetime import UTC, datetime, timedelta+import time_machinefrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch+from django.utils import timezone+from parameterized import parameterized+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration+from products.customer_analytics.backend.logic import calendar_syncfrom products.customer_analytics.backend.models import Account, Meeting, MeetingParticipant, MeetingStatus+from products.customer_analytics.backend.temporal import calendar_sync as temporal_calendar_syncdef _event(**overrides) -> dict:@@ -39,8 +45,6 @@ class TestCalendarSync(BaseTest):self.integration = self._create_integration()def _create_integration(self):- from posthog.models.integration import Integration-return Integration.objects.create(team=self.team,kind="google-calendar",@@ -140,6 +144,92 @@ class TestCalendarSync(BaseTest):self.integration.refresh_from_db()assert self.integration.config["calendar_sync_token"] == "fresh"+ @parameterized.expand([(5,), (15,), (30,), (60,)])+ @time_machine.travel("2026-09-25T12:00:00Z", tick=False)+ def test_collector_honors_configured_cadence_boundary(self, interval_minutes: int) -> None:+ now = timezone.now()+ self.integration.config.update(+ {+ calendar_sync.SYNC_INTERVAL_CONFIG_KEY: interval_minutes,+ calendar_sync.LAST_SYNCED_AT_CONFIG_KEY: (+ now - timedelta(minutes=interval_minutes) + timedelta(seconds=1)+ ).isoformat(),+ }+ )+ self.integration.save(update_fields=["config"])++ assert temporal_calendar_sync._collect_calendar_integrations() == []++ self.integration.config[calendar_sync.LAST_SYNCED_AT_CONFIG_KEY] = (+ now - timedelta(minutes=interval_minutes)+ ).isoformat()+ self.integration.save(update_fields=["config"])+ selected = temporal_calendar_sync._collect_calendar_integrations()++ assert [item.integration_id for item in selected] == [self.integration.id]+ self.integration.refresh_from_db(fields=["config"])+ assert calendar_sync.SYNC_ATTEMPTED_AT_CONFIG_KEY not in self.integration.config++ @parameterized.expand([("google_error", False), ("token_refresh_failed", True)])+ @time_machine.travel("2026-09-25T12:00:00Z", tick=False)+ def test_failed_sync_clears_active_marker_and_waits_for_its_cadence(+ self, _name: str, token_refresh_failed: bool+ ) -> None:+ self.integration.config[calendar_sync.SYNC_INTERVAL_CONFIG_KEY] = 5+ if token_refresh_failed:+ self.integration.errors = ERROR_TOKEN_REFRESH_FAILED+ self.integration.save(update_fields=["config", "errors"])+ error_response = MagicMock(status_code=500, text="Google Calendar unavailable")++ with self.assertRaises(calendar_sync.CalendarSyncError):+ self._sync([error_response])++ self.integration.refresh_from_db(fields=["config"])+ assert calendar_sync.SYNC_STARTED_AT_CONFIG_KEY not in self.integration.config+ assert self.integration.config[calendar_sync.SYNC_ATTEMPTED_AT_CONFIG_KEY] == timezone.now().isoformat()+ assert temporal_calendar_sync._collect_calendar_integrations() == []++ with time_machine.travel("2026-09-25T12:05:00Z", tick=False):+ selected = temporal_calendar_sync._collect_calendar_integrations()++ assert [item.integration_id for item in selected] == [self.integration.id]++ @time_machine.travel("2026-09-25T12:00:00Z", tick=False)+ def test_collector_waits_for_retry_window(self) -> None:+ self.integration.config[calendar_sync.SYNC_RETRY_AT_CONFIG_KEY] = (+ timezone.now() + timedelta(minutes=5)+ ).isoformat()+ self.integration.save(update_fields=["config"])++ assert temporal_calendar_sync._collect_calendar_integrations() == []++ with time_machine.travel("2026-09-25T12:05:00Z", tick=False):+ selected = temporal_calendar_sync._collect_calendar_integrations()++ assert [item.integration_id for item in selected] == [self.integration.id]++ @time_machine.travel("2026-09-25T12:00:00Z", tick=False)+ def test_collector_limits_each_run_to_the_two_hundred_longest_waiting_accounts(self) -> None:+ self.integration.config[calendar_sync.LAST_SYNCED_AT_CONFIG_KEY] = (+ timezone.now() - timedelta(hours=1)+ ).isoformat()+ self.integration.save(update_fields=["config"])+ Integration.objects.bulk_create(+ [+ Integration(+ team=self.team,+ kind="google-calendar",+ integration_id=f"google-sub-{index + 2}",+ )+ for index in range(temporal_calendar_sync.MAX_SYNCS_PER_RUN)+ ]+ )++ selected = temporal_calendar_sync._collect_calendar_integrations()++ assert len(selected) == 200+ assert self.integration.id not in [item.integration_id for item in selected]+def test_backfill_uses_the_date_range_without_changing_the_incremental_cursor(self) -> None:self.integration.config["calendar_sync_token"] = "existing"self.integration.save(update_fields=["config"])diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex dd70c93b41de..e31eb8f8d09f 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -3527,6 +3527,46 @@ class TestCalendarSyncViewSet(APIBaseTest):},)+ def test_sync_interval_defaults_and_is_scoped_to_one_account(self):+ self._become_admin()+ first = self._create_syncable_integration()+ second = Integration.objects.create(team=self.team, kind="google-calendar", integration_id="second-account")+ endpoint = f"/api/environments/{self.team.id}/calendar_sync/"+ initial = self.client.get(endpoint)+ self.assertEqual({row["sync_interval_minutes"] for row in initial.json()}, {60})++ response = self.client.post(f"{endpoint}interval/", {"integration_id": first.id, "sync_interval_minutes": 15})+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ {row["integration_id"]: row["sync_interval_minutes"] for row in self.client.get(endpoint).json()},+ {first.id: 15, second.id: 60},+ )++ def test_sync_interval_rejects_invalid_or_unowned_integrations(self):+ self._become_admin()+ integration = self._create_syncable_integration()+ endpoint = f"/api/environments/{self.team.id}/calendar_sync/interval/"+ self.assertEqual(+ self.client.post(endpoint, {"integration_id": integration.id, "sync_interval_minutes": 10}).status_code,+ status.HTTP_400_BAD_REQUEST,+ )+ other_team = Team.objects.create(organization=self.organization, name="Other team")+ other = self._create_syncable_integration(team=other_team)+ wrong_kind = Integration.objects.create(team=self.team, kind="slack", integration_id="wrong-kind")+ for integration_id in (other.id, wrong_kind.id):+ self.assertEqual(+ self.client.post(endpoint, {"integration_id": integration_id, "sync_interval_minutes": 5}).status_code,+ status.HTTP_404_NOT_FOUND,+ )++ def test_sync_interval_requires_project_admin(self):+ integration = self._create_syncable_integration()+ response = self.client.post(+ f"/api/environments/{self.team.id}/calendar_sync/interval/",+ {"integration_id": integration.id, "sync_interval_minutes": 5},+ )+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+def test_sync_now_starts_the_workflow_for_a_team_owned_integration(self):self._become_admin()integration = Integration.objects.create(team=self.team, kind="google-calendar", integration_id="sub-1")diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex c28f303eceb4..c40b7a32e3a6 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -2491,6 +2491,8 @@ export interface CalendarSyncStatusApi {readonly last_synced_at: string | null/** Whether a sync run is currently in flight. */readonly is_syncing: boolean+ /** Minutes between scheduled syncs. */+ readonly sync_interval_minutes: number}export interface CalendarSyncBackfillApi {@@ -2525,6 +2527,13 @@ export interface CalendarSyncTriggerResponseApi {status: CalendarSyncTriggerResponseStatusEnumApi}+export interface CalendarSyncIntervalApi {+ /** Id of the connected Google account. */+ integration_id: number+ /** Minutes between scheduled syncs: 5, 15, 30, or 60. */+ sync_interval_minutes: number+}+/*** Request body of the calendar sync-now trigger.*/diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex a392ea53b80f..66e77832620c 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -39,6 +39,7 @@ import type {AnnouncementChannelApi,AnnouncementsListParams,CalendarSyncBackfillApi,+ CalendarSyncIntervalApi,CalendarSyncStatusApi,CalendarSyncTriggerApi,CalendarSyncTriggerResponseApi,@@ -1111,6 +1112,28 @@ export const calendarSyncBackfillCreate = async (})}+export const getCalendarSyncIntervalCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/calendar_sync/interval/`+}++/**+ * Calendar-sync controls for Customer analytics settings. Sync runs on an hourly+ * Temporal schedule; this surface only offers the manual "sync now" escape hatch.+ * @summary Set Google account sync interval+ */+export const calendarSyncIntervalCreate = async (+ projectId: string,+ calendarSyncIntervalApi: CalendarSyncIntervalApi,+ options?: RequestInit+): Promise<CalendarSyncIntervalApi> => {+ return apiMutator<CalendarSyncIntervalApi>(getCalendarSyncIntervalCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(calendarSyncIntervalApi),+ })+}+export const getCalendarSyncSyncNowCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/calendar_sync/sync_now/`}diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex 9f35f7f94b14..497e5bfa1f1d 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -449,6 +449,16 @@ export const CalendarSyncBackfillCreateBody = /* @__PURE__ */ zod.object({end_date: zod.iso.date().describe('Final UTC date to include. Cannot be after today.'),})+/**+ * Calendar-sync controls for Customer analytics settings. Sync runs on an hourly+ * Temporal schedule; this surface only offers the manual "sync now" escape hatch.+ * @summary Set Google account sync interval+ */+export const CalendarSyncIntervalCreateBody = /* @__PURE__ */ zod.object({+ integration_id: zod.number().describe('Id of the connected Google account.'),+ sync_interval_minutes: zod.number().describe('Minutes between scheduled syncs: 5, 15, 30, or 60.'),+})+/*** Start a sync run for one connected Google Calendar immediately, outside the hourly schedule.* @summary Sync a connected calendar nowdiff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsxindex f82c5c827a0d..9c5f8fbf2d48 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'import { IconRefresh, IconRewind, IconTrash } from '@posthog/icons'-import { LemonBanner, LemonButton } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonSelect } from '@posthog/lemon-ui'import api from 'lib/api'import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'@@ -18,6 +18,17 @@ import { calendarSyncLogic } from './calendarSyncLogic'const GMAIL_READONLY_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly'+function getSyncIntervalDisabledReason(+ hasSyncStatus: boolean,+ statusesLoading: boolean,+ savingInterval: boolean+): string | undefined {+ if (!hasSyncStatus) {+ return statusesLoading ? 'Loading sync frequency...' : 'Sync frequency unavailable'+ }+ return savingInterval ? 'Saving...' : undefined+}+export function CalendarSyncConfig(): JSX.Element {const { integrations, integrationsLoading } = useValues(integrationsLogic)const { deleteIntegration } = useActions(integrationsLogic)@@ -29,9 +40,18 @@ export function CalendarSyncConfig(): JSX.Element {backfillEndDate,backfillDateError,backfillSubmitting,+ savingIntervalIds,+ statusesLoading,} = useValues(calendarSyncLogic)- const { syncNow, openBackfill, closeBackfill, setBackfillStartDate, setBackfillEndDate, submitBackfill } =- useActions(calendarSyncLogic)+ const {+ syncNow,+ openBackfill,+ closeBackfill,+ setBackfillStartDate,+ setBackfillEndDate,+ submitBackfill,+ saveInterval,+ } = useActions(calendarSyncLogic)const { user } = useValues(userLogic)const adminRestrictedReason = useRestrictedArea({scope: RestrictionScope.Project,@@ -101,6 +121,32 @@ export function CalendarSyncConfig(): JSX.Element {// A custom suffix replaces IntegrationView's built-in Disconnect button, so it returns here.suffix={<div className="flex flex-row flex-wrap items-center justify-end gap-2">+ {!adminRestrictedReason && (+ <label className="flex items-center gap-2 text-xs whitespace-nowrap">+ Sync every+ <LemonSelect<number>+ data-attr={`google-account-sync-interval-${integration.id}`}+ value={syncStatus?.sync_interval_minutes}+ placeholder={+ statusesLoading+ ? 'Loading sync frequency...'+ : 'Sync frequency unavailable'+ }+ options={[+ { value: 5, label: '5 minutes' },+ { value: 15, label: '15 minutes' },+ { value: 30, label: '30 minutes' },+ { value: 60, label: '1 hour' },+ ]}+ disabledReason={getSyncIntervalDisabledReason(+ !!syncStatus,+ statusesLoading,+ savingIntervalIds.includes(integration.id)+ )}+ onChange={(value) => saveInterval(integration.id, value)}+ />+ </label>+ )}<span className="text-xs text-secondary whitespace-nowrap">{isSyncing ? ('Syncing Google account...'diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.tsindex 3c34c09cae66..b6cd2b1b3b03 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.ts@@ -8,6 +8,7 @@ import { teamLogic } from 'scenes/teamLogic'import {calendarSyncBackfillCreate,+ calendarSyncIntervalCreate,calendarSyncList,calendarSyncSyncNowCreate,} from 'products/customer_analytics/frontend/generated/api'@@ -49,6 +50,8 @@ export interface calendarSyncLogicValues {backfillIntegrationId: number | nullbackfillStartDate: string | nullbackfillSubmitting: boolean+ savingIntervalById: Record<number, boolean>+ savingIntervalIds: number[]statusByIntegrationId: Record<number, CalendarSyncStatusApi>statuses: CalendarSyncStatusApi[]statusesLoading: boolean@@ -64,6 +67,9 @@ export interface calendarSyncLogicActions {closeBackfill: () => {value: true}+ intervalSaveFinished: (integrationId: number) => {+ integrationId: number+ }loadStatuses: () => anyloadStatusesFailure: (error: string,@@ -84,6 +90,13 @@ export interface calendarSyncLogicActions {integrationId: numberstartDate: string}+ saveInterval: (+ integrationId: number,+ intervalMinutes: number+ ) => {+ integrationId: number+ intervalMinutes: number+ }setBackfillEndDate: (endDate: string | null) => {endDate: string | null}@@ -112,6 +125,7 @@ export interface calendarSyncLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface calendarSyncLogicMeta {__keaTypeGenInternalSelectorTypes: {+ savingIntervalIds: (savingIntervalById: Record<number, boolean>) => number[]statusByIntegrationId: (statuses: CalendarSyncStatusApi[]) => Record<number, CalendarSyncStatusApi>triggeringIntegrationIds: (triggeredAtByIntegrationId: Record<number, number>) => number[]backfillDateError: (backfillStartDate: string | null, backfillEndDate: string | null) => string | null@@ -131,6 +145,8 @@ export const calendarSyncLogic = kea<calendarSyncLogicType>([values: [teamLogic, ['currentTeamId']],})),actions({+ saveInterval: (integrationId: number, intervalMinutes: number) => ({ integrationId, intervalMinutes }),+ intervalSaveFinished: (integrationId: number) => ({ integrationId }),syncNow: (integrationId: number) => ({ integrationId, triggeredAt: Date.now() }),triggerFinished: (integrationId: number) => ({ integrationId }),openBackfill: (integrationId: number) => {@@ -168,6 +184,14 @@ export const calendarSyncLogic = kea<calendarSyncLogicType>([],})),reducers({+ savingIntervalById: [+ {} as Record<number, boolean>,+ {+ saveInterval: (state, { integrationId }) => ({ ...state, [integrationId]: true }),+ intervalSaveFinished: (state, { integrationId }) =>+ Object.fromEntries(Object.entries(state).filter(([id]) => Number(id) !== integrationId)),+ },+ ],triggeredAtByIntegrationId: [{} as Record<number, number>,{@@ -209,6 +233,10 @@ export const calendarSyncLogic = kea<calendarSyncLogicType>([],}),selectors({+ savingIntervalIds: [+ (s) => [s.savingIntervalById],+ (savingIntervalById: Record<number, boolean>): number[] => Object.keys(savingIntervalById).map(Number),+ ],statusByIntegrationId: [(s) => [s.statuses],(statuses: CalendarSyncStatusApi[]): Record<number, CalendarSyncStatusApi> =>@@ -226,6 +254,20 @@ export const calendarSyncLogic = kea<calendarSyncLogicType>([],}),listeners(({ actions, values }) => ({+ saveInterval: async ({ integrationId, intervalMinutes }) => {+ try {+ await calendarSyncIntervalCreate(String(values.currentTeamId), {+ integration_id: integrationId,+ sync_interval_minutes: intervalMinutes,+ })+ actions.loadStatuses()+ } catch (error) {+ posthog.captureException(error as Error, { scope: 'calendarSyncLogic.saveInterval' })+ lemonToast.error('Could not save sync frequency. Try again.')+ } finally {+ actions.intervalSaveFinished(integrationId)+ }+ },// A sync in flight (or a trigger awaiting its server-side start marker) self-perpetuates// the status poll; the breakpoint cancels it on unmount.loadStatusesSuccess: async (_, breakpoint) => {diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex ffdb6794d31e..35cf594611f2 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -547,6 +547,9 @@ tools:calendar-sync-backfill-create:operation: calendar_sync_backfill_createenabled: false+ calendar-sync-interval-create:+ operation: calendar_sync_interval_create+ enabled: falsecalendar-sync-list:operation: calendar_sync_listenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 389ed288774a..7cf70b318217 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -17758,6 +17758,13 @@ export namespace Schemas {end_date: string;}+ export interface CalendarSyncInterval {+ /** Id of the connected Google account. */+ integration_id: number;+ /** Minutes between scheduled syncs: 5, 15, 30, or 60. */+ sync_interval_minutes: number;+ }+/*** Sync state of one connected calendar (read-only).*/@@ -17771,6 +17778,8 @@ export namespace Schemas {readonly last_synced_at: string | null;/** Whether a sync run is currently in flight. */readonly is_syncing: boolean;+ /** Minutes between scheduled syncs. */+ readonly sync_interval_minutes: number;}/**