Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Let agents finish onboarding (EVE-442) (#977)
Carter Smith0d87b04681e8
diff --git a/.agents/skills/setup-openseo/SKILL.md b/.agents/skills/setup-openseo/SKILL.mdindex 4f912c17..1e2bc344 100644--- a/.agents/skills/setup-openseo/SKILL.md+++ b/.agents/skills/setup-openseo/SKILL.md@@ -55,7 +55,8 @@ For self-hosted OpenSEO, use its endpoint directly; the official plugin targets- Use the current agent’s native reload flow, checking its installed version, help, or official documentation. Prefer automatic discovery or an in-place reload; restart only if required to load the new tools and skills.- Once tools load in this session, run whoami and list_projects (free reads). Check skill discovery too. If a reload needs my action, give the instructions rather than repeatedly retrying unavailable tools.- Track installation, sign-in, and verification separately. A connected server is not proof that this session can use its tools. Never claim verification before the free reads succeed.-- Do not create projects or run paid research during installation.+- If list_projects returns no projects, ask for my website and create a project for it with create_project. Creating a project uses no credits.+- Do not run paid research during installation.## 7. Finish with a short handoffdiff --git a/src/client/features/gsc/GscReEngagementModal.tsx b/src/client/features/gsc/GscReEngagementModal.tsxindex 61b9119e..9844e024 100644--- a/src/client/features/gsc/GscReEngagementModal.tsx+++ b/src/client/features/gsc/GscReEngagementModal.tsx@@ -18,8 +18,8 @@ import { getGscGrantStatus } from "@/serverFunctions/gsc";import { dismissGscNudge } from "@/serverFunctions/onboarding";/**- * One-time re-engagement prompt nudging users who finished onboarding *before*- * the Search Console step existed to connect GSC. Hosted-only because this is+ * One-time prompt nudging users who finished onboarding without the Search+ * Console step (legacy users, and users onboarded by an agent) to connect GSC. Hosted-only because this is* a hosted onboarding re-engagement nudge. Shows once — server-persisted* dismissal means it never reappears after the user connects or dismisses, on* any device.@@ -38,6 +38,7 @@ export function GscReEngagementModal({const queryClient = useQueryClient();const [closed, setClosed] = React.useState(false);const shownRef = React.useRef(false);+ const connectRef = React.useRef<HTMLButtonElement>(null);const onboardingQuery = useQuery({...onboardingAnswersQueryOptions(),@@ -56,10 +57,10 @@ export function GscReEngagementModal({},});- // Legacy users — those who finished onboarding before it included the Search- // Console step — have no gscNudgeDismissedAt set, so they're the only ones who- // see this. Anyone who completes current onboarding gets it stamped (they- // already saw that step), and dismissing/connecting clears it too.+ // Users who finished onboarding without seeing the Search Console step have no+ // gscNudgeDismissedAt set: legacy users from before the step existed, and+ // users whose agent completed onboarding via create_project. Anyone who+ // completes the wizard gets it stamped, and dismissing/connecting clears it.const eligible =hosted &&!suppressed &&@@ -110,10 +111,10 @@ export function GscReEngagementModal({if (!open) handleDismiss();}}>- <DialogContent className="sm:max-w-lg">+ <DialogContent className="sm:max-w-lg" initialFocus={connectRef}><DialogHeader><DialogTitle className="text-lg">- New: Connect Google Search Console+ Connect Google Search Console</DialogTitle><DialogDescription>Bring your real clicks, impressions, and rankings into OpenSEO and@@ -121,11 +122,18 @@ export function GscReEngagementModal({</DialogDescription></DialogHeader><DialogFooter>- <Button variant="ghost" onClick={handleDismiss}>+ <button+ type="button"+ className="px-2 text-sm text-muted-foreground outline-none hover:text-foreground focus-visible:underline"+ onClick={handleDismiss}+ >Maybe later- </Button>- <Button variant="outline" onClick={handleConnect}>- <GoogleGlyph className="size-[18px]" />+ </button>+ <Button ref={connectRef} onClick={handleConnect}>+ {/* Google's mark needs a white tile to stay legible on a colored button. */}+ <span className="flex size-6 items-center justify-center rounded bg-white">+ <GoogleGlyph className="size-[16px]" />+ </span>Connect with Google</Button></DialogFooter>diff --git a/src/client/features/onboarding/useOnboardingRedirect.ts b/src/client/features/onboarding/useOnboardingRedirect.tsindex b182a0d3..38d44396 100644--- a/src/client/features/onboarding/useOnboardingRedirect.ts+++ b/src/client/features/onboarding/useOnboardingRedirect.ts@@ -3,6 +3,7 @@ import { useNavigate } from "@tanstack/react-router";import { useEffect } from "react";import { onboardingAnswersQueryOptions } from "@/client/features/onboarding/onboardingModel";import { useSession } from "@/lib/auth-client";+import { getCurrentAuthRedirectFromHref } from "@/lib/auth-redirect";import {isEmailVerificationBypassed,isHostedClientAuthMode,@@ -32,7 +33,14 @@ export function useOnboardingRedirect() {return;}- void navigate({ to: "/onboarding", search: { step: 0 }, replace: true });+ // Remember the page the user asked for, so a deep link (a project page,+ // say) still lands there after onboarding.+ const redirect = getCurrentAuthRedirectFromHref(window.location.href);+ void navigate({+ to: "/onboarding",+ search: { step: 0, redirect: redirect === "/" ? undefined : redirect },+ replace: true,+ });}, [isHostedMode,navigate,diff --git a/src/routes/_authenticated.onboarding.index.tsx b/src/routes/_authenticated.onboarding.index.tsxindex 00be971a..6b21406c 100644--- a/src/routes/_authenticated.onboarding.index.tsx+++ b/src/routes/_authenticated.onboarding.index.tsx@@ -11,6 +11,7 @@ import {import { captureClientEvent } from "@/client/lib/posthog";import { queryClient } from "@/client/tanstack-db";import { useSession } from "@/lib/auth-client";+import { normalizeAuthRedirect } from "@/lib/auth-redirect";import { saveOnboardingAnswers } from "@/serverFunctions/onboarding";const clampStep = (step: number) =>@@ -23,14 +24,19 @@ export const Route = createFileRoute("/_authenticated/onboarding/")({ssr: false,// Step lives in the URL so it survives refresh and works with back/forward.// `domain` arrives from sign-up when the visitor checked a site with the- // marketing site's free keyword tool.+ // marketing site's free keyword tool. `redirect` is the app page the user+ // asked for before useOnboardingRedirect sent them here.validateSearch: (search: Record<string, unknown>,- ): { step: number; domain?: string } => {+ ): { step: number; domain?: string; redirect?: string } => {const raw = Number(search.step);return {step: Number.isFinite(raw) ? clampStep(raw) : 0,domain: typeof search.domain === "string" ? search.domain : undefined,+ redirect:+ typeof search.redirect === "string"+ ? normalizeAuthRedirect(search.redirect)+ : undefined,};},// Send users who already finished onboarding home before rendering. Running@@ -50,7 +56,7 @@ export const Route = createFileRoute("/_authenticated/onboarding/")({function OnboardingPage() {const { data: session } = useSession();const navigate = useNavigate();- const { step, domain } = Route.useSearch();+ const { step, domain, redirect: returnTo } = Route.useSearch();const saveMutation = useMutation({mutationFn: (extra: { completed?: boolean }) =>@@ -62,7 +68,7 @@ function OnboardingPage() {const goToStep = (next: number) =>void navigate({to: "/onboarding",- search: { step: clampStep(next), domain },+ search: { step: clampStep(next), domain, redirect: returnTo },});const handleNext = () => goToStep(step + 1);@@ -116,7 +122,7 @@ function OnboardingPage() {return;}}- void navigate({ to: "/", replace: true });+ void navigate({ href: returnTo ?? "/", replace: true });};return (diff --git a/src/server/features/activation/repositories/ActivationRepository.ts b/src/server/features/activation/repositories/ActivationRepository.tsindex 8abb9eec..a435e5f7 100644--- a/src/server/features/activation/repositories/ActivationRepository.ts+++ b/src/server/features/activation/repositories/ActivationRepository.ts@@ -6,6 +6,7 @@ import {invitation,organizationActivationState,projectActivationState,+ userOnboardingAnswers,} from "@/db/schema";import type {@@ -69,6 +70,27 @@ async function recordFirstMcpToolCall(organizationId: string): Promise<void> {});}+// An agent that creates a project through MCP has done the wizard's main job,+// so the app stops sending the user to onboarding. COALESCE keeps an earlier+// completion. The Search Console nudge stays pending: the user never saw that+// step.+async function markOnboardingCompleted(+ userId: string,+ organizationId: string,+): Promise<void> {+ const now = new Date().toISOString();+ await db+ .insert(userOnboardingAnswers)+ .values({ userId, organizationId, completedAt: now, updatedAt: now })+ .onConflictDoUpdate({+ target: userOnboardingAnswers.userId,+ set: {+ completedAt: sql`coalesce(${userOnboardingAnswers.completedAt}, ${now})`,+ updatedAt: now,+ },+ });+}+const clickStepColumns = {competitor: "competitorStepClickedAt",keywords: "keywordStepClickedAt",@@ -179,6 +201,7 @@ export const ActivationRepository = {getProjectActivation,recordFirstMcpAuthorized,recordFirstMcpToolCall,+ markOnboardingCompleted,markStepClicked,markGa4CardDismissed,};diff --git a/src/server/mcp/server.ts b/src/server/mcp/server.tsindex a4d94b04..5e12273c 100644--- a/src/server/mcp/server.ts+++ b/src/server/mcp/server.ts@@ -193,6 +193,7 @@ export function createOpenSeoMcpServer(authProps: McpProps) {// Without the pre-declaration, registerTool defaults it to true.capabilities: { tools: { listChanged: false } },instructions:+ "Most tools need a projectId from list_projects. When the user has no projects, ask for their website and call create_project with its domain. " +"OpenSEO research tools use credits. Proceed with normal focused research, but ask the user for confirmation before planned batches over 2,000 credits. OpenSEO cannot purchase credits or charge cards. Explain unsupported purchase requests without promoting subscriptions, upgrades or credit purchases. When a tool reports that the organization is out of credits, you may share the billing link from that error as a plain link.",},);diff --git a/src/server/mcp/tools/create-project.test.ts b/src/server/mcp/tools/create-project.test.tsindex dd717646..e4eae9c0 100644--- a/src/server/mcp/tools/create-project.test.ts+++ b/src/server/mcp/tools/create-project.test.ts@@ -5,6 +5,7 @@ import { makeToolContext } from "./tool-test-support";const mocks = vi.hoisted(() => ({createProject: vi.fn(),listMembershipsForUser: vi.fn(),+ markOnboardingCompleted: vi.fn(),}));vi.mock("@/server/features/projects/services/ProjectService", () => ({@@ -13,6 +14,15 @@ vi.mock("@/server/features/projects/services/ProjectService", () => ({},}));+vi.mock(+ "@/server/features/activation/repositories/ActivationRepository",+ () => ({+ ActivationRepository: {+ markOnboardingCompleted: mocks.markOnboardingCompleted,+ },+ }),+);+vi.mock("@/server/auth/repositories/AuthRepository", () => ({AuthRepository: {listMembershipsForUser: mocks.listMembershipsForUser,@@ -51,6 +61,8 @@ describe("create_project MCP tool", () => {languageCode: "en",url: "https://open-seo.test/p/project_new",});+ // Self-host and SAM connections have no onboarding wizard to finish.+ expect(mocks.markOnboardingCompleted).not.toHaveBeenCalled();const first = result.content?.[0];expect(first?.type).toBe("text");if (first?.type === "text") {@@ -113,6 +125,7 @@ describe("create_project with a user-scoped credential", () => {languageCode: "en",});mocks.listMembershipsForUser.mockResolvedValue(memberships);+ mocks.markOnboardingCompleted.mockResolvedValue(undefined);});it("errors with the organization list when no organizationId is given and the user has several", async () => {@@ -139,6 +152,22 @@ describe("create_project with a user-scoped credential", () => {});});+ it("still returns the project when marking onboarding complete fails", async () => {+ mocks.listMembershipsForUser.mockResolvedValue([memberships[0]]);+ mocks.markOnboardingCompleted.mockRejectedValue(new Error("db down"));+ vi.spyOn(console, "error").mockImplementation(() => {});++ const result = await createProjectTool.handler(+ { name: "Acme" },+ userScopedContext,+ );++ // A failed tool call would make the agent retry and duplicate the project.+ expect(result.structuredContent?.project).toMatchObject({+ id: "project_new",+ });+ });+it("rejects a organizationId the user is not a member of", async () => {await expect(createProjectTool.handler(@@ -157,5 +186,10 @@ describe("create_project with a user-scoped credential", () => {expect(mocks.createProject).toHaveBeenCalledWith("org_a", {name: "Acme",});+ // The agent did the wizard's main job, so the app skips onboarding.+ expect(mocks.markOnboardingCompleted).toHaveBeenCalledWith(+ "user_123",+ "org_a",+ );});});diff --git a/src/server/mcp/tools/create-project.ts b/src/server/mcp/tools/create-project.tsindex cdf66ece..fa27ebf5 100644--- a/src/server/mcp/tools/create-project.ts+++ b/src/server/mcp/tools/create-project.ts@@ -1,5 +1,6 @@import { requireOrgPermission } from "@/server/auth/org-gate";import { AuthRepository } from "@/server/auth/repositories/AuthRepository";+import { ActivationRepository } from "@/server/features/activation/repositories/ActivationRepository";import { ProjectService } from "@/server/features/projects/services/ProjectService";import { AppError } from "@/server/lib/errors";import { mcpResponse } from "@/server/mcp/formatters";@@ -151,6 +152,17 @@ export const createProjectTool = {target.organizationId,input,);+ // Hosted users only: self-host and SAM never run the onboarding wizard.+ // Best-effort: the project already exists, and an error here would make+ // the agent retry and create a duplicate.+ if (auth.orgScope === "user") {+ await ActivationRepository.markOnboardingCompleted(+ auth.userId,+ target.organizationId,+ ).catch((error: unknown) => {+ console.error("create_project: onboarding completion failed", error);+ });+ }return mcpResponse({text: `Created project ${project.id} ${project.name}${project.domain ? ` (${project.domain})` : ""diff --git a/src/server/mcp/tools/list-projects.ts b/src/server/mcp/tools/list-projects.tsindex ae0b76fb..82d4cf65 100644--- a/src/server/mcp/tools/list-projects.ts+++ b/src/server/mcp/tools/list-projects.ts@@ -71,7 +71,9 @@ export const listProjectsTool = {const projects = await listVisibleProjects(auth);const lines =projects.length === 0- ? ["No projects yet. Create one in the dashboard."]+ ? [+ "No projects yet. Ask the user for their website, then call create_project with its domain. Creating a project uses no credits.",+ ]: projects.map((p) =>`- ${p.id} ${p.name}${p.domain ? ` (${p.domain})` : ""}${p.organization ? ` organization:${p.organization} [${p.organizationId}]` : ""} market:${p.locationCode}/${p.languageCode}`,