: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
fix(marketing): preserve source connection context through oauth (#114725)
Javier Bahamondes30e89e5334b9
diff --git a/docs/internal/marketing-source-suggestions.md b/docs/internal/marketing-source-suggestions.mdindex fd41f9fcb46e..49b3254c1545 100644--- a/docs/internal/marketing-source-suggestions.md+++ b/docs/internal/marketing-source-suggestions.md@@ -108,6 +108,15 @@ The view groups search distribution metrics by destination URL and currency, witThe connector uses `ConversionsQualified` because Microsoft deprecated `Conversions` for this report.Keyword reporting continues to use `keyword_performance_report`.+## Source connection context++Setup scan recommendations include a connection link with the suggested source kind, a project-scoped `returnUrl`, and `returnLabel=Marketing analytics`.+The `entry_point` query parameter identifies the originating surface separately from the visible return label.+Marketing links identify MCP (`marketing_analytics_mcp`), onboarding, Setup, the integration menu, search suggestions, and search detail.+The connection flow preserves return URLs, labels, access mode, and origin metadata through OAuth.+The `warehouse source connect completed` event records the originating entry point.+Users complete platform authorization through the connection flow.+## Google Ads campaign trendsCampaign trend charts accept both `campaign_overview_stats` and the legacy `campaign_stats` schema.diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex c59e8b45b0c9..16d74fc3b7ad 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -1475,7 +1475,8 @@ export const productUrls = {kind?: string,returnUrl?: string,returnLabel?: string,- accessMethod?: 'warehouse' | 'direct'+ accessMethod?: 'warehouse' | 'direct',+ entryPoint?: string): string => {const params = new URLSearchParams()if (kind) {@@ -1490,6 +1491,9 @@ export const productUrls = {if (accessMethod) {params.set('access_method', accessMethod)}+ if (entryPoint) {+ params.set('entry_point', entryPoint)+ }const queryString = params.toString()return `/data-warehouse/new-source${queryString ? `?${queryString}` : ''}`},diff --git a/frontend/src/scenes/marketing-analytics/Onboarding/AddSourceStep.tsx b/frontend/src/scenes/marketing-analytics/Onboarding/AddSourceStep.tsxindex 6b7055eb2a30..4d037943ed2c 100644--- a/frontend/src/scenes/marketing-analytics/Onboarding/AddSourceStep.tsx+++ b/frontend/src/scenes/marketing-analytics/Onboarding/AddSourceStep.tsx@@ -65,7 +65,15 @@ export function AddSourceStep({ onContinue, hasSources }: AddSourceStepProps): Jintent_context: ProductIntentContext.MARKETING_ANALYTICS_DATA_SOURCE_CONNECTED,metadata: { source_type: sourceId },})- router.actions.push(urls.dataWarehouseSourceNew(sourceId, urls.marketingAnalyticsApp(), 'Marketing analytics'))+ router.actions.push(+ urls.dataWarehouseSourceNew(+ sourceId,+ urls.marketingAnalyticsApp(),+ 'Marketing analytics',+ undefined,+ 'marketing_analytics_onboarding'+ )+ )}const nativeSources = allSources.filter((s) => s.category === 'native')diff --git a/frontend/src/scenes/marketing-analytics/Setup/navigateOps.ts b/frontend/src/scenes/marketing-analytics/Setup/navigateOps.tsindex 6f887fa3d4fe..7492e262f284 100644--- a/frontend/src/scenes/marketing-analytics/Setup/navigateOps.ts+++ b/frontend/src/scenes/marketing-analytics/Setup/navigateOps.ts@@ -33,7 +33,13 @@ export function runNavigateOp(op: ApplyOp, entryPoint: string): boolean {return truecase 'open_source_wizard':window.open(- urls.dataWarehouseSourceNew(op.kind as string, urls.marketingAnalyticsApp(), 'Marketing analytics'),+ urls.dataWarehouseSourceNew(+ op.kind as string,+ urls.marketingAnalyticsApp(),+ 'Marketing analytics',+ undefined,+ `marketing_analytics_setup_${entryPoint}`+ ),'_blank','noopener')diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsxindex 33819eb92d88..a8fc504e77d5 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/sourceWizardLogic.tsx@@ -501,6 +501,7 @@ export interface sourceWizardLogicValues {prefixRequired: booleanrequiredTables: anyreturnConfig: {+ entryPoint?: stringreturnLabel: stringreturnUrl: string} | null@@ -722,8 +723,10 @@ export interface sourceWizardLogicActions {}setReturnConfig: (returnUrl: string,- returnLabel: string+ returnLabel: string,+ entryPoint?: string) => {+ entryPoint: string | undefinedreturnLabel: stringreturnUrl: string}@@ -962,6 +965,7 @@ export interface sourceWizardLogicMeta {showDestinationStep: boolean,arg: any,returnConfig: {+ entryPoint?: stringreturnLabel: stringreturnUrl: string} | null,@@ -1055,7 +1059,11 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([source,searchParams,}),- setReturnConfig: (returnUrl: string, returnLabel: string) => ({ returnUrl, returnLabel }),+ setReturnConfig: (returnUrl: string, returnLabel: string, entryPoint?: string) => ({+ returnUrl,+ returnLabel,+ entryPoint,+ }),clearReturnConfig: true,onClear: true,onBack: true,@@ -1369,9 +1377,13 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([},],returnConfig: [- null as { returnUrl: string; returnLabel: string } | null,+ null as { returnUrl: string; returnLabel: string; entryPoint?: string } | null,{- setReturnConfig: (_, { returnUrl, returnLabel }) => ({ returnUrl, returnLabel }),+ setReturnConfig: (_, { returnUrl, returnLabel, entryPoint }) => ({+ returnUrl,+ returnLabel,+ entryPoint,+ }),clearReturnConfig: () => null,},],@@ -2311,6 +2323,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([posthog.capture('warehouse source connect completed', {sourceType: values.selectedConnector.name,returnLabel: values.returnConfig?.returnLabel,+ entry_point: values.returnConfig?.entryPoint,accessMethod: values.source.access_method,hasWebhookSchemas: values.hasWebhookSchemas,})@@ -2633,7 +2646,7 @@ export const sourceWizardLogic = kea<sourceWizardLogicType>([const returnLabel = searchParams.returnLabelif (returnUrl && returnLabel) {- actions.setReturnConfig(returnUrl, returnLabel)+ actions.setReturnConfig(returnUrl, returnLabel, searchParams.entry_point)} else {actions.clearReturnConfig()}diff --git a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.tsindex e833a78d5e45..efe496355f8e 100644--- a/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts+++ b/products/data_warehouse/frontend/scenes/NewSourceScene/tests/sourceWizardLogic.test.ts@@ -147,7 +147,8 @@ describe('sourceWizardLogic', () => {if (category !== 'Databases') {logic.actions.setReturnConfig('/project/997/marketing?tab=ad-performance',- 'Marketing analytics'+ 'Marketing analytics',+ 'marketing_analytics_mcp')}await expectLogic(logic, () => logic.actions.createSource()).toFinishAllListeners()@@ -156,6 +157,7 @@ describe('sourceWizardLogic', () => {expect.objectContaining({sourceType: source.name,returnLabel: category === 'Databases' ? undefined : 'Marketing analytics',+ entry_point: category === 'Databases' ? undefined : 'marketing_analytics_mcp',}))const conversions = jestdiff --git a/products/data_warehouse/frontend/shared/components/forms/IntegrationChoice.test.ts b/products/data_warehouse/frontend/shared/components/forms/IntegrationChoice.test.tsindex 2728f5771f0e..fa1313159acb 100644--- a/products/data_warehouse/frontend/shared/components/forms/IntegrationChoice.test.ts+++ b/products/data_warehouse/frontend/shared/components/forms/IntegrationChoice.test.ts@@ -1,6 +1,6 @@import { IntegrationType } from '~/types'-import { authorizedIntegrationId } from './IntegrationChoice'+import { authorizedIntegrationId, sourceOAuthRedirectUrl } from './IntegrationChoice'const integration = (id: number, kind: string): IntegrationType => ({ id, kind }) as IntegrationType@@ -21,4 +21,23 @@ describe('SourceIntegrationChoice', () => {it('waits for the connection list rather than adopting an unverified id', () => {expect(authorizedIntegrationId({ integration_id: '7' }, null, 'linkedin-ads')).toBeNull()})+ it.each(['/data-warehouse/new-source', '/onboarding'])(+ 'preserves source origin and return destination through OAuth from %s',+ (pathname) => {+ const search = new URLSearchParams({+ kind: 'MetaAds',+ returnUrl: '/project/997/marketing?tab=ad-performance',+ returnLabel: 'Marketing analytics',+ entry_point: 'marketing_analytics_mcp',+ }).toString()+ const redirect = new URL(sourceOAuthRedirectUrl('GoogleAds', pathname, `?${search}`), 'https://example.com')+ expect(Object.fromEntries(redirect.searchParams)).toEqual({+ kind: 'GoogleAds',+ returnUrl: '/project/997/marketing?tab=ad-performance',+ returnLabel: 'Marketing analytics',+ entry_point: 'marketing_analytics_mcp',+ })+ expect(redirect.pathname).toBe(pathname)+ }+ )})diff --git a/products/data_warehouse/frontend/shared/components/forms/IntegrationChoice.tsx b/products/data_warehouse/frontend/shared/components/forms/IntegrationChoice.tsxindex b5537c543216..efeb4d9ba75a 100644--- a/products/data_warehouse/frontend/shared/components/forms/IntegrationChoice.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/IntegrationChoice.tsx@@ -41,6 +41,27 @@ export function authorizedIntegrationId(return integrations?.some((integration) => integration.id === id && integration.kind === kind) ? id : null}+export function sourceOAuthRedirectUrl(sourceKind: string, pathname: string, search: string): string {+ const searchParams = Object.fromEntries(new URLSearchParams(search))+ const isOnboarding = pathname.includes('/onboarding')+ let redirectUrl: string+ if (isOnboarding) {+ const params = new URLSearchParams(search)+ params.set('kind', sourceKind)+ redirectUrl = `${pathname}?${params.toString()}`+ } else {+ redirectUrl = urls.dataWarehouseSourceNew(+ sourceKind,+ searchParams.returnUrl,+ searchParams.returnLabel,+ searchParams.access_method === 'direct' ? 'direct' : undefined,+ searchParams.entry_point+ )+ }++ return redirectUrl+}+export function SourceIntegrationChoice({sourceConfig,integration,@@ -93,15 +114,7 @@ export function SourceIntegrationChoice({// on an onboarding route we return to the current onboarding URL with the source kind instead.// InlineSourceSetup reads that kind on mount and resumes the wizard (credentials are restored// from the state saved by beforeRedirect). Outside onboarding the standalone scene is correct.- const isOnboarding = location.pathname.includes('/onboarding')- let redirectUrl: string- if (isOnboarding) {- const params = new URLSearchParams(location.search)- params.set('kind', sourceKind)- redirectUrl = `${location.pathname}?${params.toString()}`- } else {- redirectUrl = urls.dataWarehouseSourceNew(sourceKind)- }+ const redirectUrl = sourceOAuthRedirectUrl(sourceKind, location.pathname, location.search)return (<div className="flex flex-col gap-2">diff --git a/products/data_warehouse/manifest.tsx b/products/data_warehouse/manifest.tsxindex c2642a6c011d..1d3155a22dad 100644--- a/products/data_warehouse/manifest.tsx+++ b/products/data_warehouse/manifest.tsx@@ -126,7 +126,8 @@ export const manifest: ProductManifest = {kind?: string,returnUrl?: string,returnLabel?: string,- accessMethod?: 'warehouse' | 'direct'+ accessMethod?: 'warehouse' | 'direct',+ entryPoint?: string): string => {const params = new URLSearchParams()if (kind) {@@ -141,6 +142,9 @@ export const manifest: ProductManifest = {if (accessMethod) {params.set('access_method', accessMethod)}+ if (entryPoint) {+ params.set('entry_point', entryPoint)+ }const queryString = params.toString()return `/data-warehouse/new-source${queryString ? `?${queryString}` : ''}`},diff --git a/products/marketing_analytics/backend/services/setup_plan.py b/products/marketing_analytics/backend/services/setup_plan.pyindex fa81a3920fcd..006bf5dfe7d0 100644--- a/products/marketing_analytics/backend/services/setup_plan.py+++ b/products/marketing_analytics/backend/services/setup_plan.py@@ -19,6 +19,7 @@ there's nothing to say), everything else degrades to a missing section recordedimport asynciofrom typing import Any, cast+from urllib.parse import urlencodefrom django.utils import timezone@@ -167,7 +168,7 @@ async def get_setup_plan(goal_flags = _or_degraded(goal_flags_result, "goal_flags", degraded, team) or {}suggestions: list[Suggestion] = []- suggestions.extend(_integration_suggestions(diagnostic))+ suggestions.extend(_integration_suggestions(diagnostic, team_id=team.pk))# Ahead of the mapping suggester so its proposals can be injected there.campaign_mappings: CampaignMappingSuggestions | None = None@@ -267,10 +268,10 @@ def _load_goal_flags(team: Team) -> dict[str, dict[str, Any]]:# --- Suggestion builders ----------------------------------------------------def _integration_suggestions(diagnostic: MarketingDiagnosticResponse) -> list[Suggestion]:+def _integration_suggestions(diagnostic: MarketingDiagnosticResponse, *, team_id: int) -> list[Suggestion]:suggestions: list[Suggestion] = []for integration in diagnostic.integrations:- suggestion = _integration_suggestion(integration)+ suggestion = _integration_suggestion(integration, team_id=team_id)if suggestion is not None:suggestions.append(suggestion)return suggestions@@ -283,7 +284,7 @@ def _looks_like_auth_failure(last_error: str | None) -> bool:return any(token in lowered for token in ("token", "unauthor", "auth", "credential", "expired", "401", "403"))-def _integration_suggestion(integration: IntegrationDiagnostic) -> Suggestion | None:+def _integration_suggestion(integration: IntegrationDiagnostic, *, team_id: int) -> Suggestion | None:key: NativeIntegration = integration.integration_keynative = KEY_TO_NATIVE.get(key)display = integration.display_name@@ -312,6 +313,15 @@ def _integration_suggestion(integration: IntegrationDiagnostic) -> Suggestion |unlocks=[Capability.COST, Capability.ROAS, Capability.CAC],apply=OpenSourceWizard(kind=source_type),integration=source_type,+ deep_link=f"/project/{team_id}/data-warehouse/new-source?"+ + urlencode(+ {+ "kind": source_type,+ "returnUrl": f"/project/{team_id}/marketing",+ "returnLabel": "Marketing analytics",+ "entry_point": "marketing_analytics_mcp",+ }+ ),event_volume=paid_volume,)diff --git a/products/marketing_analytics/backend/services/test_setup_plan.py b/products/marketing_analytics/backend/services/test_setup_plan.pyindex fb9114aa9ecd..245a6f78425c 100644--- a/products/marketing_analytics/backend/services/test_setup_plan.py+++ b/products/marketing_analytics/backend/services/test_setup_plan.py@@ -1,3 +1,5 @@+from urllib.parse import parse_qs, urlsplit+import pytestfrom unittest.mock import AsyncMock, patch@@ -695,6 +697,16 @@ class TestIntegrationSuggestions(SetupPlanTestCase):"Connect the platform to add spend data.")+ assert connect.deep_link is not None+ link = urlsplit(connect.deep_link)+ assert link.path == f"/project/{self.team.pk}/data-warehouse/new-source"+ assert parse_qs(link.query) == {+ "kind": ["PinterestAds"],+ "returnUrl": [f"/project/{self.team.pk}/marketing"],+ "returnLabel": ["Marketing analytics"],+ "entry_point": ["marketing_analytics_mcp"],+ }+@pytest.mark.asyncioasync def test_healthy_integration_produces_nothing(self):plan = await get_setup_plan(self.team)diff --git a/products/marketing_analytics/frontend/components/AddIntegrationButton.tsx b/products/marketing_analytics/frontend/components/AddIntegrationButton.tsxindex 6a4f9b6ce04b..3d0ec193cfdf 100644--- a/products/marketing_analytics/frontend/components/AddIntegrationButton.tsx+++ b/products/marketing_analytics/frontend/components/AddIntegrationButton.tsx@@ -95,7 +95,9 @@ export function AddIntegrationButton({ onIntegrationSelect }: AddIntegrationButt: urls.dataWarehouseSourceNew(integrationId,urls.marketingAnalyticsApp(),- 'Marketing analytics'+ 'Marketing analytics',+ undefined,+ 'marketing_analytics_integration_menu'),onClick: () => handleIntegrateClick(integrationId),})),diff --git a/products/marketing_analytics/frontend/search/SearchPerformanceDetail.tsx b/products/marketing_analytics/frontend/search/SearchPerformanceDetail.tsxindex 2d271e80f6e6..5498af170db3 100644--- a/products/marketing_analytics/frontend/search/SearchPerformanceDetail.tsx+++ b/products/marketing_analytics/frontend/search/SearchPerformanceDetail.tsx@@ -108,7 +108,9 @@ export function SearchPerformanceDetail(): JSX.Element {to={urls.dataWarehouseSourceNew('GoogleSearchConsole',`${urls.marketingAnalyticsApp()}?tab=ad-performance`,- 'Marketing analytics'+ 'Marketing analytics',+ undefined,+ 'marketing_analytics_search_detail')}>Connect Google Search Consolediff --git a/products/marketing_analytics/frontend/search/SearchSourceSuggestions.tsx b/products/marketing_analytics/frontend/search/SearchSourceSuggestions.tsxindex 5c16e5c2763f..13f81f7e4562 100644--- a/products/marketing_analytics/frontend/search/SearchSourceSuggestions.tsx+++ b/products/marketing_analytics/frontend/search/SearchSourceSuggestions.tsx@@ -30,7 +30,9 @@ export function SearchSourceSuggestions(): JSX.Element {to: urls.dataWarehouseSourceNew(source,`${urls.marketingAnalyticsApp()}?tab=ad-performance`,- 'Marketing analytics'+ 'Marketing analytics',+ undefined,+ 'marketing_analytics_search_suggestions'),}}>