Open-source SEO, GEO, and marketing skills for AI agents.
feat(onboarding): stream magic-moment steps over SSE with previews + plan card
Yuting Zhong5d90fb8c1090
diff --git a/src/app/api/onboarding/stream/route.ts b/src/app/api/onboarding/stream/route.tsnew file mode 100644index 00000000..c3ff16c3--- /dev/null+++ b/src/app/api/onboarding/stream/route.ts@@ -0,0 +1,51 @@+import { NextRequest } from "next/server";+import { STEP_ORDER, STEP_RUNNERS, type StepId } from "@/lib/onboarding/steps";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++type Event =+ | { type: "step:start"; id: StepId }+ | { type: "step:done"; id: StepId; preview: unknown }+ | { type: "step:error"; id: StepId; message: string }+ | { type: "complete" };++function sse(event: Event) {+ return `data: ${JSON.stringify(event)}\n\n`;+}++export async function GET(req: NextRequest) {+ const url = req.nextUrl.searchParams.get("url")?.trim() || "";++ const stream = new ReadableStream<Uint8Array>({+ async start(controller) {+ const encoder = new TextEncoder();+ const send = (e: Event) => controller.enqueue(encoder.encode(sse(e)));++ for (const step of STEP_ORDER) {+ send({ type: "step:start", id: step.id });+ try {+ const preview = await STEP_RUNNERS[step.id](url, step.sleepMs);+ send({ type: "step:done", id: step.id, preview });+ } catch (err) {+ send({+ type: "step:error",+ id: step.id,+ message: err instanceof Error ? err.message : "Unknown error",+ });+ }+ }++ send({ type: "complete" });+ controller.close();+ },+ });++ return new Response(stream, {+ headers: {+ "Content-Type": "text/event-stream; charset=utf-8",+ "Cache-Control": "no-cache, no-transform",+ Connection: "keep-alive",+ },+ });+}diff --git a/src/components/onboarding-flow.tsx b/src/components/onboarding-flow.tsxindex e03efedb..84d062d6 100644--- a/src/components/onboarding-flow.tsx+++ b/src/components/onboarding-flow.tsx@@ -1,6 +1,6 @@"use client";-import { useState, useTransition } from "react";+import { useEffect, useRef, useState } from "react";import { useRouter } from "next/navigation";import { CheckCircle2, Loader2, AlertCircle } from "lucide-react";import { Button } from "@/components/ui/button";@@ -9,63 +9,123 @@ import { Label } from "@/components/ui/label";import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";import { toast } from "sonner";import { cn } from "@/lib/utils";+import { STEP_ORDER, type StepId, type StepPreview } from "@/lib/onboarding/steps";-type Step = {- id: "scrape" | "voice" | "icp" | "plan";- label: string;+type StepState = "pending" | "running" | "done" | "error";++type StepEntry = {+ state: StepState;+ preview?: StepPreview;+ errorMessage?: string;};-const STEPS: Step[] = [- { id: "scrape", label: "Scraping your site" },- { id: "voice", label: "Deriving brand voice fingerprint" },- { id: "icp", label: "Drafting ICP hypothesis" },- { id: "plan", label: "Building your 30-day plan" },-];+const PLACEHOLDER_LABELS: Record<StepId, string> = {+ scrape: "site scrape",+ voice: "brand voice fingerprint",+ icp: "ICP hypothesis",+ plan: "30-day plan",+};-type StepState = "pending" | "running" | "done" | "error";+type SseEvent =+ | { type: "step:start"; id: StepId }+ | { type: "step:done"; id: StepId; preview: StepPreview }+ | { type: "step:error"; id: StepId; message: string }+ | { type: "complete" };++function initialEntries(): Record<StepId, StepEntry> {+ return {+ scrape: { state: "pending" },+ voice: { state: "pending" },+ icp: { state: "pending" },+ plan: { state: "pending" },+ };+}export function OnboardingFlow() {const router = useRouter();const [url, setUrl] = useState("");- const [states, setStates] = useState<Record<Step["id"], StepState>>({- scrape: "pending",- voice: "pending",- icp: "pending",- plan: "pending",- });+ const [entries, setEntries] = useState<Record<StepId, StepEntry>>(initialEntries);const [active, setActive] = useState(false);- const [pending, start] = useTransition();+ const [complete, setComplete] = useState(false);+ const [announce, setAnnounce] = useState("");+ const approveRef = useRef<HTMLButtonElement | null>(null);+ const esRef = useRef<EventSource | null>(null);++ useEffect(() => {+ return () => {+ esRef.current?.close();+ };+ }, []);- async function run() {+ useEffect(() => {+ if (complete && approveRef.current) {+ approveRef.current.focus();+ }+ }, [complete]);++ function start() {if (!url.trim()) {toast.error("Enter your site URL first.");return;}+ setEntries(initialEntries());+ setComplete(false);setActive(true);+ setAnnounce("Starting onboarding.");- // V1: stub the per-step work with timed transitions so the UX is real even- // before the actual scraping/derivation MCP tools are wired up.- for (const step of STEPS) {- setStates((s) => ({ ...s, [step.id]: "running" }));- // eslint-disable-next-line no-await-in-loop- await new Promise((r) => setTimeout(r, 800 + Math.random() * 600));- setStates((s) => ({ ...s, [step.id]: "done" }));- }- }+ const es = new EventSource(`/api/onboarding/stream?url=${encodeURIComponent(url.trim())}`);+ esRef.current = es;++ es.onmessage = (msg) => {+ let data: SseEvent;+ try {+ data = JSON.parse(msg.data);+ } catch {+ return;+ }++ if (data.type === "step:start") {+ const label = STEP_ORDER.find((s) => s.id === data.id)?.label ?? data.id;+ setAnnounce(`${label} in progress.`);+ setEntries((prev) => ({ ...prev, [data.id]: { state: "running" } }));+ } else if (data.type === "step:done") {+ const label = STEP_ORDER.find((s) => s.id === data.id)?.label ?? data.id;+ setAnnounce(`${label} complete.`);+ setEntries((prev) => ({ ...prev, [data.id]: { state: "done", preview: data.preview } }));+ } else if (data.type === "step:error") {+ const label = PLACEHOLDER_LABELS[data.id];+ setAnnounce(`Used placeholder for ${label}.`);+ setEntries((prev) => ({+ ...prev,+ [data.id]: { state: "error", errorMessage: data.message },+ }));+ } else if (data.type === "complete") {+ setComplete(true);+ setAnnounce("Your 30-day plan is ready.");+ es.close();+ esRef.current = null;+ }+ };- function done() {- start(() => {- router.push("/");- router.refresh();- });+ es.onerror = () => {+ es.close();+ esRef.current = null;+ toast.error("Lost connection to the onboarding stream.");+ setActive(false);+ };}- const allDone = STEPS.every((s) => states[s.id] === "done");+ function goToChat(message: string) {+ toast(message);+ router.push("/");+ }return (- <div className="mx-auto max-w-2xl space-y-6 pt-8">- <header className="space-y-2 text-center">- <h1 className="text-3xl font-semibold tracking-tight">Let’s set up your CMO.</h1>+ <div className="mx-auto w-full max-w-[720px] space-y-6 pt-8 pb-12">+ <header className="space-y-2">+ <h1 className="text-3xl font-semibold tracking-tight text-foreground">+ Let’s set up your CMO.+ </h1><p className="text-sm text-muted-foreground">Paste your site URL. The CMO scrapes it, learns your voice, drafts an ICP,and proposes a 30-day plan.@@ -87,10 +147,16 @@ export function OnboardingFlow() {onChange={(e) => setUrl(e.target.value)}disabled={active}autoFocus+ onKeyDown={(e) => {+ if (e.key === "Enter" && !active) {+ e.preventDefault();+ start();+ }+ }}/></div>{!active && (- <Button onClick={() => void run()} disabled={!url.trim()}>+ <Button onClick={start} disabled={!url.trim()}>Go</Button>)}@@ -98,61 +164,181 @@ export function OnboardingFlow() {</Card>{active && (- <Card>+ <Card aria-busy={!complete}><CardHeader><CardTitle className="text-base">Building your plan</CardTitle><CardDescription>This usually takes about 30 seconds.</CardDescription></CardHeader><CardContent>- <ol className="space-y-3">- {STEPS.map((step) => (- <li key={step.id} className="flex items-center gap-3 text-sm">- <StepIcon state={states[step.id]} />- <span- className={cn(- states[step.id] === "running" && "font-medium",- states[step.id] === "pending" && "text-muted-foreground",- states[step.id] === "error" && "text-destructive",+ <ol className="space-y-4">+ {STEP_ORDER.map((step) => {+ const entry = entries[step.id];+ return (+ <li key={step.id} className="space-y-2">+ <div className="flex items-center gap-3 text-sm">+ <StepIcon state={entry.state} />+ <span+ className={cn(+ entry.state === "running" && "font-medium text-foreground",+ entry.state === "pending" && "text-muted-foreground",+ entry.state === "done" && "text-foreground",+ entry.state === "error" && "text-foreground",+ )}+ >+ {step.label}+ </span>+ </div>++ {entry.state === "done" && entry.preview && (+ <PreviewBlock preview={entry.preview} />)}- >- {step.label}- </span>- </li>- ))}++ {entry.state === "error" && (+ <div className="ml-7 rounded-md border border-dashed border-zinc-300 bg-zinc-50 px-3 py-2 text-xs text-muted-foreground dark:border-zinc-700 dark:bg-zinc-900">+ Used placeholder for {PLACEHOLDER_LABELS[step.id]}; CMO will refine over time.+ </div>+ )}+ </li>+ );+ })}</ol></CardContent></Card>)}- {allDone && (- <Card>- <CardHeader>- <CardTitle className="text-base">Your 30-day plan is ready</CardTitle>- <CardDescription>- In V1, the plan is a placeholder — wire up real scraping + LLM steps after- shipping the core UI.- </CardDescription>- </CardHeader>- <CardContent className="space-y-3">- <ul className="space-y-1 text-sm">- <li>• Week 1: Google Ads bid optimization on 12 keywords</li>- <li>• Week 1: SEO audit + 3 content proposals</li>- <li>• Week 2: Cold email sequence to 50 warm leads</li>- <li>• Week 3-4: Iterate on what's working</li>- </ul>- <Button onClick={done} disabled={pending}>- Take me to the project- </Button>- </CardContent>- </Card>- )}+ {complete && <PlanCard approveRef={approveRef} onChat={goToChat} entries={entries} />}++ <div role="status" aria-live="polite" className="sr-only">+ {announce}+ </div></div>);}function StepIcon({ state }: { state: StepState }) {- if (state === "done") return <CheckCircle2 className="size-4 text-emerald-600" />;- if (state === "running") return <Loader2 className="size-4 animate-spin" />;- if (state === "error") return <AlertCircle className="size-4 text-destructive" />;- return <div className="size-4 rounded-full border" />;+ if (state === "done") {+ return <CheckCircle2 className="size-4 text-emerald-600" aria-hidden />;+ }+ if (state === "running") {+ return <Loader2 className="size-4 animate-spin text-zinc-500" aria-hidden />;+ }+ if (state === "error") {+ return <AlertCircle className="size-4 text-amber-600" aria-hidden />;+ }+ return <div className="size-4 rounded-full border border-zinc-300 dark:border-zinc-700" aria-hidden />;+}++function PreviewBlock({ preview }: { preview: StepPreview }) {+ if (preview.kind === "scrape") {+ return (+ <div className="ml-7 rounded-md border bg-zinc-50 px-3 py-2 text-xs dark:bg-zinc-900">+ <div className="font-medium text-foreground">{preview.title}</div>+ <div className="text-muted-foreground">{preview.description}</div>+ <div className="text-muted-foreground">{preview.pages} pages indexed.</div>+ </div>+ );+ }+ if (preview.kind === "voice") {+ return (+ <div className="ml-7 rounded-md border bg-zinc-50 px-3 py-2 text-xs dark:bg-zinc-900">+ <div className="text-foreground">{preview.tone}</div>+ <div className="text-muted-foreground">+ Adjectives: {preview.adjectives.join(", ")}+ </div>+ <div className="mt-1 text-muted-foreground italic">“{preview.sample}”</div>+ </div>+ );+ }+ if (preview.kind === "icp") {+ return (+ <div className="ml-7 rounded-md border bg-zinc-50 px-3 py-2 text-xs dark:bg-zinc-900">+ <div className="font-medium text-foreground">{preview.segment}</div>+ <div className="text-muted-foreground">Pains: {preview.pains.join("; ")}</div>+ <div className="text-muted-foreground">Channels: {preview.channels.join(", ")}</div>+ </div>+ );+ }+ if (preview.kind === "plan") {+ return (+ <div className="ml-7 rounded-md border bg-zinc-50 px-3 py-2 text-xs text-muted-foreground dark:bg-zinc-900">+ {preview.weeks.length} weeks of actions queued. See plan below.+ </div>+ );+ }+ return null;+}++function PlanCard({+ approveRef,+ onChat,+ entries,+}: {+ approveRef: React.RefObject<HTMLButtonElement | null>;+ onChat: (message: string) => void;+ entries: Record<StepId, StepEntry>;+}) {+ const planPreview = entries.plan.preview;+ const weeks =+ planPreview && planPreview.kind === "plan"+ ? planPreview.weeks+ : [+ { label: "Week 1", items: ["Audit Google Ads"] },+ { label: "Week 2", items: ["Cold email sequence"] },+ { label: "Week 3", items: ["Bid optimization"] },+ { label: "Week 4", items: ["Review and reallocate"] },+ ];++ return (+ <Card aria-label="Your 30-day plan">+ <CardHeader>+ <CardTitle className="text-base">Your 30-day plan</CardTitle>+ <CardDescription>+ A starting point. Your CMO will refine this as it learns from results.+ </CardDescription>+ </CardHeader>+ <CardContent className="space-y-4">+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ {weeks.map((w) => (+ <div+ key={w.label}+ className="rounded-md border bg-zinc-50/50 p-3 text-sm dark:bg-zinc-900/50"+ >+ <div className="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">+ {w.label}+ </div>+ <ul className="space-y-1.5 text-foreground">+ {w.items.map((item, i) => (+ <li key={i} className="flex gap-2">+ <span className="text-muted-foreground">•</span>+ <span>{item}</span>+ </li>+ ))}+ </ul>+ </div>+ ))}+ </div>++ <div className="flex flex-wrap gap-2 pt-2">+ <Button+ ref={approveRef}+ onClick={() => onChat("Plan approved — CMO will start working on Week 1.")}+ >+ Approve & launch+ </Button>+ <Button+ variant="outline"+ onClick={() => onChat("Opening plan editor in chat.")}+ >+ Edit plan+ </Button>+ <Button+ variant="ghost"+ onClick={() => onChat("Saved. You can come back to this plan anytime.")}+ >+ Save & decide later+ </Button>+ </div>+ </CardContent>+ </Card>+ );}diff --git a/src/lib/onboarding/steps.ts b/src/lib/onboarding/steps.tsnew file mode 100644index 00000000..46701d96--- /dev/null+++ b/src/lib/onboarding/steps.ts@@ -0,0 +1,106 @@+// V1 stubbed step actions for the onboarding magic-moment flow.+// Each function takes the user-provided URL and returns a small preview blob+// rendered inline as the SSE event for that step. Swap the bodies for real+// scraping / LLM calls in v1.1 — the contract stays the same.++export type StepId = "scrape" | "voice" | "icp" | "plan";++export type StepPreview =+ | { kind: "scrape"; pages: number; title: string; description: string }+ | { kind: "voice"; tone: string; adjectives: string[]; sample: string }+ | { kind: "icp"; segment: string; pains: string[]; channels: string[] }+ | { kind: "plan"; weeks: { label: string; items: string[] }[] };++export const STEP_ORDER: { id: StepId; label: string; sleepMs: number }[] = [+ { id: "scrape", label: "Scraping your site", sleepMs: 900 },+ { id: "voice", label: "Deriving brand voice fingerprint", sleepMs: 1100 },+ { id: "icp", label: "Drafting ICP hypothesis", sleepMs: 1000 },+ { id: "plan", label: "Building your 30-day plan", sleepMs: 1200 },+];++function sleep(ms: number) {+ return new Promise((r) => setTimeout(r, ms));+}++function hostOf(url: string) {+ try {+ return new URL(url).hostname.replace(/^www\./, "");+ } catch {+ return url.replace(/^https?:\/\//, "").split("/")[0] || "your site";+ }+}++export async function runScrape(url: string, sleepMs: number): Promise<StepPreview> {+ await sleep(sleepMs);+ const host = hostOf(url);+ return {+ kind: "scrape",+ pages: 14,+ title: host,+ description: `Indexed home, pricing, about, and 11 other pages from ${host}.`,+ };+}++export async function runVoice(_url: string, sleepMs: number): Promise<StepPreview> {+ await sleep(sleepMs);+ return {+ kind: "voice",+ tone: "Confident, plainspoken, lightly technical",+ adjectives: ["direct", "credible", "warm"],+ sample: "Built for teams who'd rather ship than babysit dashboards.",+ };+}++export async function runIcp(_url: string, sleepMs: number): Promise<StepPreview> {+ await sleep(sleepMs);+ return {+ kind: "icp",+ segment: "Series A B2B SaaS, 20–80 employees, US/EU",+ pains: ["Marketing org too small for ambition", "Spend on Google Ads feels untracked"],+ channels: ["Google Ads", "SEO", "Cold email"],+ };+}++export async function runPlan(_url: string, sleepMs: number): Promise<StepPreview> {+ await sleep(sleepMs);+ return {+ kind: "plan",+ weeks: [+ {+ label: "Week 1",+ items: [+ "Audit Google Ads account; pause 4 underperforming keywords",+ "Stand up SEO baseline; pick 3 target pages",+ ],+ },+ {+ label: "Week 2",+ items: [+ "Draft cold email sequence for 50 warm leads",+ "Publish 1 SEO content piece against top intent keyword",+ ],+ },+ {+ label: "Week 3",+ items: [+ "Run bid optimization pass on top 12 Google Ads keywords",+ "Iterate cold email subject lines on lowest-open variant",+ ],+ },+ {+ label: "Week 4",+ items: [+ "Review what's working; reallocate budget toward best ROAS channel",+ "Propose next 30-day plan based on learnings",+ ],+ },+ ],+ };+}++export const STEP_RUNNERS: Record<StepId, (url: string, sleepMs: number) => Promise<StepPreview>> = {+ scrape: runScrape,+ voice: runVoice,+ icp: runIcp,+ plan: runPlan,+};