: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(data-warehouse): autocomplete Google Search Console property URL from connected account (#61709)
Javier Bahamondes7be9a9aa0abf
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 2f5045545647..096ccf22071a 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -298,7 +298,7 @@ jobs:run: |prefix="posthog/temporal/data_imports/sources/"# Space-separated, double-quoted, single line — parsed by the guard test.- coupled="common mysql postgres salesforce stripe"+ coupled="common google_search_console mysql postgres salesforce stripe"only_sources=falseif [ -n "$BACKEND_FILES" ]; thenonly_sources=truediff --git a/frontend/src/lib/integrations/googleSearchConsoleIntegrationLogic.ts b/frontend/src/lib/integrations/googleSearchConsoleIntegrationLogic.tsnew file mode 100644index 000000000000..94efde16d564--- /dev/null+++ b/frontend/src/lib/integrations/googleSearchConsoleIntegrationLogic.ts@@ -0,0 +1,67 @@+import { actions, isBreakpoint, kea, key, listeners, path, props, reducers } from 'kea'++import api from 'lib/api'++import type { googleSearchConsoleIntegrationLogicType } from './googleSearchConsoleIntegrationLogicType'++export interface GoogleSearchConsoleSite {+ // Canonical Google format: `https://example.com/` (URL-prefix, trailing slash required)+ // or `sc-domain:example.com` (Domain property). We surface the string verbatim so the+ // backend comparison in `validate_credentials` matches without normalization.+ siteUrl: string+ permissionLevel: 'siteOwner' | 'siteFullUser' | 'siteRestrictedUser' | 'siteUnverifiedUser'+}++interface SitesResponse {+ sites: GoogleSearchConsoleSite[]+}++export const googleSearchConsoleIntegrationLogic = kea<googleSearchConsoleIntegrationLogicType>([+ props({} as { id: number }),+ key((props) => props.id),+ path((key) => ['lib', 'integrations', 'googleSearchConsoleIntegrationLogic', key]),++ actions({+ loadSites: true,+ loadSitesSuccess: (sites: GoogleSearchConsoleSite[]) => ({ sites }),+ loadSitesFailure: true,+ }),++ reducers({+ sites: [+ [] as GoogleSearchConsoleSite[],+ {+ loadSites: () => [],+ loadSitesSuccess: (_, { sites }) => sites,+ },+ ],+ sitesLoading: [+ false,+ {+ loadSites: () => true,+ loadSitesSuccess: () => false,+ loadSitesFailure: () => false,+ },+ ],+ }),++ listeners(({ actions, props }) => ({+ loadSites: async (_, breakpoint) => {+ try {+ // Manual typing for now — the autogenerated `api.integrations.googleSearchConsoleSites`+ // will replace this once `hogli build:openapi` succeeds. Path mirrors the @action+ // decorator on `IntegrationViewSet.google_search_console_sites`.+ const response = (await api.get(+ `api/projects/@current/integrations/${props.id}/google_search_console_sites/`+ )) as SitesResponse+ await breakpoint()+ actions.loadSitesSuccess(response.sites)+ } catch (e: any) {+ if (isBreakpoint(e)) {+ throw e+ }+ actions.loadSitesFailure()+ }+ },+ })),+])diff --git a/posthog/api/integration.py b/posthog/api/integration.pyindex c684f028daa5..f072c7fd6dba 100644--- a/posthog/api/integration.py+++ b/posthog/api/integration.py@@ -84,6 +84,9 @@ logger = structlog.get_logger(__name__)GITHUB_REPOSITORY_NAME_RE = re.compile(r"[A-Za-z0-9_.\-]+")+# Short TTL for the Search Console sites dropdown — just enough to dedupe repeated UI loads.+GSC_AUTOCOMPLETE_CACHE_TTL_SECONDS = 60+def validate_github_repository_name(repo: str) -> str:"""Validate repository paths accepted by GitHub integration endpoints."""@@ -302,6 +305,25 @@ class SlackChannelsResponseSerializer(serializers.Serializer):)+class GoogleSearchConsoleSiteSerializer(serializers.Serializer):+ siteUrl = serializers.CharField(+ help_text=(+ "Site URL in canonical Google format — `https://example.com/` for URL-prefix "+ "properties (trailing slash mandatory) or `sc-domain:example.com` for Domain properties."+ )+ )+ permissionLevel = serializers.CharField(+ help_text=(+ "The connected user's permission level for this site. One of `siteOwner`, "+ "`siteFullUser`, `siteRestrictedUser`, `siteUnverifiedUser`."+ )+ )+++class GoogleSearchConsoleSitesResponseSerializer(serializers.Serializer):+ sites = GoogleSearchConsoleSiteSerializer(many=True)++class IntegrationAccessRequestSerializer(serializers.Serializer):kind = serializers.ChoiceField(choices=Integration.IntegrationKind.choices,@@ -681,6 +703,9 @@ class IntegrationViewSet("github_oauth_authorize",# Side-effecting POST (emails admins) — a read-only token must not be able to trigger it."request_access",+ # Enumerates every Search Console property on the connected Google account — gate behind+ # manage access so read-only members can't discover unrelated domains (info disclosure).+ "google_search_console_sites",]permission_classes = [TeamMemberStrictManagementPermission]queryset = defer_repository_cache_fields(Integration.objects.all())@@ -963,6 +988,35 @@ class IntegrationViewSet(cache.set(key, response_data, 60)return Response(response_data)+ @extend_schema(responses={200: GoogleSearchConsoleSitesResponseSerializer})+ @action(methods=["GET"], detail=True, url_path="google_search_console_sites")+ def google_search_console_sites(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """List the Search Console properties the connected Google account has access to."""+ # Lazy import — keeps the Google data-imports SDK dependency off the api/ module+ # import path, mirroring how other ad-platform endpoints stay self-contained.+ from posthog.temporal.data_imports.sources.google_search_console.google_search_console import ( # noqa: PLC0415 — keeps the heavy dep off the import path+ google_search_console_session,+ list_sites,+ )++ instance = self.get_object()+ if instance.kind != "google-search-console":+ raise ValidationError(+ "google_search_console_sites endpoint is only supported for Google Search Console integrations"+ )+ _ensure_oauth_token_valid(instance)++ cache_key = f"google_search_console/{instance.id}/sites"+ cached = cache.get(cache_key)+ if cached is not None:+ return Response(cached)++ session = google_search_console_session(instance.id, instance.team_id)+ sites = list_sites(session)+ response_data = {"sites": sites}+ cache.set(cache_key, response_data, GSC_AUTOCOMPLETE_CACHE_TTL_SECONDS)+ return Response(response_data)+@action(methods=["GET"], detail=True, url_path="linkedin_ads_conversion_rules")def linkedin_ad_conversion_rules(self, request: Request, *args: Any, **kwargs: Any) -> Response:instance = self.get_object()diff --git a/products/data_warehouse/frontend/shared/components/forms/GoogleSearchConsoleSiteSelector.tsx b/products/data_warehouse/frontend/shared/components/forms/GoogleSearchConsoleSiteSelector.tsxnew file mode 100644index 000000000000..8999460bae47--- /dev/null+++ b/products/data_warehouse/frontend/shared/components/forms/GoogleSearchConsoleSiteSelector.tsx@@ -0,0 +1,139 @@+import { useActions, useValues } from 'kea'+import { FormContext } from 'kea-forms'+import { useContext, useEffect, useMemo } from 'react'++import { LemonInput } from '@posthog/lemon-ui'++import { googleSearchConsoleIntegrationLogic } from 'lib/integrations/googleSearchConsoleIntegrationLogic'+import { integrationsLogic } from 'lib/integrations/integrationsLogic'+import { LemonField } from 'lib/lemon-ui/LemonField'++import { InputWithSuggestionsDropdown } from './InputWithSuggestionsDropdown'++const SITE_URL_PLACEHOLDER = 'https://example.com/ or sc-domain:example.com'++/**+ * Renders the Search Console `site_url` field as a free-text input with a popover+ * of the connected integration's verified properties for autocomplete-style picking.+ *+ * Falls back to a plain text input before the user picks an OAuth account (or when+ * the form's stored integration ID points at a stale integration), so the field+ * stays usable while the integration choice above is being fixed.+ *+ * Works in both contexts that render this field:+ * - The new-source wizard (`sourceWizardLogic`, form key `sourceConnectionDetails`)+ * - The existing-source Config tab (`sourceSettingsLogic`, form key `sourceConfig`)+ *+ * We read the OAuth integration ID via `FormContext` from kea-forms instead of+ * binding directly to a specific logic, so this stays decoupled from which scene+ * renders it.+ */+export function GoogleSearchConsoleSiteSelector(): JSX.Element {+ // FormContext.logic is set whenever this field renders inside a kea <Form> (both the+ // new-source wizard and the existing-source config tab do). Only mount the hook-using+ // inner component when it's present, so we never pass a null logic into useValues — and+ // calling the hook conditionally here would itself violate the rules of hooks.+ const formContext = useContext(FormContext)+ if (!formContext.logic) {+ return <SiteUrlTextField />+ }+ return <GoogleSearchConsoleSiteSelectorInner formLogic={formContext.logic} formKey={formContext.formKey} />+}++function GoogleSearchConsoleSiteSelectorInner({+ formLogic,+ formKey,+}: {+ formLogic: any+ formKey: string+}): JSX.Element {+ const integrationId = useFormIntegrationId(formLogic, formKey)+ const { integrations, integrationsLoading } = useValues(integrationsLogic)++ const integrationIsValid = useMemo(() => {+ if (!integrationId || integrationsLoading || !integrations) {+ return false+ }+ return integrations.some(+ (integration) => integration.id === integrationId && integration.kind === 'google-search-console'+ )+ }, [integrationId, integrations, integrationsLoading])++ if (integrationIsValid && integrationId) {+ return <GoogleSearchConsoleSiteFieldWithSuggestions integrationId={integrationId} />+ }++ return <SiteUrlTextField />+}++function SiteUrlTextField(): JSX.Element {+ return (+ <LemonField name="site_url" label="Property URL">+ {({ value, onChange }) => (+ <LemonInput+ className="ph-ignore-input"+ data-attr="site_url"+ placeholder={SITE_URL_PLACEHOLDER}+ type="text"+ value={value || ''}+ onChange={onChange}+ />+ )}+ </LemonField>+ )+}++function useFormIntegrationId(formLogic: any, formKey: string): number | undefined {+ // formLogic is guaranteed non-null by the caller, so useValues always runs with a valid logic.+ const values = useValues(formLogic) as Record<string, any> | null+ if (!values) {+ return undefined+ }+ // Coerce to number — when the form is hydrated from a saved source's `job_inputs`+ // the integration ID arrives as a string from JSONB. Without the cast, downstream+ // `integration.id === id` lookups in `integrationsLogic` silently miss the match.+ const raw = values[formKey]?.payload?.google_search_console_integration_id+ const id = raw === undefined || raw === null || raw === '' ? undefined : Number(raw)+ return id && Number.isFinite(id) ? id : undefined+}++function GoogleSearchConsoleSiteFieldWithSuggestions({ integrationId }: { integrationId: number }): JSX.Element {+ const { sites, sitesLoading } = useValues(googleSearchConsoleIntegrationLogic({ id: integrationId }))+ const { loadSites } = useActions(googleSearchConsoleIntegrationLogic({ id: integrationId }))++ useEffect(() => {+ loadSites()+ }, [loadSites])++ const siteUrls = useMemo(() => sites.map((site) => site.siteUrl), [sites])++ return (+ <LemonField name="site_url" label="Property URL">+ {({ value, onChange }) => {+ const savedValueMissing = !!value && !sitesLoading && sites.length > 0 && !siteUrls.includes(value)+ return (+ <div className="flex flex-col gap-2">+ <InputWithSuggestionsDropdown+ data-attr="site_url"+ placeholder={SITE_URL_PLACEHOLDER}+ value={value || ''}+ onChange={onChange}+ suggestions={siteUrls}+ suggestionsLoading={sitesLoading}+ searchPlaceholder="Filter verified properties…"+ emptyMessage="No properties accessible by this account."+ loadingMessage="Loading from Google…"+ />+ {savedValueMissing && (+ <p className="m-0 text-xs text-warning">+ The currently saved property <code>{value}</code> isn't in the verified list for the+ connected Google account. Save anyway if you know it's correct, or pick a different one+ from the list.+ </p>+ )}+ </div>+ )+ }}+ </LemonField>+ )+}diff --git a/products/data_warehouse/frontend/shared/components/forms/InputWithSuggestionsDropdown.tsx b/products/data_warehouse/frontend/shared/components/forms/InputWithSuggestionsDropdown.tsxnew file mode 100644index 000000000000..d45e06e40d19--- /dev/null+++ b/products/data_warehouse/frontend/shared/components/forms/InputWithSuggestionsDropdown.tsx@@ -0,0 +1,124 @@+import { useMemo, useState } from 'react'++import { IconCheck } from '@posthog/icons'+import { LemonButton, LemonInput, Spinner } from '@posthog/lemon-ui'++import { Popover } from 'lib/lemon-ui/Popover/Popover'++export interface InputWithSuggestionsDropdownProps {+ /** Current value of the input. Free text — user can type anything, suggestions are only hints. */+ value: string+ onChange: (next: string) => void+ placeholder?: string+ 'data-attr'?: string+ /** Suggestions to surface in the popover. Each value is shown verbatim and copied into `value` on click. */+ suggestions: string[]+ suggestionsLoading?: boolean+ /** Search input placeholder inside the popover. */+ searchPlaceholder?: string+ /** Text shown when `suggestions` is empty after loading. */+ emptyMessage?: string+ /** Text shown when the search term filters out every suggestion. Receives the current term. */+ noMatchMessage?: (term: string) => string+ /** Text shown next to the spinner while suggestions load. */+ loadingMessage?: string+}++/**+ * A free-text input that opens a searchable popover of suggestions on focus.+ *+ * The popover's search input is independent from the main input — typing in the+ * search filters the suggestions list without touching `value`, so the user can+ * use suggestions as a shortcut without losing the value they typed. Clicking a+ * suggestion overwrites `value` and closes the popover.+ *+ * Stateless / presentation only — bring your own data source (e.g. an integration's+ * available resources).+ */+export function InputWithSuggestionsDropdown({+ value,+ onChange,+ placeholder,+ 'data-attr': dataAttr,+ suggestions,+ suggestionsLoading = false,+ searchPlaceholder = 'Filter suggestions…',+ emptyMessage = 'No suggestions available.',+ noMatchMessage = (term) => `No suggestions match "${term}".`,+ loadingMessage = 'Loading…',+}: InputWithSuggestionsDropdownProps): JSX.Element {+ const [open, setOpen] = useState(false)+ const [searchTerm, setSearchTerm] = useState('')++ const filtered = useMemo(() => {+ const needle = searchTerm.trim().toLowerCase()+ if (!needle) {+ return suggestions+ }+ return suggestions.filter((suggestion) => suggestion.toLowerCase().includes(needle))+ }, [suggestions, searchTerm])++ return (+ <Popover+ visible={open}+ onClickOutside={() => {+ setSearchTerm('')+ setOpen(false)+ }}+ placement="bottom-start"+ matchWidth+ overlay={+ <div className="flex flex-col gap-2 p-2 min-w-80">+ <LemonInput+ type="search"+ size="small"+ placeholder={searchPlaceholder}+ value={searchTerm}+ onChange={setSearchTerm}+ />+ {suggestionsLoading ? (+ <p className="m-0 px-2 py-1 text-xs text-secondary flex items-center gap-1">+ <Spinner /> {loadingMessage}+ </p>+ ) : suggestions.length === 0 ? (+ <p className="m-0 px-2 py-1 text-xs text-secondary">{emptyMessage}</p>+ ) : filtered.length === 0 ? (+ <p className="m-0 px-2 py-1 text-xs text-secondary">{noMatchMessage(searchTerm)}</p>+ ) : (+ <div className="flex flex-col max-h-64 overflow-y-auto">+ {filtered.map((suggestion) => {+ const isCurrent = suggestion === value+ return (+ <LemonButton+ key={suggestion}+ size="small"+ fullWidth+ active={isCurrent}+ icon={isCurrent ? <IconCheck /> : undefined}+ onClick={() => {+ onChange(suggestion)+ setSearchTerm('')+ setOpen(false)+ }}+ >+ {suggestion}+ </LemonButton>+ )+ })}+ </div>+ )}+ </div>+ }+ >+ <LemonInput+ className="ph-ignore-input"+ data-attr={dataAttr}+ placeholder={placeholder}+ type="text"+ value={value}+ onChange={onChange}+ onFocus={() => setOpen(true)}+ />+ </Popover>+ )+}diff --git a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsxindex e756690065ec..24895ecbe7cf 100644--- a/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx+++ b/products/data_warehouse/frontend/shared/components/forms/SourceForm.tsx@@ -34,6 +34,7 @@ import {import { CDC_SOURCE_TYPES } from '../../cdc'import { CustomSourceManifestBuilder } from './CustomSourceManifestBuilder'import { GitHubRepositorySelector } from './GitHubRepositorySelector'+import { GoogleSearchConsoleSiteSelector } from './GoogleSearchConsoleSiteSelector'import { SourceIntegrationChoice } from './IntegrationChoice'import { parseConnectionStringForSource } from './parsers'import { supportsDirectQuery } from './schemaGroupingUtils'@@ -305,6 +306,13 @@ export const sourceFieldToElement = (return <GitHubRepositorySelector key={field.name} />}+ if (field.type === 'text' && field.name === 'site_url' && sourceConfig.name === 'GoogleSearchConsole') {+ // Special case — once the user picks an OAuth integration the selector swaps the+ // text input for a dropdown populated from the Search Console API. Avoids the+ // `sc-domain:` vs trailing-slash typos that bounce off `validate_credentials`.+ return <GoogleSearchConsoleSiteSelector key={field.name} />+ }+return (<LemonFieldkey={field.name}diff --git a/products/integrations/frontend/generated/api.schemas.ts b/products/integrations/frontend/generated/api.schemas.tsindex 84e8ae4d6c4c..37cd0febda4c 100644--- a/products/integrations/frontend/generated/api.schemas.ts+++ b/products/integrations/frontend/generated/api.schemas.ts@@ -336,6 +336,17 @@ export interface GitHubTeamsResponseApi {has_more: boolean}+export interface GoogleSearchConsoleSiteApi {+ /** Site URL in canonical Google format — `https://example.com/` for URL-prefix properties (trailing slash mandatory) or `sc-domain:example.com` for Domain properties. */+ siteUrl: string+ /** The connected user's permission level for this site. One of `siteOwner`, `siteFullUser`, `siteRestrictedUser`, `siteUnverifiedUser`. */+ permissionLevel: string+}++export interface GoogleSearchConsoleSitesResponseApi {+ sites: GoogleSearchConsoleSiteApi[]+}+export interface IntegrationAccessRequestApi {/** The kind of integration the member is requesting be connected (e.g. 'slack', 'github').*diff --git a/products/integrations/frontend/generated/api.ts b/products/integrations/frontend/generated/api.tsindex 67dfab6edab7..f22877f6f755 100644--- a/products/integrations/frontend/generated/api.ts+++ b/products/integrations/frontend/generated/api.ts@@ -13,6 +13,7 @@ import type {GitHubReposRefreshResponseApi,GitHubReposResponseApi,GitHubTeamsResponseApi,+ GoogleSearchConsoleSitesResponseApi,IntegrationAccessRequestApi,IntegrationAccessRequestResponseApi,IntegrationConfigApi,@@ -539,6 +540,27 @@ export const integrationsGoogleConversionActionsRetrieve = async (})}+export const getIntegrationsGoogleSearchConsoleSitesRetrieveUrl = (projectId: string, id: number) => {+ return `/api/projects/${projectId}/integrations/${id}/google_search_console_sites/`+}++/**+ * List the Search Console properties the connected Google account has access to.+ */+export const integrationsGoogleSearchConsoleSitesRetrieve = async (+ projectId: string,+ id: number,+ options?: RequestInit+): Promise<GoogleSearchConsoleSitesResponseApi> => {+ return apiMutator<GoogleSearchConsoleSitesResponseApi>(+ getIntegrationsGoogleSearchConsoleSitesRetrieveUrl(projectId, id),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getIntegrationsJiraProjectsRetrieveUrl = (projectId: string, id: number) => {return `/api/projects/${projectId}/integrations/${id}/jira_projects/`}diff --git a/products/integrations/mcp/tools.yaml b/products/integrations/mcp/tools.yamlindex a0bbd53632ac..a6558d46ca35 100644--- a/products/integrations/mcp/tools.yaml+++ b/products/integrations/mcp/tools.yaml@@ -137,6 +137,9 @@ tools:integrations-google-conversion-actions-retrieve:operation: integrations_google_conversion_actions_retrieveenabled: false+ integrations-google-search-console-sites-retrieve:+ operation: integrations_google_search_console_sites_retrieve+ enabled: falseintegrations-jira-projects-retrieve:operation: integrations_jira_projects_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 26e31991bbfd..3809a149df65 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -23362,6 +23362,17 @@ export namespace Schemas {notes: string[];}+ export interface GoogleSearchConsoleSite {+ /** Site URL in canonical Google format — `https://example.com/` for URL-prefix properties (trailing slash mandatory) or `sc-domain:example.com` for Domain properties. */+ siteUrl: string;+ /** The connected user's permission level for this site. One of `siteOwner`, `siteFullUser`, `siteRestrictedUser`, `siteUnverifiedUser`. */+ permissionLevel: string;+ }++ export interface GoogleSearchConsoleSitesResponse {+ sites: GoogleSearchConsoleSite[];+ }+/*** * `line` - line* * `symbol` - symbol