: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): sync Gmail account email (#84534)
Arthur Moreira de Deus48716aa2ba73
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex 1ab4c237070a..b95bd6f1a93b 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -456,17 +456,17 @@ export const SETTINGS_MAP: SettingSection[] = [},{id: 'customer-analytics-calendar-sync',- title: 'Calendar sync',+ title: 'Google account sync',description:- 'Connect your Google Calendar to sync meetings with customers into their accounts. Each team member connects their own calendar.',+ 'Connect your Google account to sync customer meetings and email to matching accounts. Each team member connects their own account.',component: <CalendarSyncConfig />,flag: ['CUSTOMER_ANALYTICS', 'CUSTOMER_ANALYTICS_CSP'],- keywords: ['calendar', 'meetings', 'google', 'sync', 'accounts'],+ keywords: ['calendar', 'email', 'meetings', 'google', 'sync', 'accounts'],},{id: 'customer-analytics-email-sync',- title: 'Email sync',- description: 'Connect your work email to show customer conversations on matching accounts.',+ title: 'Email forwarding',+ description: 'Manage existing email forwarding connections.',component: <CustomerEmailConfig />,flag: ['CUSTOMER_ANALYTICS', 'CUSTOMER_ANALYTICS_CSP'],keywords: ['email', 'inbox', 'forwarding', 'sync', 'accounts'],diff --git a/posthog/egress/google_workspace/__init__.py b/posthog/egress/google_workspace/__init__.pynew file mode 100644index 000000000000..9bca9bda3902--- /dev/null+++ b/posthog/egress/google_workspace/__init__.py@@ -0,0 +1,3 @@+from posthog.egress.google_workspace.transport import google_workspace_request++__all__ = ["google_workspace_request"]diff --git a/posthog/egress/google_workspace/limiter.py b/posthog/egress/google_workspace/limiter.pynew file mode 100644index 000000000000..24113438029f--- /dev/null+++ b/posthog/egress/google_workspace/limiter.py@@ -0,0 +1,27 @@+from django.conf import settings++from posthog.egress.limiter.outbound import get_outbound_rate_limiter+from posthog.egress.limiter.policies import Priority, RatePolicy, register_policy++GOOGLE_WORKSPACE_DOMAIN = "google_workspace"+++def _google_workspace_policy(_key: str) -> RatePolicy:+ return RatePolicy(+ limits=(+ (int(getattr(settings, "GOOGLE_WORKSPACE_EGRESS_PER_MINUTE_BUDGET", 250)), 60.0),+ (int(getattr(settings, "GOOGLE_WORKSPACE_EGRESS_HOURLY_BUDGET", 10_000)), 3600.0),+ ),+ in_memory_divider=4,+ )+++register_policy(GOOGLE_WORKSPACE_DOMAIN, _google_workspace_policy)+++def consume_google_workspace_sync(account_id: str, *, priority: Priority, source: str) -> bool:+ return get_outbound_rate_limiter().consume_sync(+ f"{GOOGLE_WORKSPACE_DOMAIN}:account:{account_id}",+ priority=priority,+ source=source,+ )diff --git a/posthog/egress/google_workspace/observability.py b/posthog/egress/google_workspace/observability.pynew file mode 100644index 000000000000..2c66ed44928c--- /dev/null+++ b/posthog/egress/google_workspace/observability.py@@ -0,0 +1,79 @@+import requests+from prometheus_client import Counter, Gauge++from posthog.egress.google_workspace.limiter import GOOGLE_WORKSPACE_DOMAIN+from posthog.egress.observability.observability import (+ EgressMetrics,+ EgressObservability,+ RateLimitSnapshot,+ register_egress_observability,+)++_metrics = EgressMetrics(+ request_counter=Counter(+ "google_workspace_api_requests",+ "Outbound Google Workspace API requests.",+ labelnames=["scope", "method", "endpoint", "status_code", "source"],+ ),+ remaining_gauge=Gauge(+ "google_workspace_api_rate_limit_remaining",+ "Last observed Google Workspace API rate-limit remaining value.",+ labelnames=["scope", "resource"],+ ),+ limit_gauge=Gauge(+ "google_workspace_api_rate_limit_limit",+ "Last observed Google Workspace API rate-limit ceiling.",+ labelnames=["scope", "resource"],+ ),+ reset_gauge=Gauge(+ "google_workspace_api_rate_limit_reset_at",+ "Last observed Google Workspace API rate-limit reset timestamp.",+ labelnames=["scope", "resource"],+ ),+)+++def _parse_google_workspace_rate_limit(_response: requests.Response) -> RateLimitSnapshot:+ return RateLimitSnapshot(resource="api")+++google_workspace_egress = EgressObservability(+ GOOGLE_WORKSPACE_DOMAIN,+ _metrics,+ _parse_google_workspace_rate_limit,+)+register_egress_observability(google_workspace_egress)+++def record_google_workspace_api_response(+ response: requests.Response,+ *,+ source: str,+ account_id: str,+ method: str,+ endpoint: str,+) -> None:+ google_workspace_egress.record_response(+ response,+ source=source,+ scope=account_id,+ method=method,+ endpoint=endpoint,+ )+++def record_google_workspace_api_exception(+ *,+ source: str,+ account_id: str,+ method: str,+ endpoint: str,+ url: str,+) -> None:+ google_workspace_egress.record_exception(+ source=source,+ scope=account_id,+ method=method,+ endpoint=endpoint,+ url=url,+ )diff --git a/posthog/egress/google_workspace/transport.py b/posthog/egress/google_workspace/transport.pynew file mode 100644index 000000000000..276cbc09883a--- /dev/null+++ b/posthog/egress/google_workspace/transport.py@@ -0,0 +1,88 @@+from typing import Any++import requests++from posthog.egress.google_workspace.limiter import consume_google_workspace_sync+from posthog.egress.google_workspace.observability import (+ record_google_workspace_api_exception,+ record_google_workspace_api_response,+)+from posthog.egress.limiter.policies import Priority+from posthog.egress.transport.transport import EgressBudgetExhausted, EgressClient+++class GoogleWorkspaceEgressBudgetExhausted(EgressBudgetExhausted):+ pass+++class GoogleWorkspaceClient(EgressClient):+ def _standard_headers(self) -> dict[str, str]:+ return {"Accept": "application/json"}++ def _consume(self, scope: str, priority: Priority, source: str, url: str) -> bool:+ return consume_google_workspace_sync(scope, priority=priority, source=source)++ def _record_response(+ self,+ response: requests.Response,+ *,+ source: str,+ scope: str | None,+ method: str,+ endpoint: str | None,+ ) -> None:+ record_google_workspace_api_response(+ response,+ source=source,+ account_id=scope or "",+ method=method,+ endpoint=endpoint or "unknown",+ )++ def _record_exception(+ self,+ *,+ source: str,+ scope: str | None,+ method: str,+ url: str,+ endpoint: str | None,+ ) -> None:+ record_google_workspace_api_exception(+ source=source,+ account_id=scope or "",+ method=method,+ endpoint=endpoint or "unknown",+ url=url,+ )++ def _budget_exhausted_error(self, scope: str) -> GoogleWorkspaceEgressBudgetExhausted:+ return GoogleWorkspaceEgressBudgetExhausted("Google Workspace egress budget exhausted")+++_google_workspace_client = GoogleWorkspaceClient()+++def google_workspace_request(+ method: str,+ url: str,+ *,+ access_token: str,+ account_id: str,+ source: str,+ endpoint: str,+ priority: Priority = Priority.BATCH,+ timeout: float | tuple[float, float] | None = None,+ **kwargs: Any,+) -> requests.Response:+ return _google_workspace_client.request(+ method,+ url,+ source=source,+ headers={"Authorization": f"Bearer {access_token}"},+ scope=account_id,+ priority=priority,+ endpoint=endpoint,+ timeout=timeout,+ **kwargs,+ )diff --git a/posthog/models/integration.py b/posthog/models/integration.pyindex 83053915d4e5..57371d99cf4f 100644--- a/posthog/models/integration.py+++ b/posthog/models/integration.py@@ -1077,7 +1077,7 @@ class OauthIntegration:token_url="https://oauth2.googleapis.com/token",client_id=settings.GOOGLE_CALENDAR_APP_CLIENT_ID,client_secret=settings.GOOGLE_CALENDAR_APP_CLIENT_SECRET,- scope="https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/userinfo.email",+ scope="https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/userinfo.email",id_path="sub",name_path="email",)diff --git a/posthog/models/test/test_integration_model.py b/posthog/models/test/test_integration_model.pyindex b9ea80c115d4..776f3326d653 100644--- a/posthog/models/test/test_integration_model.py+++ b/posthog/models/test/test_integration_model.py@@ -393,7 +393,7 @@ class TestOauthIntegrationModel(BaseTest):url = OauthIntegration.authorize_url("google-calendar", token="state_token", next="/projects/test")assert (url- == "https://accounts.google.com/o/oauth2/v2/auth?client_id=google-calendar-client-id&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&redirect_uri=https%3A%2F%2Flocalhost%3A8010%2Fintegrations%2Fgoogle-calendar%2Fcallback&response_type=code&state=next%3D%252Fprojects%252Ftest%26token%3Dstate_token&access_type=offline&prompt=consent"+ == "https://accounts.google.com/o/oauth2/v2/auth?client_id=google-calendar-client-id&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar.readonly+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.readonly+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&redirect_uri=https%3A%2F%2Flocalhost%3A8010%2Fintegrations%2Fgoogle-calendar%2Fcallback&response_type=code&state=next%3D%252Fprojects%252Ftest%26token%3Dstate_token&access_type=offline&prompt=consent")@patch("posthog.models.integration.requests.post")diff --git a/products/conversations/README.md b/products/conversations/README.mdindex b21418b1d8e1..372f45a29356 100644--- a/products/conversations/README.md+++ b/products/conversations/README.md@@ -2,11 +2,17 @@## Customer communication email+### Google account sync++A Customer Analytics Google account connection grants read access to Calendar and Gmail. The hourly sync imports customer meetings and messages from Inbox and Sent into matching accounts. The first run imports up to 100 messages from the previous 30 days. Later runs use the Gmail history cursor and do not store internal-only messages.++### Email forwarding+Customer communication channels use a unique PostHog forwarding address. New channels remain pending until their owner completes Gmail forwarding confirmation.While setup is pending, the inbound webhook discards normal email. It stores only a short-lived Google confirmation action after Mailgun verifies the webhook, Google SPF and DKIM pass, the source mailbox matches the channel, and the action uses the expected Google host. The encrypted setup record is visible only through the owner-scoped setup flow and is deleted after use or expiration.-After confirmation, incoming messages are stored as email threads. Customer analytics links those threads to matching accounts before exposing them in the account view.+After confirmation, incoming messages are stored as email threads. Customer Analytics links those threads to matching accounts before exposing them in the account view.## Management commandsdiff --git a/products/conversations/backend/facade/api.py b/products/conversations/backend/facade/api.pyindex 4b5ed1abc6a0..2d4221532c94 100644--- a/products/conversations/backend/facade/api.py+++ b/products/conversations/backend/facade/api.py@@ -59,6 +59,10 @@ class _EmailThreadWithFacadePrefetch(Protocol):facade_participants: list[EmailThreadParticipant]+class GoogleAccountEmailSyncError(Exception):+ pass++class SupportMessageSendError(Exception):"""Slack rejected a SupportHog bot message.@@ -72,6 +76,18 @@ class SupportMessageSendError(Exception):self.retry_after = retry_after+def sync_google_account_email(integration_id: int, team_id: int) -> None:+ from products.conversations.backend.services.gmail_sync import ( # noqa: PLC0415 -- avoids the Conversations and Customer Analytics facade cycle+ GmailSyncError,+ sync_gmail_integration,+ )++ try:+ sync_gmail_integration(integration_id, team_id)+ except GmailSyncError as error:+ raise GoogleAccountEmailSyncError(str(error)) from error++def list_support_bot_channels(team_id: int, *, members_only: bool = False) -> list[SupportChannel]:"""Slack channels the SupportHog bot can see for this team, sorted by name.diff --git a/products/conversations/backend/services/email_thread_ingestion.py b/products/conversations/backend/services/email_thread_ingestion.pyindex dd829cee978c..710c24831987 100644--- a/products/conversations/backend/services/email_thread_ingestion.py+++ b/products/conversations/backend/services/email_thread_ingestion.py@@ -214,6 +214,8 @@ def _ingest_customer_email_once(channel: EmailChannel,email: ParsedEmail,direction: EmailThreadMessageDirection,+ source_type: str,+ source_id: str | None,) -> EmailThreadIngestionResult:existing_message = _find_existing_message(team_id=team_id, email=email)if existing_message is not None:@@ -255,8 +257,8 @@ def _ingest_customer_email_once(cc_recipients=[recipient.as_dict() for recipient in email.cc_recipients],sender_authenticated=email.sender_authenticated,direction=direction,- source_type="mailgun",- source_id=_mailgun_source_id(email.message_id),+ source_type=source_type,+ source_id=source_id or _mailgun_source_id(email.message_id),)_upsert_participants(team_id=team_id, thread=thread, channel=channel, email=email)_update_thread_summary(thread=thread, email=email, content=content)@@ -269,6 +271,8 @@ def ingest_customer_email(channel: EmailChannel,email: ParsedEmail,direction: EmailThreadMessageDirection,+ source_type: str = "mailgun",+ source_id: str | None = None,) -> EmailThreadIngestionResult:try:with transaction.atomic():@@ -277,6 +281,8 @@ def ingest_customer_email(channel=channel,email=email,direction=direction,+ source_type=source_type,+ source_id=source_id,)except IntegrityError:existing_message = _find_existing_message(team_id=team_id, email=email)diff --git a/products/conversations/backend/services/gmail_sync.py b/products/conversations/backend/services/gmail_sync.pynew file mode 100644index 000000000000..501b88764383--- /dev/null+++ b/products/conversations/backend/services/gmail_sync.py@@ -0,0 +1,547 @@+import re+import base64+import binascii+from collections.abc import Callable+from datetime import UTC, datetime+from email.header import decode_header, make_header+from email.utils import getaddresses, parseaddr+from html import unescape+from typing import Any++from django.utils import timezone+from django.utils.html import strip_tags++import requests++from posthog.dataclasses import frozen+from posthog.egress.google_workspace import google_workspace_request+from posthog.models.integration import ERROR_TOKEN_REFRESH_FAILED, Integration, OauthIntegration+from posthog.models.organization import OrganizationMembership++from products.conversations.backend.models import EmailChannel, EmailChannelKind, EmailThreadMessageDirection+from products.conversations.backend.services.email_thread_ingestion import (+ EmailAddress,+ ParsedEmail,+ ingest_customer_email,+)++GMAIL_READONLY_SCOPE = "https://www.googleapis.com/auth/gmail.readonly"+GMAIL_HISTORY_ID_CONFIG_KEY = "gmail_history_id"+GMAIL_LAST_SYNCED_AT_CONFIG_KEY = "gmail_last_synced_at"+GMAIL_HISTORY_START_ID_CONFIG_KEY = "gmail_history_start_id"+GMAIL_HISTORY_PAGE_TOKEN_CONFIG_KEY = "gmail_history_page_token"+GMAIL_HISTORY_TARGET_ID_CONFIG_KEY = "gmail_history_target_id"+GMAIL_PENDING_MESSAGE_IDS_CONFIG_KEY = "gmail_pending_message_ids"+GMAIL_API_BASE_URL = "https://gmail.googleapis.com/gmail/v1/users/me"+INITIAL_IMPORT_QUERY = "{in:inbox in:sent} newer_than:30d"+INITIAL_IMPORT_LIMIT = 100+HISTORY_PAGE_SIZE = 100+HISTORY_MESSAGE_BATCH_SIZE = 100+MAX_ATTACHMENT_BACKED_BODY_PARTS = 4+_MESSAGE_ID_RE = re.compile(r"<[^<>\s]+>")+++class GmailSyncError(Exception):+ pass+++class _GmailBodyPartLimitExceeded(Exception):+ pass+++@frozen+class _EmailBodies:+ plain: str+ html: str+++def integration_has_gmail_scope(integration: Integration) -> bool:+ scopes = integration.config.get("scope") or ""+ return GMAIL_READONLY_SCOPE in scopes.split()+++def sync_gmail_integration(integration_id: int, team_id: int) -> None:+ integration = Integration.objects.select_related("team", "created_by").get(+ id=integration_id,+ team_id=team_id,+ kind="google-calendar",+ )+ if not integration_has_gmail_scope(integration) or not _has_active_owner(integration):+ return++ access_token = _get_fresh_access_token(integration)+ channel = _email_channel(integration)+ internal_emails = _organization_member_emails(integration)+ history_id = integration.config.get(GMAIL_HISTORY_ID_CONFIG_KEY)++ if history_id:+ next_history_id = _sync_history(+ integration=integration,+ channel=channel,+ access_token=access_token,+ start_history_id=str(history_id),+ internal_emails=internal_emails,+ )+ else:+ next_history_id = _initial_sync(+ integration=integration,+ channel=channel,+ access_token=access_token,+ internal_emails=internal_emails,+ )++ if next_history_id is None:+ return++ integration.refresh_from_db(fields=["config"])+ integration.config[GMAIL_HISTORY_ID_CONFIG_KEY] = next_history_id+ integration.config[GMAIL_LAST_SYNCED_AT_CONFIG_KEY] = timezone.now().isoformat()+ integration.save(update_fields=["config"])+++def _has_active_owner(integration: Integration) -> bool:+ owner = integration.created_by+ return bool(owner and owner.is_active and owner.teams.filter(id=integration.team_id).exists())+++def _get_fresh_access_token(integration: Integration) -> str:+ oauth = OauthIntegration(integration)+ if integration.errors != ERROR_TOKEN_REFRESH_FAILED and oauth.access_token_expired():+ oauth.refresh_access_token()+ if integration.errors == ERROR_TOKEN_REFRESH_FAILED:+ raise GmailSyncError(f"Token refresh failed for integration {integration.id}")+ token = integration.access_token+ if not token:+ raise GmailSyncError(f"Integration {integration.id} has no access token")+ return token+++def _email_channel(integration: Integration) -> EmailChannel:+ owner = integration.created_by+ email = str(integration.config.get("email") or "").strip().lower()+ if owner is None or not email or "@" not in email:+ raise GmailSyncError(f"Integration {integration.id} has no mailbox owner")++ name = " ".join(part for part in (owner.first_name, owner.last_name) if part).strip() or email+ return EmailChannel(+ team=integration.team,+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,+ owner=owner,+ inbound_token="",+ from_email=email,+ from_name=name,+ domain=email.rsplit("@", 1)[1],+ domain_verified=False,+ dns_records={},+ is_default=False,+ )+++def _organization_member_emails(integration: Integration) -> set[str]:+ return {+ email.lower()+ for email in OrganizationMembership.objects.filter(+ organization_id=integration.team.organization_id,+ user__is_active=True,+ ).values_list("user__email", flat=True)+ }+++def _initial_sync(+ *,+ integration: Integration,+ channel: EmailChannel,+ access_token: str,+ internal_emails: set[str],+) -> str:+ profile = _get_json(+ integration=integration,+ access_token=access_token,+ url=f"{GMAIL_API_BASE_URL}/profile",+ endpoint="/gmail/v1/users/me/profile",+ )+ history_id = str(profile.get("historyId") or "")+ if not history_id:+ raise GmailSyncError("Gmail profile did not include a history cursor")++ payload = _get_json(+ integration=integration,+ access_token=access_token,+ url=f"{GMAIL_API_BASE_URL}/messages",+ endpoint="/gmail/v1/users/me/messages",+ params={"q": INITIAL_IMPORT_QUERY, "maxResults": INITIAL_IMPORT_LIMIT},+ )+ _ingest_message_ids(+ integration=integration,+ channel=channel,+ access_token=access_token,+ message_ids=[str(message["id"]) for message in payload.get("messages", []) if message.get("id")],+ internal_emails=internal_emails,+ )+ return history_id+++def _sync_history(+ *,+ integration: Integration,+ channel: EmailChannel,+ access_token: str,+ start_history_id: str,+ internal_emails: set[str],+) -> str | None:+ processed_messages = 0+ while processed_messages < HISTORY_MESSAGE_BATCH_SIZE:+ integration.refresh_from_db(fields=["config"])+ config = integration.config or {}+ progress_start_id = str(config.get(GMAIL_HISTORY_START_ID_CONFIG_KEY) or start_history_id)+ page_token = str(config.get(GMAIL_HISTORY_PAGE_TOKEN_CONFIG_KEY) or "") or None+ target_history_id = str(config.get(GMAIL_HISTORY_TARGET_ID_CONFIG_KEY) or "") or None+ pending_message_ids = [str(message_id) for message_id in config.get(GMAIL_PENDING_MESSAGE_IDS_CONFIG_KEY) or []]++ if pending_message_ids:+ _ingest_message_id(+ integration=integration,+ channel=channel,+ access_token=access_token,+ gmail_message_id=pending_message_ids[0],+ internal_emails=internal_emails,+ )+ _save_history_progress(+ integration,+ start_history_id=progress_start_id,+ page_token=page_token,+ target_history_id=target_history_id,+ pending_message_ids=pending_message_ids[1:],+ )+ processed_messages += 1+ continue++ if target_history_id and page_token is None:+ _clear_history_progress(integration)+ return target_history_id++ params = {+ "startHistoryId": progress_start_id,+ "historyTypes": "messageAdded",+ "maxResults": HISTORY_PAGE_SIZE,+ }+ if page_token:+ params["pageToken"] = page_token+ response = _request(+ integration=integration,+ access_token=access_token,+ url=f"{GMAIL_API_BASE_URL}/history",+ endpoint="/gmail/v1/users/me/history",+ params=params,+ )+ if response.status_code == 404:+ _clear_history_progress(integration)+ return _initial_sync(+ integration=integration,+ channel=channel,+ access_token=access_token,+ internal_emails=internal_emails,+ )+ payload = _response_json(response, "Gmail history")+ message_ids = list(+ dict.fromkeys(+ str(added["message"]["id"])+ for history in payload.get("history", [])+ for added in history.get("messagesAdded", [])+ if added.get("message", {}).get("id")+ )+ )+ _save_history_progress(+ integration,+ start_history_id=progress_start_id,+ page_token=str(payload.get("nextPageToken") or "") or None,+ target_history_id=str(payload.get("historyId") or target_history_id or progress_start_id),+ pending_message_ids=message_ids,+ )++ return None+++def _save_history_progress(+ integration: Integration,+ *,+ start_history_id: str,+ page_token: str | None,+ target_history_id: str | None,+ pending_message_ids: list[str],+) -> None:+ integration.refresh_from_db(fields=["config"])+ integration.config[GMAIL_HISTORY_START_ID_CONFIG_KEY] = start_history_id+ integration.config[GMAIL_HISTORY_PAGE_TOKEN_CONFIG_KEY] = page_token+ integration.config[GMAIL_HISTORY_TARGET_ID_CONFIG_KEY] = target_history_id+ integration.config[GMAIL_PENDING_MESSAGE_IDS_CONFIG_KEY] = pending_message_ids+ integration.save(update_fields=["config"])+++def _clear_history_progress(integration: Integration) -> None:+ integration.refresh_from_db(fields=["config"])+ for key in (+ GMAIL_HISTORY_START_ID_CONFIG_KEY,+ GMAIL_HISTORY_PAGE_TOKEN_CONFIG_KEY,+ GMAIL_HISTORY_TARGET_ID_CONFIG_KEY,+ GMAIL_PENDING_MESSAGE_IDS_CONFIG_KEY,+ ):+ integration.config.pop(key, None)+ integration.save(update_fields=["config"])+++def _ingest_message_ids(+ *,+ integration: Integration,+ channel: EmailChannel,+ access_token: str,+ message_ids: list[str],+ internal_emails: set[str],+) -> None:+ for gmail_message_id in message_ids:+ _ingest_message_id(+ integration=integration,+ channel=channel,+ access_token=access_token,+ gmail_message_id=gmail_message_id,+ internal_emails=internal_emails,+ )+++def _ingest_message_id(+ *,+ integration: Integration,+ channel: EmailChannel,+ access_token: str,+ gmail_message_id: str,+ internal_emails: set[str],+) -> None:+ payload = _get_json(+ integration=integration,+ access_token=access_token,+ url=f"{GMAIL_API_BASE_URL}/messages/{gmail_message_id}",+ endpoint="/gmail/v1/users/me/messages/{message_id}",+ params={"format": "full"},+ )++ def load_attachment_data(attachment_id: str) -> str:+ attachment = _get_json(+ integration=integration,+ access_token=access_token,+ url=f"{GMAIL_API_BASE_URL}/messages/{gmail_message_id}/attachments/{attachment_id}",+ endpoint="/gmail/v1/users/me/messages/{message_id}/attachments/{attachment_id}",+ )+ return str(attachment.get("data") or "")++ try:+ parsed = _parse_gmail_message(+ payload,+ channel.from_email,+ str(integration.integration_id),+ load_attachment_data=load_attachment_data,+ )+ except _GmailBodyPartLimitExceeded:+ return+ if parsed is None or not _has_external_participant(parsed, internal_emails):+ return+ labels = set(payload.get("labelIds") or [])+ if not labels.intersection({"INBOX", "SENT"}):+ return+ direction = EmailThreadMessageDirection.OUTBOUND if "SENT" in labels else EmailThreadMessageDirection.INBOUND+ ingest_customer_email(+ team_id=integration.team_id,+ channel=channel,+ email=parsed,+ direction=direction,+ source_type="gmail",+ source_id=f"{integration.id}:{gmail_message_id}",+ )+++def _parse_gmail_message(+ payload: dict[str, Any],+ mailbox_email: str,+ google_account_id: str,+ *,+ load_attachment_data: Callable[[str], str] | None = None,+) -> ParsedEmail | None:+ gmail_message_id = str(payload.get("id") or "")+ message_payload = payload.get("payload") or {}+ headers = _message_headers(message_payload.get("headers") or [])+ sender_name, sender_email = parseaddr(headers.get("from", ""))+ sender_email = sender_email.strip().lower()[:400]+ if not gmail_message_id or not sender_email:+ return None++ message_id = headers.get("message-id") or f"gmail:{google_account_id}:{gmail_message_id}"+ in_reply_to_ids = _parse_message_ids(headers.get("in-reply-to", ""))+ sent_at = _parse_internal_date(payload.get("internalDate"))+ bodies = _message_bodies(message_payload, load_attachment_data=load_attachment_data)+ body_plain = bodies.plain+ if not body_plain and bodies.html:+ body_plain = unescape(strip_tags(bodies.html))++ return ParsedEmail(+ message_id=message_id[:998],+ in_reply_to=in_reply_to_ids[0] if in_reply_to_ids else None,+ references=_parse_message_ids(headers.get("references", "")),+ sent_at=sent_at,+ sender=EmailAddress(name=_decode_header(sender_name)[:400], email=sender_email),+ to_recipients=_parse_addresses(headers.get("to", "")),+ cc_recipients=_parse_addresses(headers.get("cc", "")),+ subject=_decode_header(headers.get("subject", ""))[:500],+ body_plain=body_plain[:50_000],+ stripped_text=body_plain[:50_000],+ sender_authenticated=False,+ dkim_passed=False,+ dkim_signing_domains=(),+ capture_address=mailbox_email,+ attachments=(),+ )+++def _message_headers(raw_headers: list[dict[str, Any]]) -> dict[str, str]:+ values: dict[str, list[str]] = {}+ for header in raw_headers:+ name = str(header.get("name") or "").lower()+ value = str(header.get("value") or "")+ if name and value:+ values.setdefault(name, []).append(value)+ return {name: ", ".join(items) for name, items in values.items()}+++def _decode_header(value: str) -> str:+ try:+ return str(make_header(decode_header(value)))+ except (LookupError, UnicodeError):+ return value+++def _parse_message_ids(value: str) -> tuple[str, ...]:+ message_ids = _MESSAGE_ID_RE.findall(value)+ if not message_ids:+ message_ids = value.split()+ return tuple(dict.fromkeys(message_id.strip()[:998] for message_id in message_ids if message_id.strip()))+++def _parse_addresses(value: str) -> tuple[EmailAddress, ...]:+ addresses: list[EmailAddress] = []+ seen: set[str] = set()+ for name, email in getaddresses([value]):+ normalized = email.strip().lower()[:400]+ if not normalized or normalized in seen:+ continue+ seen.add(normalized)+ addresses.append(EmailAddress(name=_decode_header(name)[:400], email=normalized))+ return tuple(addresses)+++def _parse_internal_date(value: Any) -> datetime:+ try:+ return datetime.fromtimestamp(int(str(value)) / 1000, tz=UTC)+ except (TypeError, ValueError, OverflowError):+ return timezone.now()+++def _message_bodies(+ payload: dict[str, Any],+ *,+ load_attachment_data: Callable[[str], str] | None = None,+) -> _EmailBodies:+ plain_parts: list[str] = []+ html_parts: list[str] = []+ attachment_backed_body_parts = 0++ def visit(part: dict[str, Any]) -> None:+ nonlocal attachment_backed_body_parts+ mime_type = str(part.get("mimeType") or "").lower()+ body = part.get("body") or {}+ data = str(body.get("data") or "")+ attachment_id = str(body.get("attachmentId") or "")+ if mime_type in ("text/plain", "text/html") and not data and attachment_id and load_attachment_data:+ if attachment_backed_body_parts >= MAX_ATTACHMENT_BACKED_BODY_PARTS:+ raise _GmailBodyPartLimitExceeded+ attachment_backed_body_parts += 1+ data = load_attachment_data(attachment_id)+ decoded = _decode_body(data)+ if decoded and mime_type == "text/plain":+ plain_parts.append(decoded)+ elif decoded and mime_type == "text/html":+ html_parts.append(decoded)+ for child in part.get("parts") or []:+ visit(child)++ visit(payload)+ return _EmailBodies(+ plain="\n".join(plain_parts).strip(),+ html="\n".join(html_parts).strip(),+ )+++def _decode_body(data: str) -> str:+ if not data:+ return ""+ try:+ padded = data + "=" * (-len(data) % 4)+ return base64.urlsafe_b64decode(padded).decode("utf-8", errors="replace")+ except (ValueError, binascii.Error):+ return ""+++def _has_external_participant(email: ParsedEmail, internal_emails: set[str]) -> bool:+ addresses = {+ email.sender.email,+ *(recipient.email for recipient in email.to_recipients),+ *(recipient.email for recipient in email.cc_recipients),+ }+ return any(address and address not in internal_emails for address in addresses)+++def _request(+ *,+ integration: Integration,+ access_token: str,+ url: str,+ endpoint: str,+ params: dict[str, Any] | None = None,+) -> requests.Response:+ return google_workspace_request(+ "GET",+ url,+ access_token=access_token,+ account_id=str(integration.integration_id),+ source="customer_analytics",+ endpoint=endpoint,+ params=params,+ timeout=30,+ )+++def _get_json(+ *,+ integration: Integration,+ access_token: str,+ url: str,+ endpoint: str,+ params: dict[str, Any] | None = None,+) -> dict[str, Any]:+ response = _request(+ integration=integration,+ access_token=access_token,+ url=url,+ endpoint=endpoint,+ params=params,+ )+ return _response_json(response, "Gmail API")+++def _response_json(response: requests.Response, operation: str) -> dict[str, Any]:+ if response.status_code != 200:+ raise GmailSyncError(f"{operation} returned {response.status_code}: {response.text[:200]}")+ try:+ payload = response.json()+ except ValueError as error:+ raise GmailSyncError(f"{operation} returned an invalid response") from error+ if not isinstance(payload, dict):+ raise GmailSyncError(f"{operation} returned an invalid response")+ return payloaddiff --git a/products/conversations/backend/tests/test_gmail_sync.py b/products/conversations/backend/tests/test_gmail_sync.pynew file mode 100644index 000000000000..ee0a77aab66d--- /dev/null+++ b/products/conversations/backend/tests/test_gmail_sync.py@@ -0,0 +1,295 @@+import base64++import pytest+from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterized++from posthog.constants import AvailableFeature+from posthog.egress.google_workspace.transport import GoogleWorkspaceEgressBudgetExhausted+from posthog.models.integration import Integration+from posthog.models.organization import OrganizationMembership++from products.conversations.backend.models import (+ EmailThread,+ EmailThreadAccountLink,+ EmailThreadMessage,+ EmailThreadMessageDirection,+)+from products.conversations.backend.services import gmail_sync+from products.customer_analytics.backend.facade.email_matching import recalculate_email_thread_links+from products.customer_analytics.backend.models import Account++from ee.models.rbac.access_control import AccessControl+++def _response(payload: dict, status_code: int = 200) -> MagicMock:+ response = MagicMock(status_code=status_code)+ response.json.return_value = payload+ response.text = ""+ return response+++def _gmail_message(*, label: str, sender: str, recipient: str, message_id: str = "gmail-1") -> dict:+ body = base64.urlsafe_b64encode(b"Customer message body").decode().rstrip("=")+ return {+ "id": message_id,+ "threadId": "thread-1",+ "historyId": "101",+ "internalDate": "1785855600000",+ "labelIds": [label],+ "payload": {+ "mimeType": "text/plain",+ "headers": [+ {"name": "Message-ID", "value": f"<{message_id}@example.com>"},+ {"name": "From", "value": sender},+ {"name": "To", "value": recipient},+ {"name": "Subject", "value": "Account follow-up"},+ ],+ "body": {"data": body},+ },+ }+++class TestGmailSync(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.integration = Integration.objects.create(+ team=self.team,+ kind="google-calendar",+ integration_id="google-sub-1",+ created_by=self.user,+ config={+ "email": self.user.email,+ "scope": f"https://www.googleapis.com/auth/calendar.readonly {gmail_sync.GMAIL_READONLY_SCOPE}",+ "refreshed_at": 9_999_999_999,+ "expires_in": 3600,+ },+ sensitive_config={"access_token": "ACCESS", "refresh_token": "REFRESH"},+ )++ @parameterized.expand(+ [+ ("inbox", "INBOX", "[email protected]", "[email protected]", EmailThreadMessageDirection.INBOUND),+ ("sent", "SENT", "[email protected]", "[email protected]", EmailThreadMessageDirection.OUTBOUND),+ ]+ )+ def test_google_connection_imports_account_email(+ self,+ _name: str,+ label: str,+ sender: str,+ recipient: str,+ expected_direction: EmailThreadMessageDirection,+ ) -> None:+ self.user.email = "[email protected]"+ self.user.save(update_fields=["email"])+ self.integration.config["email"] = self.user.email+ self.integration.save(update_fields=["config"])+ account = Account.objects.for_team(self.team.id).create(team=self.team, name="Example", external_id="example")+ account.properties = {"email_domains": ["example.com"]}+ account.save()++ with patch.object(+ gmail_sync,+ "google_workspace_request",+ side_effect=[+ _response({"emailAddress": self.user.email, "historyId": "100"}),+ _response({"messages": [{"id": "gmail-1"}]}),+ _response(_gmail_message(label=label, sender=sender, recipient=recipient)),+ ],+ ):+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)++ recalculate_email_thread_links(self.team.id)++ message = EmailThreadMessage.objects.for_team(self.team.id).select_related("comment").get()+ assert message.direction == expected_direction+ assert message.source_type == "gmail"+ assert message.comment.content == "Customer message body"+ assert EmailThreadAccountLink.objects.for_team(self.team.id).get().account_id == str(account.id)+ self.integration.refresh_from_db()+ assert self.integration.config[gmail_sync.GMAIL_HISTORY_ID_CONFIG_KEY] == "100"++ def test_attachment_backed_body_is_imported(self) -> None:+ message = _gmail_message(label="INBOX", sender="[email protected]", recipient=self.user.email)+ message["payload"]["body"] = {"attachmentId": "body-attachment"}+ attachment_body = base64.urlsafe_b64encode(b"Attachment-backed message body").decode().rstrip("=")++ with patch.object(+ gmail_sync,+ "google_workspace_request",+ side_effect=[+ _response({"emailAddress": self.user.email, "historyId": "100"}),+ _response({"messages": [{"id": "gmail-1"}]}),+ _response(message),+ _response({"data": attachment_body}),+ ],+ ):+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)++ imported = EmailThreadMessage.objects.for_team(self.team.id).select_related("comment").get()+ assert imported.comment.content == "Attachment-backed message body"++ def test_message_with_too_many_attachment_backed_bodies_is_skipped(self) -> None:+ message = _gmail_message(label="INBOX", sender="[email protected]", recipient=self.user.email)+ message["payload"]["mimeType"] = "multipart/alternative"+ message["payload"]["body"] = {}+ message["payload"]["parts"] = [+ {"mimeType": "text/plain", "body": {"attachmentId": f"body-{index}"}}+ for index in range(gmail_sync.MAX_ATTACHMENT_BACKED_BODY_PARTS + 1)+ ]+ attachment_body = base64.urlsafe_b64encode(b"Body part").decode().rstrip("=")++ with patch.object(+ gmail_sync,+ "google_workspace_request",+ side_effect=[+ _response({"emailAddress": self.user.email, "historyId": "100"}),+ _response({"messages": [{"id": "gmail-1"}]}),+ _response(message),+ *[_response({"data": attachment_body}) for _ in range(gmail_sync.MAX_ATTACHMENT_BACKED_BODY_PARTS)],+ ],+ ) as mock_request:+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)++ assert mock_request.call_count == 3 + gmail_sync.MAX_ATTACHMENT_BACKED_BODY_PARTS+ assert not EmailThread.objects.for_team(self.team.id).exists()+ self.integration.refresh_from_db()+ assert self.integration.config[gmail_sync.GMAIL_HISTORY_ID_CONFIG_KEY] == "100"++ def test_incremental_sync_checkpoints_each_imported_message(self) -> None:+ self.integration.config[gmail_sync.GMAIL_HISTORY_ID_CONFIG_KEY] = "100"+ self.integration.save(update_fields=["config"])+ history = {+ "history": [+ {+ "id": "101",+ "messagesAdded": [+ {"message": {"id": "gmail-1"}},+ {"message": {"id": "gmail-2"}},+ ],+ }+ ],+ "historyId": "101",+ }+ first_message = _gmail_message(+ label="INBOX", sender="[email protected]", recipient=self.user.email, message_id="gmail-1"+ )+ second_message = _gmail_message(+ label="INBOX", sender="[email protected]", recipient=self.user.email, message_id="gmail-2"+ )++ with (+ patch.object(+ gmail_sync,+ "google_workspace_request",+ side_effect=[+ _response(history),+ _response(first_message),+ GoogleWorkspaceEgressBudgetExhausted("budget exhausted"),+ ],+ ),+ pytest.raises(GoogleWorkspaceEgressBudgetExhausted),+ ):+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)++ self.integration.refresh_from_db()+ assert self.integration.config[gmail_sync.GMAIL_PENDING_MESSAGE_IDS_CONFIG_KEY] == ["gmail-2"]+ assert EmailThreadMessage.objects.for_team(self.team.id).count() == 1++ with patch.object(gmail_sync, "google_workspace_request", return_value=_response(second_message)):+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)++ self.integration.refresh_from_db()+ assert self.integration.config[gmail_sync.GMAIL_HISTORY_ID_CONFIG_KEY] == "101"+ assert gmail_sync.GMAIL_PENDING_MESSAGE_IDS_CONFIG_KEY not in self.integration.config+ assert EmailThreadMessage.objects.for_team(self.team.id).count() == 2++ def test_incremental_sync_is_idempotent(self) -> None:+ self.integration.config[gmail_sync.GMAIL_HISTORY_ID_CONFIG_KEY] = "100"+ self.integration.save(update_fields=["config"])+ history = {+ "history": [+ {+ "id": "101",+ "messagesAdded": [+ {"message": {"id": "gmail-1"}},+ {"message": {"id": "gmail-1"}},+ ],+ }+ ],+ "historyId": "101",+ }+ responses = [+ _response(history),+ _response(_gmail_message(label="INBOX", sender="[email protected]", recipient=self.user.email)),+ _response(history),+ _response(_gmail_message(label="INBOX", sender="[email protected]", recipient=self.user.email)),+ ]++ with patch.object(gmail_sync, "google_workspace_request", side_effect=responses):+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)++ assert EmailThread.objects.for_team(self.team.id).count() == 1+ assert EmailThreadMessage.objects.for_team(self.team.id).count() == 1++ def test_existing_calendar_only_connection_does_not_call_gmail(self) -> None:+ self.integration.config["scope"] = "https://www.googleapis.com/auth/calendar.readonly"+ self.integration.save(update_fields=["config"])++ with patch.object(gmail_sync, "google_workspace_request") as mock_request:+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)++ mock_request.assert_not_called()+ assert not EmailThread.objects.for_team(self.team.id).exists()++ def test_removed_organization_member_is_not_synced(self) -> None:+ OrganizationMembership.objects.filter(+ organization=self.team.organization,+ user=self.user,+ ).delete()++ with patch.object(gmail_sync, "google_workspace_request") as mock_request:+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)++ mock_request.assert_not_called()+ assert not EmailThread.objects.for_team(self.team.id).exists()++ def test_owner_without_project_access_is_not_synced(self) -> None:+ self.team.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": "Access control"}+ ]+ self.team.organization.save(update_fields=["available_product_features"])+ OrganizationMembership.objects.filter(+ organization=self.team.organization,+ user=self.user,+ ).update(level=OrganizationMembership.Level.MEMBER)+ AccessControl.objects.create(+ team=self.team,+ resource="project",+ resource_id=str(self.team.id),+ access_level="none",+ )++ with patch.object(gmail_sync, "google_workspace_request") as mock_request:+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)++ mock_request.assert_not_called()+ assert not EmailThread.objects.for_team(self.team.id).exists()++ def test_internal_only_email_is_not_stored(self) -> None:+ with patch.object(+ gmail_sync,+ "google_workspace_request",+ side_effect=[+ _response({"emailAddress": self.user.email, "historyId": "100"}),+ _response({"messages": [{"id": "gmail-1"}]}),+ _response(_gmail_message(label="INBOX", sender=self.user.email, recipient=self.user.email)),+ ],+ ):+ gmail_sync.sync_gmail_integration(self.integration.id, self.team.id)++ assert not EmailThread.objects.for_team(self.team.id).exists()diff --git a/products/customer_analytics/backend/temporal/calendar_sync.py b/products/customer_analytics/backend/temporal/calendar_sync.pyindex 8337b5f19a25..c9d063d495c7 100644--- a/products/customer_analytics/backend/temporal/calendar_sync.py+++ b/products/customer_analytics/backend/temporal/calendar_sync.py@@ -89,6 +89,7 @@ async def calendar_sync_collect_integrations_activity(def _run_calendar_sync(input: CalendarSyncInput) -> CalendarSyncOutput:# Deferred: the sync logic pulls requests/HogQL layers that don't belong in the sandbox.+ from products.conversations.backend.facade import api as conversations # noqa: PLC0415from products.customer_analytics.backend.logic.calendar_sync import ( # noqa: PLC0415CalendarSyncError,sync_calendar_integration,@@ -96,7 +97,8 @@ def _run_calendar_sync(input: CalendarSyncInput) -> CalendarSyncOutput:try:counts = sync_calendar_integration(input.integration_id, input.team_id)- except CalendarSyncError as e:+ conversations.sync_google_account_email(input.integration_id, input.team_id)+ except (CalendarSyncError, conversations.GoogleAccountEmailSyncError) as e:# A dead refresh token can't heal by retrying; the user must reconnect.raise ApplicationError(str(e), non_retryable="refresh failed" in str(e).lower()) from ereturn CalendarSyncOutput(diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig.tsxindex 45bceba43962..251cb7d203d0 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, IconTrash } from '@posthog/icons'-import { LemonButton } from '@posthog/lemon-ui'+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'import api from 'lib/api'import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'@@ -14,6 +14,8 @@ import { urls } from 'scenes/urls'import { calendarSyncLogic } from './calendarSyncLogic'+const GMAIL_READONLY_SCOPE = 'https://www.googleapis.com/auth/gmail.readonly'+export function CalendarSyncConfig(): JSX.Element {const { integrations, integrationsLoading } = useValues(integrationsLogic)const { deleteIntegration } = useActions(integrationsLogic)@@ -25,9 +27,32 @@ export function CalendarSyncConfig(): JSX.Element {})const calendarIntegrations = integrations?.filter((integration) => integration.kind === 'google-calendar') ?? []+ const needsEmailPermission = calendarIntegrations.some(+ (integration) =>+ !String(integration.config?.scope ?? '')+ .split(' ')+ .includes(GMAIL_READONLY_SCOPE)+ )+ const authorizeUrl = api.integrations.authorizeUrl({+ kind: 'google-calendar',+ next: `${urls.customerAnalyticsConfiguration('customer-analytics-calendar-sync')}#selectedSetting=customer-analytics-calendar-sync`,+ })return (<div className="flex flex-col gap-4">+ {needsEmailPermission && (+ <LemonBanner+ type="warning"+ action={{+ children: 'Reconnect Google account',+ to: authorizeUrl,+ disableClientSideRouting: true,+ 'data-attr': 'reconnect-google-account',+ }}+ >+ Reconnect your Google account to let PostHog sync customer email as well as calendar meetings.+ </LemonBanner>+ )}{calendarIntegrations.map((integration) => {const syncStatus = statusByIntegrationId[integration.id]const isSyncing = !!syncStatus?.is_syncing || triggeringIntegrationIds.includes(integration.id)@@ -40,7 +65,7 @@ export function CalendarSyncConfig(): JSX.Element {<div className="flex flex-row items-center gap-2"><span className="text-xs text-secondary whitespace-nowrap">{isSyncing ? (- 'Syncing...'+ 'Syncing Google account...') : syncStatus?.last_synced_at ? (<>Last synced <TZLabel time={syncStatus.last_synced_at} />@@ -79,12 +104,9 @@ export function CalendarSyncConfig(): JSX.Element {icon={<img src={ICONS['google-calendar']} className="h-4 w-4" alt="" />}disableClientSideRoutingloading={integrationsLoading}- to={api.integrations.authorizeUrl({- kind: 'google-calendar',- next: urls.settings('environment-customer-analytics'),- })}+ to={authorizeUrl}>- {calendarIntegrations.length ? 'Connect another calendar' : 'Connect Google Calendar'}+ {calendarIntegrations.length ? 'Connect another Google account' : 'Connect Google account'}</LemonButton></div></div>diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.tsindex 1dd3297b194e..5d21c7504fa7 100644--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.ts+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/calendarSyncLogic.ts@@ -134,14 +134,14 @@ export const calendarSyncLogic = kea<calendarSyncLogicType>([integration_id: integrationId,})if (result.status === 'already_running') {- lemonToast.info('A sync for this calendar is already running')+ lemonToast.info('A sync for this Google account is already running')actions.triggerFinished(integrationId)} else {- lemonToast.success('Calendar sync started. New meetings appear in a few minutes.')+ lemonToast.success('Google account sync started. New meetings and emails appear in a few minutes.')}} catch (error) {posthog.captureException(error as Error, { scope: 'calendarSyncLogic.syncNow' })- lemonToast.error('Failed to start the calendar sync')+ lemonToast.error('Could not start the Google account sync. Try again.')actions.triggerFinished(integrationId)} finally {actions.loadStatuses()