Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(community): add guided onboarding journey

Gus6d790c39bf62
diff --git a/src/web/knip.json b/src/web/knip.json
index 2c8602824..a1404278f 100644
--- a/src/web/knip.json
+++ b/src/web/knip.json
@@ -18,7 +18,8 @@
"lsof"
],
"ignore": [
- "src/components/ui/**"
+ "src/components/ui/**",
+ "src/app/(app)/workspaces/client.tsx"
],
"vitest": {
"entry": ["src/**/*.test.{ts,tsx}", "src/test/**/*.{ts,tsx}"]
diff --git a/src/web/src/app/(app)/workspaces/page.tsx b/src/web/src/app/(app)/workspaces/page.tsx
index 4bc15afde..71a096755 100644
--- a/src/web/src/app/(app)/workspaces/page.tsx
+++ b/src/web/src/app/(app)/workspaces/page.tsx
@@ -1,41 +1,5 @@
-import { redirect } from "next/navigation"
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { queries, generateWorkspaceSlug } from "@alook/shared"
-import { getDb } from "@/lib/db"
-import { requireSession } from "@/lib/session"
-import { WorkspaceListClient } from "./client"
+import { redirect } from "next/navigation";
-export default async function WorkspacesPage({
- searchParams,
-}: {
- searchParams: Promise<Record<string, string | undefined>>
-}) {
- const session = await requireSession()
- const { env } = await getCloudflareContext({ async: true })
- const db = getDb((env as Env).DB)
-
- const workspaces = await queries.workspace.listWorkspaces(db, session.user.id)
-
- if (workspaces.length === 0) {
- const ws = await queries.workspace.createWorkspace(db, {
- name: "Personal",
- slug: generateWorkspaceSlug(),
- })
- await queries.member.createMember(db, {
- workspaceId: ws.id,
- userId: session.user.id,
- role: "owner",
- })
- redirect(`/studio/new?workspace_id=${ws.id}`)
- }
-
- const params = await searchParams
- if (workspaces.length === 1 && params.auto !== undefined) {
- if (!workspaces[0].onboarded) {
- redirect(`/studio/new?workspace_id=${workspaces[0].id}`)
- }
- redirect(`/w/${workspaces[0].slug}/home`)
- }
-
- return <WorkspaceListClient workspaces={workspaces} />
+export default function WorkspacesPage() {
+ redirect("/c/me");
}
diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
index a2edd3e1d..dda88f5d1 100644
--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
@@ -1123,9 +1123,10 @@ function ChannelView() {
unreadCount={unreadCount}
onOpenContextSheet={openContextSeq}
/>
- <Composer
- channel={channelName}
- context="thread"
+ <div data-onboarding-target="channel-composer" className="shrink-0">
+ <Composer
+ channel={channelName}
+ context="thread"
members={composerMembers}
onSearchMembers={membersHook.searchMembers}
channelRefCandidates={channelRefCandidates}
@@ -1134,8 +1135,9 @@ function ChannelView() {
replyingTo={replyTo?.authorName}
onCancelReply={() => setReplyTo(null)}
autoFocus={bp !== "mobile"}
- draftKey={`${serverId}/${channelId}`}
- />
+ draftKey={`${serverId}/${channelId}`}
+ />
+ </div>
</main>
{rightPanel && (
@@ -1271,9 +1273,10 @@ function ChannelView() {
unreadCount={unreadCount}
onOpenContextSheet={openContextSeq}
/>
- <Composer
- channel={channelName}
- context="channel"
+ <div data-onboarding-target="channel-composer" className="shrink-0">
+ <Composer
+ channel={channelName}
+ context="channel"
members={composerMembers}
onSearchMembers={membersHook.searchMembers}
channelRefCandidates={channelRefCandidates}
@@ -1282,8 +1285,9 @@ function ChannelView() {
replyingTo={replyTo?.authorName}
onCancelReply={() => setReplyTo(null)}
autoFocus={bp !== "mobile"}
- draftKey={`${serverId}/${channelId}`}
- />
+ draftKey={`${serverId}/${channelId}`}
+ />
+ </div>
</main>
{rightPanel && (
diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsx
index 2f71b081b..54d599bc2 100644
--- a/src/web/src/app/c/community-shell.tsx
+++ b/src/web/src/app/c/community-shell.tsx
@@ -12,6 +12,7 @@ import {
import { useCommunityWs } from "@/hooks/community/use-community-ws"
import { useCommunityWsStore } from "@/stores/community/ws"
import { PerfTraceBootstrap } from "@/components/perf/perf-trace-bootstrap"
+import { CommunityOnboardingGuide } from "@/components/community/onboarding/community-onboarding-guide"
/**
* Client wrapper that provides the QueryClient, CurrentUser, and the
@@ -87,6 +88,7 @@ function CommunityBootstrap({ children }: { children: ReactNode }) {
return (
<>
<PerfTraceBootstrap />
+ <CommunityOnboardingGuide />
{children}
</>
)
diff --git a/src/web/src/app/c/layout.tsx b/src/web/src/app/c/layout.tsx
index e03c3ffac..ee0a003f8 100644
--- a/src/web/src/app/c/layout.tsx
+++ b/src/web/src/app/c/layout.tsx
@@ -5,6 +5,7 @@ import { usePathname, useRouter } from "next/navigation"
import { useSession } from "@/lib/auth-client"
import { CommunityShell } from "./community-shell"
import { avatarInitial } from "@/lib/community/avatar"
+import { SignupTracker } from "@/components/signup-tracker"
// The invite landing page is preview-first: a logged-out visitor must be able
// to see it (and only hit the login wall on Join). It's a standalone
@@ -34,7 +35,7 @@ export default function CommunityLayout({
// Public community pages (invite landing) render standalone — no session
// gate, no CommunityShell (a logged-out visitor has no currentUser).
- if (isPublic) return <>{children}</>
+ if (isPublic) return <><SignupTracker />{children}</>
if (isPending || !session) return null
@@ -45,5 +46,10 @@ export default function CommunityLayout({
avatar: session.user.image || avatarInitial(session.user.name),
}
- return <CommunityShell currentUser={currentUser}>{children}</CommunityShell>
+ return (
+ <>
+ <SignupTracker redirectTo="/c/me/machines" />
+ <CommunityShell currentUser={currentUser}>{children}</CommunityShell>
+ </>
+ )
}
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index ab29ed3df..2e6d75dd9 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -44,6 +44,10 @@ import {
communityWsSendTyping,
communityWsResetTypingThrottle,
} from "@/hooks/community/use-community-ws"
+import {
+ advanceCommunityOnboarding,
+ readCommunityOnboardingState,
+} from "@/lib/community-onboarding"
// Thin re-mount wrapper — same reason as the server-side channel view: the
// dynamic segment reuses the same component instance across DM switches, so
@@ -254,6 +258,13 @@ function DmView() {
}
}, [friends, currentUser.id, currentUser.name, dm])
+ const advanceOnboardingAfterSend = useCallback(() => {
+ const state = readCommunityOnboardingState()
+ if (state?.status === "active" && state.stage === "dm" && state.dmId === dmId) {
+ advanceCommunityOnboarding("dm", "server")
+ }
+ }, [dmId])
+
const messageActions = useMemo(() => ({
onToggleReaction: (id: string, emoji: string) =>
toggleReaction({ dmId, messageId: id, emoji, userId: currentUser.id }),
@@ -272,19 +283,22 @@ function DmView() {
onRetry: (id: string) => {
const m = messages.find((x) => x.id === id)
if (m?.content) {
- sendDmMessage.mutate({
- dmId,
- content: m.content,
- replyToId: m.replyTo?.id,
- // Reuse the failed row's nonce so the resend dedupes server-side if
- // the original committed (`onMutate` drops the stale row first).
- nonce: m.clientNonce,
- author: {
- id: currentUser.id,
- name: currentUser.name,
- avatar: currentUser.avatar,
+ sendDmMessage.mutate(
+ {
+ dmId,
+ content: m.content,
+ replyToId: m.replyTo?.id,
+ // Reuse the failed row's nonce so the resend dedupes server-side if
+ // the original committed (`onMutate` drops the stale row first).
+ nonce: m.clientNonce,
+ author: {
+ id: currentUser.id,
+ name: currentUser.name,
+ avatar: currentUser.avatar,
+ },
},
- })
+ { onSuccess: advanceOnboardingAfterSend },
+ )
}
},
onPreviewImage: (url: string) => {
@@ -296,7 +310,7 @@ function DmView() {
a.download = url.split("/").pop() ?? "file"
a.click()
},
- }), [toggleReaction, toggleMark, dmId, currentUser.id, currentUser.name, currentUser.avatar, messages, sendDmMessage, uiHandlers])
+ }), [toggleReaction, toggleMark, dmId, currentUser.id, currentUser.name, currentUser.avatar, messages, sendDmMessage, uiHandlers, advanceOnboardingAfterSend])
// DM endpoint ignores mentionType. Replies are supported — the backend
// persists replyToId for DMs too.
@@ -315,20 +329,21 @@ function DmView() {
)
uploadedAttachments = zipUploadResultsWithDimensions(results, attachments)
}
- sendDmMessage.mutate({
- dmId,
- content: markdown || "",
- replyToId: replyTo?.id,
- attachments: uploadedAttachments.length > 0 ? uploadedAttachments : undefined,
- // Fresh send mints an idempotency nonce; a retry reuses the failed row's
- // (see `onRetry`) so a 500-after-commit resend dedupes server-side.
- nonce: sendNonce(),
- author: {
- id: currentUser.id,
- name: currentUser.name,
- avatar: currentUser.avatar,
+ sendDmMessage.mutate(
+ {
+ dmId,
+ content: markdown || "",
+ replyToId: replyTo?.id,
+ attachments: uploadedAttachments.length > 0 ? uploadedAttachments : undefined,
+ nonce: sendNonce(),
+ author: {
+ id: currentUser.id,
+ name: currentUser.name,
+ avatar: currentUser.avatar,
+ },
},
- })
+ )
+ advanceOnboardingAfterSend()
communityWsResetTypingThrottle({ channelId: dmId })
setReplyTo(null)
}
@@ -420,9 +435,10 @@ function DmView() {
You have blocked this user. Unblock to send messages.
</div>
) : (
- <Composer
- channel={dm.name}
- context="dm"
+ <div data-onboarding-target="dm-composer" data-onboarding-name={dm.name} className="shrink-0">
+ <Composer
+ channel={dm.name}
+ context="dm"
// DM context short-circuits `rankMentionItems` to `[]` — no popup,
// no candidate pool needed. Passing [] keeps the Member[] typing
// honest without shimming friends into a member shape.
@@ -433,8 +449,9 @@ function DmView() {
replyingTo={replyTo?.authorName}
onCancelReply={() => setReplyTo(null)}
autoFocus={bp !== "mobile"}
- draftKey={`dm/${dmId}`}
- />
+ draftKey={`dm/${dmId}`}
+ />
+ </div>
)}
</main>
<MessageContextSheet
diff --git a/src/web/src/app/c/page.tsx b/src/web/src/app/c/page.tsx
index 046a74921..dca4fdac9 100644
--- a/src/web/src/app/c/page.tsx
+++ b/src/web/src/app/c/page.tsx
@@ -5,6 +5,6 @@ import { useEffect } from "react"
export default function CommunityIndex() {
const router = useRouter()
- useEffect(() => { router.replace("/c/me") }, [router])
+ useEffect(() => { router.replace("/c/me/machines") }, [router])
return null
}
diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.css
index 7dd8cc3b8..da79824de 100644
--- a/src/web/src/app/globals.css
+++ b/src/web/src/app/globals.css
@@ -2,6 +2,7 @@
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@import "katex/dist/katex.min.css";
+@import "driver.js/dist/driver.css";
@source "../node_modules/streamdown/dist/*.js";
@source "../node_modules/@streamdown/mermaid/dist/*.js";
@source "../node_modules/@streamdown/cjk/dist/*.js";
@@ -60,8 +61,276 @@
--radius-4xl: calc(var(--radius) * 2.6);
}
+.driver-popover.community-onboarding-popover {
+ width: min(300px, calc(100vw - 24px));
+ max-width: 300px;
+ padding: 0;
+ overflow: visible;
+ color: var(--foreground);
+ background: transparent;
+ border: 0;
+ border-radius: 0;
+ box-shadow: none;
+}
+
+.driver-popover.community-onboarding-popover .driver-popover-description {
+ margin: 0;
+ color: inherit;
+}
+
+.driver-popover.community-onboarding-popover .driver-popover-arrow {
+ display: none;
+}
+
+.community-guide-me {
+ position: relative;
+ display: inline-flex;
+ isolation: isolate;
+}
+
+.community-guide-me-orbit {
+ position: absolute;
+ inset: -17px -22px;
+ z-index: 1;
+ pointer-events: none;
+ animation: community-guide-me-orbit 4.8s linear infinite;
+}
+
+.community-guide-me-avatar {
+ position: absolute;
+ top: -3px;
+ left: 50%;
+ display: inline-flex;
+ transform: translateX(-50%);
+ animation: community-guide-me-counter-orbit 4.8s linear infinite;
+}
+
+.community-guide-me > button {
+ position: relative;
+ z-index: 0;
+}
+
+@keyframes community-guide-me-orbit {
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+@keyframes community-guide-me-counter-orbit {
+ to {
+ transform: translateX(-50%) rotate(-360deg);
+ }
+}
+
+.driver-popover.community-onboarding-popover .driver-popover-arrow-side-left {
+ border-left-color: var(--card);
+}
+
+.driver-popover.community-onboarding-popover .driver-popover-arrow-side-right {
+ border-right-color: var(--card);
+}
+
+.driver-popover.community-onboarding-popover .driver-popover-arrow-side-top {
+ border-top-color: var(--card);
+}
+
+.driver-popover.community-onboarding-popover .driver-popover-arrow-side-bottom {
+ border-bottom-color: var(--card);
+}
+
+.community-onboarding-card {
+ position: relative;
+ isolation: isolate;
+ padding: 12px 14px;
+ background: color-mix(in oklab, var(--card) 72%, transparent);
+ border: 1px solid color-mix(in oklab, var(--border) 38%, transparent);
+ border-radius: 12px;
+ box-shadow: 0 10px 28px color-mix(in oklab, var(--foreground) 9%, transparent);
+ backdrop-filter: blur(8px);
+ animation: community-onboarding-float 2.8s ease-in-out infinite;
+}
+
+.community-onboarding-focus-avatar {
+ position: fixed;
+ z-index: 10003;
+ display: inline-flex;
+ width: 28px;
+ height: 28px;
+ pointer-events: none;
+ animation: community-onboarding-companion 2.4s ease-in-out infinite;
+}
+
+.community-onboarding-content {
+ display: grid;
+ min-width: 0;
+ gap: 8px;
+}
+
+.community-onboarding-card::before {
+ position: absolute;
+ inset: -10px -12px;
+ z-index: -1;
+ border-radius: 18px;
+ background: radial-gradient(
+ ellipse at center,
+ color-mix(in oklab, var(--primary) 18%, transparent),
+ transparent 72%
+ );
+ filter: blur(7px);
+ content: "";
+ pointer-events: none;
+ animation: community-onboarding-breathe 2.8s ease-in-out infinite;
+}
+
+.driver-active .driver-active-element {
+ position: relative;
+ z-index: 10001;
+}
+
+.dark .driver-active .driver-active-element {
+ outline: 2px solid color-mix(in oklab, var(--primary) 72%, white) !important;
+ outline-offset: 3px !important;
+ box-shadow:
+ 0 0 0 6px color-mix(in oklab, var(--primary) 24%, transparent),
+ 0 0 24px color-mix(in oklab, var(--primary) 42%, transparent) !important;
+}
+
+body.community-onboarding-active.driver-active :is(
+ a[href],
+ button:not([disabled]),
+ [role="button"],
+ [contenteditable="true"]
+),
+body.community-onboarding-active.driver-active :is(
+ a[href],
+ button:not([disabled]),
+ [role="button"],
+ [contenteditable="true"]
+) * {
+ pointer-events: auto;
+}
+
+.community-onboarding-eyebrow {
+ margin: 0;
+ color: var(--muted-foreground);
+ font-family: var(--font-mono);
+ font-size: 10px;
+ font-weight: 600;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+}
+
+.community-onboarding-meta {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+}
+
+.community-onboarding-skip {
+ min-height: 0 !important;
+ height: auto !important;
+ padding: 0 !important;
+ color: var(--muted-foreground) !important;
+ font-size: 11px !important;
+ line-height: 1 !important;
+}
+
+.community-onboarding-skip:hover {
+ color: var(--foreground) !important;
+ background: transparent !important;
+}
+
+.community-onboarding-card h2 {
+ margin: 0;
+ max-width: 28ch;
+ font-size: 15px;
+ font-weight: 650;
+ line-height: 1.35;
+ letter-spacing: -0.01em;
+}
+
+@keyframes community-onboarding-breathe {
+ 0%,
+ 100% {
+ opacity: 0.3;
+ transform: scale(0.98);
+ }
+
+ 50% {
+ opacity: 0.72;
+ transform: scale(1.035);
+ }
+}
+
+@keyframes community-onboarding-float {
+ 0%,
+ 100% {
+ transform: translateY(1px);
+ }
+
+ 50% {
+ transform: translateY(-2px);
+ }
+}
+
+@keyframes community-onboarding-companion {
+ 0%,
+ 100% {
+ transform: translateY(1px);
+ }
+
+ 50% {
+ transform: translateY(-2px);
+ }
+}
+
+@media (max-width: 639px) {
+ .community-onboarding-card {
+ padding: 11px 12px;
+ }
+}
+
+@media (max-height: 520px) {
+ .community-onboarding-card {
+ padding: 8px 10px;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .community-guide-me-orbit,
+ .community-guide-me-avatar {
+ animation: none;
+ }
+
+ .community-guide-me-orbit {
+ inset: -10px -8px;
+ }
+
+ .community-guide-me-avatar {
+ top: -3px;
+ right: 0;
+ left: auto;
+ transform: none;
+ }
+
+ .community-onboarding-card {
+ animation: none;
+ }
+
+ .community-onboarding-focus-avatar {
+ animation: none;
+ }
+
+ .community-onboarding-card::before {
+ opacity: 0.45;
+ animation: none;
+ }
+}
+
:root {
--app-bg: oklch(0.955 0.008 80);
+ --community-onboarding-overlay: oklch(0.18 0.03 230);
--background: oklch(1 0 0);
--foreground: oklch(0.18 0.03 230);
--card: oklch(1 0.003 80);
@@ -110,6 +379,7 @@
.dark {
--app-bg: transparent;
+ --community-onboarding-overlay: oklch(0.08 0.02 230);
--background: oklch(0.16 0.008 60);
--foreground: oklch(0.93 0.006 80);
--card: oklch(0.21 0.008 60);
@@ -2438,4 +2708,4 @@ body {
html.dark,
.dark body {
background-color: oklch(0.16 0.008 60);
-}
\ No newline at end of file
+}
diff --git a/src/web/src/app/templates/[id]/client.tsx b/src/web/src/app/templates/[id]/client.tsx
index 2e7ddd677..7f3dcb67e 100644
--- a/src/web/src/app/templates/[id]/client.tsx
+++ b/src/web/src/app/templates/[id]/client.tsx
@@ -49,7 +49,7 @@ export function TemplateDetailClient({
</Link>
{isLoggedIn ? (
<Link
- href="/workspaces?auto"
+ href="/c/me"
className="inline-flex items-center gap-2 px-4 py-2 text-xs uppercase tracking-widest font-mono border border-current transition-opacity hover:opacity-70"
>
App
diff --git a/src/web/src/app/templates/client.tsx b/src/web/src/app/templates/client.tsx
index fc816c8de..32341f2f9 100644
--- a/src/web/src/app/templates/client.tsx
+++ b/src/web/src/app/templates/client.tsx
@@ -57,7 +57,7 @@ export function TemplatesClient({
</Link>
{isLoggedIn ? (
<Link
- href="/workspaces?auto"
+ href="/c/me"
className="inline-flex items-center gap-2 px-4 py-2 text-xs uppercase tracking-widest font-mono border border-current transition-opacity hover:opacity-70"
>
App
diff --git a/src/web/src/components/community/bots/bot-list.tsx b/src/web/src/components/community/bots/bot-list.tsx
index b04e79d8a..e497b407c 100644
--- a/src/web/src/components/community/bots/bot-list.tsx
+++ b/src/web/src/components/community/bots/bot-list.tsx
@@ -39,6 +39,13 @@ import { EditBotSheet } from "./edit-bot-sheet"
import { BotActivityModal } from "./bot-activity-modal"
import { CreateTile } from "@/components/community/onboarding-tiles/create-tile"
import { AgentHelpGallery } from "@/components/community/onboarding-tiles/agent-help-gallery"
+import {
+ advanceCommunityOnboarding,
+ readCommunityOnboardingState,
+ recoverCommunityOnboardingMachine,
+ updateCommunityOnboardingResources,
+ useCommunityOnboarding,
+} from "@/lib/community-onboarding"
/**
* BotList — the /c/me/bots surface.
@@ -70,7 +77,7 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
const router = useRouter()
const searchParams = useSearchParams()
const { bots, isLoading } = useBots()
- const { machines } = useMachines()
+ const { machines, isLoading: machinesLoading } = useMachines()
// Presence read: single API for humans + bots, server-pushed identically
// (see plans/community-account-debt-fixes.md Fix 3 — the owner is always
// part of its own bots' presence audience, even for a bot not yet in any
@@ -97,6 +104,13 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
const resetSession = useResetBotSession()
const resetMachineAgents = useResetMachineAgents()
const createOrGetDm = useCreateOrGetDm()
+ const onboardingState = useCommunityOnboarding()
+ const guidedActive = onboardingState?.status === "active" && onboardingState.stage === "bot"
+ const guidedPendingBotId =
+ guidedActive ? onboardingState.botId : undefined
+ const guidedNeedsMachine =
+ guidedActive &&
+ !machines.some((machine) => isPresenceOnline(machine.status))
const chatWithBot = async (bot: BotSummary) => {
try {
@@ -107,6 +121,47 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
}
}
+ const openGuidedBotDm = async (botId: string) => {
+ try {
+ const data = await createOrGetDm.mutateAsync({ userId: botId })
+ advanceCommunityOnboarding("bot", "dm", {
+ botId,
+ dmId: data.conversation.id,
+ })
+ router.push(`/c/me/${data.conversation.id}`)
+ } catch (e) {
+ toastApiError(e, "Bot created, but the chat couldn't open")
+ }
+ }
+
+ const onBotCreated = async (bot: BotSummary) => {
+ const state = readCommunityOnboardingState()
+ if (state?.status !== "active" || state.stage !== "bot") return
+ updateCommunityOnboardingResources({ botId: bot.id })
+ await openGuidedBotDm(bot.id)
+ }
+
+ const openGuidedCreate = () => {
+ const state = readCommunityOnboardingState()
+ const hasUsableMachine = machines.some((machine) => isPresenceOnline(machine.status))
+ if (state?.status === "active" && state.stage === "bot" && !hasUsableMachine) {
+ recoverCommunityOnboardingMachine()
+ router.push("/c/me/machines")
+ return
+ }
+ if (state?.status === "active" && state.stage === "bot" && state.botId) {
+ void openGuidedBotDm(state.botId)
+ return
+ }
+ setCreateOpen(true)
+ }
+
+ const guidedCreateLabel = guidedNeedsMachine
+ ? "Connect a machine"
+ : guidedPendingBotId
+ ? "Open bot chat"
+ : "Create a bot"
+
const machineName = (id: string): string => {
const m = machines.find((x) => x.id === id)
if (!m) return "Unknown machine"
@@ -166,7 +221,7 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
</header>
) : null
- if (isLoading && bots.length === 0) {
+ if ((isLoading || machinesLoading) && bots.length === 0) {
return (
<div className="flex min-h-0 flex-1 flex-col">
{backBar}
@@ -180,6 +235,7 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
}
if (bots.length === 0) {
+ const needsMachine = machines.length === 0
return (
<div className="flex min-h-0 flex-1 flex-col">
{backBar}
@@ -190,18 +246,33 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
</div>
</div>
<div className="flex flex-col gap-1">
- <h2 className="text-lg font-medium text-foreground">No bots yet</h2>
+ <h2 className="text-lg font-medium text-foreground">
+ {needsMachine ? "Connect a machine first" : "No bots yet"}
+ </h2>
<p className="max-w-md text-sm text-muted-foreground">
- Create a bot and chat with it from anywhere — spin up servers and
- share it with family and friends.
+ {needsMachine
+ ? "Bots need a connected machine to run. Connect one first, then come back to create your bot."
+ : "Create a bot and chat with it from anywhere — spin up servers and share it with family and friends."}
</p>
</div>
{/* No help ? in the empty state (Gus): the gallery is about mechanics
a user only needs AFTER they own a bot — it lives in the populated
header instead. */}
- <Button onClick={() => setCreateOpen(true)}>Create a bot</Button>
+ <div data-onboarding-target="create-bot" className="w-fit">
+ <Button
+ onClick={needsMachine ? () => router.push("/c/me/machines") : openGuidedCreate}
+ >
+ {needsMachine ? "Connect a machine" : guidedCreateLabel}
+ </Button>
+ </div>
</div>
- <CreateBotSheet open={createOpen} onOpenChange={setCreateOpen} />
+ <CreateBotSheet
+ open={createOpen}
+ onOpenChange={setCreateOpen}
+ onCreated={onBotCreated}
+ guided={guidedActive}
+ avatarSeed={guidedActive ? onboardingState.guideAvatarSeed : undefined}
+ />
</div>
)
}
@@ -227,7 +298,9 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
>
<HelpCircle className="size-5" />
</Button>
- <Button onClick={() => setCreateOpen(true)}>Create a bot</Button>
+ <div data-onboarding-target="create-bot" className="w-fit">
+ <Button onClick={openGuidedCreate}>{guidedCreateLabel}</Button>
+ </div>
</div>
</header>
@@ -439,7 +512,13 @@ export function BotList({ onBack }: { onBack?: () => void } = {}) {
</div>
</div>
- <CreateBotSheet open={createOpen} onOpenChange={setCreateOpen} />
+ <CreateBotSheet
+ open={createOpen}
+ onOpenChange={setCreateOpen}
+ onCreated={onBotCreated}
+ guided={guidedActive}
+ avatarSeed={guidedActive ? onboardingState.guideAvatarSeed : undefined}
+ />
<AgentHelpGallery open={helpOpen} onOpenChange={setHelpOpen} />
<EditBotSheet bot={editingBot} open={editOpen} onOpenChange={setEditOpen} />
<BotActivityModal
diff --git a/src/web/src/components/community/bots/bot-runtime-fields.test.ts b/src/web/src/components/community/bots/bot-runtime-fields.test.ts
new file mode 100644
index 000000000..5c831ac59
--- /dev/null
+++ b/src/web/src/components/community/bots/bot-runtime-fields.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it, vi } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+
+vi.mock("@/components/provider-logo", () => ({
+ ProviderLogo: () => React.createElement("span", { "data-mock": "provider-logo" }),
+}))
+
+vi.mock("@/components/ui/label", () => ({
+ Label: ({ children }: { children?: React.ReactNode }) =>
+ React.createElement("label", null, children),
+}))
+
+vi.mock("@/lib/utils", () => ({
+ cn: (...values: unknown[]) => values.filter(Boolean).join(" "),
+}))
+
+vi.mock("./model-field", () => ({
+ ModelField: ({ runtime, value }: { runtime: string; value: string | null }) =>
+ React.createElement("div", { "data-runtime": runtime, "data-model": value }),
+}))
+
+import { BotRuntimeFields } from "./bot-runtime-fields"
+
+const OPTIONS = [
+ { id: "claude", unhealthy: true },
+ { id: "codex", unhealthy: false },
+ { id: "gemini", unhealthy: true },
+]
+
+function renderFields(overrides: Partial<React.ComponentProps<typeof BotRuntimeFields>> = {}) {
+ const onRuntimeChange = vi.fn()
+ const onModelChange = vi.fn()
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(BotRuntimeFields, {
+ options: OPTIONS,
+ runtime: "claude",
+ model: "claude-sonnet-4-6",
+ onRuntimeChange,
+ onModelChange,
+ ...overrides,
+ }),
+ )
+ })
+ return { renderer, onRuntimeChange, onModelChange }
+}
+
+function radio(renderer: TestRenderer.ReactTestRenderer, value: string) {
+ return renderer.root.find(
+ (node) => node.type === "input" && node.props.value === value,
+ )
+}
+
+describe("BotRuntimeFields", () => {
+ it("keeps the selected unhealthy runtime enabled and disables other unhealthy options", () => {
+ const { renderer } = renderFields()
+ expect(radio(renderer, "claude").props.disabled).toBe(false)
+ expect(radio(renderer, "codex").props.disabled).toBe(false)
+ expect(radio(renderer, "gemini").props.disabled).toBe(true)
+ })
+
+ it("changes runtime and clears the previous provider model together", () => {
+ const { renderer, onRuntimeChange, onModelChange } = renderFields()
+ act(() => radio(renderer, "codex").props.onChange())
+ expect(onRuntimeChange).toHaveBeenCalledWith("codex")
+ expect(onModelChange).toHaveBeenCalledWith(null)
+ })
+
+ it("does not clear the model when the selected runtime is chosen again", () => {
+ const { renderer, onRuntimeChange, onModelChange } = renderFields()
+ act(() => radio(renderer, "claude").props.onChange())
+ expect(onRuntimeChange).not.toHaveBeenCalled()
+ expect(onModelChange).not.toHaveBeenCalled()
+ })
+
+ it("exposes optional motion targets without changing the form contract", () => {
+ const { renderer } = renderFields({
+ motionTargetPrefix: "runtime",
+ modelMotionTarget: "model",
+ })
+ expect(
+ renderer.root.find((node) => node.props["data-motion-target"] === "runtime-codex"),
+ ).toBeTruthy()
+ expect(
+ renderer.root.find((node) => node.props["data-motion-target"] === "model"),
+ ).toBeTruthy()
+ expect(radio(renderer, "codex").props.name).toBe("edit-bot-runtime")
+ })
+})
diff --git a/src/web/src/components/community/bots/bot-runtime-fields.tsx b/src/web/src/components/community/bots/bot-runtime-fields.tsx
new file mode 100644
index 000000000..8a96d117e
--- /dev/null
+++ b/src/web/src/components/community/bots/bot-runtime-fields.tsx
@@ -0,0 +1,107 @@
+"use client"
+
+import { ProviderLogo } from "@/components/provider-logo"
+import { Label } from "@/components/ui/label"
+import { cn } from "@/lib/utils"
+import { ModelField } from "./model-field"
+
+export type BotRuntimeOption = {
+ id: string
+ unhealthy: boolean
+}
+
+export function BotRuntimeFields({
+ options,
+ runtime,
+ model,
+ onRuntimeChange,
+ onModelChange,
+ radioName = "edit-bot-runtime",
+ motionTargetPrefix,
+ modelMotionTarget,
+ runtimeOptionClassName,
+ modelClassName,
+ runtimeError,
+ disableUnhealthyOptions = false,
+}: {
+ options: BotRuntimeOption[]
+ runtime: string
+ model: string | null
+ onRuntimeChange: (runtime: string) => void
+ onModelChange: (model: string | null) => void
+ radioName?: string
+ motionTargetPrefix?: string
+ modelMotionTarget?: string
+ runtimeOptionClassName?: (runtime: string) => string | undefined
+ modelClassName?: string
+ runtimeError?: string
+ disableUnhealthyOptions?: boolean
+}) {
+ function selectRuntime(next: string) {
+ if (next === runtime) return
+ onRuntimeChange(next)
+ onModelChange(null)
+ }
+
+ return (
+ <>
+ <div className="flex flex-col gap-2">
+ <Label className="text-xs text-muted-foreground">Runtime</Label>
+ {options.length === 0 ? (
+ <p className="text-xs text-muted-foreground">
+ This machine has no runtimes installed.
+ </p>
+ ) : (
+ <div
+ className="flex flex-col gap-2"
+ role="radiogroup"
+ aria-label="Runtime"
+ data-testid="bot-provider-picker"
+ >
+ {options.map((option) => {
+ const selected = runtime === option.id
+ const disabled = option.unhealthy && (disableUnhealthyOptions || !selected)
+ return (
+ <label
+ key={option.id}
+ data-motion-target={
+ motionTargetPrefix ? `${motionTargetPrefix}-${option.id}` : undefined
+ }
+ className={cn(
+ "flex items-center gap-2 rounded-lg border p-2 cursor-pointer transition-colors",
+ selected
+ ? "border-primary bg-primary/5"
+ : "border-border/50 hover:border-foreground/20",
+ disabled && "opacity-40 pointer-events-none",
+ runtimeOptionClassName?.(option.id),
+ )}
+ >
+ <input
+ type="radio"
+ name={radioName}
+ value={option.id}
+ checked={selected}
+ disabled={disabled}
+ onChange={() => selectRuntime(option.id)}
+ className="accent-primary size-3.5"
+ />
+ <ProviderLogo provider={option.id} className="size-4 shrink-0" />
+ <span className="text-sm">{option.id}</span>
+ {option.unhealthy && (
+ <span className="ml-auto text-xs text-muted-foreground">unavailable</span>
+ )}
+ </label>
+ )
+ })}
+ </div>
+ )}
+ {runtimeError ? <p className="text-xs text-destructive">{runtimeError}</p> : null}
+ </div>
+ {runtime ? (
+ <div data-motion-target={modelMotionTarget} className={modelClassName}>
+ <ModelField runtime={runtime} value={model} onChange={onModelChange} />
+ </div>
+ ) : null}
+ </>
+ )
+}
diff --git a/src/web/src/components/community/bots/create-bot-sheet.test.ts b/src/web/src/components/community/bots/create-bot-sheet.test.ts
index eeb13a189..5befd8fe7 100644
--- a/src/web/src/components/community/bots/create-bot-sheet.test.ts
+++ b/src/web/src/components/community/bots/create-bot-sheet.test.ts
@@ -130,8 +130,12 @@ vi.mock("@/components/ui/sheet", () => {
}
})
+const botFormFieldsRenders: Array<{ avatarDraft: { image?: string } }> = []
vi.mock("./bot-form-fields", () => ({
- BotFormFields: () => React.createElement("div", { "data-mock": "form-fields" }),
+ BotFormFields: ({ avatarDraft }: { avatarDraft: { image?: string } }) => {
+ botFormFieldsRenders.push({ avatarDraft })
+ return React.createElement("div", { "data-mock": "form-fields" })
+ },
}))
// Capture ModelField's incoming `value` so we can assert the create sheet
@@ -162,11 +166,11 @@ function checkedValue(renderer: TestRenderer.ReactTestRenderer, name: string): s
return radios(renderer, name).find((r) => r.checked)?.value ?? null
}
-function render(): TestRenderer.ReactTestRenderer {
+function render(props: { avatarSeed?: string } = {}): TestRenderer.ReactTestRenderer {
let renderer!: TestRenderer.ReactTestRenderer
act(() => {
renderer = TestRenderer.create(
- React.createElement(CreateBotSheet, { open: true, onOpenChange: vi.fn() }),
+ React.createElement(CreateBotSheet, { open: true, onOpenChange: vi.fn(), ...props }),
)
})
return renderer
@@ -175,6 +179,14 @@ function render(): TestRenderer.ReactTestRenderer {
describe("CreateBotSheet — auto-select defaults", () => {
beforeEach(() => {
useMachinesMock.mockReset()
+ botFormFieldsRenders.length = 0
+ })
+
+ it("uses the guide companion seed for a guided bot avatar", () => {
+ useMachinesMock.mockReturnValue({ machines: [] })
+ render({ avatarSeed: "guide-face-7" })
+
+ expect(botFormFieldsRenders.at(-1)?.avatarDraft.image).toBe("avatar:beam:guide-face-7")
})
it("pre-checks the machine and runtime with one online machine + one healthy runtime", () => {
diff --git a/src/web/src/components/community/bots/create-bot-sheet.tsx b/src/web/src/components/community/bots/create-bot-sheet.tsx
index 4df13f340..ba64d4159 100644
--- a/src/web/src/components/community/bots/create-bot-sheet.tsx
+++ b/src/web/src/components/community/bots/create-bot-sheet.tsx
@@ -21,7 +21,7 @@ import { ProviderLogo } from "@/components/provider-logo"
import { useMachines } from "@/hooks/community/use-machines"
import { useCreateBot, useUploadBotAvatar } from "@/hooks/community/use-bots"
import { BotFormFields } from "./bot-form-fields"
-import { ModelField } from "./model-field"
+import { BotRuntimeFields } from "./bot-runtime-fields"
import {
type BotCreateFieldErrors,
hasBotCreateFieldErrors,
@@ -29,6 +29,7 @@ import {
} from "./bot-form-validation"
import { uniqueNamesGenerator, names } from "unique-names-generator"
import { cn } from "@/lib/utils"
+import type { BotSummary } from "@/hooks/community/use-bots"
// Stable initial seed avoids hydration mismatch (real seed is rerolled on mount).
const INITIAL_AVATAR = serializeBeamSeed("initial")
@@ -72,9 +73,15 @@ export function firstOnlineMachineId(machines: CommunityMachineSummary[]): strin
export function CreateBotSheet({
open,
onOpenChange,
+ onCreated,
+ guided = false,
+ avatarSeed,
}: {
open: boolean
onOpenChange: (open: boolean) => void
+ onCreated?: (bot: BotSummary) => void | Promise<void>
+ guided?: boolean
+ avatarSeed?: string
}) {
const { machines } = useMachines()
const create = useCreateBot()
@@ -85,6 +92,7 @@ export function CreateBotSheet({
const [runtime, setRuntime] = useState<string>("")
const [model, setModel] = useState<string | null>(null)
const [fieldErrors, setFieldErrors] = useState<BotCreateFieldErrors>({})
+ const [technicalExpanded, setTechnicalExpanded] = useState(false)
const [avatarDraft, setAvatarDraft] = useState<AvatarDraft>({
kind: "procedural",
image: INITIAL_AVATAR,
@@ -92,6 +100,11 @@ export function CreateBotSheet({
const selectedMachine = machines.find((m) => m.id === machineId)
const runtimeOptions = useMemo(() => normalizeRuntimes(selectedMachine), [selectedMachine])
+ const singleTechnicalDefault =
+ guided &&
+ Boolean(selectedMachine && runtime) &&
+ machines.filter((machine) => isPresenceOnline(machine.status)).length === 1 &&
+ runtimeOptions.filter((option) => !option.unhealthy).length === 1
// Randomize name + avatar on client mount (not during SSR — Math.random would
// hydration-mismatch). Fires once per sheet open.
@@ -104,13 +117,17 @@ export function CreateBotSheet({
if (initializedFor.current) return
initializedFor.current = true
setName(randomBotName())
- setAvatarDraft({ kind: "procedural", image: serializeBeamSeed(crypto.randomUUID()) })
+ setAvatarDraft({
+ kind: "procedural",
+ image: serializeBeamSeed(avatarSeed ?? crypto.randomUUID()),
+ })
setDescription("")
setMachineId("")
setRuntime("")
setModel(null)
setFieldErrors({})
- }, [open])
+ setTechnicalExpanded(false)
+ }, [open, avatarSeed])
// Auto-select sensible defaults once machine data arrives. useMachines()
// loads async, so `machines` is often [] on the open transition and
@@ -153,9 +170,6 @@ export function CreateBotSheet({
function selectRuntime(id: string) {
setRuntime(id)
- // Reset the model to Default — carrying (e.g.) gpt-5.4 across to claude
- // would be nonsense.
- setModel(null)
setFieldErrors((prev) => ({ ...prev, runtime: undefined }))
}
@@ -188,6 +202,7 @@ export function CreateBotSheet({
}
if (!avatarFailed) toast.success(`Created ${name.trim()}`)
onOpenChange(false)
+ await onCreated?.(data.bot)
} catch (e) {
toastApiError(e, "Couldn't create the bot")
}
@@ -216,6 +231,17 @@ export function CreateBotSheet({
nameError={fieldErrors.name}
/>
+ {singleTechnicalDefault && !technicalExpanded ? (
+ <div className="flex items-center gap-3 rounded-lg bg-muted/60 px-3 py-2.5">
+ <ProviderLogo provider={runtime} className="size-5 shrink-0" />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium">Ready on {selectedMachine ? machineName(selectedMachine) : "your machine"}</p>
+ <p className="text-xs text-muted-foreground">{runtime} · Default model</p>
+ </div>
+ <Button variant="ghost" size="sm" onClick={() => setTechnicalExpanded(true)}>Change</Button>
+ </div>
+ ) : (
+ <>
<div className="flex flex-col gap-2">
<Label className="text-xs text-muted-foreground">Machine</Label>
{machines.length === 0 ? (
@@ -272,51 +298,20 @@ export function CreateBotSheet({
{selectedMachine && (
<div className="flex flex-col gap-2">
- <Label className="text-xs text-muted-foreground">Runtime</Label>
- {runtimeOptions.length === 0 ? (
- <p className="text-xs text-muted-foreground">
- This machine has no runtimes installed.
- </p>
- ) : (
- <div className="flex flex-col gap-2" role="radiogroup" aria-label="Runtime">
- {runtimeOptions.map((r) => {
- const selected = runtime === r.id
- return (
- <label
- key={r.id}
- className={cn(
- "flex items-center gap-2 rounded-lg border p-2 cursor-pointer transition-colors",
- selected ? "border-primary bg-primary/5" : "border-border/50 hover:border-foreground/20",
- r.unhealthy && "opacity-40 pointer-events-none",
- )}
- >
- <input
- type="radio"
- name="bot-runtime"
- value={r.id}
- checked={selected}
- disabled={r.unhealthy}
- onChange={() => selectRuntime(r.id)}
- className="accent-primary size-3.5"
- />
- <ProviderLogo provider={r.id} className="size-4 shrink-0" />
- <span className="text-sm">{r.id}</span>
- {r.unhealthy && (
- <span className="ml-auto text-xs text-muted-foreground">unavailable</span>
- )}
- </label>
- )
- })}
- </div>
- )}
- {fieldErrors.runtime && (
- <p className="text-xs text-destructive">{fieldErrors.runtime}</p>
- )}
- {runtime && (
- <ModelField runtime={runtime} value={model} onChange={setModel} />
- )}
+ <BotRuntimeFields
+ options={runtimeOptions}
+ runtime={runtime}
+ model={model}
+ onRuntimeChange={selectRuntime}
+ onModelChange={setModel}
+ radioName="bot-runtime"
+ runtimeError={fieldErrors.runtime}
+ disableUnhealthyOptions
+ />
</div>
)}
+ </>
+ )}
</SheetBody>
<SheetFooter>
diff --git a/src/web/src/components/community/bots/edit-bot-sheet.tsx b/src/web/src/components/community/bots/edit-bot-sheet.tsx
index fbe5b961a..dbb78b880 100644
--- a/src/web/src/components/community/bots/edit-bot-sheet.tsx
+++ b/src/web/src/components/community/bots/edit-bot-sheet.tsx
@@ -13,7 +13,6 @@ import {
SheetTitle,
} from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
-import { Label } from "@/components/ui/label"
import {
AlertDialog,
AlertDialogAction,
@@ -29,15 +28,13 @@ import {
isPhotoAvatarUrl,
} from "@/components/avatar"
import { serializeBeamSeed, parseBeamSeed } from "@/lib/avatar/seed-url"
-import { ProviderLogo } from "@/components/provider-logo"
import { useUpdateBot, useUploadBotAvatar, type BotSummary } from "@/hooks/community/use-bots"
import { useMachines } from "@/hooks/community/use-machines"
import { BotFormFields } from "./bot-form-fields"
-import { ModelField } from "./model-field"
+import { BotRuntimeFields } from "./bot-runtime-fields"
import { validateBotModel } from "./bot-form-validation"
import { uniqueNamesGenerator, names } from "unique-names-generator"
import { normalizeRuntimes } from "./create-bot-sheet"
-import { cn } from "@/lib/utils"
function draftFromBot(bot: BotSummary): AvatarDraft {
if (isPhotoAvatarUrl(bot.image)) return { kind: "photo", file: null, previewUrl: bot.image! }
@@ -109,12 +106,6 @@ export function EditBotSheet({
setNameError(undefined)
}
- function selectRuntime(next: string) {
- if (next === runtime) return
- setRuntime(next)
- setModel(null)
- }
-
async function performSubmit() {
if (!bot) return
if (!name.trim()) {
@@ -206,54 +197,13 @@ export function EditBotSheet({
nameError={nameError}
/>
{bot && (
- <>
- <div className="flex flex-col gap-2">
- <Label className="text-xs text-muted-foreground">Runtime</Label>
- {runtimeOptions.length === 0 ? (
- <p className="text-xs text-muted-foreground">
- This machine has no runtimes installed.
- </p>
- ) : (
- <div
- className="flex flex-col gap-2"
- role="radiogroup"
- aria-label="Runtime"
- data-testid="bot-provider-picker"
- >
- {runtimeOptions.map((option) => {
- const selected = runtime === option.id
- const disabled = option.unhealthy && !selected
- return (
- <label
- key={option.id}
- className={cn(
- "flex items-center gap-2 rounded-lg border p-2 cursor-pointer transition-colors",
- selected ? "border-primary bg-primary/5" : "border-border/50 hover:border-foreground/20",
- disabled && "opacity-40 pointer-events-none",
- )}
- >
- <input
- type="radio"
- name="edit-bot-runtime"
- value={option.id}
- checked={selected}
- disabled={disabled}
- onChange={() => selectRuntime(option.id)}
- className="accent-primary size-3.5"
- />
- <ProviderLogo provider={option.id} className="size-4 shrink-0" />
- <span className="text-sm">{option.id}</span>
- {option.unhealthy && (
- <span className="ml-auto text-xs text-muted-foreground">unavailable</span>
- )}
- </label>
- )
- })}
- </div>
- )}
- </div>
- <ModelField runtime={runtime} value={model} onChange={setModel} />
- </>
+ <BotRuntimeFields
+ options={runtimeOptions}
+ runtime={runtime}
+ model={model}
+ onRuntimeChange={setRuntime}
+ onModelChange={setModel}
+ />
)}
</SheetBody>
diff --git a/src/web/src/components/community/create-server-dialog.tsx b/src/web/src/components/community/create-server-dialog.tsx
index 34fe07b12..01c7170ee 100644
--- a/src/web/src/components/community/create-server-dialog.tsx
+++ b/src/web/src/components/community/create-server-dialog.tsx
@@ -12,12 +12,13 @@ import { previewSlug } from "@/lib/community/slug-preview"
import { validateIconSourceFile } from "@/lib/community/image-crop"
// Create / join server dialog.
-export function CreateServerDialog({ onClose, onCreateServer, onJoinServer }: {
+export function CreateServerDialog({ onClose, onCreateServer, onJoinServer, initialStep = "choose" }: {
onClose: () => void
onCreateServer?: (name: string, icon?: File) => void
onJoinServer?: (invite: string) => void
+ initialStep?: "choose" | "create" | "join"
}) {
- const [step, setStep] = useState<"choose" | "create" | "join">("choose")
+ const [step, setStep] = useState<"choose" | "create" | "join">(initialStep)
const [name, setName] = useState("")
const [invite, setInvite] = useState("")
const [iconFile, setIconFile] = useState<File | null>(null)
diff --git a/src/web/src/components/community/machines/machine-card.tsx b/src/web/src/components/community/machines/machine-card.tsx
index 8833d8840..8888c0a52 100644
--- a/src/web/src/components/community/machines/machine-card.tsx
+++ b/src/web/src/components/community/machines/machine-card.tsx
@@ -5,6 +5,7 @@ import { Monitor, MoreVertical } from "lucide-react"
import type { CommunityMachineSummary } from "@alook/shared"
import { isPresenceOnline } from "@alook/shared"
import { Card } from "@/components/ui/card"
+import { Button } from "@/components/ui/button"
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"
import {
DropdownMenu,
@@ -110,6 +111,19 @@ export function MachineCard({
</DropdownMenuContent>
</DropdownMenu>
</div>
+ {!isOnline && (
+ <div className="flex justify-end">
+ <Button
+ variant="outline"
+ size="sm"
+ data-onboarding-target="reconnect-machine"
+ data-onboarding-id={machine.id}
+ onClick={onReconnect}
+ >
+ Reconnect
+ </Button>
+ </div>
+ )}
</Card>
)
}
diff --git a/src/web/src/components/community/machines/machine-list.tsx b/src/web/src/components/community/machines/machine-list.tsx
index e28a76905..be5e7b10e 100644
--- a/src/web/src/components/community/machines/machine-list.tsx
+++ b/src/web/src/components/community/machines/machine-list.tsx
@@ -10,6 +10,7 @@ import { isPresenceOnline } from "@alook/shared"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
+import { BoringAvatar } from "@/components/avatar"
import {
AlertDialog,
AlertDialogContent,
@@ -28,6 +29,13 @@ import { useMachines, type MachinesResponse } from "@/hooks/community/use-machin
import { useBots } from "@/hooks/community/use-bots"
import { useCommunityStore, usePendingMachineTokenId } from "@/stores/community"
import { communityKeys } from "@/lib/query-keys"
+import {
+ advanceCommunityOnboarding,
+ readCommunityOnboardingState,
+ startCommunityOnboarding,
+ updateCommunityOnboardingResources,
+ useCommunityOnboarding,
+} from "@/lib/community-onboarding"
// Loading placeholder shaped like a real MachineCard (size-10 rounded-xl icon +
// name row + meta lines + trailing kebab slot) so the list doesn't reflow when
@@ -62,6 +70,12 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
const [pendingTokenId, setPendingTokenId] = useState<string | null>(null)
const [connectedHostname, setConnectedHostname] = useState<string | null>(null)
const [confirmDelete, setConfirmDelete] = useState<CommunityMachineSummary | null>(null)
+ const [guideAvatarSeed, setGuideAvatarSeed] = useState("alook-guide")
+ const onboardingState = useCommunityOnboarding()
+
+ useEffect(() => {
+ setGuideAvatarSeed(`alook-guide-${crypto.randomUUID()}`)
+ }, [])
// When the WS layer announces a machine for our pending token, flip the sheet.
useEffect(() => {
@@ -74,8 +88,22 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
)
if (justConnected && !connectedHostname) {
setConnectedHostname(justConnected.hostname || "machine")
+ const onboarding = readCommunityOnboardingState()
+ let continueOnboarding = false
+ if (onboarding?.status === "active" && onboarding.stage === "machine") {
+ advanceCommunityOnboarding("machine", "bot")
+ continueOnboarding = true
+ } else if (
+ onboarding?.status === "active" &&
+ onboarding.stage === "bot" &&
+ onboarding.machineRecovery
+ ) {
+ updateCommunityOnboardingResources({ machineRecovery: false })
+ continueOnboarding = true
+ }
+ if (continueOnboarding) router.push("/c/me/bots")
}
- }, [machines, pendingMachineTokenId, pendingTokenId, connectedHostname])
+ }, [machines, pendingMachineTokenId, pendingTokenId, connectedHostname, router])
const openPair = useCallback(() => {
setPairMode({ kind: "pair" })
@@ -201,7 +229,30 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
your phone or anywhere, wherever you sign in.
</p>
</div>
- <Button onClick={openPair}>Connect a machine</Button>
+ <div className="flex items-center gap-2">
+ <Button data-onboarding-target="connect-machine" onClick={openPair}>
+ Connect a machine
+ </Button>
+ <span className="community-guide-me">
+ {onboardingState === null ? (
+ <span className="community-guide-me-orbit" aria-hidden="true">
+ <span className="community-guide-me-avatar">
+ <BoringAvatar
+ seed={guideAvatarSeed}
+ size={24}
+ className="rounded-full ring-2 ring-background shadow-sm"
+ />
+ </span>
+ </span>
+ ) : null}
+ <Button
+ variant="ghost"
+ onClick={() => startCommunityOnboarding({ guideAvatarSeed })}
+ >
+ Guide me
+ </Button>
+ </span>
+ </div>
</div>
<PairMachineSheet
open={pairOpen}
@@ -226,7 +277,9 @@ export function MachineList({ onBack }: { onBack?: () => void } = {}) {
Your computers running the alook daemon.
</p>
</div>
- <Button onClick={openPair}>Connect a machine</Button>
+ <div data-onboarding-target="connect-machine" className="w-fit">
+ <Button onClick={openPair}>Connect a machine</Button>
+ </div>
</header>
<div className="flex flex-col gap-3">
{machines.map((m) => (
diff --git a/src/web/src/components/community/onboarding/community-onboarding-guide.test.ts b/src/web/src/components/community/onboarding/community-onboarding-guide.test.ts
new file mode 100644
index 000000000..325d62a93
--- /dev/null
+++ b/src/web/src/components/community/onboarding/community-onboarding-guide.test.ts
@@ -0,0 +1,210 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ adjacentAvatarLayout,
+ dismissGuideOnTargetClick,
+ guideCopy,
+ findGuideTarget,
+ guidePopoverSide,
+ nonOverlappingPopoverLayout,
+ rectFitsViewport,
+ shouldAutoRouteGuide,
+ waitForTarget,
+} from "./community-onboarding-guide";
+
+const botStage = { status: "active", stage: "bot" } as const;
+const machine = (id: string, status: "online" | "offline") => ({ id, status });
+
+describe("community onboarding guide routing", () => {
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ it("routes a zero-machine bot step to Pair", () => {
+ const copy = guideCopy(botStage, { machines: [], bots: [] });
+
+ expect(copy).toMatchObject({
+ target: { name: "connect-machine" },
+ route: "/c/me/machines",
+ });
+ });
+
+ it("routes an offline-only bot step to the exact Reconnect control", () => {
+ const copy = guideCopy(botStage, {
+ machines: [machine("machine-b", "offline"), machine("machine-a", "offline")],
+ bots: [],
+ });
+
+ expect(copy).toMatchObject({
+ target: { name: "reconnect-machine", resourceId: "machine-a" },
+ route: "/c/me/machines",
+ });
+ });
+
+ it("keeps the normal bot step when an online machine is available", () => {
+ const copy = guideCopy(botStage, {
+ machines: [machine("offline", "offline"), machine("online", "online")],
+ bots: [],
+ });
+
+ expect(copy).toMatchObject({
+ target: { name: "create-bot" },
+ route: "/c/me/bots",
+ });
+ });
+
+ it("prefers the pending bot's bound offline machine over another online machine", () => {
+ const copy = guideCopy(
+ { ...botStage, botId: "bot-7" },
+ {
+ machines: [machine("online", "online"), machine("bound", "offline")],
+ bots: [{ id: "bot-7", machineId: "bound" }],
+ },
+ );
+
+ expect(copy).toMatchObject({
+ target: { name: "reconnect-machine", resourceId: "bound" },
+ route: "/c/me/machines",
+ });
+ });
+
+ it("cleans up and resolves null when a target times out", async () => {
+ vi.useFakeTimers();
+ const disconnect = vi.fn();
+ vi.stubGlobal("document", {
+ body: {},
+ querySelectorAll: () => [],
+ });
+ vi.stubGlobal("window", {
+ setTimeout,
+ clearTimeout,
+ });
+ vi.stubGlobal("MutationObserver", class {
+ observe() {}
+ disconnect() {
+ disconnect();
+ }
+ });
+
+ const pending = waitForTarget({ name: "connect-machine" }, 50);
+ await vi.advanceTimersByTimeAsync(50);
+
+ await expect(pending).resolves.toBeNull();
+ expect(disconnect).toHaveBeenCalledOnce();
+ });
+
+ it("accepts a full-width composer that legitimately touches viewport edges", () => {
+ expect(rectFitsViewport({
+ top: 780,
+ right: 390,
+ bottom: 844,
+ left: 0,
+ width: 390,
+ height: 64,
+ }, 390, 844)).toBe(true);
+ });
+
+ it("auto-routes a stage once without trapping later navigation", () => {
+ const route = "/c/me/dm-7";
+ const routeKey = `active:dm:${route}`;
+
+ expect(shouldAutoRouteGuide(route, "/c/me/bots", routeKey, null)).toBe(true);
+ expect(shouldAutoRouteGuide(route, "/c/me/bots", routeKey, routeKey)).toBe(false);
+ });
+
+ it("places bottom-edge composer cards above their targets", () => {
+ expect(guidePopoverSide({ name: "dm-composer" })).toBe("top");
+ expect(guidePopoverSide({ name: "channel-composer" })).toBe("top");
+ expect(guidePopoverSide({ name: "add-server" })).toBe("right");
+ expect(guidePopoverSide({ name: "reconnect-machine", resourceId: "machine-1" })).toBe("bottom");
+ });
+
+ it("hands Driver the inner interactive control instead of its large wrapper", () => {
+ const control = {
+ isConnected: true,
+ matches: () => true,
+ querySelector: () => null,
+ getBoundingClientRect: () => ({ width: 320, height: 48 }),
+ dataset: {},
+ } as unknown as HTMLElement;
+ const wrapper = {
+ isConnected: true,
+ matches: () => false,
+ querySelector: () => control,
+ getBoundingClientRect: () => ({ width: 1214, height: 136 }),
+ dataset: {},
+ } as unknown as HTMLElement;
+ vi.stubGlobal("document", {
+ querySelectorAll: () => [wrapper],
+ });
+ vi.stubGlobal("window", {
+ getComputedStyle: () => ({
+ display: "block",
+ visibility: "visible",
+ pointerEvents: "auto",
+ }),
+ });
+
+ expect(findGuideTarget({ name: "dm-composer" })).toBe(control);
+ });
+
+ it("places a compact card entirely away from a lower-screen button", () => {
+ const layout = nonOverlappingPopoverLayout(
+ { top: 170, right: 220, bottom: 210, left: 100, width: 120, height: 40 },
+ { width: 390, height: 90 },
+ { top: 0, left: 0, width: 430, height: 240 },
+ );
+
+ expect(layout).toEqual({ top: 68, left: 12 });
+ expect(layout.top + 90).toBeLessThan(170);
+ });
+
+ it("places a compact card below an upper-screen button when above is unavailable", () => {
+ const layout = nonOverlappingPopoverLayout(
+ { top: 20, right: 220, bottom: 60, left: 100, width: 120, height: 40 },
+ { width: 390, height: 90 },
+ { top: 0, left: 0, width: 430, height: 240 },
+ );
+
+ expect(layout).toEqual({ top: 72, left: 12 });
+ expect(layout.top).toBeGreaterThan(60);
+ });
+
+ it("prefers step 1 and 2 cards below their buttons when both sides fit", () => {
+ const layout = nonOverlappingPopoverLayout(
+ { top: 200, right: 260, bottom: 240, left: 140, width: 120, height: 40 },
+ { width: 300, height: 90 },
+ { top: 0, left: 0, width: 600, height: 600 },
+ "bottom",
+ );
+
+ expect(layout).toEqual({ top: 252, left: 50 });
+ });
+
+ it("keeps the companion beside a button and away from its bottom popover", () => {
+ const layout = adjacentAvatarLayout(
+ { top: 100, right: 220, bottom: 140, left: 100 },
+ 28,
+ { top: 0, left: 0, width: 400, height: 300 },
+ "bottom",
+ );
+
+ expect(layout).toEqual({ top: 108, left: 230 });
+ });
+
+ it("puts the companion above a full-width bottom composer when needed", () => {
+ const layout = adjacentAvatarLayout(
+ { top: 780, right: 390, bottom: 844, left: 0 },
+ 28,
+ { top: 0, left: 0, width: 390, height: 844 },
+ "top",
+ );
+
+ expect(layout).toEqual({ top: 742, left: 8 });
+ });
+
+ it("keeps step 3 visible while the user focuses and types in the composer", () => {
+ expect(dismissGuideOnTargetClick({ name: "dm-composer" })).toBe(false);
+ expect(dismissGuideOnTargetClick({ name: "create-bot" })).toBe(true);
+ });
+});
diff --git a/src/web/src/components/community/onboarding/community-onboarding-guide.tsx b/src/web/src/components/community/onboarding/community-onboarding-guide.tsx
new file mode 100644
index 000000000..a1d478f84
--- /dev/null
+++ b/src/web/src/components/community/onboarding/community-onboarding-guide.tsx
@@ -0,0 +1,648 @@
+"use client";
+
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+import { usePathname, useRouter } from "next/navigation";
+import { BoringAvatar } from "@/components/avatar";
+import { Button } from "@/components/ui/button";
+import { driver, type Driver } from "driver.js";
+import { isPresenceOnline, type CommunityMachineSummary } from "@alook/shared";
+import { useMachines } from "@/hooks/community/use-machines";
+import { useBots, type BotSummary } from "@/hooks/community/use-bots";
+import {
+ advanceCommunityOnboarding,
+ recoverCommunityOnboardingMachine,
+ skipCommunityOnboarding,
+ type CommunityOnboardingState,
+ useCommunityOnboarding,
+} from "@/lib/community-onboarding";
+
+type GuideCopy = {
+ target: GuideTarget;
+ eyebrow: string;
+ title: string;
+ route?: string;
+};
+
+type GuideTarget = {
+ name: "channel-composer" | "connect-machine" | "reconnect-machine" | "create-bot" | "dm-composer" | "add-server";
+ resourceId?: string;
+};
+
+type GuidePopoverSide = "top" | "right" | "bottom";
+
+type GuideContext = {
+ machines: Pick<CommunityMachineSummary, "id" | "status">[];
+ bots: Pick<BotSummary, "id" | "machineId">[];
+};
+
+const target = (name: GuideTarget["name"], resourceId?: string): GuideTarget => ({
+ name,
+ ...(resourceId ? { resourceId } : {}),
+});
+
+function stableOfflineMachine(machines: GuideContext["machines"]) {
+ return machines
+ .filter((machine) => !isPresenceOnline(machine.status))
+ .sort((a, b) => a.id.localeCompare(b.id))[0];
+}
+
+function recoveryCopy(machine: GuideContext["machines"][number], eyebrow: string): GuideCopy {
+ return {
+ target: target("reconnect-machine", machine.id),
+ eyebrow,
+ title: "Bring your machine back online",
+ route: "/c/me/machines",
+ };
+}
+
+export function guideCopy(
+ state: CommunityOnboardingState,
+ { machines, bots }: GuideContext,
+): GuideCopy | null {
+ if (state.stage === "machine") {
+ if (machines.some((machine) => isPresenceOnline(machine.status))) return null;
+ const offlineMachine = stableOfflineMachine(machines);
+ if (offlineMachine) return recoveryCopy(offlineMachine, "Step 1 of 4");
+ return {
+ target: target("connect-machine"),
+ eyebrow: "Step 1 of 4",
+ title: "Give your bot a place to run",
+ route: "/c/me/machines",
+ };
+ }
+ if (state.stage === "bot") {
+ const boundMachineId = state.botId
+ ? bots.find((bot) => bot.id === state.botId)?.machineId
+ : undefined;
+ const boundMachine = boundMachineId
+ ? machines.find((machine) => machine.id === boundMachineId)
+ : undefined;
+ if (boundMachine && !isPresenceOnline(boundMachine.status)) {
+ return recoveryCopy(boundMachine, "Step 2 of 4");
+ }
+ if (!machines.some((machine) => isPresenceOnline(machine.status))) {
+ const offlineMachine = stableOfflineMachine(machines);
+ if (offlineMachine) return recoveryCopy(offlineMachine, "Step 2 of 4");
+ return {
+ target: target("connect-machine"),
+ eyebrow: "Step 2 of 4",
+ title: "Give your bot a place to run",
+ route: "/c/me/machines",
+ };
+ }
+ if (state.botId) {
+ return {
+ target: target("create-bot"),
+ eyebrow: "Step 2 of 4",
+ title: "Meet your bot in chat",
+ route: "/c/me/bots",
+ };
+ }
+ return {
+ target: target("create-bot"),
+ eyebrow: "Step 2 of 4",
+ title: "Create a bot with a voice of its own",
+ route: "/c/me/bots",
+ };
+ }
+ if (state.stage === "dm") {
+ return {
+ target: target("dm-composer"),
+ eyebrow: "Step 3 of 4",
+ title: "Start a conversation with your bot",
+ route: state.dmId ? `/c/me/${state.dmId}` : undefined,
+ };
+ }
+ const recovering = Boolean(state.serverId);
+ return {
+ target: target("add-server"),
+ eyebrow: "Step 4 of 4",
+ title: recovering
+ ? "Bring your bot into the server"
+ : "Make a shared home for friends and family",
+ };
+}
+
+function guideTargetControl(element: HTMLElement) {
+ if (element.matches("button:not([disabled]), [role=button], .ProseMirror")) return element;
+ return element.querySelector<HTMLElement>("button:not([disabled]), [role=button], .ProseMirror");
+}
+
+function isGuideTargetUsable(element: HTMLElement) {
+ if (!element.isConnected) return false;
+ const control = guideTargetControl(element);
+ if (!control) return false;
+ const elementStyle = window.getComputedStyle(element);
+ const controlStyle = window.getComputedStyle(control);
+ const rect = element.getBoundingClientRect();
+ return (
+ rect.width > 0 &&
+ rect.height > 0 &&
+ elementStyle.display !== "none" &&
+ elementStyle.visibility !== "hidden" &&
+ controlStyle.display !== "none" &&
+ controlStyle.visibility !== "hidden" &&
+ controlStyle.pointerEvents !== "none"
+ );
+}
+
+export function findGuideTarget(guideTarget: GuideTarget) {
+ const candidates = document.querySelectorAll<HTMLElement>(
+ `[data-onboarding-target="${guideTarget.name}"]`,
+ );
+ for (const candidate of candidates) {
+ if (guideTarget.resourceId && candidate.dataset.onboardingId !== guideTarget.resourceId) {
+ continue;
+ }
+ if (!isGuideTargetUsable(candidate)) continue;
+ const control = guideTargetControl(candidate);
+ if (control) return control;
+ }
+ return null;
+}
+
+export function waitForTarget(
+ guideTarget: GuideTarget,
+ timeoutMs = 2000,
+ signal?: AbortSignal,
+) {
+ return new Promise<HTMLElement | null>((resolve) => {
+ if (signal?.aborted) {
+ resolve(null);
+ return;
+ }
+ let candidate: HTMLElement | null = null;
+ let settleTimer: number | null = null;
+ let observer: MutationObserver | null = null;
+ let timeout: number | null = null;
+ let finished = false;
+ const finish = (target: HTMLElement | null) => {
+ if (finished) return;
+ finished = true;
+ observer?.disconnect();
+ if (settleTimer !== null) window.clearTimeout(settleTimer);
+ if (timeout !== null) window.clearTimeout(timeout);
+ signal?.removeEventListener("abort", handleAbort);
+ resolve(target);
+ };
+ const handleAbort = () => finish(null);
+ const check = () => {
+ const next = findGuideTarget(guideTarget);
+ if (next === candidate) return;
+ if (settleTimer !== null) window.clearTimeout(settleTimer);
+ candidate = next;
+ if (!candidate) return;
+ settleTimer = window.setTimeout(() => {
+ const current = findGuideTarget(guideTarget);
+ if (current && current === candidate) finish(current);
+ else check();
+ }, 200);
+ };
+ observer = new MutationObserver(check);
+ timeout = window.setTimeout(() => finish(null), timeoutMs);
+ signal?.addEventListener("abort", handleAbort, { once: true });
+ observer.observe(document.body, { attributes: true, childList: true, subtree: true });
+ check();
+ });
+}
+
+export function rectFitsViewport(
+ rect: Pick<DOMRect, "top" | "right" | "bottom" | "left" | "width" | "height">,
+ viewportWidth: number,
+ viewportHeight: number,
+) {
+ const tolerance = 1;
+ return (
+ rect.width > 0 &&
+ rect.height > 0 &&
+ rect.top >= -tolerance &&
+ rect.left >= -tolerance &&
+ rect.bottom <= viewportHeight + tolerance &&
+ rect.right <= viewportWidth + tolerance
+ );
+}
+
+function targetIsInViewport(element: HTMLElement) {
+ const control = guideTargetControl(element) ?? element;
+ return rectFitsViewport(control.getBoundingClientRect(), window.innerWidth, window.innerHeight);
+}
+
+export function shouldAutoRouteGuide(
+ route: string | undefined,
+ pathname: string,
+ routeKey: string,
+ routedKey: string | null,
+) {
+ return Boolean(route && pathname !== route && routedKey !== routeKey);
+}
+
+export function guidePopoverSide(guideTarget: GuideTarget): GuidePopoverSide {
+ if (guideTarget.name === "dm-composer" || guideTarget.name === "channel-composer") {
+ return "top";
+ }
+ if (guideTarget.name === "add-server") return "right";
+ return "bottom";
+}
+
+export function dismissGuideOnTargetClick(guideTarget: GuideTarget) {
+ return guideTarget.name !== "dm-composer";
+}
+
+type ViewportRect = { top: number; left: number; width: number; height: number };
+
+export function adjacentAvatarLayout(
+ targetRect: Pick<DOMRect, "top" | "right" | "bottom" | "left">,
+ avatarSize: number,
+ viewport: ViewportRect,
+ popoverSide: GuidePopoverSide,
+) {
+ const margin = 8;
+ const gap = 10;
+ const viewportRight = viewport.left + viewport.width;
+ const viewportBottom = viewport.top + viewport.height;
+ const clampLeft = (left: number) =>
+ Math.min(Math.max(left, viewport.left + margin), viewportRight - avatarSize - margin);
+ const clampTop = (top: number) =>
+ Math.min(Math.max(top, viewport.top + margin), viewportBottom - avatarSize - margin);
+ const positions = {
+ right: { top: clampTop(targetRect.top + 8), left: targetRect.right + gap },
+ left: { top: clampTop(targetRect.top + 8), left: targetRect.left - gap - avatarSize },
+ top: { top: targetRect.top - gap - avatarSize, left: clampLeft(targetRect.left + 8) },
+ bottom: { top: targetRect.bottom + gap, left: clampLeft(targetRect.left + 8) },
+ };
+ const candidates =
+ popoverSide === "right"
+ ? [positions.bottom, positions.top, positions.left, positions.right]
+ : popoverSide === "bottom"
+ ? [positions.right, positions.left, positions.top, positions.bottom]
+ : [positions.right, positions.left, positions.bottom, positions.top];
+ const fits = ({ top, left }: { top: number; left: number }) =>
+ top >= viewport.top + margin &&
+ left >= viewport.left + margin &&
+ top + avatarSize <= viewportBottom - margin &&
+ left + avatarSize <= viewportRight - margin;
+
+ return candidates.find(fits) ?? {
+ top: clampTop(targetRect.top - avatarSize - gap),
+ left: clampLeft(targetRect.left + 8),
+ };
+}
+
+export function nonOverlappingPopoverLayout(
+ targetRect: Pick<DOMRect, "top" | "right" | "bottom" | "left" | "width" | "height">,
+ popoverRect: Pick<DOMRect, "width" | "height">,
+ viewport: ViewportRect,
+ preferredSide: GuidePopoverSide = "top",
+) {
+ const margin = 12;
+ const gap = 12;
+ const viewportRight = viewport.left + viewport.width;
+ const viewportBottom = viewport.top + viewport.height;
+ const centeredLeft = Math.min(
+ Math.max(
+ targetRect.left + targetRect.width / 2 - popoverRect.width / 2,
+ viewport.left + margin,
+ ),
+ viewportRight - popoverRect.width - margin,
+ );
+ const centeredTop = Math.min(
+ Math.max(
+ targetRect.top + targetRect.height / 2 - popoverRect.height / 2,
+ viewport.top + margin,
+ ),
+ viewportBottom - popoverRect.height - margin,
+ );
+ const above = { top: targetRect.top - gap - popoverRect.height, left: centeredLeft };
+ const below = { top: targetRect.bottom + gap, left: centeredLeft };
+ const right = { top: centeredTop, left: targetRect.right + gap };
+ const left = { top: centeredTop, left: targetRect.left - gap - popoverRect.width };
+ const candidates =
+ preferredSide === "bottom"
+ ? [below, above, right, left]
+ : preferredSide === "right"
+ ? [right, left, below, above]
+ : [above, below, right, left];
+ const fits = ({ top, left }: { top: number; left: number }) =>
+ top >= viewport.top + margin &&
+ left >= viewport.left + margin &&
+ top + popoverRect.height <= viewportBottom - margin &&
+ left + popoverRect.width <= viewportRight - margin;
+ const fittingCandidate = candidates.find(fits);
+ if (fittingCandidate) return fittingCandidate;
+
+ const targetCenterY = targetRect.top + targetRect.height / 2;
+ return {
+ top:
+ targetCenterY >= viewport.top + viewport.height / 2
+ ? viewport.top + margin
+ : viewportBottom - popoverRect.height - margin,
+ left: centeredLeft,
+ };
+}
+
+function pinPopoverAwayFromTarget(
+ popoverContainer: HTMLElement,
+ instance: Driver,
+ preferredSide: GuidePopoverSide,
+) {
+ const wrapper = popoverContainer.closest<HTMLElement>(".driver-popover");
+ const activeTarget = instance.getActiveElement();
+ if (!wrapper || !activeTarget) return;
+ const visualViewport = window.visualViewport;
+ const viewport = {
+ top: visualViewport?.offsetTop ?? 0,
+ left: visualViewport?.offsetLeft ?? 0,
+ width: visualViewport?.width ?? window.innerWidth,
+ height: visualViewport?.height ?? window.innerHeight,
+ };
+ const layout = nonOverlappingPopoverLayout(
+ activeTarget.getBoundingClientRect(),
+ wrapper.getBoundingClientRect(),
+ viewport,
+ preferredSide,
+ );
+ wrapper.style.setProperty("top", `${layout.top}px`, "important");
+ wrapper.style.setProperty("left", `${layout.left}px`, "important");
+ wrapper.style.setProperty("right", "auto", "important");
+ wrapper.style.setProperty("bottom", "auto", "important");
+}
+
+function positionFocusAvatar(
+ avatarContainer: HTMLElement,
+ activeTarget: Element,
+ popoverSide: GuidePopoverSide,
+) {
+ const visualViewport = window.visualViewport;
+ const viewport = {
+ top: visualViewport?.offsetTop ?? 0,
+ left: visualViewport?.offsetLeft ?? 0,
+ width: visualViewport?.width ?? window.innerWidth,
+ height: visualViewport?.height ?? window.innerHeight,
+ };
+ const layout = adjacentAvatarLayout(
+ activeTarget.getBoundingClientRect(),
+ 28,
+ viewport,
+ popoverSide,
+ );
+ avatarContainer.style.top = `${layout.top}px`;
+ avatarContainer.style.left = `${layout.left}px`;
+}
+
+function nextFrame() {
+ return new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));
+}
+
+function GuideCard({
+ copy,
+ onSkip,
+}: {
+ copy: GuideCopy;
+ onSkip: () => void;
+}) {
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Escape") return;
+ event.preventDefault();
+ event.stopPropagation();
+ onSkip();
+ };
+ window.addEventListener("keydown", handleKeyDown, true);
+ return () => window.removeEventListener("keydown", handleKeyDown, true);
+ }, [onSkip]);
+ return (
+ <div className="community-onboarding-card">
+ <div className="community-onboarding-content">
+ <div className="community-onboarding-meta">
+ <p className="community-onboarding-eyebrow">{copy.eyebrow}</p>
+ <Button variant="ghost" className="community-onboarding-skip" onClick={onSkip}>
+ Skip guide
+ </Button>
+ </div>
+ <h2>{copy.title}</h2>
+ </div>
+ </div>
+ );
+}
+
+export function CommunityOnboardingGuide() {
+ const router = useRouter();
+ const pathname = usePathname();
+ const machinesQuery = useMachines();
+ const botsQuery = useBots();
+ const state = useCommunityOnboarding();
+ const [popoverContainer, setPopoverContainer] = useState<HTMLElement | null>(null);
+ const [targetAvatarContainer, setTargetAvatarContainer] = useState<HTMLElement | null>(null);
+ const driverRef = useRef<Driver | null>(null);
+ const targetAvatarRef = useRef<HTMLElement | null>(null);
+ const routedGuideRef = useRef<string | null>(null);
+
+ const copy = useMemo(
+ () => {
+ if (!state) return null;
+ if ((state.stage === "machine" || state.stage === "bot") && !machinesQuery.isSuccess) {
+ return null;
+ }
+ if (
+ state.stage === "bot" &&
+ state.botId &&
+ !botsQuery.isSuccess
+ ) {
+ return null;
+ }
+ return guideCopy(state, {
+ machines: machinesQuery.machines,
+ bots: botsQuery.bots,
+ });
+ },
+ [state, machinesQuery.isSuccess, machinesQuery.machines, botsQuery.isSuccess, botsQuery.bots],
+ );
+ const destroyGuide = useCallback(() => {
+ const instance = driverRef.current;
+ driverRef.current = null;
+ instance?.destroy();
+ targetAvatarRef.current?.remove();
+ targetAvatarRef.current = null;
+ document.body.classList.remove("community-onboarding-active");
+ setPopoverContainer(null);
+ setTargetAvatarContainer(null);
+ }, []);
+
+ useEffect(() => {
+ if (
+ state?.status !== "active" ||
+ state.stage !== "machine" ||
+ !machinesQuery.isSuccess ||
+ !machinesQuery.machines.some((machine) => isPresenceOnline(machine.status))
+ ) {
+ return;
+ }
+ advanceCommunityOnboarding("machine", "bot");
+ }, [state, machinesQuery.isSuccess, machinesQuery.machines]);
+
+ useEffect(() => {
+ const recoveryTarget =
+ copy?.target.name === "connect-machine" || copy?.target.name === "reconnect-machine";
+ if (!recoveryTarget || state?.status !== "active" || state.stage !== "bot" || state.machineRecovery) return;
+ recoverCommunityOnboardingMachine();
+ }, [copy, state]);
+
+ useLayoutEffect(() => {
+ if (!popoverContainer) return;
+ let positionFrame: number | null = null;
+ const refresh = () => {
+ const instance = driverRef.current;
+ if (!instance) return;
+ instance.refresh();
+ if (positionFrame !== null) window.cancelAnimationFrame(positionFrame);
+ positionFrame = window.requestAnimationFrame(() => {
+ positionFrame = null;
+ if (!copy) return;
+ const popoverSide = guidePopoverSide(copy.target);
+ pinPopoverAwayFromTarget(popoverContainer, instance, popoverSide);
+ const activeTarget = instance.getActiveElement();
+ if (targetAvatarRef.current && activeTarget) {
+ positionFocusAvatar(targetAvatarRef.current, activeTarget, popoverSide);
+ }
+ });
+ };
+ refresh();
+ if (typeof ResizeObserver === "undefined") {
+ return () => {
+ if (positionFrame !== null) window.cancelAnimationFrame(positionFrame);
+ };
+ }
+ const observer = new ResizeObserver(refresh);
+ observer.observe(popoverContainer);
+ if (popoverContainer.parentElement) observer.observe(popoverContainer.parentElement);
+ window.addEventListener("resize", refresh);
+ window.addEventListener("scroll", refresh, true);
+ window.visualViewport?.addEventListener("resize", refresh);
+ window.visualViewport?.addEventListener("scroll", refresh);
+ return () => {
+ if (positionFrame !== null) window.cancelAnimationFrame(positionFrame);
+ observer.disconnect();
+ window.removeEventListener("resize", refresh);
+ window.removeEventListener("scroll", refresh, true);
+ window.visualViewport?.removeEventListener("resize", refresh);
+ window.visualViewport?.removeEventListener("scroll", refresh);
+ };
+ }, [popoverContainer, copy]);
+
+ useEffect(() => {
+ destroyGuide();
+ if (!copy || !state) return;
+ const stageKey = state.stage;
+ const routeKey = `${state.status}:${stageKey}:${copy.route ?? ""}`;
+ if (copy.route && pathname === copy.route) routedGuideRef.current = routeKey;
+ if (
+ copy.route &&
+ shouldAutoRouteGuide(copy.route, pathname, routeKey, routedGuideRef.current)
+ ) {
+ routedGuideRef.current = routeKey;
+ router.replace(copy.route);
+ return;
+ }
+ if (copy.route && pathname !== copy.route) {
+ return;
+ }
+
+ const abortController = new AbortController();
+ let target: HTMLElement | null = null;
+ let instance: Driver | null = null;
+ let avatarContainer: HTMLElement | null = null;
+ let handleTargetClick: (() => void) | null = null;
+
+ void (async () => {
+ while (!abortController.signal.aborted && !target) {
+ const candidate = await waitForTarget(copy.target, 2000, abortController.signal);
+ if (!candidate || abortController.signal.aborted) continue;
+ candidate.scrollIntoView({ behavior: "auto", block: "nearest", inline: "nearest" });
+ await nextFrame();
+ await nextFrame();
+ if (isGuideTargetUsable(candidate) && targetIsInViewport(candidate)) target = candidate;
+ }
+ if (abortController.signal.aborted || !target) return;
+ const popoverSide = guidePopoverSide(copy.target);
+ instance = driver({
+ animate: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
+ allowClose: false,
+ overlayClickBehavior: () => undefined,
+ overlayColor: "var(--community-onboarding-overlay)",
+ overlayOpacity: 0.46,
+ stagePadding: 8,
+ stageRadius: 12,
+ disableActiveInteraction: false,
+ showButtons: [],
+ popoverClass: `community-onboarding-popover community-onboarding-popover-${popoverSide}`,
+ onPopoverRender: (popover) => {
+ popover.description.replaceChildren();
+ setPopoverContainer(popover.description);
+ },
+ });
+ driverRef.current = instance;
+ instance.highlight({
+ element: target,
+ popover: {
+ description: "Loading",
+ side: popoverSide,
+ align: "center",
+ },
+ });
+ avatarContainer = document.createElement("div");
+ avatarContainer.className = "community-onboarding-focus-avatar";
+ document.body.appendChild(avatarContainer);
+ targetAvatarRef.current = avatarContainer;
+ positionFocusAvatar(avatarContainer, target, popoverSide);
+ setTargetAvatarContainer(avatarContainer);
+ document.body.classList.add("community-onboarding-active");
+ if (dismissGuideOnTargetClick(copy.target)) {
+ handleTargetClick = () => {
+ destroyGuide();
+ };
+ target.addEventListener("click", handleTargetClick, { once: true });
+ }
+ })();
+
+ return () => {
+ abortController.abort();
+ if (handleTargetClick) target?.removeEventListener("click", handleTargetClick);
+ if (driverRef.current === instance) driverRef.current = null;
+ if (targetAvatarRef.current === avatarContainer) targetAvatarRef.current = null;
+ avatarContainer?.remove();
+ instance?.destroy();
+ document.body.classList.remove("community-onboarding-active");
+ setTargetAvatarContainer(null);
+ instance = null;
+ };
+ }, [copy, destroyGuide, pathname, router, state]);
+
+ if (!copy || !state) return null;
+ return (
+ <>
+ {popoverContainer
+ ? createPortal(
+ <GuideCard
+ copy={copy}
+ onSkip={() => {
+ destroyGuide();
+ skipCommunityOnboarding();
+ }}
+ />,
+ popoverContainer,
+ )
+ : null}
+ {targetAvatarContainer
+ ? createPortal(
+ <BoringAvatar
+ seed={state.guideAvatarSeed ?? "alook-guide"}
+ size={28}
+ className="rounded-full ring-2 ring-background shadow-md"
+ />,
+ targetAvatarContainer,
+ )
+ : null}
+ </>
+ );
+}
diff --git a/src/web/src/components/community/rail-icon.tsx b/src/web/src/components/community/rail-icon.tsx
index 9f5a790ec..e2652c653 100644
--- a/src/web/src/components/community/rail-icon.tsx
+++ b/src/web/src/components/community/rail-icon.tsx
@@ -1,7 +1,7 @@
import type React from "react"
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"
-export function RailIcon({ label, round, accent, active, onClick, tooltip, testId }: {
+export function RailIcon({ label, round, accent, active, onClick, tooltip, testId, onboardingTarget }: {
label: React.ReactNode
round?: boolean
accent?: boolean
@@ -9,9 +9,13 @@ export function RailIcon({ label, round, accent, active, onClick, tooltip, testI
onClick?: () => void
tooltip?: string
testId?: string
+ onboardingTarget?: string
}) {
const btn = (
- <div className="group relative flex w-full justify-center">
+ <div
+ className="group relative flex w-full justify-center"
+ data-onboarding-target={onboardingTarget}
+ >
<span className={[
"absolute left-0 top-1/2 w-1 -translate-y-1/2 rounded-r-full bg-foreground transition-all duration-150",
active ? "h-8" : "h-0 group-hover:h-5",
diff --git a/src/web/src/components/community/server-rail.tsx b/src/web/src/components/community/server-rail.tsx
index 715d93e2e..1eebb6697 100644
--- a/src/web/src/components/community/server-rail.tsx
+++ b/src/web/src/components/community/server-rail.tsx
@@ -17,32 +17,25 @@ import { CreateServerDialog } from "./create-server-dialog"
import { useRailOrder, isFolderKey, extractFolderId } from "./use-rail-order"
import { MarbleBackground } from "@/components/avatar"
import type { Server, CommunityFolder, MobileZone, View } from "./_types"
+import {
+ completeCommunityOnboarding,
+ isCommunityOnboardingStage,
+} from "@/lib/community-onboarding"
export const ServerRail = memo(function ServerRail({
- servers, folders, activeServerId: activeServerIdProp, serversLoading, serversReady, setMobileZone, view, bottomInset,
- onHome, onServer, onEmptyState, onServerNavigate, onCreateServer, onJoinServer, onLeaveServer,
+ servers, folders, activeServerId: activeServerIdProp, serversLoading, setMobileZone, view, bottomInset,
+ onHome, onServer, onServerNavigate, onCreateServer, onJoinServer, onLeaveServer,
onOpenSettings, onOpenInvitePopover, onUngroupFolder, onReorderRail, onReorderFolders, onFolderItemsChange, onDragCreateFolder,
}: {
servers: Server[]
folders: CommunityFolder[]
activeServerId?: string
serversLoading?: boolean
- // Auto-open the "Create a Server" dialog when the user genuinely has no
- // servers — gated on `serversReady` (query has completed at least one
- // fetch AND isn't refetching) instead of `!serversLoading`. TanStack v5
- // `isLoading` is only true on the very first fetch, so any subsequent
- // invalidate (WS `member.leave`, reconnect) briefly flips servers=[] with
- // `isLoading=false`, which would re-trigger the dialog mid-session.
- serversReady?: boolean
setMobileZone?: (z: MobileZone) => void
view: View
bottomInset?: number
onHome: () => void
onServer: () => void
- // Fired once when a genuinely-empty user (no servers/folders) first settles —
- // routes them to the machines page (the real starting point) instead of
- // popping the create-server dialog. The manual "+" affordance still opens it.
- onEmptyState?: () => void
onServerNavigate?: (id: string) => void
onCreateServer?: (name: string, icon?: File) => void
onJoinServer?: (invite: string) => void
@@ -79,21 +72,7 @@ export const ServerRail = memo(function ServerRail({
useEffect(() => { if (activeFromProps) setActiveId(activeFromProps) }, [activeFromProps])
const [createOpen, setCreateOpen] = useState(false)
- const [didAutoOpen, setDidAutoOpen] = useState(false)
- useEffect(() => {
- // Only fire when the servers query has genuinely settled (fetched at
- // least once AND not currently refetching). `serversLoading` (from
- // TanStack `isLoading`) is only true on the very first fetch, so it
- // false-triggers on any subsequent cache invalidate where the servers
- // list is transiently empty. `serversReady` is `isFetched && !isFetching`.
- if (!didAutoOpen && serversReady && servers.length === 0 && folders.length === 0) {
- setDidAutoOpen(true)
- // A brand-new user's starting point is connecting a machine, not making a
- // server (Gus): route to machines instead of auto-popping create-server.
- // The manual "+" below still opens the dialog on demand.
- onEmptyState?.()
- }
- }, [servers.length, folders.length, serversReady, didAutoOpen, onEmptyState])
+ const [guidedCreate, setGuidedCreate] = useState(false)
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 5 } }))
const pickServer = (id: string) => { setActiveId(id); onServer(); onServerNavigate?.(id); setMobileZone?.("nav") }
@@ -259,11 +238,25 @@ export const ServerRail = memo(function ServerRail({
</DragOverlay>
</DndContext>
)}
- <RailIcon label={<Plus className="size-6" />} round accent tooltip="Add a Server" testId={tid.serverAdd} onClick={() => setCreateOpen(true)} />
+ <RailIcon
+ label={<Plus className="size-6" />}
+ round
+ accent
+ tooltip="Add a Server"
+ testId={tid.serverAdd}
+ onboardingTarget="add-server"
+ onClick={() => {
+ const guided = isCommunityOnboardingStage("server")
+ setGuidedCreate(guided)
+ setCreateOpen(true)
+ if (guided) completeCommunityOnboarding()
+ }}
+ />
{createOpen && (
<CreateServerDialog
onClose={() => setCreateOpen(false)}
+ initialStep={guidedCreate ? "create" : "choose"}
onCreateServer={(name, icon) => { onCreateServer?.(name, icon) }}
onJoinServer={(invite) => { onJoinServer?.(invite) }}
/>
diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsx
index 110d68705..55f6dc9b2 100644
--- a/src/web/src/components/community/shell-frame.tsx
+++ b/src/web/src/components/community/shell-frame.tsx
@@ -38,6 +38,7 @@ import { useFriends } from "@/hooks/community/use-friends"
import { useServerMembers } from "@/hooks/community/use-server-members"
import { useInboxUnreads, useInboxMentions, useInboxMarked } from "@/hooks/community/use-inbox"
import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"
+import { useCommunityOnboarding } from "@/lib/community-onboarding"
import {
useCreateServer,
useJoinServer,
@@ -96,6 +97,13 @@ export function ShellFrame({
const currentUser = useCurrentUser()
const setCurrentUser = useSetCurrentUser()
const onlineUserIds = useOnlineUserIds()
+ const onboardingState = useCommunityOnboarding()
+
+ useEffect(() => {
+ if (onboardingState?.status === "active") {
+ setMobileZone(onboardingState.stage === "server" ? "nav" : "messages")
+ }
+ }, [onboardingState, setMobileZone])
// Server list + folders drive the rail. Members + friends feed the profile
// popover's mutual-server count when the user opens a member card.
@@ -182,9 +190,6 @@ export function ShellFrame({
(id: string) => { markSwitch("server", id); router.push(`/c/channels/${id}`) },
[router],
)
- // A genuinely-empty user starts by connecting a machine, not creating a
- // server — route there instead of auto-popping the create-server dialog.
- const onRailEmptyState = useCallback(() => { router.push("/c/me/machines") }, [router])
const onRailCreateServer = useCallback(
async (name: string, icon?: File) => {
try {
@@ -304,16 +309,10 @@ export function ShellFrame({
folders,
activeServerId,
serversLoading: serversQuery.isLoading,
- // `serversReady` gates the ServerRail auto-open — true only after the
- // very first fetch settles AND the query isn't refetching. Using
- // `isLoading` alone would let post-invalidate races (WS member.leave,
- // reconnect) with `servers=[]` re-fire the "Create a Server" dialog.
- serversReady: serversQuery.isFetched && !serversQuery.isFetching,
setMobileZone,
view,
onHome: goHome,
onServer: goServer,
- onEmptyState: onRailEmptyState,
onServerNavigate: onRailServerNavigate,
onCreateServer: onRailCreateServer,
onJoinServer: onRailJoinServer,
diff --git a/src/web/src/components/home/hero-section.tsx b/src/web/src/components/home/hero-section.tsx
index 6560c9670..2e1c64f99 100644
--- a/src/web/src/components/home/hero-section.tsx
+++ b/src/web/src/components/home/hero-section.tsx
@@ -278,8 +278,8 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {
OPEN SOURCE
</a> */}
{isLoggedIn ? (
- <a
- href="/workspaces?auto"
+ <Link
+ href="/c/me"
onClick={() => trackLandingCtaClicked({ cta_name: "open_app" })}
className="inline-flex items-center gap-2 px-6 py-2 text-sm transition-all duration-200 hover:opacity-80"
style={{
@@ -295,7 +295,7 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {
<line x1="15" y1="12" x2="3" y2="12" />
</svg>
OPEN APP
- </a>
+ </Link>
) : (
<a
href="/sign-in"
diff --git a/src/web/src/components/home/marketing-nav.tsx b/src/web/src/components/home/marketing-nav.tsx
index f188c384e..7761fed27 100644
--- a/src/web/src/components/home/marketing-nav.tsx
+++ b/src/web/src/components/home/marketing-nav.tsx
@@ -84,7 +84,7 @@ export function MarketingNav({ isLoggedIn }: { isLoggedIn: boolean }) {
</a>
{isLoggedIn ? (
<Link
- href="/workspaces?auto"
+ href="/c/me"
className="inline-flex items-center gap-2 px-4 py-2 text-xs uppercase tracking-widest transition-opacity duration-150 hover:opacity-70"
style={{
fontFamily: "var(--font-mono)",
diff --git a/src/web/src/components/signup-tracker.test.ts b/src/web/src/components/signup-tracker.test.ts
index 7f513a9e2..0408d4fb6 100644
--- a/src/web/src/components/signup-tracker.test.ts
+++ b/src/web/src/components/signup-tracker.test.ts
@@ -12,21 +12,27 @@ vi.mock("react", () => ({
describe("SignupTracker", () => {
let cookieValue = ""
let cookieSetValue = ""
+ const replace = vi.fn()
beforeEach(() => {
vi.clearAllMocks()
cookieValue = ""
cookieSetValue = ""
+ replace.mockReset()
// @ts-expect-error stub global document
globalThis.document = {
get cookie() { return cookieValue },
set cookie(val: string) { cookieSetValue = val },
}
+ // @ts-expect-error stub global window
+ globalThis.window = { location: { replace } }
})
afterEach(() => {
// @ts-expect-error cleanup
delete globalThis.document
+ // @ts-expect-error cleanup
+ delete globalThis.window
})
it("fires sign_up event and clears cookie when is_new_signup is present", async () => {
@@ -56,4 +62,14 @@ describe("SignupTracker", () => {
expect(mockSendGTMEvent).toHaveBeenCalledWith({ event: "sign_up", method: "github" })
})
+
+ it("redirects a new signup when the host surface provides a landing", async () => {
+ cookieValue = "is_new_signup=email"
+ vi.resetModules()
+ const { SignupTracker } = await import("./signup-tracker")
+ SignupTracker({ redirectTo: "/c/me/machines" })
+
+ expect(replace).toHaveBeenCalledWith("/c/me/machines")
+ expect(cookieSetValue).toBe("is_new_signup=; max-age=0; path=/")
+ })
})
diff --git a/src/web/src/components/signup-tracker.tsx b/src/web/src/components/signup-tracker.tsx
index 1ff314d2e..e59261877 100644
--- a/src/web/src/components/signup-tracker.tsx
+++ b/src/web/src/components/signup-tracker.tsx
@@ -3,14 +3,15 @@
import { useEffect } from "react"
import { trackSignUp } from "@/lib/analytics"
-export function SignupTracker() {
+export function SignupTracker({ redirectTo }: { redirectTo?: string } = {}) {
useEffect(() => {
const match = document.cookie.match(/(?:^|; )is_new_signup=([^;]*)/)
if (!match) return
const method = decodeURIComponent(match[1])
trackSignUp(method)
document.cookie = "is_new_signup=; max-age=0; path=/"
- }, [])
+ if (redirectTo) window.location.replace(redirectTo)
+ }, [redirectTo])
return null
}
diff --git a/src/web/src/lib/analytics.ts b/src/web/src/lib/analytics.ts
index c3b6be0a6..9a7d6045c 100644
--- a/src/web/src/lib/analytics.ts
+++ b/src/web/src/lib/analytics.ts
@@ -125,6 +125,28 @@ export function trackRuntimeConnected(params: {
sendGTMEvent({ event: "runtime_connected", ...params });
}
+export type CommunityOnboardingStage = "machine" | "bot" | "dm" | "server";
+
+export function trackCommunityOnboardingStarted() {
+ sendGTMEvent({ event: "community_onboarding_started" });
+}
+
+export function trackCommunityOnboardingStageCompleted(
+ stage: CommunityOnboardingStage,
+) {
+ sendGTMEvent({ event: "community_onboarding_stage_completed", stage });
+}
+
+export function trackCommunityOnboardingCompleted() {
+ sendGTMEvent({ event: "community_onboarding_completed" });
+}
+
+export function trackCommunityOnboardingSkipped(
+ stage: CommunityOnboardingStage | "complete",
+) {
+ sendGTMEvent({ event: "community_onboarding_skipped", stage });
+}
+
// ─── P3 — Page-Level Behavior ───────────────────────────────────────────────
export function trackLandingCtaClicked(params: { cta_name: string }) {
diff --git a/src/web/src/lib/community-onboarding.test.ts b/src/web/src/lib/community-onboarding.test.ts
new file mode 100644
index 000000000..64f7f2a0b
--- /dev/null
+++ b/src/web/src/lib/community-onboarding.test.ts
@@ -0,0 +1,110 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const analytics = vi.hoisted(() => ({
+ started: vi.fn(),
+ stageCompleted: vi.fn(),
+ completed: vi.fn(),
+ skipped: vi.fn(),
+}));
+
+vi.mock("@/lib/analytics", () => ({
+ trackCommunityOnboardingStarted: analytics.started,
+ trackCommunityOnboardingStageCompleted: analytics.stageCompleted,
+ trackCommunityOnboardingCompleted: analytics.completed,
+ trackCommunityOnboardingSkipped: analytics.skipped,
+}));
+
+import {
+ advanceCommunityOnboarding,
+ completeCommunityOnboarding,
+ readCommunityOnboardingState,
+ recoverCommunityOnboardingMachine,
+ skipCommunityOnboarding,
+ startCommunityOnboarding,
+ subscribeCommunityOnboarding,
+ updateCommunityOnboardingResources,
+} from "./community-onboarding";
+
+describe("community onboarding journey", () => {
+ beforeEach(() => {
+ skipCommunityOnboarding();
+ vi.clearAllMocks();
+ });
+
+ it("starts only from an explicit trigger", () => {
+ expect(readCommunityOnboardingState()).toBeNull();
+ expect(startCommunityOnboarding()).toEqual({ status: "active", stage: "machine" });
+ expect(startCommunityOnboarding()).toEqual({ status: "active", stage: "machine" });
+ expect(analytics.started).toHaveBeenCalledOnce();
+ });
+
+ it("advances only from the expected real-success stage and keeps exact ids", () => {
+ startCommunityOnboarding();
+ advanceCommunityOnboarding("bot", "dm", { botId: "wrong" });
+ expect(readCommunityOnboardingState()).toMatchObject({ stage: "machine" });
+ advanceCommunityOnboarding("machine", "bot");
+ advanceCommunityOnboarding("bot", "dm", { botId: "bot-7", dmId: "dm-4" });
+ advanceCommunityOnboarding("dm", "server");
+ expect(readCommunityOnboardingState()).toEqual({
+ status: "active",
+ stage: "server",
+ botId: "bot-7",
+ dmId: "dm-4",
+ });
+ });
+
+ it("keeps the same companion avatar through every guide stage", () => {
+ startCommunityOnboarding({ guideAvatarSeed: "guide-face-7" });
+ advanceCommunityOnboarding("machine", "bot");
+ advanceCommunityOnboarding("bot", "dm", { botId: "bot-7" });
+ advanceCommunityOnboarding("dm", "server");
+
+ expect(readCommunityOnboardingState()).toMatchObject({
+ stage: "server",
+ guideAvatarSeed: "guide-face-7",
+ });
+ });
+
+ it("recovers a missing machine without falsely completing the bot stage", () => {
+ startCommunityOnboarding();
+ advanceCommunityOnboarding("machine", "bot");
+ recoverCommunityOnboardingMachine();
+ expect(readCommunityOnboardingState()).toEqual({
+ status: "active",
+ stage: "bot",
+ machineRecovery: true,
+ });
+ expect(analytics.stageCompleted).toHaveBeenCalledTimes(1);
+ });
+
+ it("clears an explicit skip and allows manual retry", () => {
+ startCommunityOnboarding();
+ skipCommunityOnboarding();
+ expect(readCommunityOnboardingState()).toBeNull();
+ expect(analytics.skipped).toHaveBeenCalledWith("machine");
+ expect(startCommunityOnboarding()).toEqual({ status: "active", stage: "machine" });
+ });
+
+ it("completes as soon as the user opens new-server creation", () => {
+ startCommunityOnboarding();
+ advanceCommunityOnboarding("machine", "bot");
+ advanceCommunityOnboarding("bot", "dm");
+ advanceCommunityOnboarding("dm", "server");
+ completeCommunityOnboarding();
+ expect(readCommunityOnboardingState()).toBeNull();
+ expect(analytics.stageCompleted).toHaveBeenLastCalledWith("server");
+ expect(analytics.completed).toHaveBeenCalledOnce();
+ });
+
+ it("publishes in-memory state changes to mounted consumers", () => {
+ const listener = vi.fn();
+ const unsubscribe = subscribeCommunityOnboarding(listener);
+ startCommunityOnboarding();
+ advanceCommunityOnboarding("machine", "bot");
+ skipCommunityOnboarding();
+ unsubscribe();
+ expect(listener).toHaveBeenNthCalledWith(1, { status: "active", stage: "machine" });
+ expect(listener).toHaveBeenNthCalledWith(2, { status: "active", stage: "bot" });
+ expect(listener).toHaveBeenNthCalledWith(3, null);
+ });
+});
diff --git a/src/web/src/lib/community-onboarding.ts b/src/web/src/lib/community-onboarding.ts
new file mode 100644
index 000000000..96f4847ac
--- /dev/null
+++ b/src/web/src/lib/community-onboarding.ts
@@ -0,0 +1,120 @@
+"use client";
+
+import { useSyncExternalStore } from "react";
+
+import {
+ trackCommunityOnboardingCompleted,
+ trackCommunityOnboardingSkipped,
+ trackCommunityOnboardingStageCompleted,
+ trackCommunityOnboardingStarted,
+ type CommunityOnboardingStage,
+} from "@/lib/analytics";
+
+type JourneyResources = {
+ botId?: string;
+ dmId?: string;
+ serverId?: string;
+ generalId?: string;
+ machineRecovery?: boolean;
+ guideAvatarSeed?: string;
+};
+
+export type CommunityOnboardingState = {
+ status: "active";
+ stage: CommunityOnboardingStage;
+} & JourneyResources;
+
+let currentState: CommunityOnboardingState | null = null;
+const listeners = new Set<(state: CommunityOnboardingState | null) => void>();
+
+function publish(state: CommunityOnboardingState | null) {
+ currentState = state;
+ for (const listener of listeners) listener(state);
+ return state;
+}
+
+export function readCommunityOnboardingState() {
+ return currentState;
+}
+
+export function startCommunityOnboarding(resources: Pick<JourneyResources, "guideAvatarSeed"> = {}) {
+ if (currentState) return currentState;
+ const next: CommunityOnboardingState = { ...resources, status: "active", stage: "machine" };
+ publish(next);
+ trackCommunityOnboardingStarted();
+ return next;
+}
+
+export function advanceCommunityOnboarding(
+ expected: CommunityOnboardingStage,
+ nextStage: CommunityOnboardingStage,
+ resources: JourneyResources = {},
+) {
+ if (currentState?.status !== "active" || currentState.stage !== expected) {
+ return currentState;
+ }
+ const next: CommunityOnboardingState = {
+ ...currentState,
+ ...resources,
+ status: "active",
+ stage: nextStage,
+ };
+ publish(next);
+ trackCommunityOnboardingStageCompleted(expected);
+ return next;
+}
+
+export function updateCommunityOnboardingResources(resources: JourneyResources) {
+ if (currentState?.status !== "active") return currentState;
+ return publish({ ...currentState, ...resources });
+}
+
+export function recoverCommunityOnboardingMachine() {
+ if (currentState?.status !== "active" || currentState.stage !== "bot") {
+ return currentState;
+ }
+ return publish({ ...currentState, machineRecovery: true });
+}
+
+export function completeCommunityOnboarding() {
+ if (currentState?.status !== "active" || currentState.stage !== "server") {
+ return currentState;
+ }
+ publish(null);
+ trackCommunityOnboardingStageCompleted("server");
+ trackCommunityOnboardingCompleted();
+ return null;
+}
+
+export function skipCommunityOnboarding() {
+ if (!currentState) return null;
+ const stage = currentState.stage;
+ publish(null);
+ trackCommunityOnboardingSkipped(stage);
+ return null;
+}
+
+export function isCommunityOnboardingStage(stage: CommunityOnboardingStage) {
+ return currentState?.status === "active" && currentState.stage === stage;
+}
+
+export function subscribeCommunityOnboarding(
+ listener: (state: CommunityOnboardingState | null) => void,
+) {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+function subscribeCommunityOnboardingStore(onStoreChange: () => void) {
+ return subscribeCommunityOnboarding(onStoreChange);
+}
+
+export function useCommunityOnboarding() {
+ return useSyncExternalStore(
+ subscribeCommunityOnboardingStore,
+ readCommunityOnboardingState,
+ () => null,
+ );
+}
diff --git a/src/web/src/test/e2e-ui/_setup/auth.ts b/src/web/src/test/e2e-ui/_setup/auth.ts
index 08f736e97..8612f95fb 100644
--- a/src/web/src/test/e2e-ui/_setup/auth.ts
+++ b/src/web/src/test/e2e-ui/_setup/auth.ts
@@ -4,7 +4,7 @@ import { emailFor, type SeededUser, type UserKey } from "./users"
// Drives the real dev sign-in UI: navigating to /c first makes
// middleware redirect to /sign-in?redirect=/c, so post-login lands
-// back in community (default is /workspaces?auto otherwise). In dev the form
+// back in community (the default is /c/me otherwise). In dev the form
// is email-only — `handleDevSignIn` signs in with DEV_PASSWORD and
// auto-registers on first use. Captures storageState + the seeded userId.
export async function loginAndSaveState(