Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
One plan gate for every free-plan feature (EVE-289) (#691)
Carter Smith89e4ee7d5d2d
diff --git a/src/client/components/CardShell.tsx b/src/client/components/CardShell.tsxnew file mode 100644index 00000000..a43f83ba--- /dev/null+++ b/src/client/components/CardShell.tsx@@ -0,0 +1,38 @@+import type { ReactNode } from "react";++/** Card with a header row and a divided body: dashboard and connection cards. */+export function CardShell({+ title,+ icon,+ stamp,+ action,+ children,+}: {+ title: string;+ icon?: ReactNode;+ stamp?: string;+ action?: ReactNode;+ children: ReactNode;+}) {+ return (+ <div className="overflow-hidden rounded-xl border border-base-300 bg-base-100 shadow-sm">+ <div className="flex items-center justify-between gap-4 px-5 py-4">+ <div className="flex min-w-0 items-center gap-2.5">+ {icon ? (+ <span className="grid size-8 shrink-0 place-items-center rounded-lg border border-base-300 bg-base-100 shadow-sm">+ {icon}+ </span>+ ) : null}+ <h2 className="text-base font-semibold leading-tight">{title}</h2>+ </div>+ {action}+ </div>+ <div className="border-t border-base-300 p-5">+ {children}+ {stamp ? (+ <p className="mt-4 text-[11px] text-base-content/45">{stamp}</p>+ ) : null}+ </div>+ </div>+ );+}diff --git a/src/client/components/PermissionHint.tsx b/src/client/components/PermissionHint.tsxnew file mode 100644index 00000000..59fd65c0--- /dev/null+++ b/src/client/components/PermissionHint.tsx@@ -0,0 +1,14 @@+/** Shown where a missing permission would otherwise leave a card or step empty. */+export function PermissionHint({+ action,+ className,+}: {+ action: string;+ className?: string;+}) {+ return (+ <p className={`text-sm text-base-content/60 ${className ?? ""}`}>+ Ask an organization owner or admin to {action}.+ </p>+ );+}diff --git a/src/client/features/ai-search/BrandLookupPage.tsx b/src/client/features/ai-search/BrandLookupPage.tsxindex 9e9e0b59..31138853 100644--- a/src/client/features/ai-search/BrandLookupPage.tsx+++ b/src/client/features/ai-search/BrandLookupPage.tsx@@ -9,10 +9,8 @@ import {TrendingUp,} from "lucide-react";import { lookupBrand } from "@/serverFunctions/ai-search";-import {- HostedPlanGate,- type HostedPlanGateState,-} from "@/client/features/billing/HostedPlanGate";+import { useHostedPlanGate } from "@/client/features/billing/HostedPlanGate";+import { PageLoading } from "@/client/components/Spinner";import { getStandardErrorMessage } from "@/client/lib/error-messages";import { BrandLookupResults } from "@/client/features/ai-search/components/BrandLookupResults";import { BrandLookupSearchCard } from "@/client/features/ai-search/components/BrandLookupSearchCard";@@ -67,22 +65,14 @@ const BRAND_LOOKUP_BULLETS = [},];-export function BrandLookupPage(props: Props) {- return (- <HostedPlanGate>- {(planGate) => <BrandLookupPageInner {...props} planGate={planGate} />}- </HostedPlanGate>- );-}--function BrandLookupPageInner({+export function BrandLookupPage({projectId,initialQuery,initialCompetitors,initialScope,onSearchChange,- planGate,-}: Props & { planGate: HostedPlanGateState }) {+}: Props) {+ const planStatus = useHostedPlanGate();const [query, setQuery] = useState(initialQuery);// The user's explicit scope pick, or undefined to follow the input's default.const [scopeChoice, setScopeChoice] = useState<ResearchScope | undefined>(@@ -142,7 +132,7 @@ function BrandLookupPageInner({// Client-side gate is a UX optimization only; the paywall is enforced// server-side (lookupBrand → assertPaidPlan) before any DataForSEO spend,// so a stale free-plan window here just yields a rejected request, not cost.- enabled: hasActiveQuery && !planGate.isFreePlan,+ enabled: hasActiveQuery && planStatus === "paid",staleTime: 5 * 60 * 1000,retry: false,});@@ -270,7 +260,9 @@ function BrandLookupPageInner({</p></div>- {planGate.isFreePlan ? (+ {planStatus === "loading" ? (+ <PageLoading />+ ) : planStatus === "free" ? (<AiSearchPaidPlanGatefeature="Brand Lookup"description="See how ChatGPT and Google AI Overview cite any brand or domain — total mentions, sample prompts where it appears, and the pages cited alongside it."diff --git a/src/client/features/ai-search/PromptExplorerPage.tsx b/src/client/features/ai-search/PromptExplorerPage.tsxindex 75a4aa50..0ce70271 100644--- a/src/client/features/ai-search/PromptExplorerPage.tsx+++ b/src/client/features/ai-search/PromptExplorerPage.tsx@@ -10,10 +10,8 @@ import {Sparkles,} from "lucide-react";import { explorePrompt } from "@/serverFunctions/ai-search";-import {- HostedPlanGate,- type HostedPlanGateState,-} from "@/client/features/billing/HostedPlanGate";+import { useHostedPlanGate } from "@/client/features/billing/HostedPlanGate";+import { PageLoading } from "@/client/components/Spinner";import { getStandardErrorMessage } from "@/client/lib/error-messages";import { PromptExplorerForm } from "@/client/features/ai-search/components/PromptExplorerForm";import { PromptExplorerResults } from "@/client/features/ai-search/components/PromptExplorerResults";@@ -63,20 +61,8 @@ const PROMPT_EXPLORER_BULLETS = [},];-export function PromptExplorerPage(props: Props) {- return (- <HostedPlanGate>- {(planGate) => <PromptExplorerPageInner {...props} planGate={planGate} />}- </HostedPlanGate>- );-}--function PromptExplorerPageInner({- projectId,- urlState,- onSubmit,- planGate,-}: Props & { planGate: HostedPlanGateState }) {+export function PromptExplorerPage({ projectId, urlState, onSubmit }: Props) {+ const planStatus = useHostedPlanGate();const [form, setForm] = useState<PromptExplorerFormValues>(urlState);const [validationError, setValidationError] = useState<string | null>(null);@@ -114,7 +100,7 @@ function PromptExplorerPageInner({// Client-side gate is a UX optimization only; the paywall is enforced// server-side (explorePrompt → assertPaidPlan) before any DataForSEO spend,// so a stale free-plan window here just yields a rejected request, not cost.- enabled: hasActivePrompt && !planGate.isFreePlan,+ enabled: hasActivePrompt && planStatus === "paid",staleTime: 5 * 60 * 1000,retry: false,});@@ -206,7 +192,9 @@ function PromptExplorerPageInner({</p></div>- {planGate.isFreePlan ? (+ {planStatus === "loading" ? (+ <PageLoading />+ ) : planStatus === "free" ? (<AiSearchPaidPlanGatefeature="Prompt Explorer"description="Ask one prompt across ChatGPT, Claude, Gemini, and Perplexity at the same time and compare their answers — including which sources each model cites."diff --git a/src/client/features/audit/launch/LaunchView.tsx b/src/client/features/audit/launch/LaunchView.tsxindex 9a48e563..7eacf482 100644--- a/src/client/features/audit/launch/LaunchView.tsx+++ b/src/client/features/audit/launch/LaunchView.tsx@@ -1,10 +1,7 @@-import { useCustomer } from "autumn-js/react";import { AuditHistorySection } from "@/client/features/audit/launch/AuditHistorySection";import { LaunchFormCard } from "@/client/features/audit/launch/LaunchFormCard";import { useLaunchController } from "@/client/features/audit/launch/useLaunchController";-import { getCustomerPlanStatus } from "@/client/features/billing/plan-detection";-import { useSession } from "@/lib/auth-client";-import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { useHostedPlanGate } from "@/client/features/billing/HostedPlanGate";type LaunchViewProps = {projectId: string;@@ -12,39 +9,14 @@ type LaunchViewProps = {onAuditStarted: (auditId: string) => void;};-export function LaunchView(props: LaunchViewProps) {- // Self-hosted has no Autumn customer and resolves to the paid tier on the- // server, so only hosted mode needs to look up the plan.- if (!isHostedClientAuthMode()) {- return <LaunchContent {...props} isFreePlan={false} />;- }-- return <HostedLaunchView {...props} />;-}--function HostedLaunchView(props: LaunchViewProps) {- const { data: session } = useSession();- const customerQuery = useCustomer({- queryOptions: {- enabled: Boolean(session?.user?.id),- },- });-- // Until the customer loads, leave the form unrestricted rather than flash- // free-plan copy at paid users; the server enforces the limit regardless.- const isFreePlan =- customerQuery.data != null &&- getCustomerPlanStatus(customerQuery.data) === "free";-- return <LaunchContent {...props} isFreePlan={isFreePlan} />;-}--function LaunchContent({+export function LaunchView({projectId,initialUrl,- isFreePlan,onAuditStarted,-}: LaunchViewProps & { isFreePlan: boolean }) {+}: LaunchViewProps) {+ // The plan only sets the page limit, so the form stays usable while the+ // plan loads. The server enforces the limit regardless.+ const isFreePlan = useHostedPlanGate() === "free";const controller = useLaunchController({projectId,initialUrl,diff --git a/src/client/features/billing/HostedPlanGate.tsx b/src/client/features/billing/HostedPlanGate.tsxindex ec020a64..03ef2764 100644--- a/src/client/features/billing/HostedPlanGate.tsx+++ b/src/client/features/billing/HostedPlanGate.tsx@@ -1,46 +1,27 @@-import type { ReactNode } from "react";import { useCustomer } from "autumn-js/react";import { useSession } from "@/lib/auth-client";import { isHostedClientAuthMode } from "@/lib/auth-mode";-import { getCustomerPlanStatus } from "@/client/features/billing/plan-detection";+import {+ getCustomerPlanStatus,+ type PlanStatus,+} from "@/client/features/billing/plan-detection";-export type HostedPlanGateState = {- isLoading: boolean;- isFreePlan: boolean;-};--const SELF_HOSTED_PLAN_GATE: HostedPlanGateState = {- isLoading: false,- isFreePlan: false,-};--export function HostedPlanGate({- children,-}: {- children: (state: HostedPlanGateState) => ReactNode;-}) {- if (!isHostedClientAuthMode()) {- return children(SELF_HOSTED_PLAN_GATE);- }-- return <HostedPlanGateContent>{children}</HostedPlanGateContent>;-}--function HostedPlanGateContent({- children,-}: {- children: (state: HostedPlanGateState) => ReactNode;-}) {+// The single client-side plan gate. It is a UX layer only: the server enforces+// every paid-plan limit before it spends anything.+export function useHostedPlanGate(): "loading" | PlanStatus {+ // Self-hosted has no Autumn customer and resolves to the paid tier on the+ // server, so only hosted mode looks up the plan.+ const isHostedMode = isHostedClientAuthMode();const { data: session, isPending: isSessionPending } = useSession();const hasSession = Boolean(session?.user?.id);const customerQuery = useCustomer({- queryOptions: { enabled: hasSession },+ queryOptions: { enabled: isHostedMode && hasSession },});- return children({- isLoading: isSessionPending || !hasSession || customerQuery.isLoading,- isFreePlan:- !!customerQuery.data &&- getCustomerPlanStatus(customerQuery.data) === "free",- });+ if (!isHostedMode) return "paid";+ if (isSessionPending || !hasSession || customerQuery.isLoading) {+ return "loading";+ }+ // Fails closed: a customer that failed to load resolves to "free".+ return getCustomerPlanStatus(customerQuery.data);}diff --git a/src/client/features/dashboard/DashboardCards.tsx b/src/client/features/dashboard/DashboardCards.tsxindex 4bb78c4e..589bad70 100644--- a/src/client/features/dashboard/DashboardCards.tsx+++ b/src/client/features/dashboard/DashboardCards.tsx@@ -1,7 +1,8 @@+import { CardShell } from "@/client/components/CardShell";import { Link } from "@tanstack/react-router";import { useQuery } from "@tanstack/react-query";import { Check } from "lucide-react";-import { SearchConsoleConnectionCard } from "@/client/features/gsc/SearchConsoleConnectionCard";+import { GoogleConnectionCard } from "@/client/features/integrations/GoogleConnectionCard";import { AUDIT_ISSUE_TYPES } from "@/shared/audit-issues";import {@@ -11,7 +12,6 @@ import {} from "@/client/features/search-performance/SearchPerformanceColumns";import { getSearchPerformanceReport } from "@/serverFunctions/searchPerformance";import {- CardShell,EmptyCardBody,formatDay,moreDetailsClass,@@ -53,7 +53,7 @@ export function GscCard({if (!connected || (report && !report.connected)) {return (<div id="connect-gsc">- <SearchConsoleConnectionCard projectId={projectId} />+ <GoogleConnectionCard provider="gsc" projectId={projectId} /></div>);}diff --git a/src/client/features/dashboard/DashboardSetupAction.tsx b/src/client/features/dashboard/DashboardSetupAction.tsxindex 7c08753d..3f73565b 100644--- a/src/client/features/dashboard/DashboardSetupAction.tsx+++ b/src/client/features/dashboard/DashboardSetupAction.tsx@@ -10,6 +10,7 @@ import {import { CopyButton } from "@/client/features/ai-mcp/SetupControls";import { CreateProjectModal } from "@/client/features/projects/CreateProjectModal";import { InviteTeammateModal } from "@/client/features/team/InviteTeammateModal";+import { PermissionHint } from "@/client/components/PermissionHint";import { organizationContextQueryOptions } from "@/client/features/team/organizationQueries";import { getStandardErrorMessage } from "@/client/lib/error-messages";import { captureClientEvent } from "@/client/lib/posthog";@@ -146,14 +147,16 @@ export function DashboardSetupAction({step === "project" ? { project: ["create"] } : { invitation: ["create"] },);if (!canManage)- return (+ return org.isPending ? (+ <p className="text-sm text-base-content/65">+ Checking workspace permissions…+ </p>+ ) : org.isError ? (<p className="text-sm text-base-content/65">- {org.isPending- ? "Checking workspace permissions…"- : org.isError- ? getStandardErrorMessage(org.error)- : "Ask a workspace owner or admin to help with this step."}+ {getStandardErrorMessage(org.error)}</p>+ ) : (+ <PermissionHint action="help with this step" />);if (step === "project")return (diff --git a/src/client/features/dashboard/Ga4Card.tsx b/src/client/features/dashboard/Ga4Card.tsxindex 7cb971cf..fad32d93 100644--- a/src/client/features/dashboard/Ga4Card.tsx+++ b/src/client/features/dashboard/Ga4Card.tsx@@ -1,3 +1,4 @@+import { CardShell } from "@/client/components/CardShell";import { Link } from "@tanstack/react-router";import { useQuery } from "@tanstack/react-query";import {@@ -9,7 +10,6 @@ import {YAxis,} from "recharts";import {- CardShell,moreDetailsClass,PercentDelta,Stat,diff --git a/src/client/features/dashboard/Ga4ConnectCard.tsx b/src/client/features/dashboard/Ga4ConnectCard.tsxindex 3fa6b7db..586d2e06 100644--- a/src/client/features/dashboard/Ga4ConnectCard.tsx+++ b/src/client/features/dashboard/Ga4ConnectCard.tsx@@ -1,5 +1,5 @@import { useMutation, useQueryClient } from "@tanstack/react-query";-import { GoogleAnalyticsConnectionCard } from "@/client/features/ga4/GoogleAnalyticsConnectionCard";+import { GoogleConnectionCard } from "@/client/features/integrations/GoogleConnectionCard";import { captureClientEvent } from "@/client/lib/posthog";import { dismissDashboardGa4Card } from "@/serverFunctions/dashboard";@@ -20,7 +20,8 @@ export function Ga4ConnectCard({});return (- <GoogleAnalyticsConnectionCard+ <GoogleConnectionCard+ provider="ga4"projectId={projectId}onDismiss={connecteddiff --git a/src/client/features/dashboard/cardParts.tsx b/src/client/features/dashboard/cardParts.tsxindex fe09e9f0..ee6a9751 100644--- a/src/client/features/dashboard/cardParts.tsx+++ b/src/client/features/dashboard/cardParts.tsx@@ -1,34 +1,4 @@-// Shared building blocks for the dashboard cards. Same visual language as-// the GSC IntegrationCard (rounded-xl, shadow-sm, header row + divider) so-// the embedded SearchConsoleConnectionCard doesn't read as a different-// design system.-export function CardShell({- title,- stamp,- action,- children,-}: {- title: string;- stamp?: string;- action?: React.ReactNode;- children: React.ReactNode;-}) {- return (- <div className="overflow-hidden rounded-xl border border-base-300 bg-base-100 shadow-sm">- <div className="flex items-center justify-between gap-4 px-5 py-4">- <h2 className="text-base font-semibold leading-tight">{title}</h2>- {action}- </div>- <div className="border-t border-base-300 p-5">- {children}- {stamp ? (- <p className="mt-4 text-[11px] text-base-content/45">{stamp}</p>- ) : null}- </div>- </div>- );-}-+// Shared building blocks for the dashboard cards.export function EmptyCardBody({message,cta,diff --git a/src/client/features/ga4/Ga4PropertyPicker.tsx b/src/client/features/ga4/Ga4PropertyPicker.tsxdeleted file mode 100644index 630a3c63..00000000--- a/src/client/features/ga4/Ga4PropertyPicker.tsx+++ /dev/null@@ -1,52 +0,0 @@-import { GooglePropertyPicker } from "@/client/features/integrations/GooglePropertyPicker";-type PropertyOption = {- propertyId: string;- displayName: string;- accountDisplayName: string;- isSelected: boolean;-};--type AccountOption = {- accountId: string;- email: string | null;- requiresReconnect: boolean;- propertiesUnavailable: boolean;- properties: PropertyOption[];-};--export type Ga4PropertySelection = {- accountId: string;- propertyId: string;-};--export function Ga4PropertyPicker(props: {- readOnly?: boolean;- loading: boolean;- linking?: boolean;- error: boolean;- accounts: AccountOption[];- selection: Ga4PropertySelection | null;- onSelect: (selection: Ga4PropertySelection | null) => void;- onSave: () => void;- saving: boolean;- onRetry: () => void;- onReconnect: () => void;- secondaryAction?: { label: string; onClick: () => void; disabled?: boolean };-}) {- return (- <GooglePropertyPicker- {...props}- provider="ga4"- accounts={props.accounts.map((account) => ({- ...account,- unavailable: account.propertiesUnavailable,- properties: account.properties.map((property) => ({- id: property.propertyId,- name: property.displayName,- detail: `${property.accountDisplayName} · ${property.propertyId.replace(/^properties\//, "")}`,- selectable: true,- })),- }))}- />- );-}diff --git a/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx b/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsxdeleted file mode 100644index e14b9397..00000000--- a/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx+++ /dev/null@@ -1,270 +0,0 @@-import { ga4ConnectionOptions } from "@/client/features/integrations/googleConnectionQueries";-import * as React from "react";-import { GoogleConnectedState } from "@/client/features/integrations/GoogleConnectedState";-import { useGooglePickerResume } from "@/client/features/integrations/useGooglePickerResume";-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { toast } from "sonner";-import {- Ga4PropertyPicker,- type Ga4PropertySelection,-} from "@/client/features/ga4/Ga4PropertyPicker";-import { GoogleProjectEmptyState } from "@/client/features/integrations/GoogleProjectEmptyState";-import { GoogleLinkErrorAlert } from "@/client/features/integrations/GoogleLinkErrorAlert";-import { GoogleOAuthSetupWarning } from "@/client/features/integrations/GoogleOAuthSetupWarning";-import { IntegrationConnectionCard } from "@/client/features/integrations/IntegrationConnectionCard";-import { GoogleAnalyticsLogo } from "@/client/features/integrations/GoogleProductLogos";-import { getStandardErrorMessage } from "@/client/lib/error-messages";-import { captureClientEvent } from "@/client/lib/posthog";-import { isHostedClientAuthMode } from "@/lib/auth-mode";-import {- disconnectGa4,- listGa4Properties,- setGa4Property,-} from "@/serverFunctions/ga4";-import { GA4_SELF_HOSTED_SETUP_DOCS_URL } from "@/shared/ga4";--export function GoogleAnalyticsConnectionCard({- projectId,- onDismiss,- dismissing = false,-}: {- projectId: string;- onDismiss?: () => void;- dismissing?: boolean;-}) {- const hosted = isHostedClientAuthMode();- const queryClient = useQueryClient();- const { picking, setPicking, linkAccount, linking } = useGooglePickerResume(- "ga4",- projectId,- );- const [selection, setSelection] = React.useState<Ga4PropertySelection | null>(- null,- );- const connectionOptions = ga4ConnectionOptions(projectId);- const connectionKey = connectionOptions.queryKey;- const connectionQuery = useQuery(connectionOptions);- const connection = connectionQuery.data;- const connectionUnavailable = connectionQuery.isError && !connection;- const connected = Boolean(connection?.connected);- const hasGrant = Boolean(connection?.currentUserHasGrant);- const canManage = connection?.canManage === true;- const needsGoogleOAuthSetup =- !hosted && connectionQuery.isSuccess && !connection?.googleOAuthConfigured;- const showPicker = picking ?? (!connected && hasGrant && canManage);- const propertiesQuery = useQuery({- queryKey: ["ga4Properties", projectId],- queryFn: () => listGa4Properties({ data: { projectId } }),- enabled: Boolean(showPicker && !needsGoogleOAuthSetup),- });- const accounts = React.useMemo(- () => propertiesQuery.data?.accounts ?? [],- [propertiesQuery.data?.accounts],- );-- React.useEffect(() => {- if (!picking || !connected || selection) return;- for (const account of accounts) {- const selectedProperty = account.properties.find(- (property) => property.isSelected,- );- if (selectedProperty) {- setSelection({- accountId: account.accountId,- propertyId: selectedProperty.propertyId,- });- return;- }- }- }, [accounts, selection, picking, connected]);-- const invalidateReports = () => {- void queryClient.invalidateQueries({- queryKey: ["dashboardActivation", projectId],- });- void queryClient.invalidateQueries({- queryKey: ["dashboardGa4Report", projectId],- });- };- const setPropertyMutation = useMutation({- meta: { errorToast: false },- mutationFn: (selected: Ga4PropertySelection) =>- setGa4Property({ data: { projectId, ...selected } }),- onSuccess: (saved) => {- queryClient.setQueryData(connectionKey, (current: typeof connection) =>- current ? { ...current, ...saved } : current,- );- captureClientEvent("ga4:property_select");- toast.success("Google Analytics connected");- queryClient.removeQueries({ queryKey: ["ga4Properties", projectId] });- void queryClient.invalidateQueries({ queryKey: connectionKey });- setPicking(false);- invalidateReports();- },- });- const disconnectMutation = useMutation({- meta: { errorToast: false },- mutationFn: () => disconnectGa4({ data: { projectId } }),- onSuccess: () => {- toast.success("Google Analytics disconnected from this project");- queryClient.setQueryData(connectionKey, (current: typeof connection) =>- current ? { ...current, connected: false } : current,- );- queryClient.removeQueries({ queryKey: ["ga4Properties", projectId] });- setPicking(false);- setSelection(null);- void queryClient.invalidateQueries({ queryKey: connectionKey });- invalidateReports();- },- });- const changingConnection =- setPropertyMutation.isPending || disconnectMutation.isPending || linking;- const dismissDisabled = dismissing || changingConnection;- const handleConnect = () => void linkAccount(window.location.href);-- return (- <IntegrationConnectionCard- title="Google Analytics"- icon={<GoogleAnalyticsLogo className="size-5" />}- status={- connectionQuery.isPending || connectionUnavailable- ? undefined- : needsGoogleOAuthSetup- ? "setup_required"- : connected- ? "connected"- : "disconnected"- }- >- <GoogleLinkErrorAlert provider="ga4" className="mb-4" />- {connectionQuery.isPending ? (- <div- role="status"- aria-label="Loading connection"- className="space-y-3 animate-pulse"- >- <div className="h-4 w-2/3 rounded bg-base-200" />- <div className="h-9 w-24 rounded bg-base-200" />- </div>- ) : connectionUnavailable ? (- <div role="alert" className="space-y-3 text-sm">- <p className="text-error">- Couldn't check this project's connection.- </p>- <button- type="button"- className="btn btn-ghost btn-sm"- onClick={() => void connectionQuery.refetch()}- >- Try again- </button>- </div>- ) : needsGoogleOAuthSetup ? (- <div className="space-y-3">- <GoogleOAuthSetupWarning- integrationName="Google Analytics"- docsUrl={GA4_SELF_HOSTED_SETUP_DOCS_URL}- />- <DismissButton onClick={onDismiss} disabled={dismissDisabled} />- </div>- ) : connected && !picking ? (- <GoogleConnectedState- property={connection?.propertyDisplayName ?? ""}- detail={connection?.propertyId}- canManageAccounts={hasGrant}- email={connection?.connectedByEmail}- onChange={() => {- setPropertyMutation.reset();- disconnectMutation.reset();- setSelection(null);- setPicking(true);- }}- onDisconnect={() => {- setPropertyMutation.reset();- disconnectMutation.mutate();- }}- disconnecting={disconnectMutation.isPending}- disabled={linking}- canManage={canManage}- />- ) : showPicker ? (- <fieldset disabled={changingConnection}>- <Ga4PropertyPicker- readOnly={!canManage}- linking={linking}- loading={propertiesQuery.isLoading}- error={propertiesQuery.isError}- accounts={accounts}- selection={selection}- onSelect={setSelection}- onSave={() => selection && setPropertyMutation.mutate(selection)}- saving={setPropertyMutation.isPending}- secondaryAction={{- label: "Cancel",- disabled: setPropertyMutation.isPending,- onClick: () => {- setPicking(false);- setSelection(null);- setPropertyMutation.reset();- },- }}- onRetry={() => void propertiesQuery.refetch()}- onReconnect={handleConnect}- />- </fieldset>- ) : (- <GoogleProjectEmptyState- name="Google Analytics"- hasGrant={hasGrant}- canManage={canManage}- disabled={linking}- onLink={handleConnect}- onChoose={() => {- setPropertyMutation.reset();- disconnectMutation.reset();- setSelection(null);- setPicking(true);- }}- >- <DismissButton onClick={onDismiss} disabled={dismissDisabled} />- </GoogleProjectEmptyState>- )}- {showPicker && onDismiss && !connected ? (- <DismissButton onClick={onDismiss} disabled={dismissDisabled} />- ) : null}- {setPropertyMutation.isError || disconnectMutation.isError ? (- <p role="alert" className="mt-3 text-sm text-error">- {getStandardErrorMessage(- setPropertyMutation.error ?? disconnectMutation.error,- )}- </p>- ) : null}- {connectionQuery.isSuccess && !needsGoogleOAuthSetup && !canManage ? (- <p className="mt-3 text-sm text-base-content/60">- Ask an organization owner or admin to change this project's- connection.- </p>- ) : null}- </IntegrationConnectionCard>- );-}--function DismissButton({- onClick,- disabled,-}: {- onClick?: () => void;- disabled: boolean;-}) {- if (!onClick) return null;- return (- <button- type="button"- className="btn btn-ghost btn-sm text-base-content/60"- onClick={onClick}- disabled={disabled}- >- Dismiss- </button>- );-}diff --git a/src/client/features/gsc/SearchConsoleConnectionCard.tsx b/src/client/features/gsc/SearchConsoleConnectionCard.tsxdeleted file mode 100644index e93b2667..00000000--- a/src/client/features/gsc/SearchConsoleConnectionCard.tsx+++ /dev/null@@ -1,262 +0,0 @@-import { gscConnectionOptions } from "@/client/features/integrations/googleConnectionQueries";-import * as React from "react";-import { GoogleConnectedState } from "@/client/features/integrations/GoogleConnectedState";-import { useGooglePickerResume } from "@/client/features/integrations/useGooglePickerResume";-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { toast } from "sonner";-import { getStandardErrorMessage } from "@/client/lib/error-messages";-import { captureClientEvent } from "@/client/lib/posthog";-import { GoogleProjectEmptyState } from "@/client/features/integrations/GoogleProjectEmptyState";-import { GoogleLinkErrorAlert } from "@/client/features/integrations/GoogleLinkErrorAlert";-import { IntegrationConnectionCard } from "@/client/features/integrations/IntegrationConnectionCard";-import { GoogleSearchConsoleLogo } from "@/client/features/integrations/GoogleProductLogos";-import { SelfHostedSetupWarning } from "@/client/features/gsc/SelfHostedSetupWarning";-import {- SitePicker,- type GscSiteSelection,-} from "@/client/features/gsc/SitePicker";-import { disconnectGsc, listGscSites, setGscSite } from "@/serverFunctions/gsc";--const GRANT_STATUS_KEY = ["gscGrantStatus"];--export function SearchConsoleConnectionCard({- projectId,- returnTo,-}: {- projectId: string;- returnTo?: string;-}) {- const queryClient = useQueryClient();- const { picking, setPicking, linkAccount, linking } = useGooglePickerResume(- "gsc",- projectId,- );- const [selection, setSelection] = React.useState<GscSiteSelection | null>(- null,- );-- const connectionOptions = gscConnectionOptions(projectId);- const connectionKey = connectionOptions.queryKey;- const connectionQuery = useQuery(connectionOptions);- const connection = connectionQuery.data;- const connected = Boolean(connection?.connected);- const hasGrant = Boolean(connection?.currentUserHasGrant);- const canManage = connection?.canManage === true;- const needsGoogleOAuthSetup =- connectionQuery.isSuccess && !connection?.googleOAuthConfigured;-- const showPicker = picking ?? (!connected && hasGrant && canManage);- const sitesQuery = useQuery({- queryKey: ["gscSites", projectId],- queryFn: () => listGscSites({ data: { projectId } }),- enabled: Boolean(showPicker && !needsGoogleOAuthSetup),- });- const accounts = React.useMemo(- () => sitesQuery.data?.accounts ?? [],- [sitesQuery.data?.accounts],- );- const requiresReconnect = accounts.some(- (account) => account.requiresReconnect,- );-- React.useEffect(() => {- if (!requiresReconnect) return;-- void queryClient.invalidateQueries({- queryKey: ["gscConnection", projectId],- });- void queryClient.invalidateQueries({ queryKey: GRANT_STATUS_KEY });- }, [requiresReconnect, queryClient, projectId]);-- React.useEffect(() => {- if (!picking || !connected || selection) return;- for (const account of accounts) {- const selectedSite = account.sites.find((site) => site.isSelected);- if (selectedSite) {- setSelection({- accountId: account.accountId,- siteUrl: selectedSite.siteUrl,- });- return;- }- }- }, [accounts, selection, picking, connected]);-- const setSiteMutation = useMutation({- meta: { errorToast: false },- mutationFn: (selected: GscSiteSelection) =>- setGscSite({ data: { projectId, ...selected } }),- onSuccess: (saved) => {- queryClient.setQueryData(connectionKey, (current: typeof connection) =>- current ? { ...current, ...saved } : current,- );- captureClientEvent("gsc:property_select");- toast.success("Search Console connected");- queryClient.removeQueries({ queryKey: ["gscSites", projectId] });- void queryClient.invalidateQueries({ queryKey: connectionKey });- setPicking(false);- void queryClient.invalidateQueries({ queryKey: GRANT_STATUS_KEY });- // The Search Performance report caches {connected:false}; refresh it so- // the page shows data right after connecting instead of the stale card.- void queryClient.invalidateQueries({- queryKey: ["searchPerformance", projectId],- });- void queryClient.invalidateQueries({- queryKey: ["searchPerformanceTable", projectId],- });- // The dashboard embeds this card and swaps it for the Search- // performance stats card once activation reports the connection.- void queryClient.invalidateQueries({- queryKey: ["dashboardActivation", projectId],- });- void queryClient.invalidateQueries({- queryKey: ["dashboardGscReport", projectId],- });- },- });-- const disconnectMutation = useMutation({- meta: { errorToast: false },- mutationFn: () => disconnectGsc({ data: { projectId } }),- onSuccess: () => {- toast.success("Search Console disconnected from this project");- queryClient.setQueryData(connectionKey, (current: typeof connection) =>- current ? { ...current, connected: false } : current,- );- queryClient.removeQueries({ queryKey: ["gscSites", projectId] });- setPicking(false);- setSelection(null);- void queryClient.invalidateQueries({ queryKey: connectionKey });- void queryClient.invalidateQueries({ queryKey: GRANT_STATUS_KEY });- void queryClient.invalidateQueries({- queryKey: ["searchPerformance", projectId],- });- void queryClient.invalidateQueries({- queryKey: ["searchPerformanceTable", projectId],- });- void queryClient.invalidateQueries({- queryKey: ["dashboardActivation", projectId],- });- void queryClient.invalidateQueries({- queryKey: ["dashboardGscReport", projectId],- });- },- });-- const handleConnect = () =>- void linkAccount(returnTo ?? window.location.href);-- return (- <IntegrationConnectionCard- title="Google Search Console"- icon={<GoogleSearchConsoleLogo className="size-5" />}- status={- connectionQuery.isPending || (connectionQuery.isError && !connection)- ? undefined- : needsGoogleOAuthSetup- ? "setup_required"- : connected- ? "connected"- : "disconnected"- }- >- <GoogleLinkErrorAlert provider="gsc" className="mb-4" />- {connectionQuery.isPending ? (- <div- role="status"- aria-label="Loading connection"- className="space-y-3 animate-pulse"- >- <div className="h-4 w-2/3 rounded bg-base-200" />- <div className="h-9 w-24 rounded bg-base-200" />- </div>- ) : connectionQuery.isError && !connection ? (- <div role="alert" className="space-y-3 text-sm">- <p className="text-error">- Couldn't check this project's connection.- </p>- <button- type="button"- className="btn btn-ghost btn-sm"- onClick={() => void connectionQuery.refetch()}- >- Try again- </button>- </div>- ) : needsGoogleOAuthSetup ? (- <SelfHostedSetupWarning />- ) : connected && !picking ? (- <GoogleConnectedState- property={connection?.siteUrl ?? ""}- canManageAccounts={hasGrant}- email={connection?.connectedByEmail}- onChange={() => {- setSiteMutation.reset();- disconnectMutation.reset();- setSelection(null);- setPicking(true);- }}- onDisconnect={() => {- setSiteMutation.reset();- disconnectMutation.mutate();- }}- disconnecting={disconnectMutation.isPending}- disabled={linking}- canManage={canManage}- />- ) : showPicker ? (- <fieldset disabled={linking || setSiteMutation.isPending}>- <SitePicker- readOnly={!canManage}- linking={linking}- loading={sitesQuery.isLoading}- error={sitesQuery.isError}- accounts={accounts}- selection={selection}- onSelect={setSelection}- onSave={() => selection && setSiteMutation.mutate(selection)}- saving={setSiteMutation.isPending}- secondaryAction={{- label: "Cancel",- disabled: setSiteMutation.isPending,- onClick: () => {- setPicking(false);- setSelection(null);- setSiteMutation.reset();- },- }}- onRetry={() => void sitesQuery.refetch()}- onReconnect={handleConnect}- />- </fieldset>- ) : (- <GoogleProjectEmptyState- name="Search Console"- hasGrant={hasGrant}- canManage={canManage}- disabled={linking}- onLink={handleConnect}- onChoose={() => {- setSiteMutation.reset();- disconnectMutation.reset();- setSelection(null);- setPicking(true);- }}- ></GoogleProjectEmptyState>- )}- {setSiteMutation.isError || disconnectMutation.isError ? (- <p role="alert" className="mt-3 text-sm text-error">- {getStandardErrorMessage(- setSiteMutation.error ?? disconnectMutation.error,- )}- </p>- ) : null}- {connectionQuery.isSuccess && !needsGoogleOAuthSetup && !canManage ? (- <p className="mt-3 text-sm text-base-content/60">- Ask an organization owner or admin to change this project's- connection.- </p>- ) : null}- </IntegrationConnectionCard>- );-}diff --git a/src/client/features/gsc/SelfHostedSetupWarning.tsx b/src/client/features/gsc/SelfHostedSetupWarning.tsxdeleted file mode 100644index b9824f53..00000000--- a/src/client/features/gsc/SelfHostedSetupWarning.tsx+++ /dev/null@@ -1,15 +0,0 @@-import { GoogleOAuthSetupWarning } from "@/client/features/integrations/GoogleOAuthSetupWarning";-import { GSC_SELF_HOSTED_SETUP_DOCS_URL } from "@/shared/gsc";--/**- * Shown in self-hosted deployments that haven't set GOOGLE_CLIENT_ID/SECRET yet- * — in both the Integrations card and the onboarding step.- */-export function SelfHostedSetupWarning() {- return (- <GoogleOAuthSetupWarning- integrationName="Search Console"- docsUrl={GSC_SELF_HOSTED_SETUP_DOCS_URL}- />- );-}diff --git a/src/client/features/gsc/SitePicker.tsx b/src/client/features/gsc/SitePicker.tsxdeleted file mode 100644index 59a200ef..00000000--- a/src/client/features/gsc/SitePicker.tsx+++ /dev/null@@ -1,72 +0,0 @@-import type { ReactNode } from "react";-import { GooglePropertyPicker } from "@/client/features/integrations/GooglePropertyPicker";-type SiteOption = {- siteUrl: string;- permissionLevel: string;- selectable: boolean;- isSelected: boolean;-};--type AccountOption = {- accountId: string;- email: string | null;- requiresReconnect: boolean;- propertiesUnavailable: boolean;- sites: SiteOption[];-};--export type GscSiteSelection = {- accountId: string;- siteUrl: string;-};--export function SitePicker(props: {- readOnly?: boolean;- loading: boolean;- linking?: boolean;- error: boolean;- accounts: AccountOption[];- selection: GscSiteSelection | null;- onSelect: (selection: GscSiteSelection | null) => void;- onSave: () => void;- saving: boolean;- saveLabel?: string;- renderActions?: (saveButton: ReactNode) => ReactNode;- onRetry: () => void;- onReconnect: () => void;- secondaryAction?: { label: string; onClick: () => void; disabled?: boolean };-}) {- return (- <GooglePropertyPicker- {...props}- provider="gsc"- accounts={props.accounts.map((account) => ({- ...account,- unavailable: account.propertiesUnavailable,- properties: account.sites.map((site) => ({- id: site.siteUrl,- name: site.siteUrl,- selectable: site.selectable,- })),- }))}- selection={- props.selection- ? {- accountId: props.selection.accountId,- propertyId: props.selection.siteUrl,- }- : null- }- onSelect={(selection) =>- props.onSelect(- selection- ? {- accountId: selection.accountId,- siteUrl: selection.propertyId,- }- : null,- )- }- />- );-}diff --git a/src/client/features/integrations/GoogleConnectionCard.tsx b/src/client/features/integrations/GoogleConnectionCard.tsxnew file mode 100644index 00000000..37686728--- /dev/null+++ b/src/client/features/integrations/GoogleConnectionCard.tsx@@ -0,0 +1,295 @@+import * as React from "react";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { toast } from "sonner";+import { CardShell } from "@/client/components/CardShell";+import { PermissionHint } from "@/client/components/PermissionHint";+import { GoogleConnectedState } from "@/client/features/integrations/GoogleConnectedState";+import { GoogleLinkErrorAlert } from "@/client/features/integrations/GoogleLinkErrorAlert";+import { GoogleOAuthSetupWarning } from "@/client/features/integrations/GoogleOAuthSetupWarning";+import { GoogleProjectEmptyState } from "@/client/features/integrations/GoogleProjectEmptyState";+import {+ GooglePropertyPicker,+ type GooglePickerSelection,+} from "@/client/features/integrations/GooglePropertyPicker";+import {+ googleConnectionOptions,+ googleProviders,+ type GoogleConnection,+ type GoogleProvider,+} from "@/client/features/integrations/googleProviders";+import { useGooglePickerResume } from "@/client/features/integrations/useGooglePickerResume";+import { getStandardErrorMessage } from "@/client/lib/error-messages";+import { captureClientEvent } from "@/client/lib/posthog";++/**+ * Connects one project to Search Console or Google Analytics: link a Google+ * account, pick a property, change it, or disconnect.+ */+export function GoogleConnectionCard({+ provider,+ projectId,+ onDismiss,+ dismissing = false,+}: {+ provider: GoogleProvider;+ projectId: string;+ /** Adds a Dismiss button while the project is not connected. */+ onDismiss?: () => void;+ dismissing?: boolean;+}) {+ const config = googleProviders[provider];+ const { Logo } = config;+ const queryClient = useQueryClient();+ const { picking, setPicking, linkAccount, linking } = useGooglePickerResume(+ provider,+ projectId,+ );+ const [selection, setSelection] =+ React.useState<GooglePickerSelection | null>(null);++ const connectionOptions = googleConnectionOptions(provider, projectId);+ const connectionKey = connectionOptions.queryKey;+ const connectionQuery = useQuery(connectionOptions);+ const connection = connectionQuery.data;+ const connectionUnavailable = connectionQuery.isError && !connection;+ const connected = Boolean(connection?.connected);+ const hasGrant = Boolean(connection?.currentUserHasGrant);+ const canManage = connection?.canManage === true;+ const needsGoogleOAuthSetup =+ connectionQuery.isSuccess && !connection?.googleOAuthConfigured;++ const showPicker = picking ?? (!connected && hasGrant && canManage);+ const accountsKey = [config.accountsKey, projectId];+ const accountsQuery = useQuery({+ queryKey: accountsKey,+ queryFn: () => config.listAccounts(projectId),+ enabled: Boolean(showPicker && !needsGoogleOAuthSetup),+ });+ const accounts = accountsQuery.data?.accounts ?? [];+ const savedSelection = accountsQuery.data?.selected ?? null;+ const requiresReconnect = accounts.some(+ (account) => account.requiresReconnect,+ );++ React.useEffect(() => {+ if (!requiresReconnect) return;+ void queryClient.invalidateQueries({+ queryKey: googleConnectionOptions(provider, projectId).queryKey,+ });+ if (provider === "gsc")+ void queryClient.invalidateQueries({ queryKey: ["gscGrantStatus"] });+ }, [requiresReconnect, queryClient, provider, projectId]);++ React.useEffect(() => {+ if (picking && connected && !selection && savedSelection)+ setSelection(savedSelection);+ }, [savedSelection, selection, picking, connected]);++ const afterChange = () => {+ queryClient.removeQueries({ queryKey: accountsKey });+ void queryClient.invalidateQueries({ queryKey: connectionKey });+ for (const queryKey of config.dependentKeys(projectId))+ void queryClient.invalidateQueries({ queryKey });+ setPicking(false);+ };+ const setPropertyMutation = useMutation({+ meta: { errorToast: false },+ mutationFn: (selected: GooglePickerSelection) =>+ config.save(projectId, selected),+ onSuccess: (saved) => {+ queryClient.setQueryData(+ connectionKey,+ (current: GoogleConnection | undefined) =>+ current ? { ...current, ...saved } : current,+ );+ captureClientEvent(`${provider}:property_select`);+ toast.success(`${config.name} connected`);+ afterChange();+ },+ });+ const disconnectMutation = useMutation({+ meta: { errorToast: false },+ mutationFn: () => config.disconnect(projectId),+ onSuccess: () => {+ toast.success(`${config.name} disconnected from this project`);+ queryClient.setQueryData(+ connectionKey,+ (current: GoogleConnection | undefined) =>+ current ? { ...current, connected: false } : current,+ );+ setSelection(null);+ afterChange();+ },+ });++ const changingConnection =+ setPropertyMutation.isPending || disconnectMutation.isPending || linking;+ const dismissButton = onDismiss ? (+ <button+ type="button"+ className="btn btn-ghost btn-sm text-base-content/60"+ onClick={onDismiss}+ disabled={dismissing || changingConnection}+ >+ Dismiss+ </button>+ ) : null;+ const handleConnect = () => void linkAccount(window.location.href);+ const startPicking = () => {+ setPropertyMutation.reset();+ disconnectMutation.reset();+ setSelection(null);+ setPicking(true);+ };++ return (+ <CardShell+ title={config.title}+ icon={<Logo className="size-5" />}+ action={+ connectionQuery.isPending || connectionUnavailable ? undefined : (+ <ConnectionStatusPill+ connected={connected && !needsGoogleOAuthSetup}+ setupRequired={needsGoogleOAuthSetup}+ />+ )+ }+ >+ <GoogleLinkErrorAlert provider={provider} className="mb-4" />+ {connectionQuery.isPending ? (+ <div+ role="status"+ aria-label="Loading connection"+ className="space-y-3 animate-pulse"+ >+ <div className="h-4 w-2/3 rounded bg-base-200" />+ <div className="h-9 w-24 rounded bg-base-200" />+ </div>+ ) : connectionUnavailable ? (+ <div role="alert" className="space-y-3 text-sm">+ <p className="text-error">+ Couldn't check this project's connection.+ </p>+ <button+ type="button"+ className="btn btn-ghost btn-sm"+ onClick={() => void connectionQuery.refetch()}+ >+ Try again+ </button>+ </div>+ ) : needsGoogleOAuthSetup ? (+ <div className="space-y-3">+ <GoogleOAuthSetupWarning+ integrationName={config.name}+ docsUrl={config.docsUrl}+ />+ {dismissButton}+ </div>+ ) : connected && !picking ? (+ <GoogleConnectedState+ property={connection?.property ?? ""}+ detail={connection?.propertyDetail}+ canManageAccounts={hasGrant}+ email={connection?.connectedByEmail}+ onChange={startPicking}+ onDisconnect={() => {+ setPropertyMutation.reset();+ disconnectMutation.mutate();+ }}+ disconnecting={disconnectMutation.isPending}+ disabled={linking}+ canManage={canManage}+ />+ ) : showPicker ? (+ <fieldset disabled={changingConnection}>+ <GooglePropertyPicker+ provider={provider}+ readOnly={!canManage}+ linking={linking}+ loading={accountsQuery.isLoading}+ error={accountsQuery.isError}+ accounts={accounts}+ selection={selection}+ onSelect={setSelection}+ onSave={() => selection && setPropertyMutation.mutate(selection)}+ saving={setPropertyMutation.isPending}+ secondaryAction={{+ label: "Cancel",+ disabled: setPropertyMutation.isPending,+ onClick: () => {+ setPicking(false);+ setSelection(null);+ setPropertyMutation.reset();+ },+ }}+ onRetry={() => void accountsQuery.refetch()}+ onReconnect={handleConnect}+ />+ {connected ? null : dismissButton}+ </fieldset>+ ) : (+ <GoogleProjectEmptyState+ name={config.name}+ hasGrant={hasGrant}+ canManage={canManage}+ disabled={linking}+ onLink={handleConnect}+ onChoose={startPicking}+ >+ {dismissButton}+ </GoogleProjectEmptyState>+ )}+ {setPropertyMutation.isError || disconnectMutation.isError ? (+ <p role="alert" className="mt-3 text-sm text-error">+ {getStandardErrorMessage(+ setPropertyMutation.error ?? disconnectMutation.error,+ )}+ </p>+ ) : null}+ {connectionQuery.isSuccess && !needsGoogleOAuthSetup && !canManage ? (+ <PermissionHint+ action="change this project's connection"+ className="mt-3"+ />+ ) : null}+ </CardShell>+ );+}++function ConnectionStatusPill({+ connected,+ setupRequired,+}: {+ connected: boolean;+ setupRequired: boolean;+}) {+ return (+ <span+ className={[+ "inline-flex shrink-0 items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium",+ connected+ ? "border-success/30 bg-success/10 text-success"+ : setupRequired+ ? "border-warning/30 bg-warning/10 text-warning"+ : "border-base-300 bg-base-200 text-base-content/60",+ ].join(" ")}+ >+ <span+ className={[+ "size-1.5 rounded-full",+ connected+ ? "bg-success"+ : setupRequired+ ? "bg-warning"+ : "bg-base-content/40",+ ].join(" ")}+ />+ {connected+ ? "Connected"+ : setupRequired+ ? "Setup required"+ : "Not connected"}+ </span>+ );+}diff --git a/src/client/features/integrations/GooglePropertyPicker.tsx b/src/client/features/integrations/GooglePropertyPicker.tsxindex 0405bce0..34d35fd7 100644--- a/src/client/features/integrations/GooglePropertyPicker.tsx+++ b/src/client/features/integrations/GooglePropertyPicker.tsx@@ -10,14 +10,15 @@ import {} from "react";import { Check, ChevronDown, Plus, Search } from "lucide-react";-type Selection = { accountId: string; propertyId: string };+export type GooglePickerSelection = { accountId: string; propertyId: string };type Property = {id: string;name: string;detail?: string;selectable: boolean;+ isSelected?: boolean;};-type Account = {+export type GooglePickerAccount = {accountId: string;email: string | null;requiresReconnect: boolean;@@ -30,7 +31,7 @@ type SecondaryAction = {disabled?: boolean;};-function accountLabel(account: Account) {+function accountLabel(account: GooglePickerAccount) {return account.email ?? `Google account · ${account.accountId.slice(-6)}`;}@@ -56,9 +57,9 @@ export function GooglePropertyPicker({loading: boolean;linking?: boolean;error: boolean;- accounts: Account[];- selection: Selection | null;- onSelect: (selection: Selection | null) => void;+ accounts: GooglePickerAccount[];+ selection: GooglePickerSelection | null;+ onSelect: (selection: GooglePickerSelection | null) => void;onSave: () => void;saving: boolean;saveLabel?: string;@@ -68,7 +69,7 @@ export function GooglePropertyPicker({renderActions?: (saveButton: ReactNode) => ReactNode;}) {const [open, setOpen] = useState(false);- const [removing, setRemoving] = useState<Account | null>(null);+ const [removing, setRemoving] = useState<GooglePickerAccount | null>(null);const [search, setSearch] = useState("");const panelId = useId();const trigger = useRef<HTMLButtonElement>(null);diff --git a/src/client/features/integrations/IntegrationConnectionCard.tsx b/src/client/features/integrations/IntegrationConnectionCard.tsxdeleted file mode 100644index 0d674616..00000000--- a/src/client/features/integrations/IntegrationConnectionCard.tsx+++ /dev/null@@ -1,73 +0,0 @@-import type { ReactNode } from "react";--type IntegrationConnectionStatus =- | "connected"- | "disconnected"- | "setup_required";--/** Shared shell for first-party connection cards such as GSC and GA4. */-export function IntegrationConnectionCard({- title,- icon,- status,- children,-}: {- title: string;- icon?: ReactNode;- status?: IntegrationConnectionStatus;- children: ReactNode;-}) {- return (- <div className="overflow-hidden rounded-xl border border-base-300 bg-base-100 shadow-sm">- <div className="flex flex-col items-start justify-between gap-3 p-5 sm:flex-row sm:gap-4 sm:p-6">- <div className="flex min-w-0 items-center gap-2.5">- {icon ? (- <span className="grid size-8 shrink-0 place-items-center rounded-lg border border-base-300 bg-base-100 shadow-sm">- {icon}- </span>- ) : null}- <h2 className="text-base font-semibold leading-tight">{title}</h2>- </div>- {status ? <ConnectionStatusPill status={status} /> : null}- </div>- <div className="border-t border-base-300 p-5 sm:p-6">{children}</div>- </div>- );-}--function ConnectionStatusPill({- status,-}: {- status: IntegrationConnectionStatus;-}) {- const connected = status === "connected";- const setupRequired = status === "setup_required";- return (- <span- className={[- "inline-flex shrink-0 items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium",- connected- ? "border-success/30 bg-success/10 text-success"- : setupRequired- ? "border-warning/30 bg-warning/10 text-warning"- : "border-base-300 bg-base-200 text-base-content/60",- ].join(" ")}- >- <span- className={[- "size-1.5 rounded-full",- connected- ? "bg-success"- : setupRequired- ? "bg-warning"- : "bg-base-content/40",- ].join(" ")}- />- {connected- ? "Connected"- : setupRequired- ? "Setup required"- : "Not connected"}- </span>- );-}diff --git a/src/client/features/integrations/googleConnectionQueries.ts b/src/client/features/integrations/googleConnectionQueries.tsdeleted file mode 100644index f5fca95f..00000000--- a/src/client/features/integrations/googleConnectionQueries.ts+++ /dev/null@@ -1,15 +0,0 @@-import { queryOptions } from "@tanstack/react-query";-import { getGscConnection } from "@/serverFunctions/gsc";-import { getGa4Connection } from "@/serverFunctions/ga4";--export const gscConnectionOptions = (projectId: string) =>- queryOptions({- queryKey: ["gscConnection", projectId],- queryFn: () => getGscConnection({ data: { projectId } }),- });--export const ga4ConnectionOptions = (projectId: string) =>- queryOptions({- queryKey: ["ga4Connection", projectId],- queryFn: () => getGa4Connection({ data: { projectId } }),- });diff --git a/src/client/features/integrations/googleProviders.ts b/src/client/features/integrations/googleProviders.tsnew file mode 100644index 00000000..ff718d36--- /dev/null+++ b/src/client/features/integrations/googleProviders.ts@@ -0,0 +1,189 @@+import { queryOptions, type QueryKey } from "@tanstack/react-query";+import type {+ GooglePickerAccount,+ GooglePickerSelection,+} from "@/client/features/integrations/GooglePropertyPicker";+import {+ GoogleAnalyticsLogo,+ GoogleSearchConsoleLogo,+} from "@/client/features/integrations/GoogleProductLogos";+import {+ disconnectGa4,+ getGa4Connection,+ listGa4Properties,+ setGa4Property,+} from "@/serverFunctions/ga4";+import {+ disconnectGsc,+ getGscConnection,+ listGscSites,+ setGscSite,+} from "@/serverFunctions/gsc";+import { GA4_SELF_HOSTED_SETUP_DOCS_URL } from "@/shared/ga4";+import { GSC_SELF_HOSTED_SETUP_DOCS_URL } from "@/shared/gsc";++export type GoogleProvider = "gsc" | "ga4";++/** One project's connection to a Google product, in the same shape for both. */+export type GoogleConnection = {+ connected: boolean;+ canManage: boolean;+ currentUserHasGrant: boolean;+ googleOAuthConfigured: boolean;+ connectedByEmail: string | null;+ property: string | null;+ propertyDetail: string | null;+};++type PickerOptions = {+ accounts: GooglePickerAccount[];+ selected: GooglePickerSelection | null;+};++type ProviderConfig = {+ title: string;+ name: string;+ Logo: typeof GoogleSearchConsoleLogo;+ docsUrl: string;+ getConnection: (projectId: string) => Promise<GoogleConnection>;+ accountsKey: string;+ listAccounts: (projectId: string) => Promise<PickerOptions>;+ save: (+ projectId: string,+ selection: GooglePickerSelection,+ ) => Promise<Partial<GoogleConnection>>;+ disconnect: (projectId: string) => Promise<unknown>;+ /** Queries that show this connection's data, refreshed after a change. */+ dependentKeys: (projectId: string) => QueryKey[];+};++type GscAccounts = Awaited<ReturnType<typeof listGscSites>>["accounts"];+type Ga4Accounts = Awaited<ReturnType<typeof listGa4Properties>>["accounts"];++/** The saved property is preselected when the user reopens the picker. */+function pickerOptions(accounts: GooglePickerAccount[]): PickerOptions {+ for (const account of accounts) {+ const property = account.properties.find((p) => p.isSelected);+ if (property)+ return {+ accounts,+ selected: { accountId: account.accountId, propertyId: property.id },+ };+ }+ return { accounts, selected: null };+}++function gscPickerOptions(accounts: GscAccounts): PickerOptions {+ return pickerOptions(+ accounts.map((account) => ({+ ...account,+ unavailable: account.propertiesUnavailable,+ properties: account.sites.map((site) => ({+ id: site.siteUrl,+ name: site.siteUrl,+ selectable: site.selectable,+ isSelected: site.isSelected,+ })),+ })),+ );+}++function ga4PickerOptions(accounts: Ga4Accounts): PickerOptions {+ return pickerOptions(+ accounts.map((account) => ({+ ...account,+ unavailable: account.propertiesUnavailable,+ properties: account.properties.map((property) => ({+ id: property.propertyId,+ name: property.displayName,+ detail: `${property.accountDisplayName} · ${property.propertyId.replace(/^properties\//, "")}`,+ selectable: true,+ isSelected: property.isSelected,+ })),+ })),+ );+}++export const googleProviders: Record<GoogleProvider, ProviderConfig> = {+ gsc: {+ title: "Google Search Console",+ name: "Search Console",+ Logo: GoogleSearchConsoleLogo,+ docsUrl: GSC_SELF_HOSTED_SETUP_DOCS_URL,+ getConnection: async (projectId) => {+ const connection = await getGscConnection({ data: { projectId } });+ return {+ ...connection,+ property: connection.siteUrl,+ propertyDetail: null,+ };+ },+ accountsKey: "gscSites",+ listAccounts: async (projectId) =>+ gscPickerOptions((await listGscSites({ data: { projectId } })).accounts),+ save: async (projectId, selection) => {+ const saved = await setGscSite({+ data: {+ projectId,+ accountId: selection.accountId,+ siteUrl: selection.propertyId,+ },+ });+ return {+ connected: true,+ connectedByEmail: saved.connectedByEmail,+ property: saved.siteUrl,+ };+ },+ disconnect: (projectId) => disconnectGsc({ data: { projectId } }),+ dependentKeys: (projectId) => [+ ["gscGrantStatus"],+ ["searchPerformance", projectId],+ ["searchPerformanceTable", projectId],+ ["dashboardActivation", projectId],+ ["dashboardGscReport", projectId],+ ],+ },+ ga4: {+ title: "Google Analytics",+ name: "Google Analytics",+ Logo: GoogleAnalyticsLogo,+ docsUrl: GA4_SELF_HOSTED_SETUP_DOCS_URL,+ getConnection: async (projectId) => {+ const connection = await getGa4Connection({ data: { projectId } });+ return {+ ...connection,+ property: connection.propertyDisplayName,+ propertyDetail: connection.propertyId,+ };+ },+ accountsKey: "ga4Properties",+ listAccounts: async (projectId) =>+ ga4PickerOptions(+ (await listGa4Properties({ data: { projectId } })).accounts,+ ),+ save: async (projectId, selection) => {+ const saved = await setGa4Property({ data: { projectId, ...selection } });+ return {+ connected: true,+ connectedByEmail: saved.connectedByEmail,+ property: saved.propertyDisplayName,+ propertyDetail: saved.propertyId,+ };+ },+ disconnect: (projectId) => disconnectGa4({ data: { projectId } }),+ dependentKeys: (projectId) => [+ ["dashboardActivation", projectId],+ ["dashboardGa4Report", projectId],+ ],+ },+};++export const googleConnectionOptions = (+ provider: GoogleProvider,+ projectId: string,+) =>+ queryOptions({+ queryKey: [`${provider}Connection`, projectId],+ queryFn: () => googleProviders[provider].getConnection(projectId),+ });diff --git a/src/client/features/integrations/googleSetupState.test.ts b/src/client/features/integrations/googleSetupState.test.tsindex 3f0d48ef..465a6c90 100644--- a/src/client/features/integrations/googleSetupState.test.ts+++ b/src/client/features/integrations/googleSetupState.test.ts@@ -2,8 +2,7 @@ import { createElement } from "react";import { renderToStaticMarkup } from "react-dom/server";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { describe, expect, it, vi } from "vitest";-import { SearchConsoleConnectionCard } from "@/client/features/gsc/SearchConsoleConnectionCard";-import { GoogleAnalyticsConnectionCard } from "@/client/features/ga4/GoogleAnalyticsConnectionCard";+import { GoogleConnectionCard } from "@/client/features/integrations/GoogleConnectionCard";import { SearchConsoleOnboardingStep } from "@/client/features/onboarding/SearchConsoleOnboardingStep";vi.mock("@/serverFunctions/gsc", () => ({@@ -32,7 +31,6 @@ vi.mock("@/client/features/integrations/googleLinkError", () => ({clearGoogleLinkError: vi.fn(),reportGoogleLinkErrorOnce: vi.fn(),}));-vi.mock("@/lib/auth-mode", () => ({ isHostedClientAuthMode: () => true }));vi.mock("@/client/lib/posthog", () => ({ captureClientEvent: vi.fn() }));function renderSetup(@@ -52,9 +50,7 @@ function renderSetup(currentUserHasGrant: hasGrant,canManage,googleOAuthConfigured: true,- siteUrl: "https://example.com/",- propertyId: "properties/123",- propertyDisplayName: "Example",+ property: "https://example.com/",});if (connectionError) {client@@ -75,12 +71,10 @@ function renderSetup(onBack: vi.fn(),onSkip: vi.fn(),})- : createElement(- surface === "gsc"- ? SearchConsoleConnectionCard- : GoogleAnalyticsConnectionCard,- { projectId: "project-a" },- );+ : createElement(GoogleConnectionCard, {+ provider,+ projectId: "project-a",+ });const html = renderToStaticMarkup(createElement(QueryClientProvider, { client }, component),);diff --git a/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx b/src/client/features/onboarding/SearchConsoleOnboardingStep.tsxindex 98eee519..8770fcd3 100644--- a/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx+++ b/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx@@ -6,19 +6,18 @@ import { QueryError } from "@/client/components/QueryState";import { Spinner } from "@/client/components/Spinner";import { GoogleLinkErrorAlert } from "@/client/features/integrations/GoogleLinkErrorAlert";import {- SitePicker,- type GscSiteSelection,-} from "@/client/features/gsc/SitePicker";+ GooglePropertyPicker,+ type GooglePickerSelection,+} from "@/client/features/integrations/GooglePropertyPicker";+import {+ googleConnectionOptions,+ googleProviders,+} from "@/client/features/integrations/googleProviders";import {startGoogleLink,useGoogleLinkPending,} from "@/client/features/integrations/startGoogleLink";import { captureClientEvent } from "@/client/lib/posthog";-import {- getGscConnection,- listGscSites,- setGscSite,-} from "@/serverFunctions/gsc";import { getProjects } from "@/serverFunctions/projects";const GRANT_STATUS_KEY = ["gscGrantStatus"];@@ -84,28 +83,22 @@ function GscConnect({}: { projectId: string } & NavigationProps) {const queryClient = useQueryClient();const linking = useGoogleLinkPending();- const [selection, setSelection] = React.useState<GscSiteSelection | null>(- null,- );+ const [selection, setSelection] =+ React.useState<GooglePickerSelection | null>(null);- const connectionKey = ["gscConnection", projectId];- const connectionQuery = useQuery({- queryKey: connectionKey,- queryFn: () => getGscConnection({ data: { projectId } }),- });+ const connectionOptions = googleConnectionOptions("gsc", projectId);+ const connectionKey = connectionOptions.queryKey;+ const connectionQuery = useQuery(connectionOptions);const connection = connectionQuery.data;const connected = Boolean(connection?.connected);const hasGrant = Boolean(connection?.currentUserHasGrant);const sitesQuery = useQuery({- queryKey: ["gscSites", projectId],- queryFn: () => listGscSites({ data: { projectId } }),+ queryKey: [googleProviders.gsc.accountsKey, projectId],+ queryFn: () => googleProviders.gsc.listAccounts(projectId),enabled: hasGrant && !connected,});- const accounts = React.useMemo(- () => sitesQuery.data?.accounts ?? [],- [sitesQuery.data?.accounts],- );+ const accounts = sitesQuery.data?.accounts ?? [];const requiresReconnect = accounts.some((account) => account.requiresReconnect,);@@ -114,14 +107,14 @@ function GscConnect({if (!requiresReconnect) return;void queryClient.invalidateQueries({- queryKey: ["gscConnection", projectId],+ queryKey: googleConnectionOptions("gsc", projectId).queryKey,});void queryClient.invalidateQueries({ queryKey: GRANT_STATUS_KEY });}, [requiresReconnect, queryClient, projectId]);const setSiteMutation = useMutation({- mutationFn: (selected: GscSiteSelection) =>- setGscSite({ data: { projectId, ...selected } }),+ mutationFn: (selected: GooglePickerSelection) =>+ googleProviders.gsc.save(projectId, selected),onSuccess: () => {captureClientEvent("gsc:property_select");void queryClient.invalidateQueries({ queryKey: connectionKey });@@ -158,14 +151,15 @@ function GscConnect({</span><span className="text-base-content/80">Connected to{" "}- <span className="font-mono">{connection?.siteUrl}</span>.+ <span className="font-mono">{connection?.property}</span>.</span></div>) : (<div className="space-y-4"><GoogleLinkErrorAlert provider="gsc" />{hasGrant ? (- <SitePicker+ <GooglePropertyPicker+ provider="gsc"linking={linking}loading={sitesQuery.isLoading}error={sitesQuery.isError}diff --git a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsxindex 0fcc4dfc..462e0136 100644--- a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx+++ b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx@@ -1,15 +1,13 @@import { useMemo, useState } from "react";import { toast } from "sonner";import { useQuery, useQueryClient } from "@tanstack/react-query";-import { useCustomer } from "autumn-js/react";import {getLatestRankResults,getRankPositionMatrix,estimateRankCheckCost,} from "@/serverFunctions/rank-tracking";import { AlertTriangle, ArrowLeft } from "lucide-react";-import { useSession } from "@/lib/auth-client";-import { getCustomerPlanStatus } from "@/client/features/billing/plan-detection";+import { useHostedPlanGate } from "@/client/features/billing/HostedPlanGate";import { captureClientEvent } from "@/client/lib/posthog";import { FreePlanAlert } from "./FreePlanAlert";import { RankTrackingDetailHeader } from "./RankTrackingDetailHeader";@@ -65,14 +63,7 @@ export function RankTrackingDomainDetail({onBack: () => void;onEdit: () => void;}) {- const { data: session } = useSession();- const customerQuery = useCustomer({- queryOptions: { enabled: Boolean(session?.user?.id) },- });- const isFreePlan =- !!customerQuery.data &&- getCustomerPlanStatus(customerQuery.data) === "free";-+ const planStatus = useHostedPlanGate();const queryClient = useQueryClient();const [showAddKeywords, setShowAddKeywords] = useState(false);const [showFilters, setShowFilters] = useState(false);@@ -142,8 +133,12 @@ export function RankTrackingDomainDetail({);if (result.checkScheduledSoon) {toast.info("The scheduled check within the hour covers these keywords");- } else if (!result.checkTriggered && result.added > 0) {- toast.info("Use 'Check Now' to check these keywords");+ } else if (+ !result.checkTriggered &&+ result.added > 0 &&+ planStatus === "paid"+ ) {+ toast.info("Use 'Check rankings' to check these keywords");}};@@ -225,7 +220,7 @@ export function RankTrackingDomainDetail({</div>)}- <FreePlanAlert visible={isFreePlan} />+ <FreePlanAlert visible={planStatus === "free"} />{/* Results card */}<div className="flex-1 flex flex-col min-w-0 border border-base-300 rounded-xl bg-base-100 overflow-hidden">@@ -307,7 +302,7 @@ export function RankTrackingDomainDetail({onRefreshMetrics={refreshMetrics}metricsRefreshing={metricsRefreshing}checkBusy={isBusy}- checkDisabled={isFreePlan}+ checkDisabled={planStatus !== "paid"}hasData={filtered.length > 0}/>@@ -346,6 +341,7 @@ export function RankTrackingDomainDetail({locationCode={config.locationCode}locationName={config.locationName}serpDepth={config.serpDepth}+ canCheck={planStatus === "paid"}/>)}</div>diff --git a/src/client/features/rank-tracking/RankTrackingTable.tsx b/src/client/features/rank-tracking/RankTrackingTable.tsxindex 1a1cdf8d..de85d6b2 100644--- a/src/client/features/rank-tracking/RankTrackingTable.tsx+++ b/src/client/features/rank-tracking/RankTrackingTable.tsx@@ -35,6 +35,7 @@ export function RankTrackingTable({locationCode,locationName,serpDepth,+ canCheck,}: {totalCount: number;rows: RankTrackingRow[];@@ -48,6 +49,7 @@ export function RankTrackingTable({locationCode: number;locationName?: string | null;serpDepth: number;+ canCheck: boolean;}) {const queryClient = useQueryClient();const [showConfirm, setShowConfirm] = useState(false);@@ -131,7 +133,9 @@ export function RankTrackingTable({return (<div className="rounded-xl border border-dashed border-base-300 p-10 text-center text-sm text-base-content/55">{totalCount === 0- ? 'No rank data yet. Click "Check Now" to run your first check.'+ ? canCheck+ ? 'No rank data yet. Use "Check rankings" in the More actions menu to run the first check.'+ : "No rank data yet.": "No keywords match your search."}</div>);diff --git a/src/client/features/search-performance/SearchPerformancePage.tsx b/src/client/features/search-performance/SearchPerformancePage.tsxindex 654e8094..9bd9171f 100644--- a/src/client/features/search-performance/SearchPerformancePage.tsx+++ b/src/client/features/search-performance/SearchPerformancePage.tsx@@ -9,7 +9,7 @@ import { Download, Loader2, Sheet, SlidersHorizontal } from "lucide-react";import { toast } from "sonner";import { TableExportMenu } from "@/client/components/table/TableBulkActionBar";import { TablePagination } from "@/client/components/table/TablePagination";-import { SearchConsoleConnectionCard } from "@/client/features/gsc/SearchConsoleConnectionCard";+import { GoogleConnectionCard } from "@/client/features/integrations/GoogleConnectionCard";import { SearchPerformanceLoadingState } from "@/client/features/search-performance/SearchPerformanceLoadingState";import {tableQueryOptions,@@ -227,7 +227,7 @@ export function SearchPerformancePage({ projectId }: { projectId: string }) {</div>) : !report?.connected ? (<div className="max-w-2xl">- <SearchConsoleConnectionCard projectId={projectId} />+ <GoogleConnectionCard provider="gsc" projectId={projectId} /></div>) : (<>diff --git a/src/client/lib/error-messages.test.ts b/src/client/lib/error-messages.test.tsindex e6501095..ed168c54 100644--- a/src/client/lib/error-messages.test.ts+++ b/src/client/lib/error-messages.test.ts@@ -1,34 +1,16 @@import { describe, expect, it } from "vitest";-import {- getErrorCode,- getStandardErrorMessage,-} from "@/client/lib/error-messages";+import { getStandardErrorMessage } from "@/client/lib/error-messages";-describe("coded error messages (CODE: detail)", () => {- it("shows the server detail instead of the generic text", () => {- const coded = new Error(- "AUTH_CONFIG_MISSING: TEAM_DOMAIN must be a full https URL like https://your-team.cloudflareaccess.com",- );- expect(getErrorCode(coded)).toBe("AUTH_CONFIG_MISSING");- expect(getStandardErrorMessage(coded)).toBe(- "TEAM_DOMAIN must be a full https URL like https://your-team.cloudflareaccess.com",- );- });-- it("keeps bare codes mapping to the standard copy", () => {- const bare = new Error("AUTH_CONFIG_MISSING");- expect(getErrorCode(bare)).toBe("AUTH_CONFIG_MISSING");- expect(getStandardErrorMessage(bare)).toContain("not configured");+describe("getStandardErrorMessage", () => {+ it("maps known error codes to standard copy", () => {expect(getStandardErrorMessage(new Error("PAYMENT_REQUIRED"))).toBe("An active hosted subscription is required before you can use OpenSEO.",);});- it("does not treat arbitrary colon messages as coded", () => {- const arbitrary = new Error("Something failed: try again");- expect(getErrorCode(arbitrary)).toBeNull();- expect(getStandardErrorMessage(arbitrary)).toBe(- "Something failed: try again",- );+ it("returns custom messages when the error is not a shared code", () => {+ expect(+ getStandardErrorMessage(new Error("Something failed: try again")),+ ).toBe("Something failed: try again");});});diff --git a/src/client/lib/error-messages.ts b/src/client/lib/error-messages.tsindex b570ba4a..7973252a 100644--- a/src/client/lib/error-messages.ts+++ b/src/client/lib/error-messages.ts@@ -34,33 +34,17 @@ const STANDARD_MESSAGES: Record<ErrorCode, string> = {"An unexpected error occurred. Please check server logs and try again.",};-// Setup errors cross the wire as "CODE: detail" (see toClientError) so the-// user sees the server's specific guidance while code-driven UI (error cards,-// redirects) still keys off the code.-function splitCodedMessage(- message: string,-): { code: ErrorCode; detail: string } | null {- const separatorIndex = message.indexOf(": ");- if (separatorIndex === -1) return null;- const code = message.slice(0, separatorIndex);- if (!isErrorCode(code)) return null;- return { code, detail: message.slice(separatorIndex + 2) };-}-export function getStandardErrorMessage(error: unknown,fallback: string = STANDARD_MESSAGES.INTERNAL_ERROR,): string {if (!(error instanceof Error)) return fallback;if (isErrorCode(error.message)) return STANDARD_MESSAGES[error.message];- const coded = splitCodedMessage(error.message);- if (coded) return coded.detail;if (error.message) return error.message;return fallback;}export function getErrorCode(error: unknown): ErrorCode | null {if (!(error instanceof Error)) return null;- if (isErrorCode(error.message)) return error.message;- return splitCodedMessage(error.message)?.code ?? null;+ return isErrorCode(error.message) ? error.message : null;}diff --git a/src/routes/_project/p/$projectId/settings/integrations.tsx b/src/routes/_project/p/$projectId/settings/integrations.tsxindex 34813a8d..2654fb67 100644--- a/src/routes/_project/p/$projectId/settings/integrations.tsx+++ b/src/routes/_project/p/$projectId/settings/integrations.tsx@@ -1,11 +1,7 @@import { queryClient } from "@/client/tanstack-db/queryClient";-import {- gscConnectionOptions,- ga4ConnectionOptions,-} from "@/client/features/integrations/googleConnectionQueries";+import { googleConnectionOptions } from "@/client/features/integrations/googleProviders";import { createFileRoute } from "@tanstack/react-router";-import { SearchConsoleConnectionCard } from "@/client/features/gsc/SearchConsoleConnectionCard";-import { GoogleAnalyticsConnectionCard } from "@/client/features/ga4/GoogleAnalyticsConnectionCard";+import { GoogleConnectionCard } from "@/client/features/integrations/GoogleConnectionCard";import { CrawlerAccessSettings } from "@/client/features/settings/CrawlerAccessSettings";export const Route = createFileRoute(@@ -13,8 +9,12 @@ export const Route = createFileRoute()({loader: ({ params }) => {// Start both database checks on link intent without holding up navigation.- void queryClient.prefetchQuery(gscConnectionOptions(params.projectId));- void queryClient.prefetchQuery(ga4ConnectionOptions(params.projectId));+ void queryClient.prefetchQuery(+ googleConnectionOptions("gsc", params.projectId),+ );+ void queryClient.prefetchQuery(+ googleConnectionOptions("ga4", params.projectId),+ );},component: ProjectIntegrationsRoute,});@@ -30,12 +30,12 @@ function ProjectIntegrationsRoute() {<h2 className="text-sm font-medium text-base-content/50">Search Console</h2>- <SearchConsoleConnectionCard projectId={projectId} />+ <GoogleConnectionCard provider="gsc" projectId={projectId} /></section><section id="google-analytics" className="scroll-mt-6 space-y-3"><h2 className="text-sm font-medium text-base-content/50">Analytics</h2>- <GoogleAnalyticsConnectionCard projectId={projectId} />+ <GoogleConnectionCard provider="ga4" projectId={projectId} /></section><CrawlerAccessSettings projectId={projectId} />diff --git a/src/server/lib/errors.test.ts b/src/server/lib/errors.test.tsindex d009d5cc..d321e1ad 100644--- a/src/server/lib/errors.test.ts+++ b/src/server/lib/errors.test.ts@@ -12,22 +12,11 @@ describe("toClientError", () => {message: "INTERNAL_ERROR",},{- label: "keeps public error codes unchanged",- error: new AppError("PAYMENT_REQUIRED"),- message: "PAYMENT_REQUIRED",- },- {- label: "passes setup-error detail through as CODE: detail",+ label: "strips setup-error detail down to the bare code",error: new AppError("AUTH_CONFIG_MISSING","TEAM_DOMAIN must be a full https URL like https://your-team.cloudflareaccess.com",),- message:- "AUTH_CONFIG_MISSING: TEAM_DOMAIN must be a full https URL like https://your-team.cloudflareaccess.com",- },- {- label: "keeps a detail-less setup error as its bare code",- error: new AppError("AUTH_CONFIG_MISSING"),message: "AUTH_CONFIG_MISSING",},])("$label", ({ error, message }) => {diff --git a/src/server/lib/errors.ts b/src/server/lib/errors.tsindex 313777cc..89af1f84 100644--- a/src/server/lib/errors.ts+++ b/src/server/lib/errors.ts@@ -19,21 +19,9 @@ export function asAppError(error: unknown): AppError | null {return null;}-// Codes whose server-side message is safe and useful to show the user.-// Setup errors only: their messages are static guidance ("TEAM_DOMAIN must be-// a full https URL…") that self-hosters need to fix their deployment, and the-// alternative is a generic card that makes every misconfiguration look the-// same. Everything else stays stripped to its bare code.-const CLIENT_DETAIL_ERROR_CODES = new Set<ErrorCode>(["AUTH_CONFIG_MISSING"]);-+// The client only ever receives the bare code. Server messages can carry+// internal detail, so the client maps each code to its own copy and the full+// message stays in the server logs.export function toClientError(error: unknown): Error {- const appError = asAppError(error);- if (- appError &&- CLIENT_DETAIL_ERROR_CODES.has(appError.code) &&- appError.message !== appError.code- ) {- return new Error(`${appError.code}: ${appError.message}`);- }- return new Error(appError?.code ?? "INTERNAL_ERROR");+ return new Error(asAppError(error)?.code ?? "INTERNAL_ERROR");}