Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Show query errors instead of empty states and fix retry feedback (EVE-288) (#718)
Ben Senescu9f4d5aa49b6c
diff --git a/src/client/features/ai-search/BrandLookupPage.tsx b/src/client/features/ai-search/BrandLookupPage.tsxindex 31138853..498de5ec 100644--- a/src/client/features/ai-search/BrandLookupPage.tsx+++ b/src/client/features/ai-search/BrandLookupPage.tsx@@ -1,17 +1,12 @@import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";import { useQuery } from "@tanstack/react-query";import { Link } from "@tanstack/react-router";-import {- AlertCircle,- BarChart3,- Quote,- Sparkles,- TrendingUp,-} from "lucide-react";+import { BarChart3, Quote, Sparkles, TrendingUp } from "lucide-react";import { lookupBrand } from "@/serverFunctions/ai-search";import { useHostedPlanGate } from "@/client/features/billing/HostedPlanGate";import { PageLoading } from "@/client/components/Spinner";import { getStandardErrorMessage } from "@/client/lib/error-messages";+import { QueryError } from "@/client/components/QueryState";import { BrandLookupResults } from "@/client/features/ai-search/components/BrandLookupResults";import { BrandLookupSearchCard } from "@/client/features/ai-search/components/BrandLookupSearchCard";import {@@ -246,7 +241,10 @@ export function BrandLookupPage({const isLoading = hasActiveQuery && lookupQuery.isPending;const errorMessage =hasActiveQuery && lookupQuery.isError- ? getStandardErrorMessage(lookupQuery.error)+ ? getStandardErrorMessage(+ lookupQuery.error,+ "Failed to load brand lookup",+ ): null;const resultData = hasActiveQuery ? lookupQuery.data : undefined;@@ -290,13 +288,15 @@ export function BrandLookupPage({/>{errorMessage ? (- <div- role="alert"- className="flex items-start gap-2 rounded-lg border border-error/30 bg-error/10 p-3 text-sm text-error"- >- <AlertCircle className="mt-0.5 size-4 shrink-0" />- <span>{errorMessage}</span>- </div>+ <QueryError+ fallback={+ resultData+ ? `${errorMessage} Showing earlier results.`+ : errorMessage+ }+ onRetry={() => void lookupQuery.refetch()}+ isRetrying={lookupQuery.isFetching}+ />) : null}{isLoading ? (diff --git a/src/client/features/ai-search/PromptExplorerPage.tsx b/src/client/features/ai-search/PromptExplorerPage.tsxindex 0b19a519..9ca3a4ab 100644--- a/src/client/features/ai-search/PromptExplorerPage.tsx+++ b/src/client/features/ai-search/PromptExplorerPage.tsx@@ -2,17 +2,12 @@ import { useEffect, useRef, useState, type FormEvent } from "react";import { useQuery } from "@tanstack/react-query";import { Link } from "@tanstack/react-router";import { identity, sortBy } from "remeda";-import {- AlertCircle,- Columns3,- MessageSquare,- SearchCheck,- Sparkles,-} from "lucide-react";+import { Columns3, MessageSquare, SearchCheck, Sparkles } from "lucide-react";import { explorePrompt } from "@/serverFunctions/ai-search";import { useHostedPlanGate } from "@/client/features/billing/HostedPlanGate";import { PageLoading } from "@/client/components/Spinner";import { getStandardErrorMessage } from "@/client/lib/error-messages";+import { QueryError } from "@/client/components/QueryState";import { PromptExplorerForm } from "@/client/features/ai-search/components/PromptExplorerForm";import { PromptExplorerResults } from "@/client/features/ai-search/components/PromptExplorerResults";import { PromptExplorerLoadingState } from "@/client/features/ai-search/components/PromptExplorerLoadingState";@@ -172,7 +167,10 @@ export function PromptExplorerPage({ projectId, urlState, onSubmit }: Props) {};const errorMessage = exploreQuery.isError- ? getStandardErrorMessage(exploreQuery.error)+ ? getStandardErrorMessage(+ exploreQuery.error,+ "Failed to load prompt results",+ ): null;const isLoading = hasActivePrompt && exploreQuery.isPending;const resultData = hasActivePrompt ? exploreQuery.data : undefined;@@ -223,13 +221,15 @@ export function PromptExplorerPage({ projectId, urlState, onSubmit }: Props) {/>{errorMessage ? (- <div- role="alert"- className="flex items-start gap-2 rounded-lg border border-error/30 bg-error/10 p-3 text-sm text-error"- >- <AlertCircle className="mt-0.5 size-4 shrink-0" />- <span>{errorMessage}</span>- </div>+ <QueryError+ fallback={+ resultData+ ? `${errorMessage} Showing earlier results.`+ : errorMessage+ }+ onRetry={() => void exploreQuery.refetch()}+ isRetrying={exploreQuery.isFetching}+ />) : null}{isLoading ? (diff --git a/src/client/features/audit/launch/AuditHistorySection.tsx b/src/client/features/audit/launch/AuditHistorySection.tsxindex 1f24b06d..154f4c72 100644--- a/src/client/features/audit/launch/AuditHistorySection.tsx+++ b/src/client/features/audit/launch/AuditHistorySection.tsx@@ -1,21 +1,48 @@import { Link } from "@tanstack/react-router";+import type { UseQueryResult } from "@tanstack/react-query";import { ScanSearch, Trash2 } from "lucide-react";import type { getAuditHistory } from "@/serverFunctions/audit";import { PortalMenu } from "@/client/components/PortalMenu";+import { QueryState } from "@/client/components/QueryState";import { formatDate, StatusBadge } from "@/client/features/audit/shared";+type AuditHistory = Awaited<ReturnType<typeof getAuditHistory>>;+export function AuditHistorySection({+ projectId,+ historyQuery,+ onDelete,+}: {+ projectId: string;+ historyQuery: UseQueryResult<AuditHistory>;+ onDelete: (auditId: string) => void;+}) {+ return (+ <QueryState+ query={historyQuery}+ errorFallback="Failed to load audit history"+ >+ {(history) => (+ <AuditHistoryTable+ projectId={projectId}+ history={history}+ onDelete={onDelete}+ />+ )}+ </QueryState>+ );+}++function AuditHistoryTable({projectId,history,- isLoading,onDelete,}: {projectId: string;- history: Awaited<ReturnType<typeof getAuditHistory>>;- isLoading: boolean;+ history: AuditHistory;onDelete: (auditId: string) => void;}) {- if (history.length === 0 && !isLoading) {+ if (history.length === 0) {return (<div className="flex items-center justify-center py-16"><div className="text-center text-base-content/40 space-y-3">@@ -26,8 +53,6 @@ export function AuditHistorySection({);}- if (history.length === 0) return null;-return (<div className="card bg-base-100 border border-base-300"><div className="card-body gap-3">diff --git a/src/client/features/audit/launch/LaunchView.tsx b/src/client/features/audit/launch/LaunchView.tsxindex 7eacf482..18bb1cb3 100644--- a/src/client/features/audit/launch/LaunchView.tsx+++ b/src/client/features/audit/launch/LaunchView.tsx@@ -37,8 +37,7 @@ export function LaunchView({<AuditHistorySectionprojectId={projectId}- history={controller.historyQuery.data ?? []}- isLoading={controller.historyQuery.isLoading}+ historyQuery={controller.historyQuery}onDelete={controller.deleteAudit}/></div>diff --git a/src/client/features/backlinks/BacklinksPageContent.tsx b/src/client/features/backlinks/BacklinksPageContent.tsxindex 3de271ca..76d316ea 100644--- a/src/client/features/backlinks/BacklinksPageContent.tsx+++ b/src/client/features/backlinks/BacklinksPageContent.tsx@@ -122,7 +122,9 @@ export function BacklinksBody({);}- if (data.overviewQuery.isLoading) {+ // isPending (not isLoading) also covers a fetch paused while offline, which+ // would otherwise fall through to the error card with no error.+ if (data.overviewQuery.isPending) {return (<>{tabStrip}@@ -138,6 +140,7 @@ export function BacklinksBody({<BacklinksErrorStateerrorMessage={data.overviewErrorMessage}onRetry={() => void data.overviewQuery.refetch()}+ isRetrying={data.overviewQuery.isFetching}/></>);@@ -165,8 +168,19 @@ export function BacklinksBody({hideSpam={!searchState.includeSpam}onHideSpamChange={onHideSpamChange}domainExpansion={domainExpansion}- isTabLoading={data.activeTabQuery.isLoading}+ isTabLoading={+ data.activeTabQuery.isPending && !data.activeTabFilterError+ }+ // A failed refetch keeps the loaded rows; a filter budget error hides+ // them because the query never ran for the current filters.+ showTable={activeTabPage !== undefined && !data.activeTabFilterError}tabErrorMessage={data.activeTabErrorMessage}+ onRetryTab={+ data.activeTabFilterError+ ? undefined+ : () => void data.activeTabQuery.refetch()+ }+ isTabRetrying={data.activeTabQuery.isFetching}exportTarget={overviewData.displayTarget || searchState.target}pagination={{page: searchState.page,diff --git a/src/client/features/backlinks/BacklinksPageSections.tsx b/src/client/features/backlinks/BacklinksPageSections.tsxindex 46db3c58..431d151b 100644--- a/src/client/features/backlinks/BacklinksPageSections.tsx+++ b/src/client/features/backlinks/BacklinksPageSections.tsx@@ -27,6 +27,7 @@ import {} from "@/types/schemas/backlinks";import type { ResearchScope } from "@/shared/researchScope";import { Skeleton } from "@/client/components/Skeleton";+import { QueryError } from "@/client/components/QueryState";const BACKLINKS_RESULTS_TABS: Array<{tab: BacklinksSearchState["tab"];@@ -49,7 +50,10 @@ export function BacklinksResultsCard({onHideSpamChange,domainExpansion,isTabLoading,+ showTable,tabErrorMessage,+ onRetryTab,+ isTabRetrying,exportTarget,pagination,onPageChange,@@ -69,7 +73,10 @@ export function BacklinksResultsCard({onHideSpamChange: (hideSpam: boolean) => void;domainExpansion: BacklinksDomainExpansion;isTabLoading: boolean;+ showTable: boolean;tabErrorMessage: string | null;+ onRetryTab?: () => void;+ isTabRetrying: boolean;exportTarget: string;pagination: {page: number;@@ -256,14 +263,18 @@ export function BacklinksResultsCard({<div className="p-4">{tabErrorMessage ? (- <div className="alert alert-error mb-3">- <span>{tabErrorMessage}</span>+ <div className="mb-3">+ <QueryError+ fallback={tabErrorMessage}+ onRetry={onRetryTab}+ isRetrying={isTabRetrying}+ /></div>) : null}- {isTabLoading && !tabErrorMessage ? (+ {isTabLoading ? (<TabLoadingState label={TAB_LOADING_LABELS[activeTab]} />) : null}- {!isTabLoading && !tabErrorMessage ? (+ {!isTabLoading && showTable ? (<>{activeTab === "backlinks" ? (<BacklinksTablediff --git a/src/client/features/backlinks/BacklinksPageStates.tsx b/src/client/features/backlinks/BacklinksPageStates.tsxindex 6c4c01be..c069247d 100644--- a/src/client/features/backlinks/BacklinksPageStates.tsx+++ b/src/client/features/backlinks/BacklinksPageStates.tsx@@ -37,9 +37,11 @@ export function BacklinksLoadingState() {export function BacklinksErrorState({errorMessage,onRetry,+ isRetrying,}: {errorMessage: string | null;onRetry: () => void;+ isRetrying: boolean;}) {return (<section className="rounded-2xl border border-error/30 bg-error/5 p-6 space-y-3">@@ -54,8 +56,8 @@ export function BacklinksErrorState({</p></div></div>- <button className="btn btn-sm" onClick={onRetry}>- Retry+ <button className="btn btn-sm" onClick={onRetry} disabled={isRetrying}>+ {isRetrying ? "Retrying…" : "Retry"}</button></section>);diff --git a/src/client/features/backlinks/useBacklinksPageData.ts b/src/client/features/backlinks/useBacklinksPageData.tsindex 3dfaeeee..4e11ac28 100644--- a/src/client/features/backlinks/useBacklinksPageData.ts+++ b/src/client/features/backlinks/useBacklinksPageData.ts@@ -1,5 +1,5 @@import { useMemo } from "react";-import { useQuery } from "@tanstack/react-query";+import { useQuery, type QueryKey } from "@tanstack/react-query";import type {BacklinksPageProps,BacklinksSearchState,@@ -88,6 +88,18 @@ export function useBacklinksPageData({const targetReady = Boolean(target);const baseQueryKeyParts = [projectId, scope, target] as const;const pageInputBase = { projectId, target, scope, page, pageSize };+ // Keep the current table on screen while paging, sorting or filtering the+ // same target. A new target shows the loading state instead. Each tab has+ // its own query, so switching tabs never shows another tab's rows.+ const keepSameTarget = <T>(+ previous: T | undefined,+ previousQuery: { queryKey: QueryKey } | undefined,+ ) =>+ baseQueryKeyParts.every(+ (part, index) => previousQuery?.queryKey[index + 1] === part,+ )+ ? previous+ : undefined;const overviewQuery = useQuery({queryKey: ["backlinksOverview", ...baseQueryKeyParts],@@ -125,6 +137,9 @@ export function useBacklinksPageData({],enabled: targetReady && tab === "backlinks" && !rowsFilterError,staleTime: BACKLINKS_QUERY_STALE_TIME_MS,+ // Over-budget filters never run the query, so no rows (and no export) may+ // stand in for them.+ placeholderData: rowsFilterError ? undefined : keepSameTarget,queryFn: () =>getBacklinksRows({data: {@@ -160,6 +175,7 @@ export function useBacklinksPageData({],enabled: targetReady && tab === "domains",staleTime: BACKLINKS_QUERY_STALE_TIME_MS,+ placeholderData: keepSameTarget,queryFn: () =>getBacklinksReferringDomains({data: {@@ -193,6 +209,7 @@ export function useBacklinksPageData({],enabled: targetReady && tab === "pages",staleTime: BACKLINKS_QUERY_STALE_TIME_MS,+ placeholderData: keepSameTarget,queryFn: () =>getBacklinksTopPages({data: {@@ -214,12 +231,14 @@ export function useBacklinksPageData({: tab === "domains"? referringDomainsQuery: topPagesQuery;+ const activeTabFilterError = tab === "backlinks" ? rowsFilterError : null;const activeTabErrorMessage =- (tab === "backlinks" ? rowsFilterError : null) ??+ activeTabFilterError ??getBacklinksErrorMessage(activeTabQuery.error, "Could not load this tab.");return {activeTabErrorMessage,+ activeTabFilterError,activeTabQuery,overviewErrorMessage,overviewQuery,diff --git a/src/client/features/billing/BillingFeatureBreakdown.tsx b/src/client/features/billing/BillingFeatureBreakdown.tsxindex 3435f7ce..8ce5162d 100644--- a/src/client/features/billing/BillingFeatureBreakdown.tsx+++ b/src/client/features/billing/BillingFeatureBreakdown.tsx@@ -13,6 +13,7 @@ import {getBillingUsageEvents,type BillingUsageEvent,} from "@/serverFunctions/billing";+import { QueryState } from "@/client/components/QueryState";import { Skeleton } from "@/client/components/Skeleton";const BILLING_USAGE_FEATURE_IDS: string[] = [@@ -144,9 +145,6 @@ export function BillingFeatureBreakdown() {staleTime: 60_000,});- const rows = getBillingFeatureBreakdownRows(eventsQuery.data ?? []);- const total = rows.reduce((sum, row) => sum + row.usd, 0);-return (<div className="rounded-lg border border-base-300 bg-base-100 p-4 space-y-3"><div className="flex items-baseline justify-between gap-4">@@ -154,36 +152,51 @@ export function BillingFeatureBreakdown() {<span className="text-xs text-base-content/50">Last 30 days</span></div>- {eventsQuery.isLoading ? (- <div className="space-y-3">- {[0, 1, 2, 3].map((i) => (- <Skeleton key={i} className="h-4 w-full" />- ))}- </div>- ) : rows.length === 0 ? (- <div className="text-sm text-base-content/40">- No usage recorded yet- </div>- ) : (- <ul className="space-y-2.5">- {rows.map((row) => (- <li key={row.label} className="space-y-1">- <div className="flex items-baseline justify-between gap-4 text-sm">- <span>{row.label}</span>- <span className="tabular-nums text-base-content/70">- ${row.usd.toFixed(2)}- </span>- </div>- <div className="h-1.5 w-full overflow-hidden rounded-full bg-base-200">- <div- className="h-full rounded-full bg-[#7c3aed]"- style={{ width: `${(row.usd / total) * 100}%` }}- />- </div>- </li>- ))}- </ul>- )}+ <QueryState+ query={eventsQuery}+ errorFallback="Failed to load usage"+ loading={+ <div className="space-y-3">+ {[0, 1, 2, 3].map((i) => (+ <Skeleton key={i} className="h-4 w-full" />+ ))}+ </div>+ }+ >+ {(events) => <BreakdownRows events={events} />}+ </QueryState></div>);}++function BreakdownRows({ events }: { events: BillingUsageEvent[] }) {+ const rows = getBillingFeatureBreakdownRows(events);+ const total = rows.reduce((sum, row) => sum + row.usd, 0);++ if (rows.length === 0) {+ return (+ <div className="text-sm text-base-content/40">No usage recorded yet</div>+ );+ }++ return (+ <ul className="space-y-2.5">+ {rows.map((row) => (+ <li key={row.label} className="space-y-1">+ <div className="flex items-baseline justify-between gap-4 text-sm">+ <span>{row.label}</span>+ <span className="tabular-nums text-base-content/70">+ ${row.usd.toFixed(2)}+ </span>+ </div>+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-base-200">+ <div+ className="h-full rounded-full bg-[#7c3aed]"+ style={{ width: `${(row.usd / total) * 100}%` }}+ />+ </div>+ </li>+ ))}+ </ul>+ );+}diff --git a/src/client/features/billing/BillingUsageChart.tsx b/src/client/features/billing/BillingUsageChart.tsxindex a8f42c2d..2933f3c5 100644--- a/src/client/features/billing/BillingUsageChart.tsx+++ b/src/client/features/billing/BillingUsageChart.tsx@@ -6,6 +6,7 @@ import {AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,autumnSeoDataCreditsToUsd,} from "@/shared/billing";+import { QueryError } from "@/client/components/QueryState";const BILLING_USAGE_FEATURE_IDS: string[] = [AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,@@ -58,7 +59,15 @@ export function BillingUsageChart() {</div><div ref={containerRef} className="w-full h-32 min-w-0">- {eventsQuery.isLoading ? null : chartData.length === 0 ? (+ {eventsQuery.isLoading ? null : eventsQuery.list === undefined &&+ eventsQuery.isError ? (+ <QueryError+ error={eventsQuery.error}+ fallback="Failed to load usage"+ onRetry={() => void eventsQuery.refetch()}+ isRetrying={eventsQuery.isFetching}+ />+ ) : chartData.length === 0 ? (<div className="flex h-full items-center justify-center"><span className="text-sm text-base-content/40">No usage recorded yetdiff --git a/src/client/features/billing/route-state.test.ts b/src/client/features/billing/route-state.test.tsindex eec47f8f..18b9b961 100644--- a/src/client/features/billing/route-state.test.ts+++ b/src/client/features/billing/route-state.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { getSubscribeRouteState } from "./route-state";+import { getBillingRouteState, getSubscribeRouteState } from "./route-state";describe("getSubscribeRouteState", () => {// hasManagedAccess is true for essentially every hosted customer: the free@@ -69,3 +69,21 @@ describe("getSubscribeRouteState", () => {).toBe("redirectToApp");});});++describe("getBillingRouteState", () => {+ it("keeps the loaded page when a customer refetch fails", () => {+ const failed = {+ hasSession: true,+ isSessionPending: false,+ isCustomerLoading: false,+ isCustomerError: true,+ };++ expect(getBillingRouteState({ ...failed, hasCustomerData: true })).toBe(+ "ready",+ );+ expect(getBillingRouteState({ ...failed, hasCustomerData: false })).toBe(+ "error",+ );+ });+});diff --git a/src/client/features/billing/route-state.ts b/src/client/features/billing/route-state.tsindex f2de6407..131383bd 100644--- a/src/client/features/billing/route-state.ts+++ b/src/client/features/billing/route-state.ts@@ -5,12 +5,14 @@ export function getBillingRouteState(args: {isSessionPending: boolean;isCustomerLoading: boolean;isCustomerError: boolean;+ hasCustomerData: boolean;}) {if (args.isSessionPending || !args.hasSession || args.isCustomerLoading) {return "loading" as const;}- if (args.isCustomerError) {+ // A failed refetch keeps the loaded page; the caller shows the error inline.+ if (args.isCustomerError && !args.hasCustomerData) {return "error" as const;}diff --git a/src/client/features/dashboard/DashboardPage.tsx b/src/client/features/dashboard/DashboardPage.tsxindex 72d47312..1b81aa72 100644--- a/src/client/features/dashboard/DashboardPage.tsx+++ b/src/client/features/dashboard/DashboardPage.tsx@@ -9,7 +9,7 @@ import {} from "@/client/features/dashboard/DashboardCards";import { Ga4Card } from "@/client/features/dashboard/Ga4Card";import { WorkspaceMergeBanner } from "@/client/features/dashboard/WorkspaceMergeBanner";-import { getStandardErrorMessage } from "@/client/lib/error-messages";+import { QueryError } from "@/client/components/QueryState";import {getDashboardActivation,getDashboardOverview,@@ -53,19 +53,23 @@ export function DashboardPage({ projectId }: { projectId: string }) {refreshMutation.mutate();}, [needsSnapshot, refreshMutation]);- if (activationQuery.isError) {+ if (activationQuery.isError && !activation) {return (<div className="px-4 py-4 md:px-6 md:py-6">- <div className="alert alert-error">- {getStandardErrorMessage(activationQuery.error)}- </div>+ <QueryError+ error={activationQuery.error}+ fallback="Failed to load dashboard"+ onRetry={() => void activationQuery.refetch()}+ isRetrying={activationQuery.isFetching}+ /></div>);}// Wait for the overview too: rendering cards from `overview === undefined`// flashes their empty states (and reshuffles the data-first sort) once the- // real data lands. An overview error falls through so the page still loads.+ // real data lands. An overview error falls through so the page still loads,+ // with the error in place of the audit and backlink cards.if (!activation || overviewQuery.isPending) {return (<div@@ -103,25 +107,26 @@ export function DashboardPage({ projectId }: { projectId: string }) {},]: []),- {- key: "audit",- hasData: overview?.audit != null,- node: (- <AuditHealthCard- projectId={projectId}- audit={overview?.audit ?? null}- />- ),- },- ...(showBacklinks+ ...(overview+ ? [+ {+ key: "audit",+ hasData: overview.audit != null,+ node: (+ <AuditHealthCard projectId={projectId} audit={overview.audit} />+ ),+ },+ ]+ : []),+ ...(overview && showBacklinks? [{key: "backlinks",- hasData: overview?.backlinks != null || refreshMutation.isPending,+ hasData: overview.backlinks != null || refreshMutation.isPending,node: (<BacklinkPulseCardprojectId={projectId}- backlinks={overview?.backlinks ?? null}+ backlinks={overview.backlinks}refreshing={refreshMutation.isPending}/>),@@ -143,6 +148,24 @@ export function DashboardPage({ projectId }: { projectId: string }) {activation={activation}/>+ {activationQuery.isError ? (+ <QueryError+ error={activationQuery.error}+ fallback="Failed to refresh dashboard"+ onRetry={() => void activationQuery.refetch()}+ isRetrying={activationQuery.isFetching}+ />+ ) : null}++ {overviewQuery.isError ? (+ <QueryError+ error={overviewQuery.error}+ fallback="Failed to load site audit and backlink summaries"+ onRetry={() => void overviewQuery.refetch()}+ isRetrying={overviewQuery.isFetching}+ />+ ) : null}+{/* Every card is half width on large screens (only the checklist spans).Cards with data render before setup pitches and empty states. */}<div className="grid items-start gap-5 lg:grid-cols-2">diff --git a/src/client/features/domain/DomainOverviewPage.tsx b/src/client/features/domain/DomainOverviewPage.tsxindex 041156df..47279ab5 100644--- a/src/client/features/domain/DomainOverviewPage.tsx+++ b/src/client/features/domain/DomainOverviewPage.tsx@@ -22,6 +22,7 @@ import {RecentSearches,RecentSearchesBackLink,} from "@/client/components/RecentSearches";+import { QueryError } from "@/client/components/QueryState";import { DomainSearchCard } from "@/client/features/domain/components/DomainSearchCard";import { KeywordsTab } from "@/client/features/domain/components/KeywordsTab";import { PagesTab } from "@/client/features/domain/components/PagesTab";@@ -43,12 +44,8 @@ import {toScopeSearchParam,type ResearchScope,} from "@/shared/researchScope";-import {- createFormValidationErrors,- shouldValidateFieldOnChange,-} from "@/client/lib/forms";+import { shouldValidateFieldOnChange } from "@/client/lib/forms";import { buildDomainFiltersClearSearchUpdate } from "@/client/features/domain/domainFilterUtils";-import { getStandardErrorMessage } from "@/client/lib/error-messages";import { captureClientEvent } from "@/client/lib/posthog";import type { DomainOverviewRouteState } from "@/client/features/domain/domainRouteState";import type {@@ -355,19 +352,6 @@ function useDomainOverviewState({userPickedScope.current = true;}, []);- useEffect(() => {- controlsForm.setErrorMap({- onSubmit: overviewQuery.error- ? createFormValidationErrors({- form: getStandardErrorMessage(- overviewQuery.error,- "Lookup failed.",- ),- })- : undefined,- });- }, [controlsForm, overviewQuery.error]);-useEffect(() => {if (!overviewQuery.isSuccess || !overview) return;const key = `${routeState.domain}|${routeState.scope}|${routeState.locationCode}`;@@ -424,6 +408,7 @@ function useDomainOverviewState({return {controlsForm,isLoading,+ overviewQuery,overview,canSaveKeywords,history,@@ -523,6 +508,17 @@ export function DomainOverviewPage({? "Whole domain incl. subdomains": undefined;+ // The error stays until the query for this search succeeds; editing the+ // form doesn't clear it.+ const overviewError = state.overviewQuery.isError ? (+ <QueryError+ error={state.overviewQuery.error}+ fallback="Lookup failed."+ onRetry={() => void state.overviewQuery.refetch()}+ isRetrying={state.overviewQuery.isFetching}+ />+ ) : null;+const tabControls = routeState.domain ? (<div className="flex flex-col gap-2"><RecentSearchesBackLink@@ -578,6 +574,11 @@ export function DomainOverviewPage({{tabControls}<DomainOverviewLoadingState /></>+ ) : state.overview === null && overviewError ? (+ <>+ {tabControls}+ {overviewError}+ </>) : state.overview === null ? (<div className="pt-1"><RecentSearches@@ -600,6 +601,7 @@ export function DomainOverviewPage({) : (<>{tabControls}+ {overviewError}<div className="flex flex-wrap items-center gap-2"><span className="badge badge-ghost font-medium">{state.overview.displayTarget}diff --git a/src/client/features/domain/components/DomainSearchCard.tsx b/src/client/features/domain/components/DomainSearchCard.tsxindex c2b50f72..65a2d8f0 100644--- a/src/client/features/domain/components/DomainSearchCard.tsx+++ b/src/client/features/domain/components/DomainSearchCard.tsx@@ -1,6 +1,6 @@import type { FormEvent } from "react";-import { AlertCircle, Search } from "lucide-react";-import { getFieldError, getFormError } from "@/client/lib/forms";+import { Search } from "lucide-react";+import { getFieldError } from "@/client/lib/forms";import type { DomainOverviewControlsForm } from "@/client/features/domain/DomainOverviewPage";import { toSortMode } from "@/client/features/domain/utils";import type { DomainSortMode } from "@/client/features/domain/types";@@ -129,19 +129,6 @@ export function DomainSearchCard({) : null;}}</controlsForm.Field>-- <controlsForm.Subscribe selector={(state) => state.errorMap.onSubmit}>- {(submitError) => {- const errorMessage = getFormError(submitError);-- return errorMessage ? (- <div className="rounded-lg border border-error/30 bg-error/10 p-3 text-sm text-error flex items-start gap-2">- <AlertCircle className="size-4 shrink-0 mt-0.5" />- <span>{errorMessage}</span>- </div>- ) : null;- }}- </controlsForm.Subscribe></div></div>);diff --git a/src/client/features/domain/components/KeywordsTab.tsx b/src/client/features/domain/components/KeywordsTab.tsxindex 0834bfcd..d30d5da0 100644--- a/src/client/features/domain/components/KeywordsTab.tsx+++ b/src/client/features/domain/components/KeywordsTab.tsx@@ -6,6 +6,7 @@ import {TableBulkActionButton,TableBulkExportMenu,} from "@/client/components/table/TableBulkActionBar";+import { QueryError } from "@/client/components/QueryState";import { TablePagination } from "@/client/components/table/TablePagination";import { DomainPageLink } from "@/client/features/domain/components/DomainPageLink";import { DomainKeywordsTable } from "@/client/features/domain/components/DomainKeywordsTable";@@ -312,16 +313,28 @@ export function KeywordsTab({/>}>- <DomainKeywordsTable- domain={hostname}- rows={rows}- selectedKeywords={selectedKeywords}- visibleKeywords={visibleKeywords}- sortMode={routeState.sort}- currentSortOrder={routeState.order}- onSortClick={onSortClick}- onToggleKeyword={toggleKeywordSelection}- />+ <div className="space-y-3">+ {query.isError ? (+ <QueryError+ error={query.error}+ fallback="Failed to load keywords."+ onRetry={() => void query.refetch()}+ isRetrying={query.isFetching}+ />+ ) : null}+ {query.isError && !query.data ? null : (+ <DomainKeywordsTable+ domain={hostname}+ rows={rows}+ selectedKeywords={selectedKeywords}+ visibleKeywords={visibleKeywords}+ sortMode={routeState.sort}+ currentSortOrder={routeState.order}+ onSortClick={onSortClick}+ onToggleKeyword={toggleKeywordSelection}+ />+ )}+ </div></DomainTableTabSurface></>);diff --git a/src/client/features/domain/components/PagesTab.tsx b/src/client/features/domain/components/PagesTab.tsxindex 8cfaacac..1fde29d2 100644--- a/src/client/features/domain/components/PagesTab.tsx+++ b/src/client/features/domain/components/PagesTab.tsx@@ -1,5 +1,6 @@import { useCallback, useMemo, useState } from "react";import { Copy, Download, FileSpreadsheet, Sheet } from "lucide-react";+import { QueryError } from "@/client/components/QueryState";import { TablePagination } from "@/client/components/table/TablePagination";import { DomainPageLink } from "@/client/features/domain/components/DomainPageLink";import { DomainFilterPanel } from "@/client/features/domain/components/DomainFilterPanel";@@ -222,13 +223,25 @@ export function PagesTab({/>}>- <DomainPagesTable- domain={hostname}- rows={rows}- sortMode={routeState.sort}- currentSortOrder={routeState.order}- onSortClick={onSortClick}- />+ <div className="space-y-3">+ {query.isError ? (+ <QueryError+ error={query.error}+ fallback="Failed to load pages."+ onRetry={() => void query.refetch()}+ isRetrying={query.isFetching}+ />+ ) : null}+ {query.isError && !query.data ? null : (+ <DomainPagesTable+ domain={hostname}+ rows={rows}+ sortMode={routeState.sort}+ currentSortOrder={routeState.order}+ onSortClick={onSortClick}+ />+ )}+ </div></DomainTableTabSurface>);}diff --git a/src/client/features/keywords/components/SerpAnalysisCard.tsx b/src/client/features/keywords/components/SerpAnalysisCard.tsxindex ac40bde2..27d2e106 100644--- a/src/client/features/keywords/components/SerpAnalysisCard.tsx+++ b/src/client/features/keywords/components/SerpAnalysisCard.tsx@@ -11,6 +11,7 @@ export function SerpAnalysisCard({canLoadMore,error,onRetry,+ retrying,deepFetchFailed,page,pageSize,@@ -25,6 +26,7 @@ export function SerpAnalysisCard({canLoadMore: boolean;error?: string | null;onRetry?: () => void;+ retrying: boolean;/** The failure was the deeper crawl, so retrying restores the shallow one. */deepFetchFailed: boolean;page: number;@@ -35,22 +37,23 @@ export function SerpAnalysisCard({const pageItems = items.slice(page * pageSize, (page + 1) * pageSize);if (loading) return <SerpAnalysisLoadingState />;- if (error) {- return (- <div className="rounded-lg border border-error/30 bg-error/10 p-3 text-sm text-error space-y-2">- <p>{error}</p>- {onRetry ? (- <button className="btn btn-xs" onClick={onRetry}>- {deepFetchFailed ? "Show top 20" : "Retry"}- </button>- ) : null}- </div>- );+ const errorBox = error ? (+ <div className="rounded-lg border border-error/30 bg-error/10 p-3 text-sm text-error space-y-2 mb-3">+ <p>{error}</p>+ {onRetry ? (+ <button className="btn btn-xs" onClick={onRetry} disabled={retrying}>+ {retrying ? "Retrying…" : deepFetchFailed ? "Show top 20" : "Retry"}+ </button>+ ) : null}+ </div>+ ) : null;+ if (items.length === 0) {+ return errorBox ?? <SerpAnalysisEmptyState keyword={keyword} />;}- if (items.length === 0) return <SerpAnalysisEmptyState keyword={keyword} />;return (<div>+ {errorBox}<div className="flex items-center justify-between mb-3"><div className="text-xs text-base-content/50">{items.length} organic resultsdiff --git a/src/client/features/keywords/hooks/useKeywordSerpAnalysis.ts b/src/client/features/keywords/hooks/useKeywordSerpAnalysis.tsindex 6dacc3cc..75dc0276 100644--- a/src/client/features/keywords/hooks/useKeywordSerpAnalysis.ts+++ b/src/client/features/keywords/hooks/useKeywordSerpAnalysis.ts@@ -141,5 +141,7 @@ export function useKeywordSerpAnalysis(canLoadMoreSerp,deepFetchFailed,serpError,+ // `isLoading` stays false while a failed query refetches.+ serpRetrying: serpQuery.isFetching,};}diff --git a/src/client/features/keywords/page/KeywordResearchPage.tsx b/src/client/features/keywords/page/KeywordResearchPage.tsxindex 0721bd21..a1cb2846 100644--- a/src/client/features/keywords/page/KeywordResearchPage.tsx+++ b/src/client/features/keywords/page/KeywordResearchPage.tsx@@ -248,40 +248,60 @@ function KeywordResearchContent({return <KeywordResearchLoadingState />;}- if (controller.researchError) {- const errorCode = getErrorCode(controller.researchMutationError);-- return (- <div className="flex-1 flex items-center justify-center pt-1">- <div className="w-full max-w-xl rounded-xl border border-error/30 bg-error/10 p-5 text-error space-y-3">- <div className="flex items-start gap-2">- <AlertCircle className="mt-0.5 size-4 shrink-0" />- <p className="text-sm">{controller.researchError}</p>- </div>- {errorCode === "INSUFFICIENT_CREDITS" ? (- <Link to={BILLING_ROUTE} className="btn btn-sm">- Go to Billing- </Link>- ) : errorCode === "UNKNOWN_LOCATION" ? null : (- <button className="btn btn-sm" onClick={controller.retrySearch}>- Try again- </button>- )}- </div>- </div>- );- }+ const errorCard = controller.researchError ? (+ <ResearchErrorCard controller={controller} />+ ) : null;if (controller.rows.length === 0) {return (- <KeywordResearchEmptyState- controller={controller}- projectId={projectId}- />+ errorCard ?? (+ <KeywordResearchEmptyState+ controller={controller}+ projectId={projectId}+ />+ ));}- return <KeywordResearchResults controller={controller} />;+ // A failed refetch keeps the loaded results on screen, under the error.+ return (+ <>+ {errorCard}+ <KeywordResearchResults controller={controller} />+ </>+ );+}++function ResearchErrorCard({+ controller,+}: {+ controller: KeywordResearchControllerState;+}) {+ const errorCode = getErrorCode(controller.researchMutationError);++ return (+ <div className="flex-1 flex items-center justify-center pt-1">+ <div className="w-full max-w-xl rounded-xl border border-error/30 bg-error/10 p-5 text-error space-y-3">+ <div className="flex items-start gap-2">+ <AlertCircle className="mt-0.5 size-4 shrink-0" />+ <p className="text-sm">{controller.researchError}</p>+ </div>+ {errorCode === "INSUFFICIENT_CREDITS" ? (+ <Link to={BILLING_ROUTE} className="btn btn-sm">+ Go to Billing+ </Link>+ ) : errorCode === "UNKNOWN_LOCATION" ? null : (+ <button+ className="btn btn-sm"+ onClick={controller.retrySearch}+ disabled={controller.researchRetrying}+ >+ {controller.researchRetrying ? "Retrying…" : "Try again"}+ </button>+ )}+ </div>+ </div>+ );}function KeywordSaveDialog({diff --git a/src/client/features/keywords/page/KeywordResearchResults.tsx b/src/client/features/keywords/page/KeywordResearchResults.tsxindex 0cefef7b..44355e22 100644--- a/src/client/features/keywords/page/KeywordResearchResults.tsx+++ b/src/client/features/keywords/page/KeywordResearchResults.tsx@@ -340,6 +340,7 @@ function SerpPanel({ controller }: Props) {canLoadMore={controller.canLoadMoreSerp}error={controller.serpError}onRetry={controller.retrySerp}+ retrying={controller.serpRetrying}deepFetchFailed={controller.deepFetchFailed}page={controller.serpPage}pageSize={controller.SERP_PAGE_SIZE}diff --git a/src/client/features/keywords/state/useKeywordResearchController.ts b/src/client/features/keywords/state/useKeywordResearchController.tsindex 311f71e6..97e02cf5 100644--- a/src/client/features/keywords/state/useKeywordResearchController.ts+++ b/src/client/features/keywords/state/useKeywordResearchController.ts@@ -96,6 +96,7 @@ export function useKeywordResearchController(deepFetchFailed,retrySerp,serpError,+ serpRetrying,} = useKeywordSerpAnalysis(input.projectId, locationCode, input.locationName);const {@@ -281,6 +282,8 @@ export function useKeywordResearchController(removeHistoryItem,researchError,researchMutationError,+ // `isLoading` stays false while a failed query refetches.+ researchRetrying: researchQuery.isFetching,retrySearch,resetFilters,retrySerp,@@ -291,6 +294,7 @@ export function useKeywordResearchController(canLoadMoreSerp,deepFetchFailed,serpError,+ serpRetrying,serpLoading,serpLoadingMore,serpPage,diff --git a/src/client/features/rank-tracking/KeywordTrendModal.tsx b/src/client/features/rank-tracking/KeywordTrendModal.tsxindex 79b6da52..a5563aa4 100644--- a/src/client/features/rank-tracking/KeywordTrendModal.tsx+++ b/src/client/features/rank-tracking/KeywordTrendModal.tsx@@ -4,6 +4,7 @@ import { reverse, sortBy } from "remeda";import { toast } from "sonner";import { useQuery } from "@tanstack/react-query";import { Modal } from "@/client/components/Modal";+import { QueryState } from "@/client/components/QueryState";import { buildCsv, type CsvValue } from "@/client/lib/csv";import { exportRows } from "@/client/lib/exportRows";import { captureClientEvent } from "@/client/lib/posthog";@@ -52,7 +53,7 @@ export function KeywordTrendModal({}) {const [sinceDays, setSinceDays] = useState(730);- const { data: history, isLoading } = useQuery({+ const historyQuery = useQuery({queryKey: ["rankKeywordHistory",projectId,@@ -70,6 +71,7 @@ export function KeywordTrendModal({},}),});+ const history = historyQuery.data;const points = useMemo(() => history ?? [], [history]);const devices = useMemo(() => deriveDevices(points), [points]);@@ -155,115 +157,126 @@ export function KeywordTrendModal({<TrendRangeToggle value={sinceDays} onChange={setSinceDays} /></div>- {isLoading ? (- <div className="flex items-center justify-center py-16">- <Loader2 className="size-5 animate-spin text-base-content/50" />- </div>- ) : maxPerDevice <= 1 ? (- <EmptyState count={maxPerDevice} />- ) : (- <>- <RankTrendChart- data={chartData}- series={series}- serpDepth={serpDepth}- showBottomBand- renderTooltip={(label, entries) => (- <ChartTooltip- label={label}- entries={entries}+ <QueryState+ query={historyQuery}+ errorFallback="Failed to load keyword history"+ loading={+ <div className="flex items-center justify-center py-16">+ <Loader2 className="size-5 animate-spin text-base-content/50" />+ </div>+ }+ >+ {() =>+ maxPerDevice <= 1 ? (+ <EmptyState count={maxPerDevice} />+ ) : (+ <>+ <RankTrendChart+ data={chartData}+ series={series}serpDepth={serpDepth}- bottomBandKeys={bottomBandKeys}+ showBottomBand+ renderTooltip={(label, entries) => (+ <ChartTooltip+ label={label}+ entries={entries}+ serpDepth={serpDepth}+ bottomBandKeys={bottomBandKeys}+ />+ )}/>- )}- />- <div className="flex items-center justify-end gap-2">- <button className="btn btn-ghost btn-xs gap-1" onClick={handleCopy}>- <Copy className="size-3.5" />- Copy- </button>- <button- className="btn btn-ghost btn-xs gap-1"- onClick={handleExport}- >- <Download className="size-3.5" />- Export CSV- </button>- </div>+ <div className="flex items-center justify-end gap-2">+ <button+ className="btn btn-ghost btn-xs gap-1"+ onClick={handleCopy}+ >+ <Copy className="size-3.5" />+ Copy+ </button>+ <button+ className="btn btn-ghost btn-xs gap-1"+ onClick={handleExport}+ >+ <Download className="size-3.5" />+ Export CSV+ </button>+ </div>- <div className="max-h-64 overflow-auto rounded-lg border border-base-300">- <table className="table table-sm">- <thead className="sticky top-0 bg-base-100">- <tr>- <th>Date</th>- {devices.length > 1 && <th>Device</th>}- <th>Position</th>- <th>Δ vs previous check</th>- </tr>- </thead>- <tbody>- {historyRows.map((r, idx) => {- // No prior ranking to compare against (first check, or the- // previous check was unranked): show the lone position as a- // centered neutral pill so it doesn't look like a stray number- // next to the "before → after" rows.- const noPrevious =- r.position !== null && r.previousPosition === null;- return (- <tr key={`${r.device}-${r.checkedAt}-${idx}`}>- <td className="whitespace-nowrap text-xs">- {new Date(r.checkedAt).toLocaleDateString()}- </td>- {devices.length > 1 && (- <td className="text-xs">- {DEVICE_STYLE[r.device].label}- </td>- )}- <td>- {r.position === null ? (- <span className="text-base-content/40 text-xs">- Not in top {serpDepth}- </span>- ) : (- <span className="font-mono text-sm">- {r.position}- </span>- )}- </td>- <td>- {noPrevious ? (- // Invisible placeholders matching the "before → after"- // layout so the lone pill lines up under the position- // badge column instead of floating.- <span className="inline-flex items-center gap-1.5">- <span className="w-6" aria-hidden />- <span aria-hidden className="opacity-0">- →- </span>- <span className="font-mono rounded bg-base-200 px-1.5 py-0.5 text-xs font-semibold text-base-content/70">- {r.position}- </span>- </span>- ) : (- <DeviceRankCell- result={{- position: r.position,- previousPosition: r.previousPosition,- rankingUrl: null,- serpFeatures: [],- }}- />- )}- </td>+ <div className="max-h-64 overflow-auto rounded-lg border border-base-300">+ <table className="table table-sm">+ <thead className="sticky top-0 bg-base-100">+ <tr>+ <th>Date</th>+ {devices.length > 1 && <th>Device</th>}+ <th>Position</th>+ <th>Δ vs previous check</th></tr>- );- })}- </tbody>- </table>- </div>- </>- )}+ </thead>+ <tbody>+ {historyRows.map((r, idx) => {+ // No prior ranking to compare against (first check, or the+ // previous check was unranked): show the lone position as a+ // centered neutral pill so it doesn't look like a stray number+ // next to the "before → after" rows.+ const noPrevious =+ r.position !== null && r.previousPosition === null;+ return (+ <tr key={`${r.device}-${r.checkedAt}-${idx}`}>+ <td className="whitespace-nowrap text-xs">+ {new Date(r.checkedAt).toLocaleDateString()}+ </td>+ {devices.length > 1 && (+ <td className="text-xs">+ {DEVICE_STYLE[r.device].label}+ </td>+ )}+ <td>+ {r.position === null ? (+ <span className="text-base-content/40 text-xs">+ Not in top {serpDepth}+ </span>+ ) : (+ <span className="font-mono text-sm">+ {r.position}+ </span>+ )}+ </td>+ <td>+ {noPrevious ? (+ // Invisible placeholders matching the "before → after"+ // layout so the lone pill lines up under the position+ // badge column instead of floating.+ <span className="inline-flex items-center gap-1.5">+ <span className="w-6" aria-hidden />+ <span aria-hidden className="opacity-0">+ →+ </span>+ <span className="font-mono rounded bg-base-200 px-1.5 py-0.5 text-xs font-semibold text-base-content/70">+ {r.position}+ </span>+ </span>+ ) : (+ <DeviceRankCell+ result={{+ position: r.position,+ previousPosition: r.previousPosition,+ rankingUrl: null,+ serpFeatures: [],+ }}+ />+ )}+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ </>+ )+ }+ </QueryState><div className="flex justify-end"><button className="btn btn-ghost btn-sm" onClick={onClose}>diff --git a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsxindex b1cb067e..e3dcf46c 100644--- a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx+++ b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx@@ -1,12 +1,17 @@import { useMemo, useState } from "react";import { toast } from "sonner";-import { useQuery, useQueryClient } from "@tanstack/react-query";+import {+ keepPreviousData,+ useQuery,+ useQueryClient,+} from "@tanstack/react-query";import {getLatestRankResults,getRankPositionMatrix,estimateRankCheckCost,} from "@/serverFunctions/rank-tracking";-import { AlertTriangle, ArrowLeft } from "lucide-react";+import { AlertTriangle, ArrowLeft, Loader2 } from "lucide-react";+import { QueryState } from "@/client/components/QueryState";import { useHostedPlanGate } from "@/client/features/billing/HostedPlanGate";import { captureClientEvent } from "@/client/lib/posthog";import { FreePlanAlert } from "./FreePlanAlert";@@ -106,13 +111,17 @@ export function RankTrackingDomainDetail({config.devices === "both" ? (search.device ?? "desktop") : config.devices;const viewMode = search.view ?? "table";- const { data: resultsData, isLoading: resultsLoading } = useQuery({+ // The route keys this component by config, so previous data here is always+ // the same domain at another compare period.+ const resultsQuery = useQuery({queryKey: ["rankTrackingResults", projectId, config.id, comparePeriod],queryFn: () =>getLatestRankResults({data: { projectId, configId: config.id, comparePeriod },}),+ placeholderData: keepPreviousData,});+ const resultsData = resultsQuery.data;const latestRun = useRankRunPolling(projectId, config.id);@@ -213,6 +222,15 @@ export function RankTrackingDomainDetail({: search.sort;// Fall back to the table if history disappears (e.g. device switch).const effectiveViewMode = historyAvailable ? viewMode : "table";+ const exportFiltered = (format: "csv" | "sheets") =>+ exportRankTracking({+ format,+ rows: filtered,+ showDesktop,+ showMobile,+ domain: config.domain,+ locationName: config.locationName,+ });return (<div className="space-y-3">@@ -307,26 +325,8 @@ export function RankTrackingDomainDetail({onSearchChange({ view: view === "history" ? view : undefined })}historyAvailable={historyAvailable}- onExport={() =>- exportRankTracking({- format: "csv",- rows: filtered,- showDesktop,- showMobile,- domain: config.domain,- locationName: config.locationName,- })- }- onExportToSheets={() =>- exportRankTracking({- format: "sheets",- rows: filtered,- showDesktop,- showMobile,- domain: config.domain,- locationName: config.locationName,- })- }+ onExport={() => exportFiltered("csv")}+ onExportToSheets={() => exportFiltered("sheets")}onCopyKeywords={() => {void navigator.clipboard.writeText(filtered.map((r) => r.keyword).join("\n"),@@ -365,34 +365,45 @@ export function RankTrackingDomainDetail({}))}/>) : (- <RankTrackingTable- key={defaultSortId}- totalCount={rows?.length ?? 0}- rows={filtered}- resultsLoading={resultsLoading}- showDesktop={showDesktop}- showMobile={showMobile}- sorting={- sortId- ? [{ id: sortId, desc: search.order === "desc" }]- : [{ id: defaultSortId, desc: false }]+ <QueryState+ query={resultsQuery}+ errorFallback="Failed to load rank data"+ loading={+ <div className="flex items-center justify-center p-8">+ <Loader2 className="size-5 animate-spin text-base-content/50" />+ </div>}- onSortingChange={(sorting) => {- onSearchChange({- sort: rankTrackingDetailSearchSchema.shape.sort.parse(- sorting[0]?.id,- ),- order: sorting[0]?.desc ? "desc" : undefined,- });- }}- domain={config.domain}- configId={config.id}- projectId={projectId}- locationCode={config.locationCode}- locationName={config.locationName}- serpDepth={config.serpDepth}- canCheck={planStatus === "paid"}- />+ >+ {(results) => (+ <RankTrackingTable+ key={defaultSortId}+ totalCount={results.rows.length}+ rows={filtered}+ showDesktop={showDesktop}+ showMobile={showMobile}+ sorting={+ sortId+ ? [{ id: sortId, desc: search.order === "desc" }]+ : [{ id: defaultSortId, desc: false }]+ }+ onSortingChange={(sorting) => {+ onSearchChange({+ sort: rankTrackingDetailSearchSchema.shape.sort.parse(+ sorting[0]?.id,+ ),+ order: sorting[0]?.desc ? "desc" : undefined,+ });+ }}+ domain={config.domain}+ configId={config.id}+ projectId={projectId}+ locationCode={config.locationCode}+ locationName={config.locationName}+ serpDepth={config.serpDepth}+ canCheck={planStatus === "paid"}+ />+ )}+ </QueryState>)}</div></div>diff --git a/src/client/features/rank-tracking/RankTrackingDomainList.tsx b/src/client/features/rank-tracking/RankTrackingDomainList.tsxindex 1cee37fe..d2bb1629 100644--- a/src/client/features/rank-tracking/RankTrackingDomainList.tsx+++ b/src/client/features/rank-tracking/RankTrackingDomainList.tsx@@ -29,6 +29,7 @@ import {import { Skeleton } from "@/client/components/Skeleton";import { useDebouncedDraft } from "@/client/hooks/useDebouncedDraft";import type { RankTrackingListSearch } from "@/types/schemas/rank-tracking-search";+import { QueryError } from "@/client/components/QueryState";type ConfigSummary = Awaited<ReturnType<typeof getRankTrackingConfigSummaries>@@ -81,10 +82,11 @@ export function RankTrackingDomainList({setQuery("");onSearchChange({});};- const { data: summaries, isPending } = useQuery({+ const summariesQuery = useQuery({queryKey: ["rankTrackingConfigSummaries", projectId],queryFn: () => getRankTrackingConfigSummaries({ data: { projectId } }),});+ const summaries = summariesQuery.data;const allSummaries = useMemo(() => summaries ?? [], [summaries]);const filteredSummaries = applyDomainListFilters(allSummaries, filters);const filterOptions = useMemo(() => {@@ -146,7 +148,17 @@ export function RankTrackingDomainList({/>)}<div className="divide-y divide-base-300 border-t border-base-300">- {isPending ? (+ {summariesQuery.isError && (+ <div className="px-5 py-4">+ <QueryError+ error={summariesQuery.error}+ fallback="Failed to load tracked domains"+ onRetry={() => void summariesQuery.refetch()}+ isRetrying={summariesQuery.isFetching}+ />+ </div>+ )}+ {summariesQuery.isPending ? (<div className="space-y-4 px-5 py-4" aria-busy>{Array.from({ length: 3 }).map((_, index) => (<div key={index} className="space-y-2">@@ -155,7 +167,7 @@ export function RankTrackingDomainList({</div>))}</div>- ) : allSummaries.length === 0 ? (+ ) : !summaries ? null : summaries.length === 0 ? (<div className="px-5 py-10 text-center space-y-2"><div className="mx-auto flex size-10 items-center justify-center rounded-xl bg-base-200"><Globe className="size-5 text-base-content/40" />diff --git a/src/client/features/rank-tracking/RankTrackingOverview.tsx b/src/client/features/rank-tracking/RankTrackingOverview.tsxindex 4f9aac7e..ca83d450 100644--- a/src/client/features/rank-tracking/RankTrackingOverview.tsx+++ b/src/client/features/rank-tracking/RankTrackingOverview.tsx@@ -11,6 +11,7 @@ import {} from "recharts";import type { TooltipContentProps } from "recharts";import { getRankConfigTrend } from "@/serverFunctions/rank-tracking";+import { QueryState } from "@/client/components/QueryState";import {formatDateTick,TrendRangeToggle,@@ -41,13 +42,14 @@ export function RankTrackingOverview({}) {const [sinceDays, setSinceDays] = useState(730);- const { data: trend, isLoading: trendLoading } = useQuery({+ const trendQuery = useQuery({queryKey: ["rankConfigTrend", projectId, configId, device, sinceDays],queryFn: () =>getRankConfigTrend({data: { projectId, configId, device, sinceDays },}),});+ const trend = trendQuery.data;const chartData = useMemo(() =>@@ -86,90 +88,100 @@ export function RankTrackingOverview({))}</div>- {trendLoading ? (- <div className="flex items-center justify-center p-8">- <Loader2 className="size-4 animate-spin text-base-content/50" />- </div>- ) : chartData.length <= 1 ? (- <div className="rounded-lg border border-dashed border-base-300 p-8 text-center text-xs text-base-content/60">- {chartData.length === 0- ? "No history yet — run a check to start tracking positions over time."- : "Only 1 check so far — the trend fills in after the next check."}- </div>- ) : (- <div- ref={containerRef}- className="w-full min-w-0"- style={{ height: 220 }}- >- {width > 0 ? (- <AreaChart- width={width}- height={220}- data={chartData}- margin={{ top: 8, right: 8, bottom: 0, left: 0 }}+ <QueryState+ query={trendQuery}+ errorFallback="Failed to load position history"+ loading={+ <div className="flex items-center justify-center p-8">+ <Loader2 className="size-4 animate-spin text-base-content/50" />+ </div>+ }+ >+ {() =>+ chartData.length <= 1 ? (+ <div className="rounded-lg border border-dashed border-base-300 p-8 text-center text-xs text-base-content/60">+ {chartData.length === 0+ ? "No history yet — run a check to start tracking positions over time."+ : "Only 1 check so far — the trend fills in after the next check."}+ </div>+ ) : (+ <div+ ref={containerRef}+ className="w-full min-w-0"+ style={{ height: 220 }}>- <CartesianGrid- strokeDasharray="3 3"- stroke="currentColor"- opacity={0.1}- vertical={false}- />- <XAxis- dataKey="checkedAt"- type="number"- scale="time"- domain={["dataMin", "dataMax"]}- tickFormatter={formatDateTick}- tick={{ fontSize: 10, fill: "#888" }}- tickLine={false}- axisLine={false}- minTickGap={32}- />- <YAxis- allowDecimals={false}- tick={{ fontSize: 10, fill: "#888" }}- tickLine={false}- axisLine={false}- width={28}- />- <Tooltip- content={(props: TooltipContentProps<number, string>) => {- const { active, payload, label } = props;- if (- !active ||- !payload?.length ||- typeof label !== "number"- ) {- return null;- }- const byKey = new Map(- payload.map((p: PayloadEntry) => [- String(p.dataKey),- typeof p.value === "number" ? p.value : 0,- ]),- );- return <DistributionTooltip label={label} byKey={byKey} />;- }}- cursor={{ stroke: "rgba(150,150,150,0.3)" }}- />- {BUCKETS.map((b) => (- <Area- key={b.key}- type="monotone"- dataKey={b.key}- name={b.label}- stackId="positions"- stroke={b.color}- fill={b.color}- fillOpacity={0.7}- isAnimationActive={false}- />- ))}- </AreaChart>- ) : null}- </div>- )}+ {width > 0 ? (+ <AreaChart+ width={width}+ height={220}+ data={chartData}+ margin={{ top: 8, right: 8, bottom: 0, left: 0 }}+ >+ <CartesianGrid+ strokeDasharray="3 3"+ stroke="currentColor"+ opacity={0.1}+ vertical={false}+ />+ <XAxis+ dataKey="checkedAt"+ type="number"+ scale="time"+ domain={["dataMin", "dataMax"]}+ tickFormatter={formatDateTick}+ tick={{ fontSize: 10, fill: "#888" }}+ tickLine={false}+ axisLine={false}+ minTickGap={32}+ />+ <YAxis+ allowDecimals={false}+ tick={{ fontSize: 10, fill: "#888" }}+ tickLine={false}+ axisLine={false}+ width={28}+ />+ <Tooltip+ content={(props: TooltipContentProps<number, string>) => {+ const { active, payload, label } = props;+ if (+ !active ||+ !payload?.length ||+ typeof label !== "number"+ ) {+ return null;+ }+ const byKey = new Map(+ payload.map((p: PayloadEntry) => [+ String(p.dataKey),+ typeof p.value === "number" ? p.value : 0,+ ]),+ );+ return (+ <DistributionTooltip label={label} byKey={byKey} />+ );+ }}+ cursor={{ stroke: "rgba(150,150,150,0.3)" }}+ />+ {BUCKETS.map((b) => (+ <Area+ key={b.key}+ type="monotone"+ dataKey={b.key}+ name={b.label}+ stackId="positions"+ stroke={b.color}+ fill={b.color}+ fillOpacity={0.7}+ isAnimationActive={false}+ />+ ))}+ </AreaChart>+ ) : null}+ </div>+ )+ }+ </QueryState></div></div>);diff --git a/src/client/features/rank-tracking/RankTrackingTable.tsx b/src/client/features/rank-tracking/RankTrackingTable.tsxindex 06ee3158..b0d3061c 100644--- a/src/client/features/rank-tracking/RankTrackingTable.tsx+++ b/src/client/features/rank-tracking/RankTrackingTable.tsx@@ -26,7 +26,6 @@ import type { SelectionAnchor } from "@/client/components/table/tableSelection";export function RankTrackingTable({totalCount,rows,- resultsLoading,showDesktop,showMobile,sorting,@@ -41,7 +40,6 @@ export function RankTrackingTable({}: {totalCount: number;rows: RankTrackingRow[];- resultsLoading: boolean;showDesktop: boolean;showMobile: boolean;sorting: SortingState;@@ -128,14 +126,6 @@ export function RankTrackingTable({},});- if (resultsLoading) {- return (- <div className="flex items-center justify-center p-8">- <Loader2 className="size-5 animate-spin text-base-content/50" />- </div>- );- }-if (rows.length === 0) {return (<div className="rounded-xl border border-dashed border-base-300 p-10 text-center text-sm text-base-content/55">diff --git a/src/client/features/sam/SamChat.tsx b/src/client/features/sam/SamChat.tsxindex adce62a4..430a4d12 100644--- a/src/client/features/sam/SamChat.tsx+++ b/src/client/features/sam/SamChat.tsx@@ -52,7 +52,7 @@ export function SamChat({// chat when the project has none.const firstSessionId = sessions[0]?.id;useEffect(() => {- if (activeSessionId || !optedIn || access.showSetupGate) return;+ if (activeSessionId || !optedIn || access.status !== "ready") return;if (firstSessionId) {goToSession(firstSessionId);return;@@ -62,7 +62,7 @@ export function SamChat({}, [activeSessionId,optedIn,- access.showSetupGate,+ access.status,firstSessionId,sessionsQuery.isSuccess,goToSession,@@ -94,11 +94,30 @@ export function SamChat({return <SamBetaGate onContinue={optInToSamBeta} />;}+ if (access.status === "checking") {+ return (+ <div className="flex h-full items-center justify-center p-4">+ <Spinner />+ </div>+ );+ }++ if (access.status === "error") {+ return (+ <div className="flex h-full items-center justify-center p-4">+ <QueryError+ error={access.error}+ fallback="Could not load AI agent setup status."+ onRetry={access.onRetry}+ isRetrying={access.isRetrying}+ />+ </div>+ );+ }+// SAM cannot answer a turn without OPENROUTER_API_KEY, so surface setup- // instructions instead of letting a chat fail mid-stream. Only shown once the- // check confirms the key is missing (self-hosted) — never as a blocking- // skeleton while the check is in flight.- if (access.showSetupGate) {+ // instructions instead of letting a chat fail mid-stream (self-hosted only).+ if (access.status === "setup") {return (<div className="overflow-auto px-4 py-4 md:px-6 md:py-6"><div className="mx-auto max-w-3xl">diff --git a/src/client/features/sam/SamSidebarPanel.tsx b/src/client/features/sam/SamSidebarPanel.tsxindex d9796b0a..8a0b4eee 100644--- a/src/client/features/sam/SamSidebarPanel.tsx+++ b/src/client/features/sam/SamSidebarPanel.tsx@@ -6,6 +6,7 @@ import {invalidateSamSessions,samSessionsQueryOptions,} from "@/client/features/sam/samQueries";+import { QueryState } from "@/client/components/QueryState";import { useSamBetaOptIn } from "./samBetaOptIn";import { useSamSessions } from "./useSamSessions";@@ -39,8 +40,10 @@ export function SamSidebarPanel({const location = useLocation();const activeSessionId = (location.search as { s?: string }).s;const optedIn = useSamBetaOptIn();- const { sessionsQuery, sessions, goToSession, createSession } =- useSamSessions(projectId, { onNavigate });+ const { sessionsQuery, goToSession, createSession } = useSamSessions(+ projectId,+ { onNavigate },+ );const archiveSession = useMutation({mutationFn: (sessionId: string) =>@@ -88,51 +91,59 @@ export function SamSidebarPanel({</div><div className="min-h-0 flex-1 overflow-y-auto px-2 py-1">- {sessionsQuery.isLoading ? (- <div className="flex justify-center py-6 text-base-content/50">- <Loader2 className="size-4 animate-spin" />- </div>- ) : sessions.length === 0 ? (- <p className="px-2 py-6 text-center text-xs text-base-content/50">- No chats yet. Start a new one.- </p>- ) : (- sessions.map((session) => {- const isActive = session.id === activeSessionId;- return (- <div- key={session.id}- className={`group flex items-center gap-1 rounded-md px-1 ${- isActive ? "bg-base-300/50" : "hover:bg-base-300/40"- }`}- >- <button- type="button"- onClick={() => goToSession(session.id)}- className="min-w-0 flex-1 truncate px-2 py-1.5 text-left text-sm text-base-content/80"- >- {session.title}- </button>- {/* The age and the Archive button share one grid cell, so the- button takes the place of the age when it shows. */}- <div className="grid shrink-0 place-items-center *:col-start-1 *:row-start-1">- <span className="text-xs text-base-content/40 transition-opacity group-hover:opacity-0 group-focus-within:opacity-0 pointer-coarse:opacity-0">- {ageLabel(session.updatedAt)}- </span>- <button- type="button"- aria-label="Archive chat"- className="btn btn-ghost btn-xs btn-square reveal-on-hover"- disabled={archiveSession.isPending}- onClick={() => archiveSession.mutate(session.id)}+ <QueryState+ query={sessionsQuery}+ errorFallback="Failed to load chats."+ loading={+ <div className="flex justify-center py-6 text-base-content/50">+ <Loader2 className="size-4 animate-spin" />+ </div>+ }+ >+ {(loadedSessions) =>+ loadedSessions.length === 0 ? (+ <p className="px-2 py-6 text-center text-xs text-base-content/50">+ No chats yet. Start a new one.+ </p>+ ) : (+ loadedSessions.map((session) => {+ const isActive = session.id === activeSessionId;+ return (+ <div+ key={session.id}+ className={`group flex items-center gap-1 rounded-md px-1 ${+ isActive ? "bg-base-300/50" : "hover:bg-base-300/40"+ }`}>- <Archive className="size-3.5 text-base-content/50" />- </button>- </div>- </div>- );- })- )}+ <button+ type="button"+ onClick={() => goToSession(session.id)}+ className="min-w-0 flex-1 truncate px-2 py-1.5 text-left text-sm text-base-content/80"+ >+ {session.title}+ </button>+ {/* The age and the Archive button share one grid cell, so the+ button takes the place of the age when it shows. */}+ <div className="grid shrink-0 place-items-center *:col-start-1 *:row-start-1">+ <span className="text-xs text-base-content/40 transition-opacity group-hover:opacity-0 group-focus-within:opacity-0 pointer-coarse:opacity-0">+ {ageLabel(session.updatedAt)}+ </span>+ <button+ type="button"+ aria-label="Archive chat"+ className="btn btn-ghost btn-xs btn-square reveal-on-hover"+ disabled={archiveSession.isPending}+ onClick={() => archiveSession.mutate(session.id)}+ >+ <Archive className="size-3.5 text-base-content/50" />+ </button>+ </div>+ </div>+ );+ })+ )+ }+ </QueryState></div></div>);diff --git a/src/client/features/sam/useSamAccess.ts b/src/client/features/sam/useSamAccess.tsindex 8925dddf..b93cbd2c 100644--- a/src/client/features/sam/useSamAccess.ts+++ b/src/client/features/sam/useSamAccess.ts@@ -1,26 +1,32 @@-import { useCallback } from "react";import { useQuery } from "@tanstack/react-query";import { getStandardErrorMessage } from "@/client/lib/error-messages";import { isHostedClientAuthMode } from "@/lib/auth-mode";import { getSamAccessSetupStatus } from "@/serverFunctions/samAccess";-type SamAccess = {- // Only true once the setup check has resolved to "no access". It stays false- // while the check is in flight, so the chat renders immediately instead of- // blocking behind a skeleton — the gate only replaces it if we confirm the- // OpenRouter key is missing.- showSetupGate: boolean;- errorMessage: string | null;- isRefetching: boolean;- onRetry: () => void;-};+// Fails closed: the chat only renders once the check confirms the OpenRouter+// key is set. A failed check is an error with retry, not the key-missing gate.+type SamAccess =+ | { status: "ready" }+ | { status: "checking" }+ | {+ status: "error";+ error: unknown;+ isRetrying: boolean;+ onRetry: () => void;+ }+ | {+ status: "setup";+ errorMessage: string | null;+ isRefetching: boolean;+ onRetry: () => void;+ };export function useSamAccess(projectId: string): SamAccess {// Hosted deployments always have OPENROUTER_API_KEY provisioned (the server// function short-circuits to enabled), so skip the round-trip entirely.const isHosted = isHostedClientAuthMode();- const { data, error, isRefetching, refetch } = useQuery({+ const { data, error, isFetching, isRefetching, refetch } = useQuery({queryKey: ["samAccessStatus", projectId],queryFn: () => getSamAccessSetupStatus({ data: { projectId } }),enabled: !isHosted,@@ -28,26 +34,19 @@ export function useSamAccess(projectId: string): SamAccess {staleTime: 60 * 1000,});- const onRetry = useCallback(() => {- void refetch();- }, [refetch]);+ const onRetry = () => void refetch();- if (isHosted) {- return {- showSetupGate: false,- errorMessage: null,- isRefetching: false,- onRetry,- };+ if (isHosted) return { status: "ready" };+ if (data === undefined) {+ return error+ ? { status: "error", error, isRetrying: isFetching, onRetry }+ : { status: "checking" };}-- // Optimistic: only gate once the check has actually resolved (success or- // error) and it says the key isn't there.- const resolved = data !== undefined || error != null;+ if (data.enabled) return { status: "ready" };return {- showSetupGate: resolved && !(data?.enabled ?? false),+ status: "setup",errorMessage:- data?.errorMessage ??+ data.errorMessage ??(error? getStandardErrorMessage(error,diff --git a/src/client/features/search-performance/SearchPerformanceDimensionSection.tsx b/src/client/features/search-performance/SearchPerformanceDimensionSection.tsxnew file mode 100644index 00000000..46f1f12b--- /dev/null+++ b/src/client/features/search-performance/SearchPerformanceDimensionSection.tsx@@ -0,0 +1,79 @@+import type { UseQueryResult } from "@tanstack/react-query";+import { Loader2 } from "lucide-react";+import { QueryError } from "@/client/components/QueryState";+import { TablePagination } from "@/client/components/table/TablePagination";+import { GoogleConnectionCard } from "@/client/features/integrations/GoogleConnectionCard";+import { DimensionTable } from "@/client/features/search-performance/SearchPerformanceParts";+import type { getSearchPerformanceTable } from "@/serverFunctions/searchPerformance";+import { SEARCH_PERFORMANCE_PAGE_SIZES } from "@/types/schemas/search-performance";++/** The Queries or Pages tab body: loading, error with retry, reconnect, or the paged table. */+export function DimensionSection({+ projectId,+ tableQuery,+ keyLabel,+ page,+ pageSize,+ onPageChange,+ onPageSizeChange,+}: {+ projectId: string;+ tableQuery: UseQueryResult<+ Awaited<ReturnType<typeof getSearchPerformanceTable>>+ >;+ keyLabel: string;+ page: number;+ pageSize: number;+ onPageChange: (page: number) => void;+ onPageSizeChange: (pageSize: number) => void;+}) {+ if (tableQuery.isPending) {+ return (+ <div className="flex items-center gap-2 p-8 text-sm text-base-content/60">+ <Loader2 className="size-4 animate-spin" /> Loading…+ </div>+ );+ }++ const error = tableQuery.isError ? (+ <div className="px-4 pt-4">+ <QueryError+ error={tableQuery.error}+ fallback="Failed to load Search Console data"+ onRetry={() => void tableQuery.refetch()}+ isRetrying={tableQuery.isFetching}+ />+ </div>+ ) : null;++ const tableData = tableQuery.data;+ if (!tableData) return <div className="pb-4">{error}</div>;++ // The grant died after the report loaded as connected.+ if (!tableData.connected) {+ return (+ <div className="max-w-2xl p-4">+ <GoogleConnectionCard provider="gsc" projectId={projectId} />+ </div>+ );+ }++ return (+ <>+ {error}+ <div className="p-4">+ <DimensionTable rows={tableData.rows} keyLabel={keyLabel} />+ </div>+ <TablePagination+ page={page}+ pageSize={pageSize}+ pageSizes={SEARCH_PERFORMANCE_PAGE_SIZES}+ totalCount={tableData.totalCount}+ hasNextPage={tableData.hasNextPage}+ isLoading={tableQuery.isFetching}+ onPageChange={onPageChange}+ onPageSizeChange={onPageSizeChange}+ />+ </>+ );+}diff --git a/src/client/features/search-performance/SearchPerformancePage.tsx b/src/client/features/search-performance/SearchPerformancePage.tsxindex 177d0cf5..bba788ec 100644--- a/src/client/features/search-performance/SearchPerformancePage.tsx+++ b/src/client/features/search-performance/SearchPerformancePage.tsx@@ -7,9 +7,10 @@ import {} from "@tanstack/react-query";import { Download, Loader2, Sheet, SlidersHorizontal } from "lucide-react";import { toast } from "sonner";+import { QueryError } from "@/client/components/QueryState";import { TableExportMenu } from "@/client/components/table/TableBulkActionBar";-import { TablePagination } from "@/client/components/table/TablePagination";import { GoogleConnectionCard } from "@/client/features/integrations/GoogleConnectionCard";+import { DimensionSection } from "@/client/features/search-performance/SearchPerformanceDimensionSection";import { SearchPerformanceSelects } from "@/client/features/search-performance/SearchPerformanceSelects";import { SearchPerformanceLoadingState } from "@/client/features/search-performance/SearchPerformanceLoadingState";import {@@ -21,7 +22,6 @@ import {type TextFilters,} from "@/client/features/search-performance/SearchPerformanceTextFilters";import {- DimensionTable,exportDimensionRows,exportStriking,StrikingDistanceTable,@@ -36,7 +36,6 @@ import {} from "@/serverFunctions/searchPerformance";import {SEARCH_PERFORMANCE_DEFAULT_PAGE_SIZE,- SEARCH_PERFORMANCE_PAGE_SIZES,type SearchPerformanceSearch,type SearchPerformanceTab,type SearchPerformanceTableDimension,@@ -117,10 +116,14 @@ export function SearchPerformancePage({const tableQuery = useQuery({...tableQueryOptions(projectId, dimension, page, pageSize, filterInput),enabled: report?.connected === true && isTableTab,+ // Hold the current rows while paging or filtering, but not across a tab+ // or project change: Query rows must not render under the Pages header.+ placeholderData: (previous, previousQuery) =>+ previousQuery?.queryKey[1] === projectId &&+ previousQuery.queryKey[2] === dimension+ ? previous+ : undefined,});- const tableData = tableQuery.data;- const tableRows = tableData?.connected ? tableData.rows : [];- const hasNextPage = tableData?.connected ? tableData.hasNextPage : false;// Warm the Queries tab (first page) as soon as the report connects so the tab// opens instantly instead of showing a spinner. Free first-party GSC data.@@ -161,6 +164,15 @@ export function SearchPerformancePage({}};+ const reportError = (+ <QueryError+ error={reportQuery.error}+ fallback="Failed to load Search Console data"+ onRetry={() => void reportQuery.refetch()}+ isRetrying={reportQuery.isFetching}+ />+ );+const filtersPanel = (<SearchPerformanceTextFilters// Remount on URL changes (back/forward) so the draft matches.@@ -213,21 +225,20 @@ export function SearchPerformancePage({) : null}</div>- {reportQuery.isError ? filtersPanel : null}{reportQuery.isPending ? (<SearchPerformanceLoadingState />- ) : reportQuery.isError ? (- <div className="alert alert-error">- <span className="text-sm">- {getStandardErrorMessage(reportQuery.error)}- </span>- </div>- ) : !report?.connected ? (+ ) : !report ? (+ <>+ {filtersPanel}+ {reportError}+ </>+ ) : !report.connected ? (<div className="max-w-2xl"><GoogleConnectionCard provider="gsc" projectId={projectId} /></div>) : (<>+ {reportQuery.isError ? reportError : null}{reportQuery.isPlaceholderData ? (<SearchPerformanceLoadingState />) : (@@ -317,43 +328,20 @@ export function SearchPerformancePage({projectId={projectId}rows={report.strikingDistance}/>- ) : tableQuery.isPending ? (- <div className="flex items-center gap-2 p-8 text-sm text-base-content/60">- <Loader2 className="size-4 animate-spin" /> Loading…- </div>- ) : tableQuery.isError ? (- <div className="p-4">- <div className="alert alert-error">- <span className="text-sm">- {getStandardErrorMessage(tableQuery.error)}- </span>- </div>- </div>) : (- <>- <div className="p-4">- <DimensionTable- rows={tableRows}- keyLabel={tab === "queries" ? "Query" : "Page"}- />- </div>- <TablePagination- page={page}- pageSize={pageSize}- pageSizes={SEARCH_PERFORMANCE_PAGE_SIZES}- totalCount={- tableData?.connected ? tableData.totalCount : null- }- hasNextPage={hasNextPage}- isLoading={tableQuery.isFetching}- onPageChange={(nextPage) =>- onSearchChange({ page: nextPage })- }- onPageSizeChange={(size) =>- onSearchChange({ page: undefined, size })- }- />- </>+ <DimensionSection+ projectId={projectId}+ tableQuery={tableQuery}+ keyLabel={tab === "queries" ? "Query" : "Page"}+ page={page}+ pageSize={pageSize}+ onPageChange={(nextPage) =>+ onSearchChange({ page: nextPage })+ }+ onPageSizeChange={(size) =>+ onSearchChange({ page: undefined, size })+ }+ />)}</div></>diff --git a/src/client/features/team/TeamSettings.tsx b/src/client/features/team/TeamSettings.tsxindex 8425e278..43be8ccb 100644--- a/src/client/features/team/TeamSettings.tsx+++ b/src/client/features/team/TeamSettings.tsx@@ -122,20 +122,20 @@ export function TeamSettings() {const pendingInvitations = teamQuery.data?.pendingInvitations ?? [];// The team query waits on the org context, so a failed context would- // otherwise leave the team spinner up for good.+ // otherwise leave the team spinner up for good. A failed refetch keeps the+ // loaded table, with the error above it.const failedQuery = [orgContextQuery, teamQuery].find(- (query) => query.isError && query.data === undefined,+ (query) => query.isError,);- if (failedQuery) {- return (- <QueryError- error={failedQuery.error}- fallback="We couldn't load your team right now."- onRetry={() => void failedQuery.refetch()}- isRetrying={failedQuery.isFetching}- />- );- }+ const loadError = failedQuery ? (+ <QueryError+ error={failedQuery.error}+ fallback="We couldn't load your team right now."+ onRetry={() => void failedQuery.refetch()}+ isRetrying={failedQuery.isFetching}+ />+ ) : null;+ if (failedQuery && failedQuery.data === undefined) return loadError;return (<section className="space-y-3">@@ -155,6 +155,7 @@ export function TeamSettings() {Teammates join as Admins. Admins have full access to each project exceptfor billing.</p>+ {loadError}{teamQuery.isPending ? (<PageLoading />diff --git a/src/routes/_app/billing.tsx b/src/routes/_app/billing.tsxindex 48c6fb99..74fae1fa 100644--- a/src/routes/_app/billing.tsx+++ b/src/routes/_app/billing.tsx@@ -67,6 +67,7 @@ function BillingPage() {isSessionPending,isCustomerLoading: customerQuery.isLoading,isCustomerError: customerQuery.isError,+ hasCustomerData: customerQuery.data != null,});const monthlyRemaining = autumnSeoDataCreditsToUsd(@@ -138,6 +139,15 @@ function BillingPage() {<div className="mx-auto w-full max-w-2xl space-y-5 p-4 py-10 md:p-6 md:py-12"><h1 className="text-xl font-semibold">Billing</h1>+ {customerQuery.isError ? (+ <QueryError+ error={customerQuery.error}+ fallback="Failed to refresh billing details"+ onRetry={() => void customerQuery.refetch()}+ isRetrying={customerQuery.isFetching}+ />+ ) : null}+<div className="grid gap-5 md:grid-cols-2">{/* Subscription card */}<div className="flex flex-col justify-between rounded-lg border border-base-300 bg-base-100 p-4 gap-4">diff --git a/src/routes/_app/billing_.fix-payment.tsx b/src/routes/_app/billing_.fix-payment.tsxindex 10818f46..597ce331 100644--- a/src/routes/_app/billing_.fix-payment.tsx+++ b/src/routes/_app/billing_.fix-payment.tsx@@ -48,6 +48,7 @@ function FixPaymentPage() {isSessionPending,isCustomerLoading: customerQuery.isLoading,isCustomerError: customerQuery.isError,+ hasCustomerData: customerQuery.data != null,});const isPastDue =customerQuery.data?.subscriptions?.some((s) => s.pastDue) ?? false;diff --git a/src/routes/_app/p/$projectId/rank-tracking/$configId.tsx b/src/routes/_app/p/$projectId/rank-tracking/$configId.tsxindex a5382727..dc2cca4d 100644--- a/src/routes/_app/p/$projectId/rank-tracking/$configId.tsx+++ b/src/routes/_app/p/$projectId/rank-tracking/$configId.tsx@@ -4,6 +4,7 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";import { getRankTrackingConfigs } from "@/serverFunctions/rank-tracking";import { RankTrackingDomainDetail } from "@/client/features/rank-tracking/RankTrackingDomainDetail";import { PageLoading } from "@/client/components/Spinner";+import { QueryError } from "@/client/components/QueryState";import { RankTrackingConfigModal } from "@/client/features/rank-tracking/RankTrackingConfigModal";import { rankTrackingDetailSearchSchema } from "@/types/schemas/rank-tracking-search";@@ -21,12 +22,12 @@ function RankTrackingConfigRoute() {const queryClient = useQueryClient();const [showConfigModal, setShowConfigModal] = useState(false);- const { data: configs, isPending } = useQuery({+ const configsQuery = useQuery({queryKey: ["rankTrackingConfigs", projectId],queryFn: () => getRankTrackingConfigs({ data: { projectId } }),});- const config = configs?.find((c) => c.id === configId) ?? null;+ const config = configsQuery.data?.find((c) => c.id === configId) ?? null;const invalidateConfigs = () => {void queryClient.invalidateQueries({@@ -44,10 +45,21 @@ function RankTrackingConfigRoute() {});};- if (isPending) {+ if (configsQuery.isPending) {return <PageLoading />;}+ if (!configsQuery.data) {+ return (+ <QueryError+ error={configsQuery.error}+ fallback="Failed to load domain configuration"+ onRetry={() => void configsQuery.refetch()}+ isRetrying={configsQuery.isFetching}+ />+ );+ }+if (!config) {return (<>@@ -64,6 +76,7 @@ function RankTrackingConfigRoute() {return (<><RankTrackingDomainDetail+ key={config.id}config={config}projectId={projectId}search={search}diff --git a/src/routes/_app/p/$projectId/reports/$reportId.tsx b/src/routes/_app/p/$projectId/reports/$reportId.tsxindex 19911d52..5b68db44 100644--- a/src/routes/_app/p/$projectId/reports/$reportId.tsx+++ b/src/routes/_app/p/$projectId/reports/$reportId.tsx@@ -89,8 +89,20 @@ function ReportDetailPage() {return <PageLoading />;}- if (reportQuery.isError) {- const notFound = getErrorCode(reportQuery.error) === "NOT_FOUND";+ const loadError = (+ <QueryError+ error={reportQuery.error}+ fallback="Failed to load the report"+ onRetry={() => void reportQuery.refetch()}+ isRetrying={reportQuery.isFetching}+ />+ );++ // A failed refetch keeps the loaded report on screen, unless the report is+ // gone: then the not-found answer replaces it.+ const notFound =+ reportQuery.isError && getErrorCode(reportQuery.error) === "NOT_FOUND";+ if (notFound || reportQuery.data === undefined) {return (<div className="px-4 py-6 md:px-6"><div className="mx-auto max-w-3xl space-y-4">@@ -100,12 +112,7 @@ function ReportDetailPage() {{notFound ? (<QueryError fallback="This report does not exist or you do not have access to it." />) : (- <QueryError- error={reportQuery.error}- fallback="Failed to load the report"- onRetry={() => void reportQuery.refetch()}- isRetrying={reportQuery.isFetching}- />+ loadError)}<Linkto="/p/$projectId/reports"@@ -143,6 +150,7 @@ function ReportDetailPage() {return (<div className="flex h-full min-h-0 flex-col gap-3 px-4 py-4 md:px-6 md:py-6">+ {reportQuery.isError ? loadError : null}<div className="space-y-3"><Linkto="/p/$projectId/reports"diff --git a/src/routes/_app/p/$projectId/saved.tsx b/src/routes/_app/p/$projectId/saved.tsxindex 1f2afba4..8af7b250 100644--- a/src/routes/_app/p/$projectId/saved.tsx+++ b/src/routes/_app/p/$projectId/saved.tsx@@ -19,6 +19,7 @@ import type {} from "@tanstack/react-table";import { useEffect, useMemo, useRef, useState } from "react";import { toast } from "sonner";+import { QueryError } from "@/client/components/QueryState";import { TablePagination } from "@/client/components/table/TablePagination";import { SavedKeywordsBulkActionBar } from "@/client/features/saved-keywords/SavedKeywordsBulkActionBar";import { SavedKeywordsBulkTagsModal } from "@/client/features/saved-keywords/SavedKeywordsBulkTagsModal";@@ -191,11 +192,12 @@ function SavedKeywordsPage() {[appliedFilters, order, page, pageSize, projectId, selectedTagIds, sort],);- const { data, isLoading, isFetching } = useQuery({+ const savedKeywordsQuery = useQuery({queryKey: ["savedKeywords", projectId, queryInput],queryFn: () => getSavedKeywords({ data: queryInput }),placeholderData: keepPreviousData,});+ const { data, isLoading, isFetching } = savedKeywordsQuery;const savedKeywords = data?.rows ?? [];const availableTags = data?.tags ?? [];@@ -344,15 +346,27 @@ function SavedKeywordsPage() {{removeError ? (<RemoveSavedKeywordsError message={removeError} />) : null}- <SavedKeywordsTable- rows={savedKeywords}- rowSelection={rowSelection}- sorting={sorting}- isLoading={isLoading}- hasActiveFilters={hasActiveFilters}- onRowSelectionChange={setRowSelection}- onSortingChange={handleSortingChange}- />+ {savedKeywordsQuery.isError ? (+ <QueryError+ error={savedKeywordsQuery.error}+ fallback="Failed to load saved keywords."+ onRetry={() => void savedKeywordsQuery.refetch()}+ isRetrying={isFetching}+ />+ ) : null}+ {/* Without data a failed load has nothing to show; the empty+ state would claim there are no saved keywords. */}+ {savedKeywordsQuery.isError && data === undefined ? null : (+ <SavedKeywordsTable+ rows={savedKeywords}+ rowSelection={rowSelection}+ sorting={sorting}+ isLoading={isLoading}+ hasActiveFilters={hasActiveFilters}+ onRowSelectionChange={setRowSelection}+ onSortingChange={handleSortingChange}+ />+ )}</div><TablePaginationdiff --git a/src/routes/_authenticated.yc.tsx b/src/routes/_authenticated.yc.tsxindex 24578b8d..b46be1f3 100644--- a/src/routes/_authenticated.yc.tsx+++ b/src/routes/_authenticated.yc.tsx@@ -59,6 +59,7 @@ function YcPlanPage() {isSessionPending,isCustomerLoading: customerQuery.isLoading,isCustomerError: customerQuery.isError,+ hasCustomerData: customerQuery.data != null,});const isPaid = getCustomerPlanStatus(customerQuery.data) === "paid";