Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Delete unreachable UI states and unused props before the ShadCN port (EVE-274, EVE-275) (#681)
Carter Smith1b2fc1c8bfff
diff --git a/e2e/domain-overview-filters.perf.spec.ts b/e2e/domain-overview-filters.perf.spec.tsindex a8e24ac0..bb342d5d 100644--- a/e2e/domain-overview-filters.perf.spec.ts+++ b/e2e/domain-overview-filters.perf.spec.ts@@ -38,12 +38,6 @@ type PerfCheckpoint =error: string;};-type DomainDebugEntry = {- type: string;- text: string;- parsed: unknown;-};-test.describe("Domain Overview filter performance", () => {test("captures main-thread stalls in the applied-filter edit flow", async ({page,@@ -53,20 +47,6 @@ test.describe("Domain Overview filter performance", () => {test.setTimeout(120_000);await installDomainPerfProbe(page);- await page.addInitScript(() => {- window.localStorage.setItem("debug:domain-overview", "1");- });- const domainDebugLog: DomainDebugEntry[] = [];- page.on("console", (message) => {- const text = message.text();- if (!text.startsWith("[domain-debug]")) return;- const raw = text.slice("[domain-debug]".length).trim();- domainDebugLog.push({- type: message.type(),- text,- parsed: parseDomainDebugMessage(raw),- });- });const client = await page.context().newCDPSession(page);await client.send("Emulation.setCPUThrottlingRate", {rate: CPU_THROTTLE_RATE,@@ -179,11 +159,6 @@ test.describe("Domain Overview filter performance", () => {"domain-filter-perf-checkpoints.json",checkpoints,);- await attachJsonArtifact(- testInfo,- "domain-filter-debug-log.json",- domainDebugLog,- );if (finalMetrics) {await attachDomainPerfMetrics(testInfo, finalMetrics);}@@ -239,14 +214,6 @@ function getErrorMessage(error: unknown) {return error instanceof Error ? error.message : String(error);}-function parseDomainDebugMessage(raw: string): unknown {- try {- return JSON.parse(raw);- } catch {- return raw;- }-}-async function withDeadline<T>(promise: Promise<T>,timeoutMs: number,diff --git a/src/client/components/AuthConfigErrorCard.tsx b/src/client/components/AuthConfigErrorCard.tsxindex 47b8bc5c..a79bc683 100644--- a/src/client/components/AuthConfigErrorCard.tsx+++ b/src/client/components/AuthConfigErrorCard.tsx@@ -6,7 +6,7 @@ const CLOUDFLARE_SETUP_GUIDE_URL =type AuthConfigErrorCardProps = {message: string;- onRetry?: () => void;+ onRetry: () => void;};export function AuthConfigErrorCard({@@ -44,11 +44,9 @@ export function AuthConfigErrorCard({)}<div className="card-actions justify-end">- {onRetry ? (- <button className="btn btn-ghost btn-sm" onClick={onRetry}>- Try Again- </button>- ) : null}+ <button className="btn btn-ghost btn-sm" onClick={onRetry}>+ Try Again+ </button><aclassName="btn btn-primary btn-sm"href={CLOUDFLARE_SETUP_GUIDE_URL}diff --git a/src/client/components/NotFound.tsx b/src/client/components/NotFound.tsxindex 643b1aad..24509a0a 100644--- a/src/client/components/NotFound.tsx+++ b/src/client/components/NotFound.tsx@@ -1,10 +1,10 @@-export function NotFound({ children }: { children?: React.ReactNode }) {+export function NotFound() {return (<div className="space-y-2 p-4"><h1 className="text-2xl">404</h1>- <div className="text-base-content/70">- {children || <p>The page you are looking for does not exist.</p>}- </div>+ <p className="text-base-content/70">+ The page you are looking for does not exist.+ </p></div>);}diff --git a/src/client/components/Sidebar.tsx b/src/client/components/Sidebar.tsxindex 8bb403b2..1be9811d 100644--- a/src/client/components/Sidebar.tsx+++ b/src/client/components/Sidebar.tsx@@ -27,7 +27,6 @@ import { ThemePreferenceMenuItems } from "@/client/components/ThemePreferenceMenimport { closeDropdown } from "@/client/lib/dropdown";import { getStandardErrorMessage } from "@/client/lib/error-messages";import { signOutAndRedirect, useSession } from "@/lib/auth-client";-import { isHostedClientAuthMode } from "@/lib/auth-mode";import { BILLING_ROUTE } from "@/shared/billing";interface SidebarProps {@@ -102,13 +101,13 @@ export function Sidebar({ projectId, onNavigate, onClose }: SidebarProps) {setView(onSamRoute ? "chat" : "browse");}, [onSamRoute]);- const openChat = () => {+ // Both tabs only render with a project selected, so they receive its id.+ const openChat = (activeProjectId: string) => {setView("chat");- if (!projectId) return;if (!onSamRoute) {void navigate({to: "/p/$projectId/sam",- params: { projectId },+ params: { projectId: activeProjectId },search: {},});onNavigate?.();@@ -117,10 +116,13 @@ export function Sidebar({ projectId, onNavigate, onClose }: SidebarProps) {// Coming back from Chat, land on the dashboard rather than leaving the// conversation filling the content panel next to a Browse nav.- const openBrowse = () => {+ const openBrowse = (activeProjectId: string) => {setView("browse");- if (!projectId || !onSamRoute) return;- void navigate({ to: "/p/$projectId", params: { projectId } });+ if (!onSamRoute) return;+ void navigate({+ to: "/p/$projectId",+ params: { projectId: activeProjectId },+ });onNavigate?.();};@@ -162,13 +164,13 @@ export function Sidebar({ projectId, onNavigate, onClose }: SidebarProps) {icon={LayoutGrid}label="Browse"active={view === "browse"}- onClick={openBrowse}+ onClick={() => openBrowse(projectId)}/><SidebarViewTabicon={MessageCircle}label="Chat"active={view === "chat"}- onClick={openChat}+ onClick={() => openChat(projectId)}/></div></div>@@ -232,13 +234,13 @@ function SidebarViewTab({function SidebarFooter({ onNavigate }: { onNavigate?: () => void }) {const { data: session } = useSession();- const isHostedMode = isHostedClientAuthMode();+ // Only hosted mode has a session, so the account menu below is hosted-only.const email = session?.user?.email;const [isSwitching, setIsSwitching] = useState(false);const orgContextQuery = useQuery({...organizationContextQueryOptions(),- enabled: isHostedMode && Boolean(email),+ enabled: Boolean(email),});const organizations = orgContextQuery.data?.organizations ?? [];const activeOrganizationId = orgContextQuery.data?.organizationId;@@ -326,33 +328,27 @@ function SidebarFooter({ onNavigate }: { onNavigate?: () => void }) {Settings</Link></li>- {isHostedMode ? (- <li>- <Link to={BILLING_ROUTE} onClick={closeMenu}>- <CreditCard className="h-4 w-4" />- Billing- </Link>- </li>- ) : null}+ <li>+ <Link to={BILLING_ROUTE} onClick={closeMenu}>+ <CreditCard className="h-4 w-4" />+ Billing+ </Link>+ </li><ThemePreferenceMenuItems />- {isHostedMode ? (- <>- <li- aria-hidden- className="pointer-events-none my-1 h-px bg-base-300 p-0"- />- <li>- <button- type="button"- className="text-error"- onClick={() => signOutAndRedirect()}- >- <LogOut className="h-4 w-4" />- Sign out- </button>- </li>- </>- ) : null}+ <li+ aria-hidden+ className="pointer-events-none my-1 h-px bg-base-300 p-0"+ />+ <li>+ <button+ type="button"+ className="text-error"+ onClick={() => signOutAndRedirect()}+ >+ <LogOut className="h-4 w-4" />+ Sign out+ </button>+ </li></ul></div>) : (diff --git a/src/client/components/UnauthenticatedErrorCard.tsx b/src/client/components/UnauthenticatedErrorCard.tsxindex 7508f806..5cfb9483 100644--- a/src/client/components/UnauthenticatedErrorCard.tsx+++ b/src/client/components/UnauthenticatedErrorCard.tsx@@ -4,7 +4,7 @@ import { isHostedClientAuthMode } from "@/lib/auth-mode";type UnauthenticatedErrorCardProps = {message: string;- onRetry?: () => void;+ onRetry: () => void;};export function UnauthenticatedErrorCard({@@ -38,13 +38,11 @@ export function UnauthenticatedErrorCard({This deployment uses external authentication. Refresh your accesssession, then try again.</p>- {onRetry ? (- <div className="card-actions justify-end">- <button className="btn btn-primary btn-sm" onClick={onRetry}>- Try Again- </button>- </div>- ) : null}+ <div className="card-actions justify-end">+ <button className="btn btn-primary btn-sm" onClick={onRetry}>+ Try Again+ </button>+ </div></div></div>);diff --git a/src/client/components/chat/ChatMessage.tsx b/src/client/components/chat/ChatMessage.tsxindex a0290c1d..6407382f 100644--- a/src/client/components/chat/ChatMessage.tsx+++ b/src/client/components/chat/ChatMessage.tsx@@ -11,23 +11,12 @@ import {} from "lucide-react";import { Markdown } from "@/client/components/Markdown";-// Shared chat-message rendering. A chat supplies which tools are available and-// how tool names become labels (resolveToolLabel) plus which message actions-// its server supports (onUndo/onEdit); the UI itself lives here.--type ToolLabel = { running: string; done: string };--// Maps a UIMessage tool part type (e.g. "tool-get_serp_results") to its label,-// or null to hide the badge entirely.-type ResolveToolLabel = (partType: string) => ToolLabel | null;-// Turn a tool part type ("tool-get_serp_results") into a readable label-// ("Get serp results"). Used for chats that expose too many tools to curate a-// per-tool label map by hand.-export function humanizeToolLabel(partType: string): ToolLabel {+// ("Get serp results"). SAM exposes the full MCP tool surface, too many tools+// to curate a per-tool label map by hand.+function humanizeToolLabel(partType: string): string {const name = partType.replace(/^tool-/, "").replace(/_/g, " ");- const label = name.charAt(0).toUpperCase() + name.slice(1);- return { running: label, done: label };+ return name.charAt(0).toUpperCase() + name.slice(1);}// activate_skill is the one tool where the target matters more than the tool@@ -179,17 +168,14 @@ function ReasoningBlock({function ToolBadge({part,live,- resolveToolLabel,}: {part: UIMessage["parts"][number];live: boolean;- resolveToolLabel: ResolveToolLabel;}) {- const labels = resolveToolLabel(part.type);- if (!labels) return null;+ const label = humanizeToolLabel(part.type);const skillName = skillNameFromPart(part);- const runningText = skillName ? `Activating ${skillName}` : labels.running;- const doneText = skillName ? `Skill: ${skillName}` : labels.done;+ const runningText = skillName ? `Activating ${skillName}` : label;+ const doneText = skillName ? `Skill: ${skillName}` : label;const state = "state" in part ? part.state : undefined;const isDone = state === "output-available";// A "running" part in a message that is no longer being generated never@@ -217,8 +203,7 @@ function ToolBadge({/*** One chat message bubble. User turns render as a right-aligned bubble;* assistant turns render each part (reasoning, markdown text, tool badges) in- * document order, flush with the column. `resolveToolLabel` maps tool part- * types to labels.+ * document order, flush with the column.** Every settled message gets a hover copy button. User messages additionally* get undo (rewind the conversation to before this message) and edit (rewind,@@ -227,13 +212,11 @@ function ToolBadge({*/export function ChatMessage({message,- resolveToolLabel,streaming,onUndo,onEdit,}: {message: UIMessage;- resolveToolLabel: ResolveToolLabel;/** True while this message is still being generated: reasoning spinners* stay live and the hover actions (copy) are held back until it settles. */streaming?: boolean;@@ -334,12 +317,7 @@ export function ChatMessage({}if (part.type.startsWith("tool-")) {return (- <ToolBadge- key={index}- part={part}- live={Boolean(streaming)}- resolveToolLabel={resolveToolLabel}- />+ <ToolBadge key={index} part={part} live={Boolean(streaming)} />);}return null;diff --git a/src/client/components/table/AppDataTable.tsx b/src/client/components/table/AppDataTable.tsxindex e88d1e26..501a9460 100644--- a/src/client/components/table/AppDataTable.tsx+++ b/src/client/components/table/AppDataTable.tsx@@ -237,9 +237,7 @@ function HeaderCell<TData>({.join(" ")}style={fixedLayout ? { width: header.getSize() } : undefined}>- {header.isPlaceholder- ? null- : flexRender(header.column.columnDef.header, header.getContext())}+ {flexRender(header.column.columnDef.header, header.getContext())}</th>);}diff --git a/src/client/components/table/ExportToSheetsButton.tsx b/src/client/components/table/ExportToSheetsButton.tsxindex 3e54386f..9f4c71f1 100644--- a/src/client/components/table/ExportToSheetsButton.tsx+++ b/src/client/components/table/ExportToSheetsButton.tsx@@ -12,23 +12,9 @@ type Props = {rows: CsvValue[][];/** PostHog `source_feature` for the `data:export_sheets` event. */feature: string;- disabled?: boolean;- label?: string;- /** Render the icon without a text label (icon-only mode for tight rows). */- iconOnly?: boolean;- /** Extra classes appended to the default button classes. */- className?: string;};-export function ExportToSheetsButton({- headers,- rows,- feature,- disabled,- label = "Export to Sheets",- iconOnly,- className,-}: Props) {+export function ExportToSheetsButton({ headers, rows, feature }: Props) {const [busy, setBusy] = useState(false);const handleClick = async () => {@@ -44,14 +30,13 @@ export function ExportToSheetsButton({return (<buttontype="button"- className={`btn btn-ghost btn-xs gap-1 ${className ?? ""}`}+ className="btn btn-ghost btn-xs gap-1"onClick={handleClick}- disabled={disabled || rows.length === 0 || busy}+ disabled={rows.length === 0 || busy}title="Copy table and open a new Google Sheet"- aria-label={iconOnly ? "Export to Sheets" : undefined}><Sheet className="size-3.5" />- {iconOnly ? null : label}+ Export to Sheets</button>);}diff --git a/src/client/components/table/TableBulkActionBar.tsx b/src/client/components/table/TableBulkActionBar.tsxindex f6e1e10c..6ec47dbe 100644--- a/src/client/components/table/TableBulkActionBar.tsx+++ b/src/client/components/table/TableBulkActionBar.tsx@@ -6,28 +6,21 @@ export function TableBulkActionBar({selectedLabel = "selected",actions,onClear,- placement = "fixed",}: {selectedCount: number;selectedLabel?: string;actions: ReactNode;onClear: () => void;- placement?: "fixed" | "inline";}) {if (selectedCount === 0) return null;- const wrapperClass =- placement === "fixed"- ? "pointer-events-none fixed inset-x-0 bottom-6 z-30 flex justify-center px-4"- : "flex justify-center";- const toolbarClass =- placement === "fixed"- ? "pointer-events-auto flex items-stretch overflow-visible rounded-xl border border-base-content/15 bg-base-300/85 shadow-2xl backdrop-blur"- : "flex items-stretch overflow-visible rounded-xl border border-base-content/15 bg-base-200";-return (- <div className={wrapperClass}>- <div role="toolbar" aria-label="Bulk actions" className={toolbarClass}>+ <div className="pointer-events-none fixed inset-x-0 bottom-6 z-30 flex justify-center px-4">+ <div+ role="toolbar"+ aria-label="Bulk actions"+ className="pointer-events-auto flex items-stretch overflow-visible rounded-xl border border-base-content/15 bg-base-300/85 shadow-2xl backdrop-blur"+ ><div className="flex items-center gap-2 border-r border-base-content/10 px-3 py-2 text-sm"><buttontype="button"diff --git a/src/client/components/table/url.tsx b/src/client/components/table/url.tsxindex 882b9d03..5db636de 100644--- a/src/client/components/table/url.tsx+++ b/src/client/components/table/url.tsx@@ -34,45 +34,25 @@ export function ExternalUrlCell({label,baseDomain,className = "link link-primary inline-flex items-center gap-1",- display = "formatted",- empty = "-",}: {value: string | null | undefined;- label?: string | null;+ label: string;baseDomain?: string;className?: string;- display?: "formatted" | "path" | "raw";- empty?: string;}) {const href = resolveUrlHref(value, baseDomain);if (!value || !href) {- return <span className="text-base-content/40">{empty}</span>;+ return <span className="text-base-content/40">-</span>;}- const visibleLabel = label ?? getUrlDisplayLabel(value, display);return (<a className={className} href={href} target="_blank" rel="noreferrer">- <span className="truncate">{visibleLabel}</span>+ <span className="truncate">{label}</span><ExternalLink className="size-3 shrink-0" /></a>);}-function getUrlDisplayLabel(- value: string,- display: "formatted" | "path" | "raw",-) {- if (display === "raw") return value;- if (display === "path") {- try {- return new URL(value).pathname;- } catch {- return value;- }- }- return formatUrlForDisplay(value);-}-export function getSafeExternalUrl(value: string) {try {const parsed = new URL(value);diff --git a/src/client/features/ai-mcp/AgentSetup.tsx b/src/client/features/ai-mcp/AgentSetup.tsxindex a7c97bbc..cae99e30 100644--- a/src/client/features/ai-mcp/AgentSetup.tsx+++ b/src/client/features/ai-mcp/AgentSetup.tsx@@ -13,11 +13,7 @@ export function AgentSetup({onBack: () => void;disabled?: boolean;}) {- const prompt = getAgentSetupPrompt(- typeof window === "undefined"- ? "https://app.openseo.so"- : window.location.origin,- );+ const prompt = getAgentSetupPrompt(window.location.origin);return (<fieldset disabled={disabled}>@@ -45,7 +41,7 @@ export function AgentSetup({<buttontype="button"className="btn btn-ghost btn-sm gap-2"- onClick={() => onComplete()}+ onClick={onComplete}>Skip for now <ArrowRight className="size-4" /></button>diff --git a/src/client/features/ai-search/PromptExplorerPage.tsx b/src/client/features/ai-search/PromptExplorerPage.tsxindex 6be53456..13368fb4 100644--- a/src/client/features/ai-search/PromptExplorerPage.tsx+++ b/src/client/features/ai-search/PromptExplorerPage.tsx@@ -110,8 +110,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 && urlState.models.length > 0 && !planGate.isFreePlan,+ enabled: hasActivePrompt && !planGate.isFreePlan,staleTime: 5 * 60 * 1000,retry: false,});@@ -170,10 +169,6 @@ function PromptExplorerPageInner({);return;}- if (form.models.length === 0) {- setValidationError("Select at least one model");- return;- }setValidationError(null);onSubmit({...form,diff --git a/src/client/features/ai-search/components/BrandLookupMentionTrendCard.tsx b/src/client/features/ai-search/components/BrandLookupMentionTrendCard.tsxindex 38cd99bf..d15462d5 100644--- a/src/client/features/ai-search/components/BrandLookupMentionTrendCard.tsx+++ b/src/client/features/ai-search/components/BrandLookupMentionTrendCard.tsx@@ -25,14 +25,6 @@ export function BrandLookupMentionTrendCard({ result }: Props) {[result.monthlyVolume],);- if (chartData.length === 0) {- return (- <div className="flex h-56 items-center justify-center text-sm text-base-content/60">- Not enough historical data yet.- </div>- );- }-return (<div className="h-56"><ResponsiveContainer width="100%" height="100%">diff --git a/src/client/features/audit/AuditDetail.tsx b/src/client/features/audit/AuditDetail.tsxnew file mode 100644index 00000000..c6639e36--- /dev/null+++ b/src/client/features/audit/AuditDetail.tsx@@ -0,0 +1,345 @@+import { AlertCircle, Loader2 } from "lucide-react";+import { useQuery } from "@tanstack/react-query";+import { QueryError, QueryState } from "@/client/components/QueryState";+import { PageLoading } from "@/client/components/Spinner";+import {+ getAuditResults,+ getAuditStatus,+ getCrawlProgress,+} from "@/serverFunctions/audit";+import { ResultsView } from "@/client/features/audit/results/ResultsView";+import {+ extractHostname,+ extractPathname,+ formatStartedAt,+ HttpStatusBadge,+ StatusBadge,+ SUPPORT_EMAIL,+} from "@/client/features/audit/shared";++export function AuditDetail({+ projectId,+ auditId,+ tab,+ onBack,+ onTabChange,+}: {+ projectId: string;+ auditId: string;+ tab: string;+ onBack: () => void;+ onTabChange: (tab: "issues" | "pages" | "performance") => void;+}) {+ const statusQuery = useQuery({+ queryKey: ["audit-status", projectId, auditId],+ queryFn: () => getAuditStatus({ data: { projectId, auditId } }),+ refetchInterval: (query) => {+ const data = query.state.data;+ return data?.status === "running" ? 3000 : false;+ },+ });++ const isComplete = statusQuery.data?.status === "completed";+ const isFailed = statusQuery.data?.status === "failed";+ const isRunning = statusQuery.data?.status === "running";++ // Failed audits keep whatever pages were crawled before the failure+ // (persistence is per-batch), so fetch results for them too and show the+ // partial crawl instead of a dead end.+ const resultsQuery = useQuery({+ queryKey: ["audit-results", projectId, auditId],+ queryFn: () => getAuditResults({ data: { projectId, auditId } }),+ enabled: isComplete || isFailed,+ });++ // isPending (not isLoading) also covers a fetch paused while offline, so+ // past these two returns the status is always loaded.+ if (statusQuery.isPending) {+ return <PageLoading />;+ }++ if (statusQuery.isError) {+ return (+ <div className="px-4 py-6 md:px-6">+ <div className="mx-auto max-w-3xl space-y-4">+ <QueryError+ fallback="We could not load this audit. It may have been deleted."+ onRetry={() => void statusQuery.refetch()}+ isRetrying={statusQuery.isFetching}+ />+ <button className="btn btn-ghost btn-sm" onClick={onBack}>+ ← Back to audits+ </button>+ </div>+ </div>+ );+ }++ const status = statusQuery.data;+ const partialPageCount = isFailed+ ? (resultsQuery.data?.pages.length ?? 0)+ : 0;+ const failedWithResults = isFailed && partialPageCount > 0;+ // Wait for the results fetch before choosing between the "partial results"+ // banner and the zero-page support CTA, so the CTA doesn't flash first.+ const showSupportCta =+ (isFailed && resultsQuery.isSuccess && !failedWithResults) ||+ (isComplete && status.pagesCrawled <= 1);++ return (+ <div className="px-4 py-4 md:px-6 md:py-6 pb-24 md:pb-8 overflow-auto">+ <div className="mx-auto max-w-5xl space-y-4">+ <div className="space-y-1">+ <button className="btn btn-ghost btn-sm px-0" onClick={onBack}>+ ← All audits+ </button>+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1">+ <h1 className="text-2xl font-semibold">+ {extractHostname(status.startUrl)}+ </h1>+ {!isRunning && <StatusBadge status={status.status} />}+ </div>+ <p className="text-sm text-base-content/60">+ Site audit · Started {formatStartedAt(status.startedAt)}+ </p>+ </div>++ {isRunning && (+ <ProgressCard+ projectId={projectId}+ auditId={auditId}+ status={status}+ />+ )}++ {showSupportCta && (+ <div+ className={isFailed ? "alert alert-error" : "alert alert-warning"}+ >+ <AlertCircle className="size-5" />+ <div className="space-y-1">+ <p className="font-medium">+ Site audit couldn't fully crawl this website.+ </p>+ <p>+ Sorry! This site's bot protection blocked our crawler. We don't+ have a workaround for this yet. Desktop crawlers run from your+ own machine and usually get past it: try{" "}+ <a+ className="link link-primary"+ href="https://github.com/PhialsBasement/LibreCrawl"+ target="_blank"+ rel="noreferrer"+ >+ LibreCrawl+ </a>{" "}+ (free, open source) or{" "}+ <a+ className="link link-primary"+ href="https://www.screamingfrog.co.uk/seo-spider/"+ target="_blank"+ rel="noreferrer"+ >+ Screaming Frog+ </a>{" "}+ (free up to 500 URLs).+ </p>+ </div>+ </div>+ )}++ {failedWithResults && (+ <div className="alert alert-warning">+ <AlertCircle className="size-5" />+ <div className="space-y-1">+ <p className="font-medium">+ This audit stopped early after {partialPageCount} page+ {partialPageCount === 1 ? "" : "s"}.+ </p>+ <p>+ The results below cover everything crawled before it stopped.+ Run a new audit to try again, or email{" "}+ <a+ className="link link-primary"+ href={`mailto:${SUPPORT_EMAIL}`}+ >+ {SUPPORT_EMAIL}+ </a>{" "}+ if this keeps happening.+ </p>+ </div>+ </div>+ )}++ {(isComplete || isFailed) && (+ <QueryState+ query={resultsQuery}+ errorFallback="Failed to load the audit results"+ >+ {(data) =>+ (isComplete || failedWithResults) && (+ <ResultsView+ projectId={projectId}+ data={data}+ tab={tab}+ onTabChange={onTabChange}+ />+ )+ }+ </QueryState>+ )}+ </div>+ </div>+ );+}++function ProgressCard({+ projectId,+ auditId,+ status,+}: {+ projectId: string;+ auditId: string;+ status: {+ pagesCrawled: number;+ pagesTotal: number;+ lighthouseTotal: number;+ lighthouseCompleted: number;+ lighthouseFailed: number;+ currentPhase: string | null;+ };+}) {+ const crawlProgress =+ status.pagesTotal > 0+ ? Math.round((status.pagesCrawled / status.pagesTotal) * 100)+ : 0;+ const lighthouseDone = status.lighthouseCompleted + status.lighthouseFailed;+ const lighthouseProgress =+ status.lighthouseTotal > 0+ ? Math.round((lighthouseDone / status.lighthouseTotal) * 100)+ : 0;+ const isLighthousePhase = status.currentPhase === "lighthouse";+ const phaseLabel =+ status.currentPhase === "discovery"+ ? "Discovery"+ : status.currentPhase === "crawling"+ ? "Crawling"+ : status.currentPhase === "lighthouse"+ ? "Lighthouse"+ : status.currentPhase === "finalizing"+ ? "Finalizing"+ : "Running";+ const progress = isLighthousePhase ? lighthouseProgress : crawlProgress;++ const crawlProgressQuery = useQuery({+ queryKey: ["audit-crawl-progress", projectId, auditId],+ queryFn: () => getCrawlProgress({ data: { projectId, auditId } }),+ refetchInterval: 1500,+ });++ const crawledUrls = crawlProgressQuery.data ?? [];++ return (+ <div className="space-y-3">+ <div className="card bg-base-100 border border-base-300">+ <div className="card-body gap-3">+ <div className="flex items-center justify-between">+ <h2 className="font-medium flex items-center gap-2">+ <Loader2 className="size-4 animate-spin text-primary" />+ {isLighthousePhase+ ? "Running Lighthouse checks"+ : "Crawling pages"}+ </h2>+ <span className="badge badge-ghost badge-sm">{phaseLabel}</span>+ </div>++ <progress+ className="progress progress-primary w-full"+ value={progress}+ max={100}+ />++ <div className="flex items-center justify-between text-sm">+ {isLighthousePhase ? (+ <span>+ {lighthouseDone} / {status.lighthouseTotal} checks+ {status.lighthouseFailed > 0+ ? ` (${status.lighthouseFailed} failed)`+ : ""}+ </span>+ ) : (+ <span>+ {status.pagesCrawled} / {status.pagesTotal} pages+ </span>+ )}+ <span className="text-base-content/60">{progress}%</span>+ </div>+ </div>+ </div>++ {crawledUrls.length > 0 && (+ <div className="card bg-base-100 border border-base-300">+ <div className="card-body gap-2 p-4">+ <h3 className="text-sm font-medium text-base-content/70">+ Crawled Pages ({crawledUrls.length})+ </h3>+ <p className="text-xs text-base-content/50">+ Updated {new Date(crawledUrls[0].crawledAt).toLocaleTimeString()}+ </p>+ <div className="max-h-[400px] overflow-y-auto -mx-1">+ {crawledUrls.map((entry, i) => (+ <ProgressRow+ key={`${entry.url}-${entry.crawledAt}`}+ entry={entry}+ index={i}+ />+ ))}+ </div>+ </div>+ </div>+ )}+ </div>+ );+}++function ProgressRow({+ entry,+ index,+}: {+ entry: {+ url: string;+ statusCode: number | null;+ title: string | null;+ crawledAt: number;+ };+ index: number;+}) {+ const pathname = extractPathname(entry.url);++ return (+ <div+ className={`flex items-center justify-between gap-3 px-2 py-1.5 rounded text-sm ${+ index === 0+ ? "bg-primary/5 animate-in fade-in slide-in-from-top-1 duration-300"+ : ""+ }`}+ >+ <div className="flex items-center gap-2 min-w-0 flex-1">+ <HttpStatusBadge code={entry.statusCode} />+ <span className="truncate text-base-content/80" title={entry.url}>+ {pathname}+ </span>+ </div>+ <div className="flex items-center gap-3 shrink-0">+ {entry.title && (+ <span+ className="text-xs text-base-content/40 truncate max-w-[260px] hidden md:block"+ title={entry.title}+ >+ {entry.title}+ </span>+ )}+ </div>+ </div>+ );+}diff --git a/src/client/features/audit/results/IssuesView.tsx b/src/client/features/audit/results/IssuesView.tsxindex 1ef9df2c..3d1dd3c7 100644--- a/src/client/features/audit/results/IssuesView.tsx+++ b/src/client/features/audit/results/IssuesView.tsx@@ -229,20 +229,14 @@ function AffectedUrlList({ issues }: { issues: AuditIssueRow[] }) {);}+// AuditRepository is the only writer and always stores JSON.stringify of a+// details object, so the parse cannot throw.function parseDetails(detailsJson: string): Array<[string, unknown]> | null {- try {- const parsed: unknown = JSON.parse(detailsJson);- if (- typeof parsed === "object" &&- parsed !== null &&- !Array.isArray(parsed)- ) {- return Object.entries(parsed);- }- return null;- } catch {- return null;+ const parsed: unknown = JSON.parse(detailsJson);+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {+ return Object.entries(parsed);}+ return null;}function IssueDetails({ detailsJson }: { detailsJson: string | null }) {diff --git a/src/client/features/backlinks/BacklinksFilterPanel.tsx b/src/client/features/backlinks/BacklinksFilterPanel.tsxindex d0dc70f6..eae95a0a 100644--- a/src/client/features/backlinks/BacklinksFilterPanel.tsx+++ b/src/client/features/backlinks/BacklinksFilterPanel.tsx@@ -32,7 +32,6 @@ export function BacklinksFilterPanel({return (<DomainFilterPanelkey="backlinks"- debugName="BacklinksFilterPanel"appliedFilters={state.values}fields={BACKLINKS_FILTER_FIELDS}activeFilterCount={state.activeFilterCount}@@ -88,7 +87,6 @@ export function BacklinksFilterPanel({return (<DomainFilterPanelkey="domains"- debugName="ReferringDomainsFilterPanel"appliedFilters={state.values}fields={REFERRING_DOMAINS_FILTER_FIELDS}activeFilterCount={state.activeFilterCount}@@ -136,7 +134,6 @@ export function BacklinksFilterPanel({return (<DomainFilterPanelkey="pages"- debugName="TopPagesFilterPanel"appliedFilters={state.values}fields={TOP_PAGES_FILTER_FIELDS}activeFilterCount={state.activeFilterCount}diff --git a/src/client/features/backlinks/BacklinksPage.tsx b/src/client/features/backlinks/BacklinksPage.tsxindex b6177fb4..33e0cef3 100644--- a/src/client/features/backlinks/BacklinksPage.tsx+++ b/src/client/features/backlinks/BacklinksPage.tsx@@ -3,7 +3,6 @@ import type { SortingState, Updater } from "@tanstack/react-table";import { BacklinksSearchCard } from "./BacklinksSearchCard";import { BacklinksBody } from "./BacklinksPageContent";import type { BacklinksPageProps } from "./backlinksPageTypes";-import type { BacklinksSearchState } from "./backlinksPageTypes";import {navigateToBacklinksSearch,useBacklinksPageData,@@ -11,10 +10,7 @@ import {import { useBacklinksDomainExpansion } from "./useBacklinksDomainExpansion";import { useBacklinksFilters } from "./useBacklinksFilters";import { useBacklinksSearchHistory } from "@/client/hooks/useBacklinksSearchHistory";-import type {- BacklinksSearchTabInput,- SearchTabInput,-} from "@/client/features/search-tabs/types";+import type { SearchTabInput } from "@/client/features/search-tabs/types";import { useSearchTabNavigation } from "@/client/features/search-tabs/useSearchTabNavigation";import {BACKLINKS_DEFAULT_SORT,@@ -38,82 +34,32 @@ export function BacklinksPage({return [{ id: field, desc: order === "desc" }];}, [searchState.order, searchState.sort, searchState.tab]);- const handleSortingChange = useCallback(- (updater: Updater<SortingState>) => {- const next = typeof updater === "function" ? updater(sorting) : updater;- const first = next[0];- navigate({- search: (prev) => ({- ...prev,- sort: first?.id,- order: first ? (first.desc ? "desc" : "asc") : undefined,- page: undefined,- }),- replace: true,- });- },- [navigate, sorting],- );-- const handlePageChange = useCallback(- (nextPage: number) => {- navigate({- search: (prev) => ({- ...prev,- page: nextPage === 1 ? undefined : nextPage,- }),- replace: true,- });+ const updateSearch = useCallback(+ (updates: Record<string, unknown>) => {+ navigate({ search: (prev) => ({ ...prev, ...updates }), replace: true });},[navigate],);- const handlePageSizeChange = useCallback(- (nextPageSize: number) => {- navigate({- search: (prev) => ({- ...prev,- size:- nextPageSize === DEFAULT_BACKLINKS_PAGE_SIZE- ? undefined- : nextPageSize,- page: undefined,- }),- replace: true,+ const handleSortingChange = useCallback(+ (updater: Updater<SortingState>) => {+ const next = typeof updater === "function" ? updater(sorting) : updater;+ const first = next[0];+ updateSearch({+ sort: first?.id,+ order: first ? (first.desc ? "desc" : "asc") : undefined,+ page: undefined,});},- [navigate],+ [sorting, updateSearch],);- const handleViewChange = useCallback(- (nextView: "all" | undefined) => {- navigate({- search: (prev) => ({ ...prev, view: nextView, page: undefined }),- replace: true,- });- },- [navigate],- );-- const {- activeTabErrorMessage,- activeTabQuery,- overviewErrorMessage,- overviewQuery,- referringDomainsQuery,- rowsQuery,- searchCardInitialValues,- topPagesQuery,- } = useBacklinksPageData({- projectId,- searchState,- filters,- });+ const data = useBacklinksPageData({ projectId, searchState, filters });const domainExpansion = useBacklinksDomainExpansion({projectId,searchState,- rows: activeTabErrorMessage ? [] : (rowsQuery.data?.rows ?? []),+ rows: data.activeTabErrorMessage ? [] : (data.rowsQuery.data?.rows ?? []),});const {@@ -146,21 +92,6 @@ export function BacklinksPage({},[navigate],);- const handleResultTabChange = useCallback(- (tab: BacklinksSearchState["tab"]) => {- navigate({- search: (prev) => ({- ...prev,- tab: tab === "backlinks" ? undefined : tab,- page: undefined,- sort: undefined,- order: undefined,- }),- replace: true,- });- },- [navigate],- );const searchTabs = useSearchTabNavigation({storageKey: `backlinks:${projectId}`,urlInput: urlTabInput,@@ -170,16 +101,6 @@ export function BacklinksPage({),navigateToInput: navigateToTab,});- const toBacklinksTabInput = useCallback(- (- values: Pick<BacklinksSearchState, "target" | "scope">,- ): BacklinksSearchTabInput => ({- type: "backlinks",- target: values.target,- scope: values.scope,- }),- [],- );return (<div className="px-4 py-4 pb-24 overflow-auto md:px-6 md:py-6 md:pb-8"><div className="mx-auto max-w-7xl space-y-4">@@ -192,10 +113,10 @@ export function BacklinksPage({</div><BacklinksSearchCard- errorMessage={overviewErrorMessage}- initialValues={searchCardInitialValues}+ errorMessage={data.overviewErrorMessage}+ initialValues={data.searchCardInitialValues}onSubmit={(values) => {- searchTabs.openTab(toBacklinksTabInput(values));+ searchTabs.openTab({ type: "backlinks", ...values });navigateToBacklinksSearch(navigate, values);addSearch({ target: values.target, scope: values.scope });}}@@ -205,46 +126,40 @@ export function BacklinksPage({projectId={projectId}history={history}historyLoaded={historyLoaded}- overviewData={overviewQuery.data}- overviewError={overviewErrorMessage}- overviewLoading={overviewQuery.isLoading}- backlinksRowsPage={rowsQuery.data}- referringDomainsPage={referringDomainsQuery.data}- topPagesPage={topPagesQuery.data}+ data={data}searchState={searchState}filters={filters}sorting={sorting}domainExpansion={domainExpansion}- tabErrorMessage={activeTabErrorMessage}- tabLoading={activeTabQuery.isLoading}- tabFetching={activeTabQuery.isFetching}- onPageChange={handlePageChange}- onPageSizeChange={handlePageSizeChange}+ searchTabs={searchTabs}+ onPageChange={(nextPage) =>+ updateSearch({ page: nextPage === 1 ? undefined : nextPage })+ }+ onPageSizeChange={(nextPageSize) =>+ updateSearch({+ size:+ nextPageSize === DEFAULT_BACKLINKS_PAGE_SIZE+ ? undefined+ : nextPageSize,+ page: undefined,+ })+ }onRemoveHistoryItem={removeHistoryItem}- onRetryOverview={() => void overviewQuery.refetch()}onSortingChange={handleSortingChange}- onTabChange={handleResultTabChange}- onViewChange={handleViewChange}- onHideSpamChange={(hideSpam) =>- navigate({- search: (prev) => ({- ...prev,- includeSpam: hideSpam ? undefined : true,- page: undefined,- }),- replace: true,+ onTabChange={(tab) =>+ updateSearch({+ tab: tab === "backlinks" ? undefined : tab,+ page: undefined,+ sort: undefined,+ order: undefined,})}- searchTabs={- searchState.target- ? {- activeTabId: searchTabs.activeTabId,- tabs: searchTabs.tabs,- onSelect: searchTabs.selectTab,- onClose: searchTabs.closeTab,- onViewed: searchTabs.markTabViewed,- }- : null+ onViewChange={(view) => updateSearch({ view, page: undefined })}+ onHideSpamChange={(hideSpam) =>+ updateSearch({+ includeSpam: hideSpam ? undefined : true,+ page: undefined,+ })}/></div>diff --git a/src/client/features/backlinks/BacklinksPageContent.tsx b/src/client/features/backlinks/BacklinksPageContent.tsxindex cd4089c0..50845b48 100644--- a/src/client/features/backlinks/BacklinksPageContent.tsx+++ b/src/client/features/backlinks/BacklinksPageContent.tsx@@ -9,82 +9,57 @@ import {import { BacklinksHistorySection } from "./BacklinksHistorySection";import type { BacklinksSearchHistoryItem } from "@/client/hooks/useBacklinksSearchHistory";import type {- BacklinksOverviewData,- BacklinksReferringDomainsData,- BacklinksRowsPageData,BacklinksSearchState,BacklinksTabRows,- BacklinksTopPagesData,} from "./backlinksPageTypes";import { buildSummaryStats } from "./backlinksPageUtils";import type { BacklinksDomainExpansion } from "./useBacklinksDomainExpansion";import type { BacklinksFiltersState } from "./useBacklinksFilters";-import {- SearchTabStrip,- type SearchTab,-} from "@/client/features/search-tabs/SearchTabStrip";+import type { BacklinksPageData } from "./useBacklinksPageData";+import { SearchTabStrip } from "@/client/features/search-tabs/SearchTabStrip";+import type { useSearchTabNavigation } from "@/client/features/search-tabs/useSearchTabNavigation";type BacklinksBodyProps = {projectId: string;history: BacklinksSearchHistoryItem[];historyLoaded: boolean;- overviewData: BacklinksOverviewData | undefined;- overviewError: string | null;- overviewLoading: boolean;- backlinksRowsPage: BacklinksRowsPageData | undefined;- referringDomainsPage: BacklinksReferringDomainsData | undefined;- topPagesPage: BacklinksTopPagesData | undefined;+ data: BacklinksPageData;searchState: BacklinksSearchState;filters: BacklinksFiltersState;sorting: SortingState;domainExpansion: BacklinksDomainExpansion;- tabErrorMessage: string | null;- tabLoading: boolean;- tabFetching: boolean;+ searchTabs: ReturnType<typeof useSearchTabNavigation>;onPageChange: (nextPage: number) => void;onPageSizeChange: (nextPageSize: number) => void;onRemoveHistoryItem: (timestamp: number) => void;- onRetryOverview: () => void;onSortingChange: OnChangeFn<SortingState>;onTabChange: (tab: BacklinksSearchState["tab"]) => void;onViewChange: (view: "all" | undefined) => void;onHideSpamChange: (hideSpam: boolean) => void;- searchTabs: {- activeTabId: string | null;- tabs: SearchTab[];- onSelect: (tab: SearchTab) => void;- onClose: (tabId: string) => void;- onViewed: (tabId: string, when?: number) => void;- } | null;};export function BacklinksBody({projectId,history,historyLoaded,- overviewData,- overviewError,- overviewLoading,- backlinksRowsPage,- referringDomainsPage,- topPagesPage,+ data,searchState,filters,sorting,domainExpansion,- tabErrorMessage,- tabLoading,- tabFetching,+ searchTabs,onPageChange,onPageSizeChange,onRemoveHistoryItem,- onRetryOverview,onSortingChange,onTabChange,onViewChange,onHideSpamChange,- searchTabs,}: BacklinksBodyProps) {+ const overviewData = data.overviewQuery.data;+ const backlinksRowsPage = data.rowsQuery.data;+ const referringDomainsPage = data.referringDomainsQuery.data;+ const topPagesPage = data.topPagesQuery.data;const tabRows = useMemo<BacklinksTabRows>(() => ({backlinks: backlinksRowsPage?.rows ?? [],@@ -93,26 +68,21 @@ export function BacklinksBody({}),[backlinksRowsPage, referringDomainsPage, topPagesPage],);- const activeTabPage =- searchState.tab === "backlinks"- ? backlinksRowsPage- : searchState.tab === "domains"- ? referringDomainsPage- : topPagesPage;+ const activeTabPage = data.activeTabQuery.data;const summaryStats = useMemo(() => buildSummaryStats(overviewData),[overviewData],);- const tabStrip = searchTabs ? (+ const tabStrip = (<SearchTabStripprojectId={projectId}activeTabId={searchTabs.activeTabId}tabs={searchTabs.tabs}- onSelect={searchTabs.onSelect}- onClose={searchTabs.onClose}- onViewed={searchTabs.onViewed}+ onSelect={searchTabs.selectTab}+ onClose={searchTabs.closeTab}+ onViewed={searchTabs.markTabViewed}/>- ) : null;+ );if (!searchState.target) {return (@@ -125,7 +95,7 @@ export function BacklinksBody({);}- if (overviewLoading) {+ if (data.overviewQuery.isLoading) {return (<>{tabStrip}@@ -139,8 +109,8 @@ export function BacklinksBody({<>{tabStrip}<BacklinksErrorState- errorMessage={overviewError}- onRetry={onRetryOverview}+ errorMessage={data.overviewErrorMessage}+ onRetry={() => void data.overviewQuery.refetch()}/></>);@@ -168,15 +138,15 @@ export function BacklinksBody({hideSpam={!searchState.includeSpam}onHideSpamChange={onHideSpamChange}domainExpansion={domainExpansion}- isTabLoading={tabLoading}- tabErrorMessage={tabErrorMessage}+ isTabLoading={data.activeTabQuery.isLoading}+ tabErrorMessage={data.activeTabErrorMessage}exportTarget={overviewData.displayTarget || searchState.target}pagination={{page: searchState.page,pageSize: searchState.pageSize,totalCount: activeTabPage?.totalCount ?? null,hasNextPage: activeTabPage?.hasMore ?? false,- isFetching: tabFetching,+ isFetching: data.activeTabQuery.isFetching,}}onPageChange={onPageChange}onPageSizeChange={onPageSizeChange}diff --git a/src/client/features/backlinks/BacklinksPageEmptyTableState.tsx b/src/client/features/backlinks/BacklinksPageEmptyTableState.tsxdeleted file mode 100644index fc194c3e..00000000--- a/src/client/features/backlinks/BacklinksPageEmptyTableState.tsx+++ /dev/null@@ -1,7 +0,0 @@-export function EmptyTableState({ label }: { label: string }) {- return (- <div className="rounded-xl border border-dashed border-base-300 p-10 text-center text-sm text-base-content/55">- {label}- </div>- );-}diff --git a/src/client/features/backlinks/BacklinksPageLinks.tsx b/src/client/features/backlinks/BacklinksPageLinks.tsxdeleted file mode 100644index 575c6eb7..00000000--- a/src/client/features/backlinks/BacklinksPageLinks.tsx+++ /dev/null@@ -1,20 +0,0 @@-import { SafeExternalLink } from "@/client/components/SafeExternalLink";-import { extractUrlPath, truncateMiddle } from "./backlinksPageUtils";--export function BacklinksSourceLink({- url,- maxLength,- muted = false,-}: {- url: string;- maxLength: number;- muted?: boolean;-}) {- return (- <SafeExternalLink- url={url}- label={truncateMiddle(extractUrlPath(url), maxLength)}- className={`link link-hover break-all inline-flex items-center gap-1 ${muted ? "text-xs text-base-content/55" : "text-sm"}`}- />- );-}diff --git a/src/client/features/backlinks/BacklinksPageStates.tsx b/src/client/features/backlinks/BacklinksPageStates.tsxindex b890485e..6c4c01be 100644--- a/src/client/features/backlinks/BacklinksPageStates.tsx+++ b/src/client/features/backlinks/BacklinksPageStates.tsx@@ -60,3 +60,11 @@ export function BacklinksErrorState({</section>);}++export function EmptyTableState({ label }: { label: string }) {+ return (+ <div className="rounded-xl border border-dashed border-base-300 p-10 text-center text-sm text-base-content/55">+ {label}+ </div>+ );+}diff --git a/src/client/features/backlinks/BacklinksSearchCard.tsx b/src/client/features/backlinks/BacklinksSearchCard.tsxindex 815a7da2..3c5f7561 100644--- a/src/client/features/backlinks/BacklinksSearchCard.tsx+++ b/src/client/features/backlinks/BacklinksSearchCard.tsx@@ -4,7 +4,6 @@ import { Search } from "lucide-react";import {createFormValidationErrors,getFieldError,- getFormError,shouldValidateFieldOnChange,} from "@/client/lib/forms";import { ResearchScopeSelect } from "@/client/components/ResearchScopeSelect";@@ -127,17 +126,9 @@ export function BacklinksSearchCard({)}</form.Field>- <form.Subscribe selector={(state) => state.isSubmitting}>- {(isSubmitting) => (- <button- type="submit"- className="btn btn-primary shrink-0 px-6"- disabled={isSubmitting}- >- {isSubmitting ? "Loading..." : "Search"}- </button>- )}- </form.Subscribe>+ <button type="submit" className="btn btn-primary shrink-0 px-6">+ Search+ </button></div><form.Field name="target">@@ -149,16 +140,6 @@ export function BacklinksSearchCard({) : null;}}</form.Field>-- <form.Subscribe selector={(state) => state.errorMap.onSubmit}>- {(submitError) => {- const formError = getFormError(submitError);-- return formError ? (- <p className="text-sm text-error">{formError}</p>- ) : null;- }}- </form.Subscribe></div></form>diff --git a/src/client/features/backlinks/BacklinksTable.tsx b/src/client/features/backlinks/BacklinksTable.tsxindex 43663e6c..d0d78a5b 100644--- a/src/client/features/backlinks/BacklinksTable.tsx+++ b/src/client/features/backlinks/BacklinksTable.tsx@@ -4,7 +4,7 @@ import {AppDataTable,useAppTable,} from "@/client/components/table/AppDataTable";-import { EmptyTableState } from "./BacklinksPageEmptyTableState";+import { EmptyTableState } from "./BacklinksPageStates";import {buildBacklinksColumns,type BacklinksDisplayRow,diff --git a/src/client/features/backlinks/BacklinksTableColumns.tsx b/src/client/features/backlinks/BacklinksTableColumns.tsxindex c276ddc0..98d61bd4 100644--- a/src/client/features/backlinks/BacklinksTableColumns.tsx+++ b/src/client/features/backlinks/BacklinksTableColumns.tsx@@ -2,13 +2,15 @@ import type { ColumnDef } from "@tanstack/react-table";import { ChevronRight } from "lucide-react";import { SortableHeader } from "@/client/components/table/SortableHeader";import { HeaderHelpLabel } from "@/client/features/keywords/components";-import { BacklinksSourceLink } from "./BacklinksPageLinks";+import { SafeExternalLink } from "@/client/components/SafeExternalLink";import type { BacklinksRow } from "./backlinksPageTypes";import type { BacklinksRowsSortField } from "@/types/schemas/backlinks";import {+ extractUrlPath,formatCompactDate,formatDecimal,formatNumber,+ truncateMiddle,} from "./backlinksPageUtils";import type { DomainRatings } from "./useAhrefsDomainRatings";@@ -27,6 +29,24 @@ export type BacklinksDisplayRow =}| { kind: "status"; domain: string; status: "loading" | "error" | "empty" };+function BacklinksSourceLink({+ url,+ maxLength,+ muted = false,+}: {+ url: string;+ maxLength: number;+ muted?: boolean;+}) {+ return (+ <SafeExternalLink+ url={url}+ label={truncateMiddle(extractUrlPath(url), maxLength)}+ className={`link link-hover break-all inline-flex items-center gap-1 ${muted ? "text-xs text-base-content/55" : "text-sm"}`}+ />+ );+}+function BacklinkFlags({ row }: { row: BacklinksRow }) {return (<div className="flex flex-wrap gap-1">diff --git a/src/client/features/backlinks/ReferringDomainsTable.tsx b/src/client/features/backlinks/ReferringDomainsTable.tsxindex a7a8df53..fb224971 100644--- a/src/client/features/backlinks/ReferringDomainsTable.tsx+++ b/src/client/features/backlinks/ReferringDomainsTable.tsx@@ -8,7 +8,7 @@ import {} from "@/client/components/table/AppDataTable";import { SortableHeader } from "@/client/components/table/SortableHeader";import { HeaderHelpLabel } from "@/client/features/keywords/components";-import { EmptyTableState } from "./BacklinksPageEmptyTableState";+import { EmptyTableState } from "./BacklinksPageStates";import type { ReferringDomainRow } from "./backlinksPageTypes";import type { ReferringDomainsSortField } from "@/types/schemas/backlinks";import {diff --git a/src/client/features/backlinks/TopPagesTable.tsx b/src/client/features/backlinks/TopPagesTable.tsxindex 56fd2681..bfb039ed 100644--- a/src/client/features/backlinks/TopPagesTable.tsx+++ b/src/client/features/backlinks/TopPagesTable.tsx@@ -7,7 +7,7 @@ import {} from "@/client/components/table/AppDataTable";import { SortableHeader } from "@/client/components/table/SortableHeader";import { HeaderHelpLabel } from "@/client/features/keywords/components";-import { EmptyTableState } from "./BacklinksPageEmptyTableState";+import { EmptyTableState } from "./BacklinksPageStates";import type { TopPageRow } from "./backlinksPageTypes";import type { TopPagesSortField } from "@/types/schemas/backlinks";import { formatNumber } from "./backlinksPageUtils";diff --git a/src/client/features/backlinks/useBacklinksPageData.ts b/src/client/features/backlinks/useBacklinksPageData.tsindex a56a3e3b..3dfaeeee 100644--- a/src/client/features/backlinks/useBacklinksPageData.ts+++ b/src/client/features/backlinks/useBacklinksPageData.ts@@ -230,6 +230,8 @@ export function useBacklinksPageData({};}+export type BacklinksPageData = ReturnType<typeof useBacklinksPageData>;+export function navigateToBacklinksSearch(navigate: BacklinksPageProps["navigate"],values: Pick<BacklinksSearchState, "target" | "scope">,diff --git a/src/client/features/dashboard/DashboardCards.tsx b/src/client/features/dashboard/DashboardCards.tsxindex ee314e18..4bb78c4e 100644--- a/src/client/features/dashboard/DashboardCards.tsx+++ b/src/client/features/dashboard/DashboardCards.tsx@@ -46,10 +46,11 @@ export function GscCard({}),enabled: connected,});+ const report = reportQuery.data;// Not connected (or a dead grant discovered by the report call): the// connection card sells and runs the whole flow itself.- if (!connected || (reportQuery.data && !reportQuery.data.connected)) {+ if (!connected || (report && !report.connected)) {return (<div id="connect-gsc"><SearchConsoleConnectionCard projectId={projectId} />@@ -57,8 +58,6 @@ export function GscCard({);}- const report = reportQuery.data;-return (<CardShelltitle="Search performance"@@ -73,17 +72,17 @@ export function GscCard({</Link>}>- {reportQuery.isPending ? (+ {reportQuery.isError ? (+ <p className="text-sm text-base-content/60">+ Couldn’t load Search Console data. Try again shortly.+ </p>+ ) : !report ? (<div className="grid grid-cols-2 gap-3" aria-busy>{Array.from({ length: 4 }, (_, i) => (<Skeleton key={i} className="h-20" />))}</div>- ) : reportQuery.isError ? (- <p className="text-sm text-base-content/60">- Couldn’t load Search Console data. Try again shortly.- </p>- ) : report?.connected ? (+ ) : (<div className="grid grid-cols-2 gap-3"><Statlabel="Clicks"@@ -111,7 +110,7 @@ export function GscCard({value={formatPosition(report.totals.position)}/></div>- ) : null}+ )}</CardShell>);}diff --git a/src/client/features/dashboard/Ga4Card.tsx b/src/client/features/dashboard/Ga4Card.tsxindex 86abb8b5..7cb971cf 100644--- a/src/client/features/dashboard/Ga4Card.tsx+++ b/src/client/features/dashboard/Ga4Card.tsx@@ -79,15 +79,16 @@ export function Ga4Card({queryFn: () => getGa4DashboardReport({ data: { projectId } }),enabled: connected,});+ const report = reportQuery.data;// Not connected (or a dead grant discovered by the report call): the// connection card sells and runs the whole flow itself.- if (!connected || (reportQuery.data && !reportQuery.data.connected)) {+ if (!connected || (report && !report.connected)) {return <Ga4ConnectCard projectId={projectId} connected={connected} />;}- const report = reportQuery.data;-+ // The empty state covers null sessions (no report row) and 0: a zero-session+ // period would otherwise render an all-zero flatline chart in an empty box.return (<CardShelltitle="Organic traffic"@@ -103,7 +104,11 @@ export function Ga4Card({</Link>}>- {reportQuery.isPending ? (+ {reportQuery.isError ? (+ <p className="text-sm text-base-content/60">+ Couldn’t load Google Analytics data. Try again shortly.+ </p>+ ) : !report ? (<div className="space-y-3" aria-busy><div className="grid grid-cols-2 gap-3">{Array.from({ length: 4 }, (_, i) => (@@ -112,75 +117,67 @@ export function Ga4Card({</div><Skeleton className="h-24" /></div>- ) : reportQuery.isError ? (+ ) : !report.totals.sessions ? (<p className="text-sm text-base-content/60">- Couldn’t load Google Analytics data. Try again shortly.+ No organic search traffic recorded in the last 28 days yet.</p>- ) : report?.connected ? (- // Covers null (no report row) and 0: a zero-session period would- // otherwise render an all-zero flatline chart in an empty box.- !report.totals.sessions ? (- <p className="text-sm text-base-content/60">- No organic search traffic recorded in the last 28 days yet.- </p>- ) : (- <div className="space-y-4">- <div className="grid grid-cols-2 gap-3">- <Stat- label="Sessions"- value={statValue(report.totals.sessions, formatCount)}- sub={statDelta(- report.totals.sessions,- report.prevTotals.sessions,- )}- />- <Stat- label="Active users"- value={statValue(report.totals.activeUsers, formatCount)}- sub={statDelta(- report.totals.activeUsers,- report.prevTotals.activeUsers,- )}- />- <Stat- label="Engagement rate"- value={statValue(report.totals.engagementRate, formatCtr)}- />- <Stat- label="Key events"- value={statValue(report.totals.keyEvents, formatCount)}- sub={statDelta(- report.totals.keyEvents,- report.prevTotals.keyEvents,- )}- />- </div>- <div className="h-24">- <ResponsiveContainer width="100%" height="100%">- <AreaChart- data={report.trend}- margin={{ top: 4, right: 0, bottom: 0, left: 0 }}- >- <XAxis dataKey="date" hide />- <YAxis hide domain={[0, "auto"]} />- <Tooltip- content={<SessionsTooltip />}- cursor={{ stroke: "currentColor", strokeOpacity: 0.2 }}- />- <Area- type="monotone"- dataKey="sessions"- stroke="var(--color-primary)"- strokeWidth={2}- fill="var(--color-primary)"- fillOpacity={0.08}- />- </AreaChart>- </ResponsiveContainer>- </div>+ ) : (+ <div className="space-y-4">+ <div className="grid grid-cols-2 gap-3">+ <Stat+ label="Sessions"+ value={statValue(report.totals.sessions, formatCount)}+ sub={statDelta(+ report.totals.sessions,+ report.prevTotals.sessions,+ )}+ />+ <Stat+ label="Active users"+ value={statValue(report.totals.activeUsers, formatCount)}+ sub={statDelta(+ report.totals.activeUsers,+ report.prevTotals.activeUsers,+ )}+ />+ <Stat+ label="Engagement rate"+ value={statValue(report.totals.engagementRate, formatCtr)}+ />+ <Stat+ label="Key events"+ value={statValue(report.totals.keyEvents, formatCount)}+ sub={statDelta(+ report.totals.keyEvents,+ report.prevTotals.keyEvents,+ )}+ /></div>- )- ) : null}+ <div className="h-24">+ <ResponsiveContainer width="100%" height="100%">+ <AreaChart+ data={report.trend}+ margin={{ top: 4, right: 0, bottom: 0, left: 0 }}+ >+ <XAxis dataKey="date" hide />+ <YAxis hide domain={[0, "auto"]} />+ <Tooltip+ content={<SessionsTooltip />}+ cursor={{ stroke: "currentColor", strokeOpacity: 0.2 }}+ />+ <Area+ type="monotone"+ dataKey="sessions"+ stroke="var(--color-primary)"+ strokeWidth={2}+ fill="var(--color-primary)"+ fillOpacity={0.08}+ />+ </AreaChart>+ </ResponsiveContainer>+ </div>+ </div>+ )}</CardShell>);}diff --git a/src/client/features/domain/DomainOverviewPage.tsx b/src/client/features/domain/DomainOverviewPage.tsxindex 2998fae3..78a2bf0a 100644--- a/src/client/features/domain/DomainOverviewPage.tsx+++ b/src/client/features/domain/DomainOverviewPage.tsx@@ -404,17 +404,15 @@ function useDomainOverviewState({lastTrackedKey.current = "";}, [routeState.domain]);+ // Changing location updates the form before the route navigation commits,+ // so block saves until the rendered results match the selected market.const controlsLocationCode = useStore(controlsForm.store,(s) => s.values.locationCode,);- const canSaveKeywords = useMemo(- () =>- controlsLocationCode === routeState.locationCode &&- overview !== null &&- overview.hasData,- [controlsLocationCode, overview, routeState.locationCode],- );+ const canSaveKeywords =+ controlsLocationCode === routeState.locationCode &&+ overview?.hasData === true;const handleSearchSubmit = useCallback((event: FormEvent) => {diff --git a/src/client/features/domain/components/DomainFilterPanel.tsx b/src/client/features/domain/components/DomainFilterPanel.tsxindex 32470972..00516728 100644--- a/src/client/features/domain/components/DomainFilterPanel.tsx+++ b/src/client/features/domain/components/DomainFilterPanel.tsx@@ -11,10 +11,6 @@ import {FilterRangeGroup,FilterTextInput,} from "@/client/features/domain/components/DomainFilterFields";-import {- debugDomain,- useDomainRenderDebug,-} from "@/client/features/domain/domainDebug";import { MAX_DATAFORSEO_FILTER_CONDITIONS } from "@/types/schemas/domain";type FilterValues = Record<string, string>;@@ -33,7 +29,6 @@ type FilterRangeField<TValues extends FilterValues> = {};type Props<TValues extends FilterValues> = {- debugName: string;activeFilterCount: number;appliedFilters: TValues;fields: ReadonlyArray<keyof TValues>;@@ -52,7 +47,6 @@ type Props<TValues extends FilterValues> = {};export function DomainFilterPanel<TValues extends FilterValues>({- debugName,activeFilterCount,appliedFilters,fields,@@ -86,33 +80,14 @@ export function DomainFilterPanel<TValues extends FilterValues>({}),[appliedFilters, countConditions, draftFilters, fields, maxConditions],);- useDomainRenderDebug(debugName, {- activeFilterCount,- conditionCount: meta.conditionCount,- dirtyCount: meta.dirtyCount,- });const applyFilters = useCallback(() => {if (meta.overLimit) return;- debugDomain(`${debugName}:apply`, {- conditionCount: meta.conditionCount,- dirtyCount: meta.dirtyCount,- draftFilters,- });onApply(draftFilters);- }, [- debugName,- draftFilters,- meta.conditionCount,- meta.dirtyCount,- meta.overLimit,- onApply,- ]);+ }, [draftFilters, meta.overLimit, onApply]);const cancelFilterEdits = useCallback(() => {- debugDomain(`${debugName}:cancel`);setDraftFilters(appliedFilters);- }, [appliedFilters, debugName]);+ }, [appliedFilters]);const resetFilters = useCallback(() => {- debugDomain(`${debugName}:clear`);// Also clear unapplied draft edits — when the applied filters are already// empty, the applied-sync effect won't fire (appliedKey is unchanged).setDraftFilters((current) => {@@ -121,7 +96,7 @@ export function DomainFilterPanel<TValues extends FilterValues>({return next;});onClear();- }, [debugName, fields, onClear]);+ }, [fields, onClear]);const handleKeyDown = (event: React.KeyboardEvent) => {if (event.key !== "Enter") return;// Let buttons (Cancel, toggles) handle their own Enter activation.@@ -130,16 +105,9 @@ export function DomainFilterPanel<TValues extends FilterValues>({event.preventDefault();applyFilters();};- const handleValueChange = useCallback(- (key: keyof TValues, value: string) => {- debugDomain(`${debugName}:draft-change`, {- field: String(key),- valueLength: value.length,- });- setDraftFilters((current) => ({ ...current, [key]: value }));- },- [debugName],- );+ const handleValueChange = useCallback((key: keyof TValues, value: string) => {+ setDraftFilters((current) => ({ ...current, [key]: value }));+ }, []);return (<divdiff --git a/src/client/features/domain/components/DomainKeywordsTable.tsx b/src/client/features/domain/components/DomainKeywordsTable.tsxindex 0b8a583e..ec80dbc9 100644--- a/src/client/features/domain/components/DomainKeywordsTable.tsx+++ b/src/client/features/domain/components/DomainKeywordsTable.tsx@@ -13,7 +13,6 @@ import {import { ExternalUrlCell } from "@/client/components/table/url";import { DifficultyBadge } from "@/client/features/domain/components/DifficultyBadge";import { SortableHeader } from "@/client/features/domain/components/SortableHeader";-import { useDomainRenderDebug } from "@/client/features/domain/domainDebug";import { formatNumber, formatRounded } from "@/client/features/domain/utils";import type {DomainSortMode,@@ -44,7 +43,6 @@ function DomainKeywordsTableComponent({onSortClick,onToggleKeyword,}: Props) {- const renderStarted = performance.now();const selectAnchorRef = useSelectionAnchor();const rowSelection = useMemo<RowSelectionState>(() =>@@ -159,14 +157,6 @@ function DomainKeywordsTableComponent({getRowId: (row) => row.keyword,enableRowSelection: true,});- useDomainRenderDebug("DomainKeywordsTable", {- rows: rows.length,- selectedCount: selectedKeywords.size,- durationMs: Math.round(performance.now() - renderStarted),- sortMode,- currentSortOrder,- });-return (<div className="overflow-x-auto"><div className="mb-2 text-xs text-base-content/60">diff --git a/src/client/features/domain/components/DomainPagesTable.tsx b/src/client/features/domain/components/DomainPagesTable.tsxindex 229abd95..d0f00a12 100644--- a/src/client/features/domain/components/DomainPagesTable.tsx+++ b/src/client/features/domain/components/DomainPagesTable.tsx@@ -6,7 +6,6 @@ import {} from "@/client/components/table/AppDataTable";import { ExternalUrlCell } from "@/client/components/table/url";import { SortableHeader } from "@/client/features/domain/components/SortableHeader";-import { useDomainRenderDebug } from "@/client/features/domain/domainDebug";import {formatNumber,formatRounded,@@ -35,7 +34,6 @@ function DomainPagesTableComponent({currentSortOrder,onSortClick,}: Props) {- const renderStarted = performance.now();const columns = useMemo<ColumnDef<PageRow>[]>(() => [pageColumnHelper.display({@@ -86,13 +84,6 @@ function DomainPagesTableComponent({data: tableData,columns,});- useDomainRenderDebug("DomainPagesTable", {- rows: rows.length,- durationMs: Math.round(performance.now() - renderStarted),- sortMode,- currentSortOrder,- });-return (<AppDataTabletable={table}diff --git a/src/client/features/domain/components/DomainSearchCard.tsx b/src/client/features/domain/components/DomainSearchCard.tsxindex ee9394fb..c2b50f72 100644--- a/src/client/features/domain/components/DomainSearchCard.tsx+++ b/src/client/features/domain/components/DomainSearchCard.tsx@@ -109,17 +109,13 @@ export function DomainSearchCard({)}</controlsForm.Field>- <controlsForm.Subscribe selector={(state) => state.isSubmitting}>- {(isSubmitting) => (- <button- type="submit"- className="btn btn-primary shrink-0 px-6"- disabled={isLoading || isSubmitting}- >- {isLoading || isSubmitting ? "Loading..." : "Search"}- </button>- )}- </controlsForm.Subscribe>+ <button+ type="submit"+ className="btn btn-primary shrink-0 px-6"+ disabled={isLoading}+ >+ {isLoading ? "Loading..." : "Search"}+ </button></form><controlsForm.Field name="domain">diff --git a/src/client/features/domain/components/KeywordsTab.tsx b/src/client/features/domain/components/KeywordsTab.tsxindex 8278c0be..7349f233 100644--- a/src/client/features/domain/components/KeywordsTab.tsx+++ b/src/client/features/domain/components/KeywordsTab.tsx@@ -17,10 +17,6 @@ import {buildKeywordsSearchUpdate,countKeywordFilterConditions,} from "@/client/features/domain/domainFilterUtils";-import {- debugDomain,- useDomainRenderDebug,-} from "@/client/features/domain/domainDebug";import { useDomainKeywordsQuery } from "@/client/features/domain/hooks/useDomainKeywordsQuery";import { useSaveKeywordsMutation } from "@/client/features/domain/mutations";import { useDomainKeywordFilterPreferences } from "@/client/features/domain/useDomainFilterPreferences";@@ -141,18 +137,6 @@ export function KeywordsTab({const hasNextPage = query.data?.hasMore ?? false;const isLoading = query.isFetching;const showTableLoading = isLoading && (showFilters || rows.length === 0);- useDomainRenderDebug("KeywordsTab", {- showFilters,- isLoading,- isPending: query.isPending,- rows: rows.length,- totalCount,- selectedCount: selectedKeywords.size,- activeTab: routeState.tab,- page: routeState.page,- sort: routeState.sort,- order: routeState.order,- });const visibleKeywords = useMemo(() => rows.map((r) => r.keyword), [rows]);useEffect(() => {@@ -192,10 +176,8 @@ export function KeywordsTab({const applyFilters = useCallback((values: KeywordsFilterValues) => {if (countKeywordFilterConditions(values) > maxConditions) return;- const update = buildKeywordsSearchUpdate(values);- debugDomain("KeywordsTab:apply-filters", { values, update });savePreferredFilters(values);- setSearchParams(update);+ setSearchParams(buildKeywordsSearchUpdate(values));},[maxConditions, savePreferredFilters, setSearchParams],);@@ -203,7 +185,6 @@ export function KeywordsTab({const resetFilters = useCallback(() => {const update: SearchUpdate = { page: undefined };for (const key of KEYWORD_FILTER_FIELDS) update[key] = undefined;- debugDomain("KeywordsTab:reset-filters", { update });clearPreferredFilters();setSearchParams(update);}, [clearPreferredFilters, setSearchParams]);@@ -339,7 +320,6 @@ export function KeywordsTab({filterPanel={showFilters ? (<DomainFilterPanel- debugName="KeywordsFilterPanel"activeFilterCount={activeFilterCount}appliedFilters={restoredFilters}fields={KEYWORD_FILTER_FIELDS}diff --git a/src/client/features/domain/components/PagesTab.tsx b/src/client/features/domain/components/PagesTab.tsxindex 53377f53..e5d77381 100644--- a/src/client/features/domain/components/PagesTab.tsx+++ b/src/client/features/domain/components/PagesTab.tsx@@ -11,10 +11,6 @@ import {buildPagesSearchUpdate,countPageFilterConditions,} from "@/client/features/domain/domainFilterUtils";-import {- debugDomain,- useDomainRenderDebug,-} from "@/client/features/domain/domainDebug";import { useDomainPagesQuery } from "@/client/features/domain/hooks/useDomainPagesQuery";import { useDomainPageFilterPreferences } from "@/client/features/domain/useDomainFilterPreferences";import {@@ -132,34 +128,19 @@ export function PagesTab({const hasNextPage = query.data?.hasMore ?? false;const isLoading = query.isFetching;const showTableLoading = isLoading && (showFilters || rows.length === 0);- useDomainRenderDebug("PagesTab", {- showFilters,- isLoading,- isPending: query.isPending,- rows: rows.length,- totalCount,- activeTab: routeState.tab,- page: routeState.page,- sort: routeState.sort,- order: routeState.order,- });const applyFilters = useCallback((values: PagesFilterValues) => {if (countPageFilterConditions(values) > maxConditions) return;- const update = buildPagesSearchUpdate(values);- debugDomain("PagesTab:apply-filters", { values, update });savePreferredFilters(values);- setSearchParams(update);+ setSearchParams(buildPagesSearchUpdate(values));},[maxConditions, savePreferredFilters, setSearchParams],);const resetFilters = useCallback(() => {- const update = buildPagesClearSearchUpdate();- debugDomain("PagesTab:reset-filters", { update });clearPreferredFilters();- setSearchParams(update);+ setSearchParams(buildPagesClearSearchUpdate());}, [clearPreferredFilters, setSearchParams]);const activeFilterCount = useMemo(@@ -240,7 +221,6 @@ export function PagesTab({filterPanel={showFilters ? (<DomainFilterPanel- debugName="PagesFilterPanel"activeFilterCount={activeFilterCount}appliedFilters={restoredFilters}fields={PAGE_FILTER_FIELDS}diff --git a/src/client/features/domain/domainActions.ts b/src/client/features/domain/domainActions.tsindex f8bc39ba..f3e8b2ac 100644--- a/src/client/features/domain/domainActions.ts+++ b/src/client/features/domain/domainActions.ts@@ -31,11 +31,6 @@ export function saveSelectedKeywords({projectId: string;locationCode?: number;}) {- if (selectedKeywords.size === 0) {- toast.error("Select at least one keyword first");- return;- }-const selectedRows = filteredKeywords.filter((row) =>selectedKeywords.has(row.keyword),);diff --git a/src/client/features/domain/domainDebug.ts b/src/client/features/domain/domainDebug.tsdeleted file mode 100644index 8161062a..00000000--- a/src/client/features/domain/domainDebug.ts+++ /dev/null@@ -1,33 +0,0 @@-import { useEffect, useRef } from "react";--type DebugPayload = Record<string, unknown>;--function isDomainDebugEnabled() {- if (typeof window === "undefined") return false;- return (- window.localStorage.getItem("debug:domain-overview") === "1" ||- new URLSearchParams(window.location.search).get("debugDomain") === "1"- );-}--export function debugDomain(event: string, payload?: DebugPayload) {- if (!isDomainDebugEnabled()) return;- const entry = {- event,- t: Math.round(performance.now()),- ...payload,- };- console.info("[domain-debug]", JSON.stringify(entry));-}--export function useDomainRenderDebug(name: string, payload?: DebugPayload) {- const countRef = useRef(0);- countRef.current += 1;-- useEffect(() => {- debugDomain(`${name}:render`, {- count: countRef.current,- ...payload,- });- });-}diff --git a/src/client/features/domain/hooks/useDomainKeywordsQuery.ts b/src/client/features/domain/hooks/useDomainKeywordsQuery.tsindex d279b507..05f61968 100644--- a/src/client/features/domain/hooks/useDomainKeywordsQuery.ts+++ b/src/client/features/domain/hooks/useDomainKeywordsQuery.ts@@ -1,7 +1,5 @@-import { useEffect, useMemo } from "react";import { useQuery } from "@tanstack/react-query";import { getDomainKeywordsPage } from "@/serverFunctions/domain";-import { debugDomain } from "@/client/features/domain/domainDebug";import type { ResearchScope } from "@/shared/researchScope";import type {DomainFilterValues,@@ -49,12 +47,10 @@ function toFiltersPayload(}export function useDomainKeywordsQuery(input: DomainKeywordsQueryInput) {- const filtersPayload = useMemo(- () => toFiltersPayload(input.appliedFilters),- [input.appliedFilters],- );- const queryKey = useMemo(- () => [+ const filtersPayload = toFiltersPayload(input.appliedFilters);+ return useQuery({+ enabled: input.enabled && Boolean(input.domain),+ queryKey: ["domain-keywords",input.projectId,input.domain,@@ -66,29 +62,6 @@ export function useDomainKeywordsQuery(input: DomainKeywordsQueryInput) {input.sortOrder,filtersPayload,],- [- filtersPayload,- input.domain,- input.scope,- input.locationCode,- input.page,- input.pageSize,- input.projectId,- input.sortMode,- input.sortOrder,- ],- );-- useEffect(() => {- debugDomain("useDomainKeywordsQuery:key", {- queryKey,- enabled: input.enabled && Boolean(input.domain),- });- }, [input.domain, input.enabled, queryKey]);-- const query = useQuery({- enabled: input.enabled && Boolean(input.domain),- queryKey,queryFn: () =>getDomainKeywordsPage({data: {@@ -105,18 +78,4 @@ export function useDomainKeywordsQuery(input: DomainKeywordsQueryInput) {}),staleTime: 60_000,});- useEffect(() => {- debugDomain("useDomainKeywordsQuery:state", {- status: query.status,- fetchStatus: query.fetchStatus,- isFetching: query.isFetching,- rows: query.data?.keywords.length ?? 0,- });- }, [- query.data?.keywords.length,- query.fetchStatus,- query.isFetching,- query.status,- ]);- return query;}diff --git a/src/client/features/domain/hooks/useDomainPagesQuery.ts b/src/client/features/domain/hooks/useDomainPagesQuery.tsindex c276b1ae..77ea914d 100644--- a/src/client/features/domain/hooks/useDomainPagesQuery.ts+++ b/src/client/features/domain/hooks/useDomainPagesQuery.ts@@ -1,7 +1,5 @@-import { useEffect, useMemo } from "react";import { useQuery } from "@tanstack/react-query";import { getDomainPagesPage } from "@/serverFunctions/domain";-import { debugDomain } from "@/client/features/domain/domainDebug";import { toPageSortMode } from "@/client/features/domain/utils";import type { ResearchScope } from "@/shared/researchScope";import type {@@ -25,8 +23,9 @@ type DomainPagesQueryInput = {export function useDomainPagesQuery(input: DomainPagesQueryInput) {const pageSortMode = toPageSortMode(input.sortMode);- const queryKey = useMemo(- () => [+ return useQuery({+ enabled: input.enabled && Boolean(input.domain),+ queryKey: ["domain-pages",input.projectId,input.domain,@@ -38,29 +37,6 @@ export function useDomainPagesQuery(input: DomainPagesQueryInput) {input.sortOrder,input.appliedFilters,],- [- input.appliedFilters,- input.domain,- input.scope,- input.locationCode,- input.page,- input.pageSize,- input.projectId,- input.sortOrder,- pageSortMode,- ],- );-- useEffect(() => {- debugDomain("useDomainPagesQuery:key", {- queryKey,- enabled: input.enabled && Boolean(input.domain),- });- }, [input.domain, input.enabled, queryKey]);-- const query = useQuery({- enabled: input.enabled && Boolean(input.domain),- queryKey,queryFn: () =>getDomainPagesPage({data: {@@ -77,18 +53,4 @@ export function useDomainPagesQuery(input: DomainPagesQueryInput) {}),staleTime: 60_000,});- useEffect(() => {- debugDomain("useDomainPagesQuery:state", {- status: query.status,- fetchStatus: query.fetchStatus,- isFetching: query.isFetching,- rows: query.data?.pages.length ?? 0,- });- }, [- query.data?.pages.length,- query.fetchStatus,- query.isFetching,- query.status,- ]);- return query;}diff --git a/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx b/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsxindex 4cdf0237..4198e0ff 100644--- a/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx+++ b/src/client/features/ga4/GoogleAnalyticsConnectionCard.tsx@@ -27,12 +27,10 @@ export function GoogleAnalyticsConnectionCard({projectId,onDismiss,dismissing = false,- heading,}: {projectId: string;onDismiss?: () => void;dismissing?: boolean;- heading?: React.ReactNode;}) {const hosted = isHostedClientAuthMode();const queryClient = useQueryClient();@@ -125,132 +123,129 @@ export function GoogleAnalyticsConnectionCard({const handleConnect = () => void linkAccount(window.location.href);return (- <>- {heading}- <IntegrationConnectionCard- title="Google Analytics"- icon={<GoogleAnalyticsLogo className="size-5" />}- status={- connectionQuery.isPending || connectionUnavailable- ? undefined- : selfHostedNeedsSetup- ? "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"+ <IntegrationConnectionCard+ title="Google Analytics"+ icon={<GoogleAnalyticsLogo className="size-5" />}+ status={+ connectionQuery.isPending || connectionUnavailable+ ? undefined+ : selfHostedNeedsSetup+ ? "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()}>- <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>- ) : selfHostedNeedsSetup ? (- <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}+ Try again+ </button>+ </div>+ ) : selfHostedNeedsSetup ? (+ <div className="space-y-3">+ <GoogleOAuthSetupWarning+ integrationName="Google Analytics"+ docsUrl={GA4_SELF_HOSTED_SETUP_DOCS_URL}/>- ) : 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} />+ </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();+ },}}- >- <DismissButton onClick={onDismiss} disabled={dismissDisabled} />- </GoogleProjectEmptyState>- )}- {showPicker && onDismiss && !connected ? (+ 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} />- ) : null}- {setPropertyMutation.isError || disconnectMutation.isError ? (- <p role="alert" className="mt-3 text-sm text-error">- {getStandardErrorMessage(- setPropertyMutation.error ?? disconnectMutation.error,- )}- </p>- ) : null}- {connectionQuery.isSuccess && !selfHostedNeedsSetup && !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>- </>+ </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 && !selfHostedNeedsSetup && !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/keywords/hooks/useKeywordSelection.ts b/src/client/features/keywords/hooks/useKeywordSelection.tsdeleted file mode 100644index 737c57c9..00000000--- a/src/client/features/keywords/hooks/useKeywordSelection.ts+++ /dev/null@@ -1,45 +0,0 @@-import { useCallback, useState } from "react";--function getNextSelectionSet(- current: Set<string>,- allVisibleKeywords: string[],-): Set<string> {- const allVisibleSelected =- allVisibleKeywords.length > 0 &&- allVisibleKeywords.every((keyword) => current.has(keyword));-- if (allVisibleSelected) {- return new Set();- }-- return new Set(allVisibleKeywords);-}--export function useKeywordSelection() {- const [selectedRows, setSelectedRows] = useState<Set<string>>(new Set());-- const clearSelection = useCallback(() => {- setSelectedRows(new Set());- }, []);-- const toggleRowSelection = useCallback((keyword: string) => {- setSelectedRows((prev) => {- const next = new Set(prev);- if (next.has(keyword)) next.delete(keyword);- else next.add(keyword);- return next;- });- }, []);-- const toggleAllRows = useCallback((allVisibleKeywords: string[]) => {- setSelectedRows((prev) => getNextSelectionSet(prev, allVisibleKeywords));- }, []);-- return {- selectedRows,- setSelectedRows,- clearSelection,- toggleRowSelection,- toggleAllRows,- };-}diff --git a/src/client/features/keywords/hooks/useKeywordSerpAnalysis.ts b/src/client/features/keywords/hooks/useKeywordSerpAnalysis.tsindex ccad5655..6dacc3cc 100644--- a/src/client/features/keywords/hooks/useKeywordSerpAnalysis.ts+++ b/src/client/features/keywords/hooks/useKeywordSerpAnalysis.ts@@ -134,7 +134,6 @@ export function useKeywordSerpAnalysis(serpPage: visiblePage,setSerpPage,SERP_PAGE_SIZE,- serpQuery,serpResults,activeSerpKeyword,serpLoading,diff --git a/src/client/features/keywords/page/KeywordResearchDesktopResults.tsx b/src/client/features/keywords/page/KeywordResearchDesktopResults.tsxindex 4af0581b..0232eeeb 100644--- a/src/client/features/keywords/page/KeywordResearchDesktopResults.tsx+++ b/src/client/features/keywords/page/KeywordResearchDesktopResults.tsx@@ -245,7 +245,6 @@ function DesktopTableCard({ controller }: Props) {{showFilters ? <DesktopFilters controller={controller} /> : null}<KeywordResearchDesktopTable- activeFilterCount={controller.activeFilterCount}filteredRows={pageRows}overviewKeyword={controller.overviewKeyword}selectedRows={controller.selectedRows}diff --git a/src/client/features/keywords/page/KeywordResearchDesktopTable.tsx b/src/client/features/keywords/page/KeywordResearchDesktopTable.tsxindex 2cc2ea6c..1632c2ea 100644--- a/src/client/features/keywords/page/KeywordResearchDesktopTable.tsx+++ b/src/client/features/keywords/page/KeywordResearchDesktopTable.tsx@@ -23,7 +23,6 @@ import type { KeywordResearchRow } from "@/types/keywords";import { EmptyFilterResults } from "./keywordResearchFilters";type Props = {- activeFilterCount: number;filteredRows: KeywordResearchDisplayRow[];overviewKeyword: KeywordResearchRow | null;selectedRows: Set<string>;@@ -38,7 +37,6 @@ type Props = {const keywordColumnHelper = createColumnHelper<KeywordResearchDisplayRow>();export function KeywordResearchDesktopTable({- activeFilterCount,filteredRows,overviewKeyword,selectedRows,@@ -205,10 +203,7 @@ export function KeywordResearchDesktopTable({return (<div className="flex-1 min-h-0">{filteredRows.length === 0 ? (- <EmptyFilterResults- activeFilterCount={activeFilterCount}- resetFilters={resetFilters}- />+ <EmptyFilterResults resetFilters={resetFilters} />) : (<AppDataTabletable={table}diff --git a/src/client/features/keywords/page/KeywordResearchEmptyState.tsx b/src/client/features/keywords/page/KeywordResearchEmptyState.tsxindex 9fb3d024..08db176c 100644--- a/src/client/features/keywords/page/KeywordResearchEmptyState.tsx+++ b/src/client/features/keywords/page/KeywordResearchEmptyState.tsx@@ -9,9 +9,8 @@ type Props = {};export function KeywordResearchEmptyState({ controller, projectId }: Props) {- const { hasSearched, isLoading, lastSearchError } = controller;-- if (hasSearched && !isLoading && !lastSearchError) {+ // The page renders loading and error states before this component.+ if (controller.hasSearched) {return <NoResultsState controller={controller} />;}diff --git a/src/client/features/keywords/page/KeywordResearchMobileResults.tsx b/src/client/features/keywords/page/KeywordResearchMobileResults.tsxindex eb83fa6b..044ec7d3 100644--- a/src/client/features/keywords/page/KeywordResearchMobileResults.tsx+++ b/src/client/features/keywords/page/KeywordResearchMobileResults.tsx@@ -231,7 +231,6 @@ function MobileKeywordResults({ controller }: Props) {{showFilters ? <MobileFilters controller={controller} /> : null}<KeywordResearchDesktopTable- activeFilterCount={controller.activeFilterCount}filteredRows={pageRows}overviewKeyword={controller.overviewKeyword}selectedRows={controller.selectedRows}diff --git a/src/client/features/keywords/page/keywordResearchFilters.tsx b/src/client/features/keywords/page/keywordResearchFilters.tsxindex 6d3d5f55..166adc5e 100644--- a/src/client/features/keywords/page/keywordResearchFilters.tsx+++ b/src/client/features/keywords/page/keywordResearchFilters.tsx@@ -152,10 +152,8 @@ function CompactRangeInput({}export function EmptyFilterResults({- activeFilterCount,resetFilters,}: {- activeFilterCount: number;resetFilters: () => void;}) {return (@@ -163,11 +161,9 @@ export function EmptyFilterResults({<p className="text-sm font-medium">No keywords match your current filters.</p>- {activeFilterCount > 0 ? (- <button className="btn btn-ghost btn-sm" onClick={resetFilters}>- Clear filters- </button>- ) : null}+ <button className="btn btn-ghost btn-sm" onClick={resetFilters}>+ Clear filters+ </button></div>);}diff --git a/src/client/features/keywords/state/keywordControllerActions.ts b/src/client/features/keywords/state/keywordControllerActions.tsindex b3c146d0..9dd814b6 100644--- a/src/client/features/keywords/state/keywordControllerActions.ts+++ b/src/client/features/keywords/state/keywordControllerActions.ts@@ -109,10 +109,6 @@ export function useSaveAndExportActions(params: SaveExportActionParams) {} = params;const handleSaveKeywords = () => {- if (selectedRows.size === 0) {- toast.error("Select at least one keyword first");- return;- }setShowSaveDialog(true);};@@ -159,10 +155,6 @@ export function useSaveAndExportActions(params: SaveExportActionParams) {);const exportCsv = () => {- if (sheetsExportRows.length === 0) {- toast.error("No data to export");- return;- }downloadKeywordResearchCsv(sheetsExportRows,keywordResearchHeaders(input.locationName),diff --git a/src/client/features/keywords/state/useKeywordResearchController.ts b/src/client/features/keywords/state/useKeywordResearchController.tsindex caf6c996..a6fd2df8 100644--- a/src/client/features/keywords/state/useKeywordResearchController.ts+++ b/src/client/features/keywords/state/useKeywordResearchController.ts@@ -1,4 +1,10 @@-import { useCallback, useEffect, useRef, type FormEvent } from "react";+import {+ useCallback,+ useEffect,+ useRef,+ useState,+ type FormEvent,+} from "react";import {useKeywordControlsForm,type KeywordControlsValues,@@ -7,7 +13,6 @@ import { useKeywordFiltering } from "@/client/features/keywords/hooks/useKeywordimport { usePreferredKeywordGrouping } from "@/client/features/keywords/hooks/usePreferredKeywordGrouping";import { useLocalKeywordFilters } from "@/client/features/keywords/hooks/useLocalKeywordFilters";import { useKeywordResearchData } from "@/client/features/keywords/hooks/useKeywordResearchData";-import { useKeywordSelection } from "@/client/features/keywords/hooks/useKeywordSelection";import { useKeywordSerpAnalysis } from "@/client/features/keywords/hooks/useKeywordSerpAnalysis";import { captureClientEvent } from "@/client/lib/posthog";import { useSearchHistory } from "@/client/hooks/useSearchHistory";@@ -77,19 +82,12 @@ export function useKeywordResearchController(const uiState = useKeywordUiState(Object.values(filterValues).some((v) => v.trim() !== ""),);- const {- selectedRows,- setSelectedRows,- clearSelection,- toggleRowSelection,- toggleAllRows,- } = useKeywordSelection();+ const [selectedRows, setSelectedRows] = useState<Set<string>>(new Set());const {setSerpKeyword,serpPage,setSerpPage,SERP_PAGE_SIZE,- serpQuery,serpResults,activeSerpKeyword,serpLoading,@@ -152,11 +150,11 @@ export function useKeywordResearchController(const handledSerpSearchKeyRef = useRef<string | null>(null);const clearActiveKeywordResult = useCallback(() => {- clearSelection();+ setSelectedRows(new Set());uiState.setSelectedKeyword(null);setSerpKeyword(null);setSerpPage(0);- }, [clearSelection, setSerpKeyword, setSerpPage, uiState]);+ }, [setSerpKeyword, setSerpPage, uiState]);const onFormSubmit = input.onFormSubmit;const controlsForm = useKeywordControlsForm(@@ -246,10 +244,6 @@ export function useKeywordResearchController(setShowSaveDialog: uiState.setShowSaveDialog,});- const handleToggleAllRows = () => {- toggleAllRows(filteredRows.map((row) => row.keyword));- };-const handleRowClick = (row: KeywordResearchRow) => {captureClientEvent("keyword_research:serp_open");uiState.setSelectedKeyword(row);@@ -275,7 +269,6 @@ export function useKeywordResearchController(history,historyLoaded,isLoading,- lastSearchError,lastSearchKeyword,lastSearchLocationCode,locationName: input.locationName,@@ -296,7 +289,6 @@ export function useKeywordResearchController(serpLoading,serpLoadingMore,serpPage,- serpQuery,serpResults,setMobileTab: uiState.setMobileTab,setSelectedRows,@@ -308,8 +300,6 @@ export function useKeywordResearchController(showSaveDialog: uiState.showSaveDialog,sortDir: input.sortDir,sortField: input.sortField,- toggleAllRows: handleToggleAllRows,- toggleRowSelection,toggleSort,SERP_PAGE_SIZE,};diff --git a/src/client/features/lighthouse/issues/LighthouseIssuesParts.tsx b/src/client/features/lighthouse/issues/LighthouseIssuesParts.tsxindex 4925bfd2..ab8528cb 100644--- a/src/client/features/lighthouse/issues/LighthouseIssuesParts.tsx+++ b/src/client/features/lighthouse/issues/LighthouseIssuesParts.tsx@@ -21,7 +21,6 @@ import { categoryLabel } from "./utils";import { categoryTabs } from "./types";export function LighthouseIssuesHeader({- backLabel,onBack,isLoading,scannedAt,@@ -30,7 +29,6 @@ export function LighthouseIssuesHeader({metrics,severityCounts,}: {- backLabel: string;onBack: () => void;isLoading: boolean;scannedAt?: string;@@ -43,7 +41,7 @@ export function LighthouseIssuesHeader({<><div className="flex items-center justify-between gap-3"><button className="btn btn-ghost btn-sm px-2" onClick={onBack}>- ← Back to {backLabel}+ ← Back to Site Audit</button><span className="text-xs text-base-content/60">{scannedAtdiff --git a/src/client/features/lighthouse/issues/LighthouseIssuesScreen.tsx b/src/client/features/lighthouse/issues/LighthouseIssuesScreen.tsxindex df8ca841..bee375ed 100644--- a/src/client/features/lighthouse/issues/LighthouseIssuesScreen.tsx+++ b/src/client/features/lighthouse/issues/LighthouseIssuesScreen.tsx@@ -1,4 +1,5 @@import { useMutation, useQuery } from "@tanstack/react-query";+import { useNavigate } from "@tanstack/react-router";import { TriangleAlert } from "lucide-react";import { toast } from "sonner";import {@@ -18,18 +19,20 @@ import {} from "./LighthouseIssuesParts";import { categoryTabs } from "./types";-type LighthouseIssuesScreenProps = {+export function LighthouseIssuesScreen({+ projectId,+ resultId,+ category,+ auditId,+}: {projectId: string;resultId: string;category: CategoryTab;- backLabel: string;- onBack: () => void;- onCategoryChange: (next: CategoryTab) => void;-};--export function LighthouseIssuesScreen(props: LighthouseIssuesScreenProps) {- const { projectId, resultId, category, backLabel, onBack, onCategoryChange } =- props;+ auditId: string | undefined;+}) {+ const navigate = useNavigate({+ from: "/p/$projectId/audit/issues/$resultId",+ });const issuesQuery = useQuery({queryKey: ["auditLighthouseIssues", projectId, resultId],@@ -82,8 +85,13 @@ export function LighthouseIssuesScreen(props: LighthouseIssuesScreenProps) {<div className="px-4 py-3 md:px-6 md:py-4 pb-24 md:pb-8 overflow-auto"><div className="mx-auto max-w-5xl space-y-4"><LighthouseIssuesHeader- backLabel={backLabel}- onBack={onBack}+ onBack={() =>+ void navigate({+ to: "/p/$projectId/audit",+ params: { projectId },+ search: auditId ? { auditId } : undefined,+ })+ }isLoading={issuesQuery.isPending}scannedAt={issuesQuery.data?.createdAt}finalUrl={issuesQuery.data?.finalUrl}@@ -126,7 +134,12 @@ export function LighthouseIssuesScreen(props: LighthouseIssuesScreenProps) {isBusy={exportMutation.isPending}visibleIssues={visibleIssues}allIssues={allIssues}- onCategoryChange={onCategoryChange}+ onCategoryChange={(next) =>+ void navigate({+ search: (prev) => ({ ...prev, category: next }),+ replace: true,+ })+ }onCopy={(data, message) => {void runCopy(data, message);}}diff --git a/src/client/features/onboarding/PostSignupOnboarding.tsx b/src/client/features/onboarding/PostSignupOnboarding.tsxindex d6cb78c5..f3c077bc 100644--- a/src/client/features/onboarding/PostSignupOnboarding.tsx+++ b/src/client/features/onboarding/PostSignupOnboarding.tsx@@ -22,7 +22,7 @@ type PostSignupOnboardingProps = {onNext: () => void;onBack: () => void;onSkip: () => void;- onFinish: (mcpSetupIntent?: "yes" | "no") => void;+ onFinish: () => void;isSaving: boolean;accountMenu: ReactNode;};@@ -83,14 +83,14 @@ export function PostSignupOnboarding({onToggle={(workFor) => updateAnswers({ workFor })}otherValue={answers.workForOther}onOtherChange={(workForOther) => updateAnswers({ workForOther })}- followUp={{- showForValue: CLIENT_WORK_FOR,- label: "About how many client sites do you work on?",- options: [...CLIENT_WEBSITE_COUNT_OPTIONS],- value: answers.clientWebsiteCount,- onChange: (clientWebsiteCount) =>- updateAnswers({ clientWebsiteCount }),- }}+ followUp={+ <ClientWebsiteCountPicker+ value={answers.clientWebsiteCount}+ onChange={(clientWebsiteCount) =>+ updateAnswers({ clientWebsiteCount })+ }+ />+ }/>) : step === 2 ? (<OnboardingChoiceGroup@@ -182,17 +182,10 @@ function OnboardingChoiceGroup({onOtherChange: (value: string) => void;multiple?: boolean;maxSelections?: number;- followUp?: {- showForValue: string;- label: string;- options: string[];- value: string;- onChange: (value: string) => void;- };+ /** Shown under the "My clients" option while it is selected. */+ followUp?: ReactNode;}) {const isOtherSelected = selectedValues.includes("Other");- const showFollowUp =- followUp !== undefined && selectedValues.includes(followUp.showForValue);const atLimit =maxSelections !== undefined && selectedValues.length >= maxSelections;@@ -211,8 +204,6 @@ function OnboardingChoiceGroup({{options.map((option) => {const selected = selectedValues.includes(option);const disabled = atLimit && !selected;- const showFollowUpHere =- showFollowUp && followUp?.showForValue === option;return (<Fragment key={option}>@@ -233,39 +224,7 @@ function OnboardingChoiceGroup({</span></button>- {showFollowUpHere && followUp ? (- <div className="w-full rounded-lg border border-base-300 bg-base-200/40 p-4">- <p className="text-sm text-base-content/70">- {followUp.label}- </p>- <div className="mt-2 flex flex-wrap gap-2">- {followUp.options.map((followUpOption) => {- const followUpSelected =- followUp.value === followUpOption;-- return (- <button- key={followUpOption}- type="button"- className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${- followUpSelected- ? "border-base-content bg-base-200 text-base-content"- : "border-base-300 text-base-content/75 hover:border-base-content/40 hover:bg-base-200/60"- }`}- aria-pressed={followUpSelected}- onClick={() =>- followUp.onChange(- followUpSelected ? "" : followUpOption,- )- }- >- {followUpOption}- </button>- );- })}- </div>- </div>- ) : null}+ {selected && option === CLIENT_WORK_FOR ? followUp : null}</Fragment>);})}@@ -284,3 +243,40 @@ function OnboardingChoiceGroup({</div>);}++function ClientWebsiteCountPicker({+ value,+ onChange,+}: {+ value: string;+ onChange: (value: string) => void;+}) {+ return (+ <div className="w-full rounded-lg border border-base-300 bg-base-200/40 p-4">+ <p className="text-sm text-base-content/70">+ About how many client sites do you work on?+ </p>+ <div className="mt-2 flex flex-wrap gap-2">+ {CLIENT_WEBSITE_COUNT_OPTIONS.map((option) => {+ const selected = value === option;++ return (+ <button+ key={option}+ type="button"+ className={`rounded-md border px-3 py-1.5 text-sm transition-colors ${+ selected+ ? "border-base-content bg-base-200 text-base-content"+ : "border-base-300 text-base-content/75 hover:border-base-content/40 hover:bg-base-200/60"+ }`}+ aria-pressed={selected}+ onClick={() => onChange(selected ? "" : option)}+ >+ {option}+ </button>+ );+ })}+ </div>+ </div>+ );+}diff --git a/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx b/src/client/features/onboarding/SearchConsoleOnboardingStep.tsxindex fc186dfa..98eee519 100644--- a/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx+++ b/src/client/features/onboarding/SearchConsoleOnboardingStep.tsx@@ -5,7 +5,6 @@ import { GoogleGlyph } from "@/client/features/gsc/GoogleGlyph";import { QueryError } from "@/client/components/QueryState";import { Spinner } from "@/client/components/Spinner";import { GoogleLinkErrorAlert } from "@/client/features/integrations/GoogleLinkErrorAlert";-import { SelfHostedSetupWarning } from "@/client/features/gsc/SelfHostedSetupWarning";import {SitePicker,type GscSiteSelection,@@ -97,12 +96,11 @@ function GscConnect({const connection = connectionQuery.data;const connected = Boolean(connection?.connected);const hasGrant = Boolean(connection?.currentUserHasGrant);- const needsSetup = Boolean(connection && !connection.googleOAuthConfigured);const sitesQuery = useQuery({queryKey: ["gscSites", projectId],queryFn: () => listGscSites({ data: { projectId } }),- enabled: hasGrant && !connected && !needsSetup,+ enabled: hasGrant && !connected,});const accounts = React.useMemo(() => sitesQuery.data?.accounts ?? [],@@ -141,7 +139,7 @@ function GscConnect({};const busy = linking || setSiteMutation.isPending;- const showPicker = hasGrant && !connected && !needsSetup;+ const showPicker = hasGrant && !connected;return (<fieldset disabled={busy}>@@ -153,8 +151,6 @@ function GscConnect({onRetry={() => void connectionQuery.refetch()}isRetrying={connectionQuery.isFetching}/>- ) : needsSetup ? (- <SelfHostedSetupWarning />) : connected ? (<div className="flex items-center gap-3 rounded-lg border border-success/30 bg-success/10 p-3.5 text-sm"><span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-success/20 text-success">diff --git a/src/client/features/onboarding/onboardingModel.test.ts b/src/client/features/onboarding/onboardingModel.test.tsindex 17189399..17db9fce 100644--- a/src/client/features/onboarding/onboardingModel.test.ts+++ b/src/client/features/onboarding/onboardingModel.test.ts@@ -12,7 +12,6 @@ const saved = {workFor: "My own startup or business",clientWebsiteCount: null,foundVia: "Google",- mcpSetupIntent: null,};describe("historical onboarding values", () => {@@ -43,51 +42,3 @@ describe("historical onboarding values", () => {);});});--describe("signup agent setup", () => {- it("saves the optional agent choice on the final step only", () => {- const answers = {- ...restoreOnboardingAnswers(saved),- mcpSetupIntent: "yes" as const,- };- expect(buildOnboardingPayload(answers, 3)).not.toHaveProperty(- "mcpSetupIntent",- );- expect(- buildOnboardingPayload(answers, 4, { completed: true }),- ).toMatchObject({ mcpSetupIntent: "yes", completed: true });- });- it("lets users finish without an agent or without making a choice", () => {- const answers = restoreOnboardingAnswers(saved);- expect(- buildOnboardingPayload(answers, 4, { completed: true }),- ).toMatchObject({ completed: true });- expect(- buildOnboardingPayload({ ...answers, mcpSetupIntent: "no" }, 4, {- completed: true,- }),- ).toMatchObject({ mcpSetupIntent: "no", completed: true });- });- it("saves No when finishing immediately, even before React updates the previous answer", () => {- const answers = {- ...restoreOnboardingAnswers(saved),- mcpSetupIntent: "yes" as const,- };- expect(- buildOnboardingPayload(answers, 4, {- completed: true,- mcpSetupIntent: "no",- }),- ).toMatchObject({ mcpSetupIntent: "no", completed: true });- });- it("restores a saved setup intent", () => {- expect(- restoreOnboardingAnswers({ ...saved, mcpSetupIntent: "yes" })- .mcpSetupIntent,- ).toBe("yes");- expect(- restoreOnboardingAnswers({ ...saved, mcpSetupIntent: "no" })- .mcpSetupIntent,- ).toBe("no");- });-});diff --git a/src/client/features/onboarding/onboardingModel.ts b/src/client/features/onboarding/onboardingModel.tsindex e58cfd0a..ab4e8d35 100644--- a/src/client/features/onboarding/onboardingModel.ts+++ b/src/client/features/onboarding/onboardingModel.ts@@ -62,7 +62,6 @@ export type OnboardingAnswers = {clientWebsiteCount: string;source: string;sourceOther: string;- mcpSetupIntent?: "yes" | "no" | "";};/** Answers as persisted in the DB (read back via getOnboardingAnswers). */@@ -71,7 +70,6 @@ type SavedOnboardingAnswers = {workFor: string | null;clientWebsiteCount: string | null;foundVia: string | null;- mcpSetupIntent: string | null;};export const onboardingAnswersQueryOptions = () =>@@ -112,10 +110,6 @@ export function restoreOnboardingAnswers(work.value === CLIENT_WORK_FOR ? (saved.clientWebsiteCount ?? "") : "",source: found.value,sourceOther: found.other,- mcpSetupIntent:- saved.mcpSetupIntent === "yes" || saved.mcpSetupIntent === "no"- ? saved.mcpSetupIntent- : "",};}@@ -126,7 +120,7 @@ export function restoreOnboardingAnswers(export function buildOnboardingPayload(answers: OnboardingAnswers,step: number,- extra: { completed?: boolean; mcpSetupIntent?: "yes" | "no" } = {},+ extra: { completed?: boolean } = {},) {const interestedFeatures = answers.selectedInterests.map((value) =>value === "Other" && answers.interestOther.trim()@@ -150,9 +144,6 @@ export function buildOnboardingPayload(...(step >= 0 ? { interestedFeatures } : {}),...(step >= 1 ? { workFor, clientWebsiteCount } : {}),...(step >= 2 ? { foundVia } : {}),- ...(step >= ONBOARDING_LAST_STEP && answers.mcpSetupIntent- ? { mcpSetupIntent: answers.mcpSetupIntent }- : {}),...extra,};}diff --git a/src/client/features/rank-tracking/RankTrackingConfigModal.tsx b/src/client/features/rank-tracking/RankTrackingConfigModal.tsxindex f6ffa3f7..f242a5bc 100644--- a/src/client/features/rank-tracking/RankTrackingConfigModal.tsx+++ b/src/client/features/rank-tracking/RankTrackingConfigModal.tsx@@ -172,10 +172,6 @@ function RankTrackingConfigModalContent({const handleSubmit = (e: React.FormEvent) => {e.preventDefault();if (isPending) return;- if (!domain.trim()) {- toast.error("Please enter a domain");- return;- }if (targetingMode === "local" && !locationName) {toast.error("Please select a city or region for local targeting");return;diff --git a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsxindex 85c77585..ad957c60 100644--- a/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx+++ b/src/client/features/rank-tracking/RankTrackingDomainDetail.tsx@@ -104,7 +104,7 @@ export function RankTrackingDomainDetail({// Also feeds the History toggle: the matrix view only earns its tab once// there are two checks to compare.- const { data: matrixCells, isLoading: matrixLoading } = useQuery({+ const { data: matrixCells } = useQuery({queryKey: ["rankPositionMatrix", projectId, config.id, activeDevice],queryFn: () =>getRankPositionMatrix({@@ -218,7 +218,7 @@ export function RankTrackingDomainDetail({</div>)}- {latestRun?.status === "failed" && !isRunning && (+ {latestRun?.status === "failed" && (<div className="alert alert-error text-sm py-2"><AlertTriangle className="size-4" /><span>@@ -326,7 +326,6 @@ export function RankTrackingDomainDetail({{effectiveViewMode === "history" ? (<RankTrackingHistoryMatrixcells={matrixCells ?? []}- isLoading={matrixLoading}keywords={filtered.map((r) => ({trackingKeywordId: r.trackingKeywordId,keyword: r.keyword,diff --git a/src/client/features/rank-tracking/RankTrackingDomainList.tsx b/src/client/features/rank-tracking/RankTrackingDomainList.tsxindex 66d24369..84f2100f 100644--- a/src/client/features/rank-tracking/RankTrackingDomainList.tsx+++ b/src/client/features/rank-tracking/RankTrackingDomainList.tsx@@ -145,7 +145,6 @@ export function RankTrackingDomainList({<buttonclassName="btn btn-ghost btn-xs"onClick={() => setFilters(EMPTY_DOMAIN_LIST_FILTERS)}- disabled={activeFilterCount === 0}>Clear filters</button>diff --git a/src/client/features/rank-tracking/RankTrackingHistoryMatrix.tsx b/src/client/features/rank-tracking/RankTrackingHistoryMatrix.tsxindex f0de564d..b3b59768 100644--- a/src/client/features/rank-tracking/RankTrackingHistoryMatrix.tsx+++ b/src/client/features/rank-tracking/RankTrackingHistoryMatrix.tsx@@ -1,5 +1,4 @@import { useMemo } from "react";-import { Loader2 } from "lucide-react";import { sort } from "remeda";import type { RankPositionMatrixCell } from "@/serverFunctions/rank-tracking";@@ -10,27 +9,19 @@ import type { RankPositionMatrixCell } from "@/serverFunctions/rank-tracking";*/export function RankTrackingHistoryMatrix({cells,- isLoading,keywords,}: {cells: RankPositionMatrixCell[];- isLoading: boolean;keywords: { trackingKeywordId: string; keyword: string }[];}) {const { runs, cellByKeyword } = useMemo(() => buildMatrix(cells), [cells]);- if (isLoading) {- return (- <div className="flex items-center justify-center p-8">- <Loader2 className="size-5 animate-spin text-base-content/50" />- </div>- );- }-- if (runs.length === 0 || keywords.length === 0) {+ // The History view is only offered once the matrix has loaded at least two+ // runs, so only filters can leave this empty.+ if (keywords.length === 0) {return (<div className="rounded-xl border border-dashed border-base-300 p-10 text-center text-sm text-base-content/55">- No history yet. Run a check to start building the timeline.+ No keywords match your search.</div>);}diff --git a/src/client/features/rank-tracking/RankTrackingTableParts.tsx b/src/client/features/rank-tracking/RankTrackingTableParts.tsxindex 4c7abfb0..f122d643 100644--- a/src/client/features/rank-tracking/RankTrackingTableParts.tsx+++ b/src/client/features/rank-tracking/RankTrackingTableParts.tsx@@ -1,5 +1,4 @@import { Sparkles } from "lucide-react";-import { toast } from "sonner";import { buildCsv, downloadCsv } from "@/client/lib/csv";import { exportTableToSheets } from "@/client/lib/exportToSheets";import { captureClientEvent } from "@/client/lib/posthog";@@ -250,10 +249,6 @@ export function exportRankTrackingCsv(domain: string,locationName?: string | null,) {- if (sorted.length === 0) {- toast.error("No data to export");- return;- }const { headers, rows } = buildRankTrackingExport(sorted,showDesktop,diff --git a/src/client/features/rank-tracking/rankTrackingScorecards.test.ts b/src/client/features/rank-tracking/rankTrackingScorecards.test.tsdeleted file mode 100644index 110fb653..00000000--- a/src/client/features/rank-tracking/rankTrackingScorecards.test.ts+++ /dev/null@@ -1,92 +0,0 @@-import { describe, expect, it } from "vitest";-import type {- RankTrackingDeviceResult,- RankTrackingRow,-} from "@/types/schemas/rank-tracking";-import { computeScorecards } from "./rankTrackingScorecards";--function device(- position: number | null,- previousPosition: number | null,-): RankTrackingDeviceResult {- return { position, previousPosition, rankingUrl: null, serpFeatures: [] };-}--function row(- desktop: RankTrackingDeviceResult,- mobile: RankTrackingDeviceResult = device(null, null),- searchVolume: number | null = null,-): RankTrackingRow {- return {- trackingKeywordId: crypto.randomUUID(),- keyword: "kw",- matchCase: false,- searchVolume,- keywordDifficulty: null,- cpc: null,- desktop,- mobile,- };-}--describe("computeScorecards", () => {- it("counts ranking keywords and the delta vs the comparison period", () => {- const rows = [row(device(2, 5)), row(device(null, 8))];- const result = computeScorecards(rows, "desktop");- // Only one keyword currently ranks (position 2); two ranked previously.- expect(result.ranking).toBe(1);- expect(result.rankingDelta).toBe(-1);-- const empty = computeScorecards([row(device(null, null))], "desktop");- expect(empty.ranking).toBe(0);- expect(empty.rankingDelta).toBe(0);- });-- it("counts Top 3 and Top 10 (Top 3 subset of Top 10)", () => {- const rows = [- row(device(1, null)),- row(device(3, null)),- row(device(9, null)),- row(device(15, null)),- ];- const result = computeScorecards(rows, "desktop");- expect(result.top3).toBe(2);- expect(result.top10).toBe(3);- });-- it("computes volume-weighted visibility (0–100%) and its delta", () => {- // A single keyword at #1 captures the full click potential → 100%.- const top = computeScorecards(- [row(device(1, null), undefined, 1000)],- "desktop",- );- expect(top.visibility).toBe(100);- expect(top.visibilityDelta).toBe(100); // was unranked (0%), now 100%-- // Ranking but not found now → 0% visibility.- const lost = computeScorecards(- [row(device(null, 1), undefined, 1000)],- "desktop",- );- expect(lost.visibility).toBe(0);-- // No volume anywhere → not computable.- const noVolume = computeScorecards([row(device(1, 1))], "desktop");- expect(noVolume.visibility).toBeNull();- expect(noVolume.visibilityDelta).toBeNull();- });-- it("classifies improved/declined with the 4-case null rules", () => {- const rows = [- row(device(2, 5)), // moved up -> improved- row(device(8, 4)), // moved down -> declined- row(device(3, null)), // new entry -> improved- row(device(null, 6)), // lost ranking -> declined- row(device(null, null)), // nothing -> neither- row(device(7, 7)), // unchanged -> neither- ];- const result = computeScorecards(rows, "desktop");- expect(result.improved).toBe(2);- expect(result.declined).toBe(2);- });-});diff --git a/src/client/features/rank-tracking/rankTrackingScorecards.ts b/src/client/features/rank-tracking/rankTrackingScorecards.tsdeleted file mode 100644index 8d128f39..00000000--- a/src/client/features/rank-tracking/rankTrackingScorecards.ts+++ /dev/null@@ -1,107 +0,0 @@-import type { RankTrackingRow } from "@/types/schemas/rank-tracking";--// Approximate organic CTR by position (index = position; aggregate industry-// curves). Only used to weight the visibility metric, so relative weights-// matter, not exact values. Positions past the list fall back to a small CTR.-const CTR_BY_POSITION = [- 0, 0.28, 0.15, 0.1, 0.07, 0.05, 0.04, 0.033, 0.028, 0.024, 0.021, 0.018,- 0.016, 0.014, 0.012, 0.011, 0.01, 0.009, 0.008, 0.007, 0.006,-];-const TOP_CTR = CTR_BY_POSITION[1];--function ctr(position: number | null): number {- if (position === null || position < 1) return 0;- return CTR_BY_POSITION[position] ?? 0.005;-}--interface Scorecards {- /**- * Volume-weighted, CTR-weighted share of click potential captured (0–100):- * Σ(volume × CTR@position) ÷ Σ(volume × CTR@1). null if no volume data.- */- visibility: number | null;- /** change in visibility (percentage points) vs the comparison period */- visibilityDelta: number | null;- /** keywords currently ranking (found within the tracked depth) */- ranking: number;- /** change in ranking-keyword count vs the comparison period */- rankingDelta: number;- top3: number;- top10: number;- improved: number;- declined: number;-}--/**- * Portfolio scorecards from the already-loaded latest results for one device.- * `ranking` counts keywords found within the tracked depth (a non-null- * position) — unlike an average, it correctly drops when keywords fall out.- * Improved/declined use the same 4-case null rules as DeviceRankCell: a "new"- * entry counts as improved, a "lost" ranking counts as declined, and we never- * subtract through a null.- */-export function computeScorecards(- rows: RankTrackingRow[],- device: "desktop" | "mobile",-): Scorecards {- let countCurrent = 0;- let countPrevious = 0;- let top3 = 0;- let top10 = 0;- let improved = 0;- let declined = 0;- let visNumCurrent = 0;- let visNumPrevious = 0;- let visVolume = 0; // Σ volume over keywords with known volume-- for (const row of rows) {- const { position, previousPosition } = row[device];-- if (position !== null) {- countCurrent += 1;- if (position <= 3) top3 += 1;- if (position <= 10) top10 += 1;- }- if (previousPosition !== null) {- countPrevious += 1;- }-- if (row.searchVolume != null && row.searchVolume > 0) {- visVolume += row.searchVolume;- visNumCurrent += row.searchVolume * ctr(position);- visNumPrevious += row.searchVolume * ctr(previousPosition);- }-- // 4-case change classification (mirrors DeviceRankCell)- if (position === null && previousPosition === null) {- // nothing tracked — neither improved nor declined- } else if (position === null) {- declined += 1; // was ranking, now lost- } else if (previousPosition === null) {- improved += 1; // new entry- } else if (previousPosition - position > 0) {- improved += 1; // moved up- } else if (previousPosition - position < 0) {- declined += 1; // moved down- }- }-- const visibility =- visVolume > 0 ? (visNumCurrent / (visVolume * TOP_CTR)) * 100 : null;- const visibilityPrevious =- visVolume > 0 ? (visNumPrevious / (visVolume * TOP_CTR)) * 100 : null;-- return {- visibility,- visibilityDelta:- visibility !== null && visibilityPrevious !== null- ? visibility - visibilityPrevious- : null,- ranking: countCurrent,- rankingDelta: countCurrent - countPrevious,- top3,- top10,- improved,- declined,- };-}diff --git a/src/client/features/sam/ChatComposer.tsx b/src/client/features/sam/ChatComposer.tsxindex f5609480..479252ac 100644--- a/src/client/features/sam/ChatComposer.tsx+++ b/src/client/features/sam/ChatComposer.tsx@@ -5,19 +5,17 @@ import {type FormEvent,type KeyboardEvent,} from "react";-import { ArrowUp, Loader2, Square } from "lucide-react";+import { ArrowUp, Square } from "lucide-react";export function ChatComposer({busy,onSend,onStop,- placeholder = "Ask Sam about your strategy or OpenSEO…",}: {busy: boolean;onSend: (text: string) => void;/** Cancels the running turn; while busy the send button becomes Stop. */- onStop?: () => void;- placeholder?: string;+ onStop: () => void;}) {const [value, setValue] = useState("");const textareaRef = useRef<HTMLTextAreaElement>(null);@@ -61,10 +59,10 @@ export function ChatComposer({onChange={(event) => setValue(event.target.value)}onKeyDown={handleKey}rows={1}- placeholder={placeholder}+ placeholder="Ask SAM to research, analyze, or track anything…"className="max-h-40 flex-1 resize-none border-0 bg-transparent px-1 py-1 text-sm leading-relaxed outline-none placeholder:text-base-content/50 focus:outline-none"/>- {busy && onStop ? (+ {busy ? (<buttontype="button"aria-label="Stop"@@ -77,14 +75,10 @@ export function ChatComposer({<buttontype="submit"aria-label="Send message"- disabled={busy || !value.trim()}+ disabled={!value.trim()}className="btn btn-primary btn-circle btn-sm">- {busy ? (- <Loader2 className="size-4 animate-spin" />- ) : (- <ArrowUp className="size-4" />- )}+ <ArrowUp className="size-4" /></button>)}</form>diff --git a/src/client/features/sam/SamConversation.tsx b/src/client/features/sam/SamConversation.tsxindex de0eafcd..9afb86e5 100644--- a/src/client/features/sam/SamConversation.tsx+++ b/src/client/features/sam/SamConversation.tsx@@ -11,7 +11,6 @@ import { invalidateSamSessions } from "@/client/features/sam/samQueries";import { captureClientEvent } from "@/client/lib/posthog";import {ChatMessage,- humanizeToolLabel,messageHasVisibleContent,} from "@/client/components/chat/ChatMessage";import { useStickToBottom } from "@/client/components/chat/useStickToBottom";@@ -186,10 +185,6 @@ export function SamConversation({<ChatMessagekey={message.id}message={message}- // SAM exposes the full MCP tool surface (~19 tools), too many to- // hand-label, so tool names are humanized generically rather- // than kept in a curated label map.- resolveToolLabel={humanizeToolLabel}streaming={isBusy &&index === messages.length - 1 &&@@ -264,7 +259,6 @@ export function SamConversation({busy={isBusy}onSend={sendText}onStop={() => void stop()}- placeholder="Ask SAM to research, analyze, or track anything…"/></div></div>diff --git a/src/client/features/saved-keywords/SavedKeywordsBulkActionBar.tsx b/src/client/features/saved-keywords/SavedKeywordsBulkActionBar.tsxindex 03ddf6ff..30c97c41 100644--- a/src/client/features/saved-keywords/SavedKeywordsBulkActionBar.tsx+++ b/src/client/features/saved-keywords/SavedKeywordsBulkActionBar.tsx@@ -22,10 +22,9 @@ export function SavedKeywordsBulkActionBar({onExportSheets: () => void;onDelete: () => void;onClear: () => void;- exportingSelection: "csv" | "sheets" | null;+ exportingSelection: boolean;}) {if (selectedCount === 0) return null;- const exportBusy = exportingSelection != null;return (<TableBulkActionBar@@ -42,7 +41,7 @@ export function SavedKeywordsBulkActionBar({</TableBulkActionButton><TableBulkExportMenu- busy={exportBusy}+ busy={exportingSelection}actions={[{label: "Copy keywords",diff --git a/src/client/features/saved-keywords/SavedKeywordsBulkTagsModal.tsx b/src/client/features/saved-keywords/SavedKeywordsBulkTagsModal.tsxindex 7afebb65..0a334072 100644--- a/src/client/features/saved-keywords/SavedKeywordsBulkTagsModal.tsx+++ b/src/client/features/saved-keywords/SavedKeywordsBulkTagsModal.tsx@@ -228,28 +228,22 @@ export function SavedKeywordsBulkTagsModal({</div>) : (<div className="space-y-2">- {selectedRowTags.length === 0 ? (- <div className="rounded-md border border-base-300 bg-base-200/40 px-3 py-6 text-center text-xs text-base-content/55">- The selected keywords don't have any tags to remove.- </div>- ) : (- <div className="flex flex-wrap gap-1.5 rounded-md border border-base-300 p-3">- {selectedRowTags.map((tag) => {- const checked = removeIds.includes(tag.id);- return (- <TagChip- key={tag.id}- tag={tag}- size="sm"- onClick={() => handleToggleRemove(tag)}- selected={checked}- trailing={checked ? <Check className="size-3" /> : null}- title={checked ? "Will be removed" : "Click to remove"}- />- );- })}- </div>- )}+ <div className="flex flex-wrap gap-1.5 rounded-md border border-base-300 p-3">+ {selectedRowTags.map((tag) => {+ const checked = removeIds.includes(tag.id);+ return (+ <TagChip+ key={tag.id}+ tag={tag}+ size="sm"+ onClick={() => handleToggleRemove(tag)}+ selected={checked}+ trailing={checked ? <Check className="size-3" /> : null}+ title={checked ? "Will be removed" : "Click to remove"}+ />+ );+ })}+ </div>{removeIds.length > 0 ? (<p className="text-xs text-base-content/55">{removeIds.length} tag{removeIds.length !== 1 ? "s" : ""} willdiff --git a/src/client/features/saved-keywords/TagChip.tsx b/src/client/features/saved-keywords/TagChip.tsxindex 7a3a38ca..d1fb2d36 100644--- a/src/client/features/saved-keywords/TagChip.tsx+++ b/src/client/features/saved-keywords/TagChip.tsx@@ -6,12 +6,11 @@ import {} from "@/shared/tag-colors";import type { SavedKeywordTag } from "@/types/keywords";-type Size = "xs" | "sm" | "md";+type Size = "xs" | "sm";const SIZE_CLASS: Record<Size, string> = {xs: "h-5 px-1.5 text-[11px]",sm: "h-6 px-2 text-xs",- md: "h-7 px-2.5 text-sm",};export function TagChip({diff --git a/src/client/features/saved-keywords/useSavedKeywordsExport.ts b/src/client/features/saved-keywords/useSavedKeywordsExport.tsindex 1c2d0a88..0ffc26e3 100644--- a/src/client/features/saved-keywords/useSavedKeywordsExport.ts+++ b/src/client/features/saved-keywords/useSavedKeywordsExport.ts@@ -21,9 +21,8 @@ export function useSavedKeywordsExport(params: {order: ExportSavedKeywordsInput["order"];}) {const [exporting, setExporting] = useState<"csv" | "sheets" | null>(null);- const [exportingSelection, setExportingSelection] = useState<- "csv" | "sheets" | null- >(null);+ // Only the Sheets selection export is async; the CSV download is synchronous.+ const [exportingSelection, setExportingSelection] = useState(false);const exportInput = useMemo<ExportSavedKeywordsInput>(() => ({@@ -84,24 +83,18 @@ export function useSavedKeywordsExport(params: {}};+ // The selection bar only renders with at least one row selected.const exportSelectionCsv = (selectedRows: SavedKeywordRow[]) => {- if (selectedRows.length === 0) return;- setExportingSelection("csv");- try {- downloadKeywordCsv(selectedRows);- captureClientEvent("data:export", {- source_feature: "saved_keywords",- result_count: selectedRows.length,- scope: "selection",- });- } finally {- setExportingSelection(null);- }+ downloadKeywordCsv(selectedRows);+ captureClientEvent("data:export", {+ source_feature: "saved_keywords",+ result_count: selectedRows.length,+ scope: "selection",+ });};const exportSelectionSheets = async (selectedRows: SavedKeywordRow[]) => {- if (selectedRows.length === 0) return;- setExportingSelection("sheets");+ setExportingSelection(true);try {await exportTableToSheets({headers: SAVED_KEYWORD_EXPORT_HEADERS,@@ -111,7 +104,7 @@ export function useSavedKeywordsExport(params: {} catch (error) {toast.error(getStandardErrorMessage(error, "Could not export to Sheets"));} finally {- setExportingSelection(null);+ setExportingSelection(false);}};diff --git a/src/client/features/search-performance/SearchPerformanceColumns.tsx b/src/client/features/search-performance/SearchPerformanceColumns.tsxindex 2b2efa43..9c941b19 100644--- a/src/client/features/search-performance/SearchPerformanceColumns.tsx+++ b/src/client/features/search-performance/SearchPerformanceColumns.tsx@@ -2,6 +2,7 @@ import { createColumnHelper, type ColumnDef } from "@tanstack/react-table";import type { MutableRefObject } from "react";import { makeSelectionColumn } from "@/client/components/table/AppDataTable";import { SortableHeader } from "@/client/components/table/SortableHeader";+import { getSafeExternalUrl } from "@/client/components/table/url";import type { SelectionAnchor } from "@/client/components/table/tableSelection";import type {getSearchPerformanceReport,@@ -105,22 +106,17 @@ export function buildStrikingColumns(header: () => "Page",// GSC page keys are canonical http(s) URLs of the verified property;// the scheme check is defense-in-depth before rendering an href.- cell: ({ getValue }) =>- /^https?:\/\//.test(getValue()) ? (- <a- href={getValue()}- target="_blank"- rel="noreferrer"- className="link link-hover block max-w-sm truncate"- title={getValue()}- >- {getValue()}- </a>- ) : (- <span className="block max-w-sm truncate" title={getValue()}>- {getValue()}- </span>- ),+ cell: ({ getValue }) => (+ <a+ href={getSafeExternalUrl(getValue()) ?? undefined}+ target="_blank"+ rel="noreferrer"+ className="link link-hover block max-w-sm truncate"+ title={getValue()}+ >+ {getValue()}+ </a>+ ),}),strikingHelper.accessor("impressions", {header: ({ column }) => (diff --git a/src/client/features/search-performance/SearchPerformanceParts.tsx b/src/client/features/search-performance/SearchPerformanceParts.tsxindex 93d3bf96..397209de 100644--- a/src/client/features/search-performance/SearchPerformanceParts.tsx+++ b/src/client/features/search-performance/SearchPerformanceParts.tsx@@ -264,7 +264,8 @@ export function StrikingDistanceTable({enableRowSelection: true,state: { rowSelection },onRowSelectionChange: setRowSelection,- getRowId: (row) => `${row.query}::${row.page}`,+ // The server collapses each query to its top page, so queries are unique.+ getRowId: (row) => row.query,initialState: {sorting: [{ id: "impressions", desc: true }],// All rows are already loaded; paginate client-side to keep the table@@ -274,10 +275,9 @@ export function StrikingDistanceTable({});const pagination = table.getState().pagination;- // Rows are query x page; saving/copying dedupes to the query strings.- const selectedQueries = Array.from(- new Set(table.getSelectedRowModel().rows.map((row) => row.original.query)),- );+ const selectedQueries = table+ .getSelectedRowModel()+ .rows.map((row) => row.original.query);const copyKeywords = async () => {try {diff --git a/src/client/features/search-tabs/SearchTabStrip.tsx b/src/client/features/search-tabs/SearchTabStrip.tsxindex 4d0e69b5..bc7f8755 100644--- a/src/client/features/search-tabs/SearchTabStrip.tsx+++ b/src/client/features/search-tabs/SearchTabStrip.tsx@@ -11,7 +11,6 @@ import {} from "@/client/features/keywords/hooks/useKeywordResearchData";import { getBacklinksOverview } from "@/serverFunctions/backlinks";import { getDomainOverview } from "@/serverFunctions/domain";-export type { SearchTab } from "./types";type Props = {activeTabId: string | null;diff --git a/src/client/styles/app.css b/src/client/styles/app.cssindex f8564f18..c9a4c1f0 100644--- a/src/client/styles/app.css+++ b/src/client/styles/app.css@@ -121,21 +121,6 @@ select {.pb-safe {padding-bottom: calc(env(safe-area-inset-bottom, 0.5rem) + 0.5rem);}- .pt-safe {- padding-top: max(env(safe-area-inset-top, 0), 12px);- }-}--/* Override DaisyUI dock's fixed positioning to use flex layout instead */-/* This allows the TabBar to work correctly with Safari's browser toolbar */-.dock {- position: relative;- bottom: auto;- left: auto;- right: auto;- border-top: none;- height: 4rem;- padding-bottom: 0;}/* Touch device optimizations */diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.tsindex 16245297..7e99f18e 100644--- a/src/routeTree.gen.ts+++ b/src/routeTree.gen.ts@@ -26,7 +26,6 @@ import { Route as AuthenticatedSubscribeRouteImport } from './routes/_authenticaimport { Route as AuthenticatedOauthConsentRouteImport } from './routes/_authenticated.oauth-consent'import { Route as AuthSignUpRouteImport } from './routes/_auth.sign-up'import { Route as AuthSignInRouteImport } from './routes/_auth.sign-in'-import { Route as AppTeamRouteImport } from './routes/_app/team'import { Route as AppSupportRouteImport } from './routes/_app/support'import { Route as AppSettingsRouteImport } from './routes/_app/settings'import { Route as AppProjectsRouteImport } from './routes/_app/projects'@@ -58,7 +57,6 @@ import { Route as ProjectPProjectIdDomainRouteImport } from './routes/_project/pimport { Route as ProjectPProjectIdContextRouteImport } from './routes/_project/p/$projectId/context'import { Route as ProjectPProjectIdBrandLookupRouteImport } from './routes/_project/p/$projectId/brand-lookup'import { Route as ProjectPProjectIdBacklinksRouteImport } from './routes/_project/p/$projectId/backlinks'-import { Route as ProjectPProjectIdAuditRouteImport } from './routes/_project/p/$projectId/audit'import { Route as ProjectPProjectIdSettingsIndexRouteImport } from './routes/_project/p/$projectId/settings/index'import { Route as ProjectPProjectIdReportsIndexRouteImport } from './routes/_project/p/$projectId/reports/index'import { Route as ProjectPProjectIdRankTrackingIndexRouteImport } from './routes/_project/p/$projectId/rank-tracking/index'@@ -152,11 +150,6 @@ const AuthSignInRoute = AuthSignInRouteImport.update({path: '/sign-in',getParentRoute: () => AuthRoute,} as any)-const AppTeamRoute = AppTeamRouteImport.update({- id: '/team',- path: '/team',- getParentRoute: () => AppRouteRoute,-} as any)const AppSupportRoute = AppSupportRouteImport.update({id: '/support',path: '/support',@@ -322,11 +315,6 @@ const ProjectPProjectIdBacklinksRoute =path: '/backlinks',getParentRoute: () => ProjectPProjectIdRouteRoute,} as any)-const ProjectPProjectIdAuditRoute = ProjectPProjectIdAuditRouteImport.update({- id: '/audit',- path: '/audit',- getParentRoute: () => ProjectPProjectIdRouteRoute,-} as any)const ProjectPProjectIdSettingsIndexRoute =ProjectPProjectIdSettingsIndexRouteImport.update({id: '/',@@ -347,9 +335,9 @@ const ProjectPProjectIdRankTrackingIndexRoute =} as any)const ProjectPProjectIdAuditIndexRoute =ProjectPProjectIdAuditIndexRouteImport.update({- id: '/',- path: '/',- getParentRoute: () => ProjectPProjectIdAuditRoute,+ id: '/audit/',+ path: '/audit/',+ getParentRoute: () => ProjectPProjectIdRouteRoute,} as any)const ProjectPProjectIdSettingsIntegrationsRoute =ProjectPProjectIdSettingsIntegrationsRouteImport.update({@@ -383,9 +371,9 @@ const ProjectPProjectIdRankTrackingConfigIdRoute =} as any)const ProjectPProjectIdAuditIssuesResultIdRoute =ProjectPProjectIdAuditIssuesResultIdRouteImport.update({- id: '/issues/$resultId',- path: '/issues/$resultId',- getParentRoute: () => ProjectPProjectIdAuditRoute,+ id: '/audit/issues/$resultId',+ path: '/audit/issues/$resultId',+ getParentRoute: () => ProjectPProjectIdRouteRoute,} as any)export interface FileRoutesByFullPath {@@ -400,7 +388,6 @@ export interface FileRoutesByFullPath {'/projects': typeof AppProjectsRoute'/settings': typeof AppSettingsRouteWithChildren'/support': typeof AppSupportRoute- '/team': typeof AppTeamRoute'/sign-in': typeof AuthSignInRoute'/sign-up': typeof AuthSignUpRoute'/oauth-consent': typeof AuthenticatedOauthConsentRoute@@ -420,7 +407,6 @@ export interface FileRoutesByFullPath {'/settings/': typeof AppSettingsIndexRoute'/onboarding/': typeof AuthenticatedOnboardingIndexRoute'/s/$token/': typeof STokenIndexRoute- '/p/$projectId/audit': typeof ProjectPProjectIdAuditRouteWithChildren'/p/$projectId/backlinks': typeof ProjectPProjectIdBacklinksRoute'/p/$projectId/brand-lookup': typeof ProjectPProjectIdBrandLookupRoute'/p/$projectId/context': typeof ProjectPProjectIdContextRoute@@ -457,7 +443,6 @@ export interface FileRoutesByTo {'/billing': typeof AppBillingRoute'/projects': typeof AppProjectsRoute'/support': typeof AppSupportRoute- '/team': typeof AppTeamRoute'/sign-in': typeof AuthSignInRoute'/sign-up': typeof AuthSignUpRoute'/oauth-consent': typeof AuthenticatedOauthConsentRoute@@ -515,7 +500,6 @@ export interface FileRoutesById {'/_app/projects': typeof AppProjectsRoute'/_app/settings': typeof AppSettingsRouteWithChildren'/_app/support': typeof AppSupportRoute- '/_app/team': typeof AppTeamRoute'/_auth/sign-in': typeof AuthSignInRoute'/_auth/sign-up': typeof AuthSignUpRoute'/_authenticated/oauth-consent': typeof AuthenticatedOauthConsentRoute@@ -536,7 +520,6 @@ export interface FileRoutesById {'/_app/settings/': typeof AppSettingsIndexRoute'/_authenticated/onboarding/': typeof AuthenticatedOnboardingIndexRoute'/s/$token/': typeof STokenIndexRoute- '/_project/p/$projectId/audit': typeof ProjectPProjectIdAuditRouteWithChildren'/_project/p/$projectId/backlinks': typeof ProjectPProjectIdBacklinksRoute'/_project/p/$projectId/brand-lookup': typeof ProjectPProjectIdBrandLookupRoute'/_project/p/$projectId/context': typeof ProjectPProjectIdContextRoute@@ -576,7 +559,6 @@ export interface FileRouteTypes {| '/projects'| '/settings'| '/support'- | '/team'| '/sign-in'| '/sign-up'| '/oauth-consent'@@ -596,7 +578,6 @@ export interface FileRouteTypes {| '/settings/'| '/onboarding/'| '/s/$token/'- | '/p/$projectId/audit'| '/p/$projectId/backlinks'| '/p/$projectId/brand-lookup'| '/p/$projectId/context'@@ -633,7 +614,6 @@ export interface FileRouteTypes {| '/billing'| '/projects'| '/support'- | '/team'| '/sign-in'| '/sign-up'| '/oauth-consent'@@ -690,7 +670,6 @@ export interface FileRouteTypes {| '/_app/projects'| '/_app/settings'| '/_app/support'- | '/_app/team'| '/_auth/sign-in'| '/_auth/sign-up'| '/_authenticated/oauth-consent'@@ -711,7 +690,6 @@ export interface FileRouteTypes {| '/_app/settings/'| '/_authenticated/onboarding/'| '/s/$token/'- | '/_project/p/$projectId/audit'| '/_project/p/$projectId/backlinks'| '/_project/p/$projectId/brand-lookup'| '/_project/p/$projectId/context'@@ -881,13 +859,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof AuthSignInRouteImportparentRoute: typeof AuthRoute}- '/_app/team': {- id: '/_app/team'- path: '/team'- fullPath: '/team'- preLoaderRoute: typeof AppTeamRouteImport- parentRoute: typeof AppRouteRoute- }'/_app/support': {id: '/_app/support'path: '/support'@@ -1105,13 +1076,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ProjectPProjectIdBacklinksRouteImportparentRoute: typeof ProjectPProjectIdRouteRoute}- '/_project/p/$projectId/audit': {- id: '/_project/p/$projectId/audit'- path: '/audit'- fullPath: '/p/$projectId/audit'- preLoaderRoute: typeof ProjectPProjectIdAuditRouteImport- parentRoute: typeof ProjectPProjectIdRouteRoute- }'/_project/p/$projectId/settings/': {id: '/_project/p/$projectId/settings/'path: '/'@@ -1135,10 +1099,10 @@ declare module '@tanstack/react-router' {}'/_project/p/$projectId/audit/': {id: '/_project/p/$projectId/audit/'- path: '/'+ path: '/audit'fullPath: '/p/$projectId/audit/'preLoaderRoute: typeof ProjectPProjectIdAuditIndexRouteImport- parentRoute: typeof ProjectPProjectIdAuditRoute+ parentRoute: typeof ProjectPProjectIdRouteRoute}'/_project/p/$projectId/settings/integrations': {id: '/_project/p/$projectId/settings/integrations'@@ -1177,10 +1141,10 @@ declare module '@tanstack/react-router' {}'/_project/p/$projectId/audit/issues/$resultId': {id: '/_project/p/$projectId/audit/issues/$resultId'- path: '/issues/$resultId'+ path: '/audit/issues/$resultId'fullPath: '/p/$projectId/audit/issues/$resultId'preLoaderRoute: typeof ProjectPProjectIdAuditIssuesResultIdRouteImport- parentRoute: typeof ProjectPProjectIdAuditRoute+ parentRoute: typeof ProjectPProjectIdRouteRoute}}}@@ -1205,7 +1169,6 @@ interface AppRouteRouteChildren {AppProjectsRoute: typeof AppProjectsRouteAppSettingsRoute: typeof AppSettingsRouteWithChildrenAppSupportRoute: typeof AppSupportRoute- AppTeamRoute: typeof AppTeamRouteAppIndexRoute: typeof AppIndexRouteAppHelpDataforseoApiKeyRoute: typeof AppHelpDataforseoApiKeyRouteAppHelpOpenrouterApiKeyRoute: typeof AppHelpOpenrouterApiKeyRoute@@ -1217,7 +1180,6 @@ const AppRouteRouteChildren: AppRouteRouteChildren = {AppProjectsRoute: AppProjectsRoute,AppSettingsRoute: AppSettingsRouteWithChildren,AppSupportRoute: AppSupportRoute,- AppTeamRoute: AppTeamRoute,AppIndexRoute: AppIndexRoute,AppHelpDataforseoApiKeyRoute: AppHelpDataforseoApiKeyRoute,AppHelpOpenrouterApiKeyRoute: AppHelpOpenrouterApiKeyRoute,@@ -1227,23 +1189,6 @@ const AppRouteRouteWithChildren = AppRouteRoute._addFileChildren(AppRouteRouteChildren,)-interface ProjectPProjectIdAuditRouteChildren {- ProjectPProjectIdAuditIndexRoute: typeof ProjectPProjectIdAuditIndexRoute- ProjectPProjectIdAuditIssuesResultIdRoute: typeof ProjectPProjectIdAuditIssuesResultIdRoute-}--const ProjectPProjectIdAuditRouteChildren: ProjectPProjectIdAuditRouteChildren =- {- ProjectPProjectIdAuditIndexRoute: ProjectPProjectIdAuditIndexRoute,- ProjectPProjectIdAuditIssuesResultIdRoute:- ProjectPProjectIdAuditIssuesResultIdRoute,- }--const ProjectPProjectIdAuditRouteWithChildren =- ProjectPProjectIdAuditRoute._addFileChildren(- ProjectPProjectIdAuditRouteChildren,- )-interface ProjectPProjectIdRankTrackingRouteChildren {ProjectPProjectIdRankTrackingConfigIdRoute: typeof ProjectPProjectIdRankTrackingConfigIdRouteProjectPProjectIdRankTrackingIndexRoute: typeof ProjectPProjectIdRankTrackingIndexRoute@@ -1283,7 +1228,6 @@ const ProjectPProjectIdSettingsRouteWithChildren =)interface ProjectPProjectIdRouteRouteChildren {- ProjectPProjectIdAuditRoute: typeof ProjectPProjectIdAuditRouteWithChildrenProjectPProjectIdBacklinksRoute: typeof ProjectPProjectIdBacklinksRouteProjectPProjectIdBrandLookupRoute: typeof ProjectPProjectIdBrandLookupRouteProjectPProjectIdContextRoute: typeof ProjectPProjectIdContextRoute@@ -1298,12 +1242,13 @@ interface ProjectPProjectIdRouteRouteChildren {ProjectPProjectIdIndexRoute: typeof ProjectPProjectIdIndexRouteProjectPProjectIdReportsReportIdRoute: typeof ProjectPProjectIdReportsReportIdRouteProjectPProjectIdReportsTemplatesRoute: typeof ProjectPProjectIdReportsTemplatesRoute+ ProjectPProjectIdAuditIndexRoute: typeof ProjectPProjectIdAuditIndexRouteProjectPProjectIdReportsIndexRoute: typeof ProjectPProjectIdReportsIndexRoute+ ProjectPProjectIdAuditIssuesResultIdRoute: typeof ProjectPProjectIdAuditIssuesResultIdRoute}const ProjectPProjectIdRouteRouteChildren: ProjectPProjectIdRouteRouteChildren ={- ProjectPProjectIdAuditRoute: ProjectPProjectIdAuditRouteWithChildren,ProjectPProjectIdBacklinksRoute: ProjectPProjectIdBacklinksRoute,ProjectPProjectIdBrandLookupRoute: ProjectPProjectIdBrandLookupRoute,ProjectPProjectIdContextRoute: ProjectPProjectIdContextRoute,@@ -1322,7 +1267,10 @@ const ProjectPProjectIdRouteRouteChildren: ProjectPProjectIdRouteRouteChildren =ProjectPProjectIdReportsReportIdRoute,ProjectPProjectIdReportsTemplatesRoute:ProjectPProjectIdReportsTemplatesRoute,+ ProjectPProjectIdAuditIndexRoute: ProjectPProjectIdAuditIndexRoute,ProjectPProjectIdReportsIndexRoute: ProjectPProjectIdReportsIndexRoute,+ ProjectPProjectIdAuditIssuesResultIdRoute:+ ProjectPProjectIdAuditIssuesResultIdRoute,}const ProjectPProjectIdRouteRouteWithChildren =diff --git a/src/routes/_app/ai.tsx b/src/routes/_app/ai.tsxindex 3e4738fe..deb94679 100644--- a/src/routes/_app/ai.tsx+++ b/src/routes/_app/ai.tsx@@ -39,10 +39,7 @@ export const Route = createFileRoute("/_app/ai")({});function AiPage() {- const origin =- typeof window === "undefined"- ? "https://app.openseo.so"- : window.location.origin;+ const origin = window.location.origin;const mcpUrl = `${origin}/mcp`;const prompt = getAgentSetupPrompt(origin);const [tab, setTab] = useState<"setup" | "skills">("setup");diff --git a/src/routes/_app/billing.tsx b/src/routes/_app/billing.tsxindex 08c0ce25..48c6fb99 100644--- a/src/routes/_app/billing.tsx+++ b/src/routes/_app/billing.tsx@@ -223,7 +223,6 @@ function BillingPage() {</ul><buttonclassName="btn btn-soft btn-sm w-full"- disabled={isPending}onClick={() =>void runAction(startUpgradeCheckout,@@ -237,7 +236,6 @@ function BillingPage() {) : (<buttonclassName="btn btn-soft btn-sm w-full"- disabled={isPending}onClick={() =>void runAction(() =>@@ -287,7 +285,7 @@ function BillingPage() {<buttonclassName="btn btn-soft btn-sm w-full"- disabled={isPending || !isValidTopUp}+ disabled={!isValidTopUp}onClick={() =>void runAction(() =>diff --git a/src/routes/_app/index.tsx b/src/routes/_app/index.tsxindex e19a2045..6b802f14 100644--- a/src/routes/_app/index.tsx+++ b/src/routes/_app/index.tsx@@ -30,7 +30,8 @@ function IndexRedirect() {});useEffect(() => {- if (!data || data.length === 0) return;+ // getProjects always returns at least one project.+ if (!data) return;// localStorage is untrusted — only honor the remembered project if it's// actually in the org's list; otherwise fall back to the most recent anddiff --git a/src/routes/_app/settings/index.tsx b/src/routes/_app/settings/index.tsxindex e23ab891..cda40f7d 100644--- a/src/routes/_app/settings/index.tsx+++ b/src/routes/_app/settings/index.tsx@@ -25,7 +25,7 @@ const THEME_OPTIONS: {function PersonalSettings() {const isHosted = isHostedClientAuthMode();const { themePreference, setThemePreference } = useThemePreference();- const { data: session, isPending: isSessionPending } = useSession();+ const { data: session } = useSession();const [isSaving, setIsSaving] = useState(false);const analyticsEnabled = session?.user?.analyticsOptedOut !== true;@@ -104,7 +104,7 @@ function PersonalSettings() {type="checkbox"className="toggle toggle-primary"checked={analyticsEnabled}- disabled={isSessionPending || isSaving || !session?.user}+ disabled={isSaving}onChange={(event) => {void updateAnalyticsPreference(event.currentTarget.checked);}}diff --git a/src/routes/_app/team.tsx b/src/routes/_app/team.tsxdeleted file mode 100644index 3744074f..00000000--- a/src/routes/_app/team.tsx+++ /dev/null@@ -1,9 +0,0 @@-import { createFileRoute, redirect } from "@tanstack/react-router";--// The old standalone Team page moved into Settings → Organization; keep the-// URL working for bookmarks.-export const Route = createFileRoute("/_app/team")({- beforeLoad: () => {- throw redirect({ to: "/settings/organization" });- },-});diff --git a/src/routes/_auth.sign-in.tsx b/src/routes/_auth.sign-in.tsxindex 07561431..b8a40478 100644--- a/src/routes/_auth.sign-in.tsx+++ b/src/routes/_auth.sign-in.tsx@@ -193,7 +193,6 @@ function SignInPage() {value={field.state.value}onChange={(event) => field.handleChange(event.target.value)}autoComplete="email"- disabled={!isHostedMode}required/>{error ? (@@ -217,7 +216,6 @@ function SignInPage() {value={field.state.value}onChange={(event) => field.handleChange(event.target.value)}autoComplete="current-password"- disabled={!isHostedMode}required/>{error ? (@@ -243,7 +241,7 @@ function SignInPage() {) : null}<buttonclassName="btn btn-soft w-full"- disabled={!isHostedMode || isSubmitting}+ disabled={isSubmitting}>{isSubmitting ? "Signing in..." : "Sign in"}</button>diff --git a/src/routes/_auth.sign-up.tsx b/src/routes/_auth.sign-up.tsxindex bc376387..e5a8998d 100644--- a/src/routes/_auth.sign-up.tsx+++ b/src/routes/_auth.sign-up.tsx@@ -76,15 +76,6 @@ function SignUpPage() {},onSubmit: async ({ formApi, value }) => {const captchaToken = captcha.tokenRef.current;- if (isTurnstileEnabled && !captchaToken) {- formApi.setErrorMap({- onSubmit: {- form: "Please complete the captcha to continue.",- fields: {},- },- });- return;- }try {const email = value.email.trim();captureClientEvent("auth:sign_up_submit", {@@ -246,7 +237,6 @@ function SignUpPage() {value={field.state.value}onChange={(event) => field.handleChange(event.target.value)}autoComplete="name"- disabled={!isHostedMode}/>{error ? (<p className="mt-1 text-sm text-error">{error}</p>@@ -269,7 +259,6 @@ function SignUpPage() {value={field.state.value}onChange={(event) => field.handleChange(event.target.value)}autoComplete="email"- disabled={!isHostedMode}required/>{error ? (@@ -293,7 +282,6 @@ function SignUpPage() {value={field.state.value}onChange={(event) => field.handleChange(event.target.value)}autoComplete="new-password"- disabled={!isHostedMode}requiredminLength={HOSTED_PASSWORD_MIN_LENGTH}maxLength={HOSTED_PASSWORD_MAX_LENGTH}@@ -319,7 +307,6 @@ function SignUpPage() {value={field.state.value}onChange={(event) => field.handleChange(event.target.value)}autoComplete="new-password"- disabled={!isHostedMode}requiredminLength={HOSTED_PASSWORD_MIN_LENGTH}maxLength={HOSTED_PASSWORD_MAX_LENGTH}@@ -355,9 +342,7 @@ function SignUpPage() {<buttonclassName="btn btn-soft w-full"disabled={- !isHostedMode ||- isSubmitting ||- (isTurnstileEnabled && !captcha.hasToken)+ isSubmitting || (isTurnstileEnabled && !captcha.hasToken)}>{isSubmitting ? "Creating account..." : "Create account"}diff --git a/src/routes/_authenticated.oauth-consent.tsx b/src/routes/_authenticated.oauth-consent.tsxindex 35f7629f..7946ccd9 100644--- a/src/routes/_authenticated.oauth-consent.tsx+++ b/src/routes/_authenticated.oauth-consent.tsx@@ -26,8 +26,6 @@ function OAuthConsentPage() {const [isSubmitting, setIsSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);- const userEmail = session?.user?.email ?? null;-useEffect(() => {captureClientEvent("mcp:consent_viewed");}, []);@@ -83,17 +81,16 @@ function OAuthConsentPage() {</p></div>- {userEmail ? (- <div className="mt-6 flex items-center gap-3 rounded-lg border border-base-300 bg-base-200/50 px-3 py-2 text-sm">- <div className="flex size-7 items-center justify-center rounded-full bg-base-300">- <User className="size-4" />- </div>- <div className="flex-1">- <div className="text-xs text-base-content/60">Signed in as</div>- <div className="font-medium">{userEmail}</div>- </div>+ {/* _authenticated only renders this page with a signed-in user. */}+ <div className="mt-6 flex items-center gap-3 rounded-lg border border-base-300 bg-base-200/50 px-3 py-2 text-sm">+ <div className="flex size-7 items-center justify-center rounded-full bg-base-300">+ <User className="size-4" /></div>- ) : null}+ <div className="flex-1">+ <div className="text-xs text-base-content/60">Signed in as</div>+ <div className="font-medium">{session?.user.email}</div>+ </div>+ </div><div className="mt-6"><div className="text-xs font-medium uppercase tracking-wide text-base-content/60">diff --git a/src/routes/_authenticated.onboarding.index.tsx b/src/routes/_authenticated.onboarding.index.tsxindex 8e6d7974..b7510b81 100644--- a/src/routes/_authenticated.onboarding.index.tsx+++ b/src/routes/_authenticated.onboarding.index.tsx@@ -1,4 +1,4 @@-import { useMutation, useQuery } from "@tanstack/react-query";+import { useMutation, useSuspenseQuery } from "@tanstack/react-query";import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";import { useState } from "react";import { OnboardingAccountMenu } from "@/client/features/onboarding/OnboardingAccountMenu";@@ -44,15 +44,12 @@ export const Route = createFileRoute("/_authenticated/onboarding/")({function OnboardingPage() {const { data: session } = useSession();- const onboardingQuery = useQuery(onboardingAnswersQueryOptions());-- if (!onboardingQuery.data) {- return null;- }+ // beforeLoad seeded this query with ensureQueryData, so data is ready.+ const { data } = useSuspenseQuery(onboardingAnswersQueryOptions());return (<OnboardingFlow- initialAnswers={restoreOnboardingAnswers(onboardingQuery.data.answers)}+ initialAnswers={restoreOnboardingAnswers(data.answers)}email={session?.user?.email}/>);@@ -70,10 +67,7 @@ function OnboardingFlow({const [answers, setAnswers] = useState<OnboardingAnswers>(initialAnswers);const saveMutation = useMutation({- mutationFn: (extra: {- completed?: boolean;- mcpSetupIntent?: "yes" | "no";- }) =>+ mutationFn: (extra: { completed?: boolean }) =>saveOnboardingAnswers({data: buildOnboardingPayload(answers, step, extra),}),@@ -99,12 +93,9 @@ function OnboardingFlow({goToStep(step + 1);};- const handleFinish = async (mcpSetupIntent?: "yes" | "no") => {+ const handleFinish = async () => {try {- await saveMutation.mutateAsync({- completed: true,- ...(mcpSetupIntent ? { mcpSetupIntent } : {}),- });+ await saveMutation.mutateAsync({ completed: true });// Refresh the shared cache so the destination's onboarding-redirect guard// sees the completed state and doesn't bounce the user back here.await queryClient.invalidateQueries({ queryKey: ["onboardingAnswers"] });diff --git a/src/routes/_authenticated.subscribe.tsx b/src/routes/_authenticated.subscribe.tsxindex 4b8ab0f2..6f594f60 100644--- a/src/routes/_authenticated.subscribe.tsx+++ b/src/routes/_authenticated.subscribe.tsx@@ -12,7 +12,6 @@ import {} from "@/client/features/billing/plan-offers";import { captureClientEvent } from "@/client/lib/posthog";import { useSession } from "@/lib/auth-client";-import { isHostedClientAuthMode } from "@/lib/auth-mode";import { getStandardErrorMessage } from "@/client/lib/error-messages";import { getSubscribeRouteState } from "@/client/features/billing/route-state";import { getCustomerPlanStatus } from "@/client/features/billing/plan-detection";@@ -69,12 +68,10 @@ function SubscribePage() {const canManageBilling = useCanManageBilling();// Read managed access from the already-loaded Autumn customer (local, no API- // call) instead of a separate server round-trip. Self-hosted has no Autumn- // customer, so mirror the server's "always granted" behavior there.- const hasManagedAccess = isHostedClientAuthMode()- ? customerQuery.check({ featureId: AUTUMN_MANAGED_ACCESS_FEATURE_ID })- .allowed- : true;+ // call) instead of a separate server round-trip.+ const hasManagedAccess = customerQuery.check({+ featureId: AUTUMN_MANAGED_ACCESS_FEATURE_ID,+ }).allowed;const planStatus = getCustomerPlanStatus(customerQuery.data);const subscribeRouteState = getSubscribeRouteState({diff --git a/src/routes/_authenticated.tsx b/src/routes/_authenticated.tsxindex bba0f914..87e86959 100644--- a/src/routes/_authenticated.tsx+++ b/src/routes/_authenticated.tsx@@ -1,5 +1,5 @@-import { Outlet, createFileRoute } from "@tanstack/react-router";-import { AuthPageShell } from "@/client/features/auth/AuthPage";+import { Link, Outlet, createFileRoute } from "@tanstack/react-router";+import { AuthPageCard, AuthPageShell } from "@/client/features/auth/AuthPage";import { useHostedAuthRouteGuard } from "@/client/features/auth/useHostedAuthRouteGuard";import { PageLoading } from "@/client/components/Spinner";@@ -12,7 +12,18 @@ function AuthenticatedShellLayout() {// Every page under this layout is hosted-only.if (!authGate.isHostedMode) {- return null;+ return (+ <AuthPageShell>+ <AuthPageCard+ title="Not available"+ helperText="This page isn't available right now."+ >+ <Link to="/" className="btn btn-soft w-full">+ Back to OpenSEO+ </Link>+ </AuthPageCard>+ </AuthPageShell>+ );}if (!authGate.canRenderAuthenticatedContent) {diff --git a/src/routes/_project/p/$projectId/audit.tsx b/src/routes/_project/p/$projectId/audit.tsxdeleted file mode 100644index 315b64eb..00000000--- a/src/routes/_project/p/$projectId/audit.tsx+++ /dev/null@@ -1,9 +0,0 @@-import { createFileRoute, Outlet } from "@tanstack/react-router";--export const Route = createFileRoute("/_project/p/$projectId/audit")({- component: SiteAuditLayout,-});--function SiteAuditLayout() {- return <Outlet />;-}diff --git a/src/routes/_project/p/$projectId/audit/index.tsx b/src/routes/_project/p/$projectId/audit/index.tsxindex f624564b..caf5627c 100644--- a/src/routes/_project/p/$projectId/audit/index.tsx+++ b/src/routes/_project/p/$projectId/audit/index.tsx@@ -1,25 +1,8 @@import { createFileRoute, useNavigate } from "@tanstack/react-router";import { useCallback } from "react";-import { AlertCircle, Loader2 } from "lucide-react";-import { useQuery } from "@tanstack/react-query";-import {- getAuditResults,- getAuditStatus,- getCrawlProgress,-} from "@/serverFunctions/audit";-import { QueryError, QueryState } from "@/client/components/QueryState";-import { PageLoading } from "@/client/components/Spinner";import { auditSearchSchema } from "@/types/schemas/audit";import { LaunchView } from "@/client/features/audit/launch/LaunchView";-import { ResultsView } from "@/client/features/audit/results/ResultsView";-import {- extractHostname,- extractPathname,- formatStartedAt,- HttpStatusBadge,- StatusBadge,- SUPPORT_EMAIL,-} from "@/client/features/audit/shared";+import { AuditDetail } from "@/client/features/audit/AuditDetail";export const Route = createFileRoute<"/_project/p/$projectId/audit/">("/_project/p/$projectId/audit/",@@ -65,332 +48,3 @@ function SiteAuditPage() {/>);}--function AuditDetail({- projectId,- auditId,- tab,- onBack,- onTabChange,-}: {- projectId: string;- auditId: string;- tab: string;- onBack: () => void;- onTabChange: (tab: "issues" | "pages" | "performance") => void;-}) {- const statusQuery = useQuery({- queryKey: ["audit-status", projectId, auditId],- queryFn: () => getAuditStatus({ data: { projectId, auditId } }),- refetchInterval: (query) => {- const data = query.state.data;- return data?.status === "running" ? 3000 : false;- },- });-- const isComplete = statusQuery.data?.status === "completed";- const isFailed = statusQuery.data?.status === "failed";- const isRunning = statusQuery.data?.status === "running";-- // Failed audits keep whatever pages were crawled before the failure- // (persistence is per-batch), so fetch results for them too and show the- // partial crawl instead of a dead end.- const resultsQuery = useQuery({- queryKey: ["audit-results", projectId, auditId],- queryFn: () => getAuditResults({ data: { projectId, auditId } }),- enabled: isComplete || isFailed,- });-- if (statusQuery.isLoading) {- return <PageLoading />;- }-- if (statusQuery.isError) {- return (- <div className="px-4 py-6 md:px-6">- <div className="mx-auto max-w-3xl space-y-4">- <QueryError- fallback="We could not load this audit. It may have been deleted."- onRetry={() => void statusQuery.refetch()}- isRetrying={statusQuery.isFetching}- />- <button className="btn btn-ghost btn-sm" onClick={onBack}>- ← Back to audits- </button>- </div>- </div>- );- }-- const status = statusQuery.data;- const partialPageCount = isFailed- ? (resultsQuery.data?.pages.length ?? 0)- : 0;- const failedWithResults = isFailed && partialPageCount > 0;- // Wait for the results fetch before choosing between the "partial results"- // banner and the zero-page support CTA, so the CTA doesn't flash first.- const showSupportCta =- (isFailed && resultsQuery.isSuccess && !failedWithResults) ||- (isComplete && status && status.pagesCrawled <= 1);-- return (- <div className="px-4 py-4 md:px-6 md:py-6 pb-24 md:pb-8 overflow-auto">- <div className="mx-auto max-w-5xl space-y-4">- <div className="space-y-1">- <button className="btn btn-ghost btn-sm px-0" onClick={onBack}>- ← All audits- </button>- <div className="flex flex-wrap items-center gap-x-3 gap-y-1">- <h1 className="text-2xl font-semibold">- {status ? extractHostname(status.startUrl) : "Site Audit"}- </h1>- {status?.status !== "running" && status && (- <StatusBadge status={status.status} />- )}- </div>- {status && (- <p className="text-sm text-base-content/60">- Site audit · Started {formatStartedAt(status.startedAt)}- </p>- )}- </div>-- {isRunning && status && (- <ProgressCard- projectId={projectId}- auditId={auditId}- status={status}- />- )}-- {showSupportCta && (- <div- className={isFailed ? "alert alert-error" : "alert alert-warning"}- >- <AlertCircle className="size-5" />- <div className="space-y-1">- <p className="font-medium">- Site audit couldn't fully crawl this website.- </p>- <p>- Sorry! This site's bot protection blocked our crawler. We don't- have a workaround for this yet. Desktop crawlers run from your- own machine and usually get past it: try{" "}- <a- className="link link-primary"- href="https://github.com/PhialsBasement/LibreCrawl"- target="_blank"- rel="noreferrer"- >- LibreCrawl- </a>{" "}- (free, open source) or{" "}- <a- className="link link-primary"- href="https://www.screamingfrog.co.uk/seo-spider/"- target="_blank"- rel="noreferrer"- >- Screaming Frog- </a>{" "}- (free up to 500 URLs).- </p>- </div>- </div>- )}-- {failedWithResults && (- <div className="alert alert-warning">- <AlertCircle className="size-5" />- <div className="space-y-1">- <p className="font-medium">- This audit stopped early after {partialPageCount} page- {partialPageCount === 1 ? "" : "s"}.- </p>- <p>- The results below cover everything crawled before it stopped.- Run a new audit to try again, or email{" "}- <a- className="link link-primary"- href={`mailto:${SUPPORT_EMAIL}`}- >- {SUPPORT_EMAIL}- </a>{" "}- if this keeps happening.- </p>- </div>- </div>- )}-- {(isComplete || isFailed) && (- <QueryState- query={resultsQuery}- errorFallback="Failed to load the audit results"- >- {(data) =>- (isComplete || failedWithResults) && (- <ResultsView- projectId={projectId}- data={data}- tab={tab}- onTabChange={onTabChange}- />- )- }- </QueryState>- )}- </div>- </div>- );-}--function ProgressCard({- projectId,- auditId,- status,-}: {- projectId: string;- auditId: string;- status: {- pagesCrawled: number;- pagesTotal: number;- lighthouseTotal: number;- lighthouseCompleted: number;- lighthouseFailed: number;- currentPhase: string | null;- };-}) {- const crawlProgress =- status.pagesTotal > 0- ? Math.round((status.pagesCrawled / status.pagesTotal) * 100)- : 0;- const lighthouseDone = status.lighthouseCompleted + status.lighthouseFailed;- const lighthouseProgress =- status.lighthouseTotal > 0- ? Math.round((lighthouseDone / status.lighthouseTotal) * 100)- : 0;- const isLighthousePhase = status.currentPhase === "lighthouse";- const phaseLabel =- status.currentPhase === "discovery"- ? "Discovery"- : status.currentPhase === "crawling"- ? "Crawling"- : status.currentPhase === "lighthouse"- ? "Lighthouse"- : status.currentPhase === "finalizing"- ? "Finalizing"- : (status.currentPhase ?? "Running");- const progress = isLighthousePhase ? lighthouseProgress : crawlProgress;-- const crawlProgressQuery = useQuery({- queryKey: ["audit-crawl-progress", projectId, auditId],- queryFn: () => getCrawlProgress({ data: { projectId, auditId } }),- refetchInterval: 1500,- });-- const crawledUrls = crawlProgressQuery.data ?? [];-- return (- <div className="space-y-3">- <div className="card bg-base-100 border border-base-300">- <div className="card-body gap-3">- <div className="flex items-center justify-between">- <h2 className="font-medium flex items-center gap-2">- <Loader2 className="size-4 animate-spin text-primary" />- {isLighthousePhase- ? "Running Lighthouse checks"- : "Crawling pages"}- </h2>- <span className="badge badge-ghost badge-sm">{phaseLabel}</span>- </div>-- <progress- className="progress progress-primary w-full"- value={progress}- max={100}- />-- <div className="flex items-center justify-between text-sm">- {isLighthousePhase ? (- <span>- {lighthouseDone} / {status.lighthouseTotal} checks- {status.lighthouseFailed > 0- ? ` (${status.lighthouseFailed} failed)`- : ""}- </span>- ) : (- <span>- {status.pagesCrawled} / {status.pagesTotal} pages- </span>- )}- <span className="text-base-content/60">{progress}%</span>- </div>- </div>- </div>-- {crawledUrls.length > 0 && (- <div className="card bg-base-100 border border-base-300">- <div className="card-body gap-2 p-4">- <h3 className="text-sm font-medium text-base-content/70">- Crawled Pages ({crawledUrls.length})- </h3>- <p className="text-xs text-base-content/50">- Updated {new Date(crawledUrls[0].crawledAt).toLocaleTimeString()}- </p>- <div className="max-h-[400px] overflow-y-auto -mx-1">- {crawledUrls.map((entry, i) => (- <ProgressRow- key={`${entry.url}-${entry.crawledAt}`}- entry={entry}- index={i}- />- ))}- </div>- </div>- </div>- )}- </div>- );-}--function ProgressRow({- entry,- index,-}: {- entry: {- url: string;- statusCode: number | null;- title: string | null;- crawledAt: number;- };- index: number;-}) {- const pathname = extractPathname(entry.url);-- return (- <div- className={`flex items-center justify-between gap-3 px-2 py-1.5 rounded text-sm ${- index === 0- ? "bg-primary/5 animate-in fade-in slide-in-from-top-1 duration-300"- : ""- }`}- >- <div className="flex items-center gap-2 min-w-0 flex-1">- <HttpStatusBadge code={entry.statusCode} />- <span className="truncate text-base-content/80" title={entry.url}>- {pathname}- </span>- </div>- <div className="flex items-center gap-3 shrink-0">- {entry.title && (- <span- className="text-xs text-base-content/40 truncate max-w-[260px] hidden md:block"- title={entry.title}- >- {entry.title}- </span>- )}- </div>- </div>- );-}diff --git a/src/routes/_project/p/$projectId/audit/issues/$resultId.tsx b/src/routes/_project/p/$projectId/audit/issues/$resultId.tsxindex 15ae4e1f..bcfe1fd8 100644--- a/src/routes/_project/p/$projectId/audit/issues/$resultId.tsx+++ b/src/routes/_project/p/$projectId/audit/issues/$resultId.tsx@@ -1,4 +1,4 @@-import { createFileRoute, useNavigate } from "@tanstack/react-router";+import { createFileRoute } from "@tanstack/react-router";import { LighthouseIssuesScreen } from "@/client/features/lighthouse/issues/LighthouseIssuesScreen";import { lighthouseIssuesSearchSchema } from "@/types/schemas/lighthouse";@@ -12,27 +12,13 @@ export const Route = createFileRoute(function AuditIssuesPage() {const { projectId, resultId } = Route.useParams();const { auditId, category } = Route.useSearch();- const navigate = useNavigate({ from: Route.fullPath });return (<LighthouseIssuesScreenprojectId={projectId}resultId={resultId}category={category}- backLabel="Site Audit"- onBack={() =>- void navigate({- to: "/p/$projectId/audit",- params: { projectId },- search: auditId ? { auditId } : undefined,- })- }- onCategoryChange={(next) =>- void navigate({- search: (prev) => ({ ...prev, category: next }),- replace: true,- })- }+ auditId={auditId}/>);}diff --git a/src/routes/_project/p/$projectId/reports/$reportId.tsx b/src/routes/_project/p/$projectId/reports/$reportId.tsxindex 01169597..9c9caa97 100644--- a/src/routes/_project/p/$projectId/reports/$reportId.tsx+++ b/src/routes/_project/p/$projectId/reports/$reportId.tsx@@ -49,8 +49,6 @@ function ReportDetailPage() {const [showDelete, setShowDelete] = useState(false);const [showShare, setShowShare] = useState(false);const openedRef = useRef<string | null>(null);- const exitRef = useRef<HTMLButtonElement>(null);-const reportQuery = useQuery({queryKey: reportQueryKey(projectId, reportId),queryFn: () => getReport({ data: { projectId, reportId } }),@@ -61,8 +59,6 @@ function ReportDetailPage() {// not-found copy by several seconds.retry: false,});- const report = reportQuery.data;-const deleteMutation = useDeleteReport(projectId, () => {setShowDelete(false);// `replace`, so Back does not return to the deleted report's URL.@@ -73,51 +69,29 @@ function ReportDetailPage() {});});- // useCallback so the Esc listener below is not re-registered every render.- const setExpanded = useCallback(- (expanded: boolean) => {- void navigate({- search: () => (expanded ? { full: true } : {}),- replace: true,- });- },- [navigate],- );+ // useCallback so the full-screen Esc listener is not re-registered (and+ // Exit re-focused) every render.+ const exitFullScreen = useCallback(() => {+ void navigate({ search: () => ({}), replace: true });+ }, [navigate]);// One open event per report, once its metadata (and so its skill) is known.+ const loadedReport = reportQuery.data;useEffect(() => {- if (!report || openedRef.current === report.id) return;- openedRef.current = report.id;+ if (!loadedReport || openedRef.current === loadedReport.id) return;+ openedRef.current = loadedReport.id;captureClientEvent("report:opened", {project_id: projectId,- report_id: report.id,- skill: report.skill,+ report_id: loadedReport.id,+ skill: loadedReport.skill,});- }, [projectId, report]);-- // Esc leaves the expanded view, the same key Modal.tsx uses to close. The- // listener is on the parent window, and the expanded body is almost entirely- // the sandboxed iframe: one click inside moves focus into the frame, which- // has no scripts and so cannot forward the key. Focusing Exit on entry keeps- // Esc working until the reader clicks into the report; Exit is the- // guaranteed path.- useEffect(() => {- if (!full) return;- exitRef.current?.focus();- const handleKeyDown = (event: KeyboardEvent) => {- if (event.key !== "Escape" || event.defaultPrevented) return;- event.preventDefault();- setExpanded(false);- };- window.addEventListener("keydown", handleKeyDown);- return () => window.removeEventListener("keydown", handleKeyDown);- }, [full, setExpanded]);+ }, [projectId, loadedReport]);if (reportQuery.isPending) {return <PageLoading />;}- if (reportQuery.isError || !report) {+ if (reportQuery.isError) {const notFound = getErrorCode(reportQuery.error) === "NOT_FOUND";return (<div className="px-4 py-6 md:px-6">@@ -147,6 +121,8 @@ function ReportDetailPage() {);}+ const report = reportQuery.data;+// `?print=1` serves the same document with a print() script appended, so the// new tab opens the print dialog itself.const exportPdf = () => {@@ -159,27 +135,11 @@ function ReportDetailPage() {if (full) {return (- <div className="fixed inset-0 z-50 flex flex-col bg-base-100">- <div className="flex items-center justify-between gap-3 border-b border-base-300 px-4 py-2">- <span className="truncate text-sm font-medium">{report.title}</span>- <button- type="button"- ref={exitRef}- className="btn btn-ghost btn-sm gap-1.5"- onClick={() => setExpanded(false)}- >- <Minimize2 className="size-4" />- Exit- </button>- </div>- <div className="min-h-0 flex-1 p-2">- <ReportViewer- src={`/r/${report.id}`}- title={report.title}- className="h-full w-full bg-base-100"- />- </div>- </div>+ <FullScreenReport+ reportId={report.id}+ title={report.title}+ onExit={exitFullScreen}+ />);}@@ -303,7 +263,9 @@ function ReportDetailPage() {className="btn btn-ghost btn-sm btn-square"aria-label="Full screen"title="Full screen"- onClick={() => setExpanded(true)}+ onClick={() =>+ void navigate({ search: () => ({ full: true }), replace: true })+ }><Maximize2 className="size-4" /></button>@@ -321,7 +283,7 @@ function ReportDetailPage() {<ReportViewer src={`/r/${report.id}`} title={report.title} /></div>- {hosted && showShare ? (+ {showShare ? (<ShareReportModal report={report} onClose={() => setShowShare(false)} />) : null}@@ -336,3 +298,56 @@ function ReportDetailPage() {</div>);}++// Esc leaves the expanded view, the same key Modal.tsx uses to close. The+// listener is on the parent window, and the expanded body is almost entirely+// the sandboxed iframe: one click inside moves focus into the frame, which has+// no scripts and so cannot forward the key. Focusing Exit on entry keeps Esc+// working until the reader clicks into the report; Exit is the guaranteed+// path.+function FullScreenReport({+ reportId,+ title,+ onExit,+}: {+ reportId: string;+ title: string;+ onExit: () => void;+}) {+ const exitRef = useRef<HTMLButtonElement>(null);++ useEffect(() => {+ exitRef.current?.focus();+ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key !== "Escape" || event.defaultPrevented) return;+ event.preventDefault();+ onExit();+ };+ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [onExit]);++ return (+ <div className="fixed inset-0 z-50 flex flex-col bg-base-100">+ <div className="flex items-center justify-between gap-3 border-b border-base-300 px-4 py-2">+ <span className="truncate text-sm font-medium">{title}</span>+ <button+ type="button"+ ref={exitRef}+ className="btn btn-ghost btn-sm gap-1.5"+ onClick={onExit}+ >+ <Minimize2 className="size-4" />+ Exit+ </button>+ </div>+ <div className="min-h-0 flex-1 p-2">+ <ReportViewer+ src={`/r/${reportId}`}+ title={title}+ className="h-full w-full bg-base-100"+ />+ </div>+ </div>+ );+}diff --git a/src/routes/_project/p/$projectId/settings/integrations.tsx b/src/routes/_project/p/$projectId/settings/integrations.tsxindex 0cccf810..34813a8d 100644--- a/src/routes/_project/p/$projectId/settings/integrations.tsx+++ b/src/routes/_project/p/$projectId/settings/integrations.tsx@@ -34,14 +34,8 @@ function ProjectIntegrationsRoute() {</section><section id="google-analytics" className="scroll-mt-6 space-y-3">- <GoogleAnalyticsConnectionCard- projectId={projectId}- heading={- <h2 className="text-sm font-medium text-base-content/50">- Analytics- </h2>- }- />+ <h2 className="text-sm font-medium text-base-content/50">Analytics</h2>+ <GoogleAnalyticsConnectionCard projectId={projectId} /></section><CrawlerAccessSettings projectId={projectId} />diff --git a/src/routes/reset-password.tsx b/src/routes/reset-password.tsxindex d098e7ba..3d244fcb 100644--- a/src/routes/reset-password.tsx+++ b/src/routes/reset-password.tsx@@ -103,7 +103,7 @@ function ResetPasswordPage() {const redirectTo = normalizeAuthRedirect(search.redirect);const isHostedMode = isHostedClientAuthMode();const routeError = getResetPasswordErrorMessage(search.error);- const token = typeof search.token === "string" ? search.token : null;+ const token = search.token;const form = useForm({defaultValues: {password: "",@@ -112,17 +112,8 @@ function ResetPasswordPage() {validators: {onSubmit: resetPasswordSchema,},+ // The form only renders when the URL carries a token.onSubmit: async ({ formApi, value }) => {- if (!token) {- formApi.setErrorMap({- onSubmit: {- form: "This reset link is no longer valid. Request a new one and try again.",- fields: {},- },- });- return;- }-try {const result = await authClient.resetPassword({newPassword: value.password,diff --git a/src/server/features/dashboard/services/DashboardService.ts b/src/server/features/dashboard/services/DashboardService.tsindex 2451c018..f7806d38 100644--- a/src/server/features/dashboard/services/DashboardService.ts+++ b/src/server/features/dashboard/services/DashboardService.ts@@ -7,8 +7,6 @@ import { getIssueTypePageCountsForAudit } from "@/server/features/audit/repositoimport { BacklinkSnapshotRepository } from "@/server/features/dashboard/repositories/BacklinkSnapshotRepository";import { Ga4ConnectionRepository } from "@/server/features/ga4/repositories/Ga4ConnectionRepository";import { GscConnectionRepository } from "@/server/features/gsc/repositories/GscConnectionRepository";-import { RankTrackingRepository } from "@/server/features/rank-tracking/repositories/RankTrackingRepository";-import { getLatestResults } from "@/server/features/rank-tracking/services/rankTrackingResults";import {createDataforseoClient,normalizeBacklinksTarget,@@ -19,9 +17,6 @@ import { shouldCaptureAppErrorCode } from "@/shared/error-codes";// Daily cadence: fresh numbers each visit without per-visit spend; a dormant// project costs nothing because refreshes are visit-triggered.const SNAPSHOT_MAX_AGE_MS = 24 * 60 * 60 * 1000;-// Bounds the per-config result reads on the overview path; projects rarely-// have more than a couple of configs.-const MAX_CONFIGS_FOR_OVERVIEW = 5;export type DashboardActivation = {domain: string | null;@@ -44,14 +39,6 @@ export type DashboardActivation = {dismissedSteps: string[];};-type DashboardRankSummary = {- trackedKeywords: number;- improved: number;- declined: number;- top10: number;- lastCheckedAt: string | null;-};-export type DashboardAuditSummary = {status: "running" | "completed" | "failed";pagesCrawled: number;@@ -79,7 +66,6 @@ export type DashboardBacklinkSummary = {};type DashboardOverview = {- rank: DashboardRankSummary | null;audit: DashboardAuditSummary | null;backlinks: DashboardBacklinkSummary | null;};@@ -136,56 +122,11 @@ async function getOverview(input: {projectId: string;domain: string | null;}): Promise<DashboardOverview> {- const [rank, audit, backlinks] = await Promise.all([- getRankSummary(input.projectId),+ const [audit, backlinks] = await Promise.all([getAuditSummary(input.projectId),getBacklinkSummary(input.projectId, input.domain),]);- return { rank, audit, backlinks };-}--async function getRankSummary(- projectId: string,-): Promise<DashboardRankSummary | null> {- const configs = await RankTrackingRepository.getConfigsForProject(projectId);- if (configs.length === 0) return null;-- const results = await Promise.all(- configs- .slice(0, MAX_CONFIGS_FOR_OVERVIEW)- .map((config) => getLatestResults(config.id, projectId, "7d")),- );-- const summary: DashboardRankSummary = {- trackedKeywords: 0,- improved: 0,- declined: 0,- top10: 0,- lastCheckedAt: null,- };-- for (const result of results) {- summary.trackedKeywords += result.rows.length;- if (- result.run?.lastCheckedAt &&- (!summary.lastCheckedAt ||- result.run.lastCheckedAt > summary.lastCheckedAt)- ) {- summary.lastCheckedAt = result.run.lastCheckedAt;- }- for (const row of result.rows) {- for (const device of ["desktop", "mobile"] as const) {- const { position, previousPosition } = row[device];- if (position !== null && position <= 10) summary.top10 += 1;- if (position === null || previousPosition === null) continue;- // Lower position number = better ranking.- if (position < previousPosition) summary.improved += 1;- else if (position > previousPosition) summary.declined += 1;- }- }- }-- return summary;+ return { audit, backlinks };}async function getAuditSummary(diff --git a/src/serverFunctions/onboarding.ts b/src/serverFunctions/onboarding.tsindex e7e38db8..7ec3c98f 100644--- a/src/serverFunctions/onboarding.ts+++ b/src/serverFunctions/onboarding.ts@@ -10,7 +10,6 @@ const onboardingAnswersSchema = z.object({workFor: z.string().optional(),clientWebsiteCount: z.string().optional(),foundVia: z.string().optional(),- mcpSetupIntent: z.enum(["yes", "no"]).optional(),completed: z.boolean().optional(),});@@ -25,7 +24,6 @@ export const getOnboardingAnswers = createServerFn({ method: "GET" })workFor: true,clientWebsiteCount: true,foundVia: true,- mcpSetupIntent: true,},where: eq(userOnboardingAnswers.userId, context.userId),});@@ -59,7 +57,6 @@ export const getOnboardingAnswers = createServerFn({ method: "GET" })workFor: answers?.workFor ?? null,clientWebsiteCount: answers?.clientWebsiteCount ?? null,foundVia: answers?.foundVia ?? null,- mcpSetupIntent: answers?.mcpSetupIntent ?? null,},};});@@ -79,9 +76,6 @@ export const saveOnboardingAnswers = createServerFn({ method: "POST" })? { clientWebsiteCount: data.clientWebsiteCount }: {}),...(data.foundVia !== undefined ? { foundVia: data.foundVia } : {}),- ...(data.mcpSetupIntent !== undefined- ? { mcpSetupIntent: data.mcpSetupIntent }- : {}),// Completing onboarding means the user passed the Search Console step, so// resolve the GSC prompt — the legacy re-engagement nudge must not fire// for anyone who already saw that step.@@ -100,7 +94,6 @@ export const saveOnboardingAnswers = createServerFn({ method: "POST" })workFor: data.workFor,clientWebsiteCount: data.clientWebsiteCount,foundVia: data.foundVia,- mcpSetupIntent: data.mcpSetupIntent,completedAt,gscNudgeDismissedAt: completedAt,updatedAt: now,