Open-source SEO, GEO, and marketing skills for AI agents.
fix(onboarding): block connect/skip screen on provisioning readiness
Yuting Zhong1fc850d01249
diff --git a/src/components/onboarding-flow.test.tsx b/src/components/onboarding-flow.test.tsxindex f42d6a09..a309e15e 100644--- a/src/components/onboarding-flow.test.tsx+++ b/src/components/onboarding-flow.test.tsx@@ -8,6 +8,7 @@ const {listGoogleAdsAccounts,setOnboardingAccountAction,getOnboardingTaskForSkipAction,+ awaitOnboardingReadyAction,routerPush,routerReplace,toastFns,@@ -18,6 +19,7 @@ const {listGoogleAdsAccounts: vi.fn(),setOnboardingAccountAction: vi.fn(),getOnboardingTaskForSkipAction: vi.fn(),+ awaitOnboardingReadyAction: vi.fn(),routerPush: vi.fn(),routerReplace: vi.fn(),toastFns: {@@ -42,6 +44,8 @@ vi.mock("@/server/onboarding/accounts", () => ({setOnboardingAccountAction(...args),getOnboardingTaskForSkipAction: (...args: unknown[]) =>getOnboardingTaskForSkipAction(...args),+ awaitOnboardingReadyAction: (...args: unknown[]) =>+ awaitOnboardingReadyAction(...args),}));vi.mock("next/navigation", () => ({@@ -85,6 +89,10 @@ beforeEach(() => {listGoogleAdsAccounts.mockReset();setOnboardingAccountAction.mockReset();getOnboardingTaskForSkipAction.mockReset();+ awaitOnboardingReadyAction.mockReset();+ // Default: provisioning is ready by the time ConnectStep mounts. Tests+ // that want the waiting-state UI override this in their setup.+ awaitOnboardingReadyAction.mockResolvedValue({ ok: true });routerPush.mockReset();routerReplace.mockReset();toastFns.success.mockReset();@@ -187,14 +195,38 @@ describe("OnboardingFlow — MissingSlug", () => {});describe("OnboardingFlow — ConnectStep", () => {- it("renders the connect headline + Connect/Skip buttons", () => {+ it("shows 'Setting up your agents…' until provisioning resolves", async () => {+ awaitOnboardingReadyAction.mockReturnValue(new Promise(() => {}));+ setStep("connect", "acme");+ render(<OnboardingFlow />);+ expect(screen.getByText(/Setting up your agents/i)).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: /Connect Google Ads/i }),+ ).not.toBeInTheDocument();+ });++ it("surfaces a provisioning timeout error", async () => {+ awaitOnboardingReadyAction.mockResolvedValue({+ ok: false,+ error: "Setting up your agents is taking longer than expected. Refresh to retry.",+ });+ setStep("connect", "acme");+ render(<OnboardingFlow />);+ await waitFor(() =>+ expect(+ screen.getByText(/Setting up your agents is taking longer/i),+ ).toBeInTheDocument(),+ );+ });++ it("renders the connect headline + Connect/Skip buttons once ready", async () => {setStep("connect", "acme");render(<OnboardingFlow />);expect(screen.getByRole("heading", { name: /Connect your Google Ads/i }),).toBeInTheDocument();expect(- screen.getByRole("button", { name: /Connect Google Ads/i }),+ await screen.findByRole("button", { name: /Connect Google Ads/i }),).toBeInTheDocument();expect(screen.getByRole("button", { name: /Skip Google Ads/i }),@@ -209,7 +241,9 @@ describe("OnboardingFlow — ConnectStep", () => {});setStep("connect", "acme");render(<OnboardingFlow />);- fireEvent.click(screen.getByRole("button", { name: /Connect Google Ads/i }));+ fireEvent.click(+ await screen.findByRole("button", { name: /Connect Google Ads/i }),+ );await waitFor(() =>expect(startMcpConnect).toHaveBeenCalledWith({mcp_key: "notfair-googleads",@@ -225,7 +259,9 @@ describe("OnboardingFlow — ConnectStep", () => {startMcpConnect.mockResolvedValue({ ok: false, error: "registration failed" });setStep("connect", "acme");render(<OnboardingFlow />);- const btn = screen.getByRole("button", { name: /Connect Google Ads/i });+ const btn = await screen.findByRole("button", {+ name: /Connect Google Ads/i,+ });fireEvent.click(btn);await waitFor(() =>expect(toastFns.error).toHaveBeenCalledWith("registration failed"),@@ -237,7 +273,9 @@ describe("OnboardingFlow — ConnectStep", () => {startMcpConnect.mockRejectedValue(new Error("offline"));setStep("connect", "acme");render(<OnboardingFlow />);- fireEvent.click(screen.getByRole("button", { name: /Connect Google Ads/i }));+ fireEvent.click(+ await screen.findByRole("button", { name: /Connect Google Ads/i }),+ );await waitFor(() =>expect(toastFns.error).toHaveBeenCalledWith("offline"),);@@ -251,7 +289,9 @@ describe("OnboardingFlow — ConnectStep", () => {});setStep("connect", "acme");render(<OnboardingFlow />);- fireEvent.click(screen.getByRole("button", { name: /Skip Google Ads/i }));+ fireEvent.click(+ await screen.findByRole("button", { name: /Skip Google Ads/i }),+ );await waitFor(() =>expect(routerReplace).toHaveBeenCalledWith("/acme/agents/cmo-greg/tasks?task=acme-1",@@ -266,7 +306,9 @@ describe("OnboardingFlow — ConnectStep", () => {});setStep("connect", "acme");render(<OnboardingFlow />);- fireEvent.click(screen.getByRole("button", { name: /Skip Google Ads/i }));+ fireEvent.click(+ await screen.findByRole("button", { name: /Skip Google Ads/i }),+ );await waitFor(() =>expect(toastFns.error).toHaveBeenCalledWith("Onboarding task not found."),);diff --git a/src/components/onboarding-flow.tsx b/src/components/onboarding-flow.tsxindex a9800423..d614fb68 100644--- a/src/components/onboarding-flow.tsx+++ b/src/components/onboarding-flow.tsx@@ -18,6 +18,7 @@ import {listGoogleAdsAccounts,setOnboardingAccountAction,getOnboardingTaskForSkipAction,+ awaitOnboardingReadyAction,type GoogleAdsAccount,} from "@/server/onboarding/accounts";@@ -268,11 +269,40 @@ function NameStep({ onCreated }: { onCreated: (slug: string) => void }) {// ── Step 2: Connect ────────────────────────────────────────────────+type ReadyState =+ | { phase: "waiting" }+ | { phase: "ready" }+ | { phase: "error"; message: string };+function ConnectStep({ slug }: { slug: string }) {const router = useRouter();const [busy, setBusy] = useState(false);+ const [readiness, setReadiness] = useState<ReadyState>({ phase: "waiting" });const connectionsHref = projectHref(slug, "/connections");+ // Block the screen until `ensureProjectAgents` has finished AND the+ // gateway's runtime config snapshot has surfaced the new agents. Without+ // this, clicking Skip immediately after Continue races the+ // `openclaw agents add` config write and the kickoff fails with+ // INVALID_REQUEST "Agent '<id>' no longer exists in configuration".+ // While we're waiting the user sees a "Setting up your agents…" card+ // — same screen, same place, no surprising state transitions.+ useEffect(() => {+ let cancelled = false;+ (async () => {+ const r = await awaitOnboardingReadyAction(slug);+ if (cancelled) return;+ if (!r.ok) {+ setReadiness({ phase: "error", message: r.error });+ return;+ }+ setReadiness({ phase: "ready" });+ })();+ return () => {+ cancelled = true;+ };+ }, [slug]);+async function onConnect() {setBusy(true);try {@@ -334,24 +364,44 @@ function ConnectStep({ slug }: { slug: string }) {<Card><CardContent className="space-y-4 pt-6">- <div className="flex flex-wrap gap-2">- <Button onClick={onConnect} disabled={busy} size="lg">- {busy ? (- <Loader2 className="mr-1.5 size-4 animate-spin" />- ) : (- <Plug className="mr-1.5 size-4" />- )}- Connect Google Ads- </Button>- <Button- onClick={onSkip}- variant="ghost"- disabled={busy}- aria-label="Skip Google Ads connection for now and go to CMO tasks"+ {readiness.phase === "waiting" && (+ <div+ className="flex items-center gap-2 text-sm text-muted-foreground"+ role="status"+ aria-live="polite">- Skip for now- </Button>- </div>+ <Loader2 className="size-4 animate-spin" />+ Setting up your agents…+ </div>+ )}+ {readiness.phase === "error" && (+ <p+ className="text-sm text-destructive"+ role="alert"+ >+ {readiness.message}+ </p>+ )}+ {readiness.phase === "ready" && (+ <div className="flex flex-wrap gap-2">+ <Button onClick={onConnect} disabled={busy} size="lg">+ {busy ? (+ <Loader2 className="mr-1.5 size-4 animate-spin" />+ ) : (+ <Plug className="mr-1.5 size-4" />+ )}+ Connect Google Ads+ </Button>+ <Button+ onClick={onSkip}+ variant="ghost"+ disabled={busy}+ aria-label="Skip Google Ads connection for now and go to CMO tasks"+ >+ Skip for now+ </Button>+ </div>+ )}<p className="text-xs text-muted-foreground">You can disconnect anytime in{" "}<Link href={connectionsHref} className="underline underline-offset-2">diff --git a/src/server/onboarding/accounts.ts b/src/server/onboarding/accounts.tsindex 2c85d1e7..dc9fe510 100644--- a/src/server/onboarding/accounts.ts+++ b/src/server/onboarding/accounts.ts@@ -249,6 +249,49 @@ export async function setOnboardingAccountAction(};}+export type OnboardingReadyResult =+ | { ok: true }+ | { ok: false; error: string };++/**+ * Block until the project's agents are fully provisioned AND the gateway's+ * runtime snapshot has surfaced them. Called by the onboarding "connect or+ * skip" screen so the user never sees a Connect/Skip button before the+ * agent is ready to receive its first chat.send — without this, clicking+ * Skip immediately after creating a project races the+ * `openclaw agents add` config write and the kickoff fails with+ * INVALID_REQUEST "Agent '<id>' no longer exists in configuration".+ *+ * 30-second ceiling matches the worst-case provisioning + gateway-wait+ * we've observed in dev. Returns ok=false on timeout so the UI can show+ * a retry-friendly error instead of hanging forever.+ */+export async function awaitOnboardingReadyAction(+ project_slug: string,+): Promise<OnboardingReadyResult> {+ if (!project_slug.trim()) {+ return { ok: false, error: "Missing project slug." };+ }+ const project = getProject(project_slug);+ if (!project) return { ok: false, error: "Project not found." };++ const { awaitProvisioning } = await import("./provisioning-state");+ const ready = await awaitProvisioning(project_slug, 30_000);+ if (ready.kind === "timeout") {+ return {+ ok: false,+ error: "Setting up your agents is taking longer than expected. Refresh to retry.",+ };+ }+ if (ready.kind === "no-agents") {+ return {+ ok: false,+ error: "Agent provisioning hasn't started for this project.",+ };+ }+ return { ok: true };+}+export type SkipAccountResult =| { ok: true; task_display_id: string; cmo_agent_slug: string }| { ok: false; error: string };@@ -261,9 +304,13 @@ export type SkipAccountResult =* task is only meaningful once Google Ads is wired up, and the user can* always reach the connect screen later from /connections.*- * The PROJECT.md kickoff was already fired server-side by- * createProjectForOnboardingAction (post-provisioning .then). All we do- * here is forward the slugs the client needs to navigate.+ * Blocks until provisioning has fully resolved — `ensureProjectAgents`+ * itself waits for the gateway's runtime config to surface the new agent+ * ids — so by the time the redirect fires, the agent is registered AND+ * the gateway sees it. Without this, the kickoff (server-side via+ * startTaskIfProposed OR client-side via /api/chat) can outrun the+ * `openclaw agents add` config rewrite and fail with INVALID_REQUEST+ * "Agent '<id>' no longer exists in configuration".*/export async function getOnboardingTaskForSkipAction(project_slug: string,@@ -274,6 +321,21 @@ export async function getOnboardingTaskForSkipAction(const project = getProject(project_slug);if (!project) return { ok: false, error: "Project not found." };+ const { awaitProvisioning } = await import("./provisioning-state");+ const ready = await awaitProvisioning(project_slug, 30_000);+ if (ready.kind === "timeout") {+ return {+ ok: false,+ error: "Setting up your agents is taking longer than expected. Try again in a moment.",+ };+ }+ if (ready.kind === "no-agents") {+ return {+ ok: false,+ error: "Agent provisioning hasn't started for this project.",+ };+ }+const { listTasks } = await import("@/server/db/tasks");const { listProjectAgents } = await import("@/server/agent-meta");const projectAgents = await listProjectAgents(project_slug);